Home | History | Annotate | Line # | Download | only in lfs
lfs_inode.c revision 1.90.2.4
      1 /*	$NetBSD: lfs_inode.c,v 1.90.2.4 2006/05/20 22:33:01 riz Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2001, 2002, 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Konrad E. Schroder <perseant (at) hhhh.org>.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 /*
     39  * Copyright (c) 1986, 1989, 1991, 1993
     40  *	The Regents of the University of California.  All rights reserved.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  *
     66  *	@(#)lfs_inode.c	8.9 (Berkeley) 5/8/95
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: lfs_inode.c,v 1.90.2.4 2006/05/20 22:33:01 riz Exp $");
     71 
     72 #if defined(_KERNEL_OPT)
     73 #include "opt_quota.h"
     74 #endif
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/mount.h>
     79 #include <sys/proc.h>
     80 #include <sys/file.h>
     81 #include <sys/buf.h>
     82 #include <sys/vnode.h>
     83 #include <sys/kernel.h>
     84 #include <sys/trace.h>
     85 #include <sys/resourcevar.h>
     86 
     87 #include <ufs/ufs/quota.h>
     88 #include <ufs/ufs/inode.h>
     89 #include <ufs/ufs/ufsmount.h>
     90 #include <ufs/ufs/ufs_extern.h>
     91 
     92 #include <ufs/lfs/lfs.h>
     93 #include <ufs/lfs/lfs_extern.h>
     94 
     95 static int lfs_update_seguse(struct lfs *, long, size_t);
     96 static int lfs_indirtrunc (struct inode *, daddr_t, daddr_t,
     97 			   daddr_t, int, long *, long *, long *, size_t *,
     98 			   struct proc *);
     99 static int lfs_blkfree (struct lfs *, daddr_t, size_t, long *, size_t *);
    100 static int lfs_vtruncbuf(struct vnode *, daddr_t, int, int);
    101 
    102 /* Search a block for a specific dinode. */
    103 struct ufs1_dinode *
    104 lfs_ifind(struct lfs *fs, ino_t ino, struct buf *bp)
    105 {
    106 	struct ufs1_dinode *dip = (struct ufs1_dinode *)bp->b_data;
    107 	struct ufs1_dinode *ldip, *fin;
    108 
    109 	ASSERT_NO_SEGLOCK(fs);
    110 	/*
    111 	 * Read the inode block backwards, since later versions of the
    112 	 * inode will supercede earlier ones.  Though it is unlikely, it is
    113 	 * possible that the same inode will appear in the same inode block.
    114 	 */
    115 	fin = dip + INOPB(fs);
    116 	for (ldip = fin - 1; ldip >= dip; --ldip)
    117 		if (ldip->di_inumber == ino)
    118 			return (ldip);
    119 
    120 	printf("searched %d entries\n", (int)(fin - dip));
    121 	printf("offset is 0x%x (seg %d)\n", fs->lfs_offset,
    122 	       dtosn(fs, fs->lfs_offset));
    123 	printf("block is 0x%llx (seg %lld)\n",
    124 	       (unsigned long long)dbtofsb(fs, bp->b_blkno),
    125 	       (long long)dtosn(fs, dbtofsb(fs, bp->b_blkno)));
    126 
    127 	return NULL;
    128 }
    129 
    130 int
    131 lfs_update(void *v)
    132 {
    133 	struct vop_update_args /* {
    134 				  struct vnode *a_vp;
    135 				  struct timespec *a_access;
    136 				  struct timespec *a_modify;
    137 				  int a_flags;
    138 				  } */ *ap = v;
    139 	struct inode *ip;
    140 	struct vnode *vp = ap->a_vp;
    141 	struct timespec ts;
    142 	struct lfs *fs = VFSTOUFS(vp->v_mount)->um_lfs;
    143 	int s;
    144 	int flags;
    145 
    146 	ASSERT_NO_SEGLOCK(fs);
    147 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
    148 		return (0);
    149 	ip = VTOI(vp);
    150 
    151 	/*
    152 	 * If we are called from vinvalbuf, and the file's blocks have
    153 	 * already been scheduled for writing, but the writes have not
    154 	 * yet completed, lfs_vflush will not be called, and vinvalbuf
    155 	 * will cause a panic.	So, we must wait until any pending write
    156 	 * for our inode completes, if we are called with UPDATE_WAIT set.
    157 	 */
    158 	s = splbio();
    159 	simple_lock(&vp->v_interlock);
    160 	while ((ap->a_flags & (UPDATE_WAIT|UPDATE_DIROP)) == UPDATE_WAIT &&
    161 	    WRITEINPROG(vp)) {
    162 		DLOG((DLOG_SEG, "lfs_update: sleeping on ino %d"
    163 		      " (in progress)\n", ip->i_number));
    164 		ltsleep(vp, (PRIBIO+1), "lfs_update", 0, &vp->v_interlock);
    165 	}
    166 	simple_unlock(&vp->v_interlock);
    167 	splx(s);
    168 	TIMEVAL_TO_TIMESPEC(&time, &ts);
    169 	LFS_ITIMES(ip,
    170 		   ap->a_access ? ap->a_access : &ts,
    171 		   ap->a_modify ? ap->a_modify : &ts, &ts);
    172 	if (ap->a_flags & UPDATE_CLOSE)
    173 		flags = ip->i_flag & (IN_MODIFIED | IN_ACCESSED | IN_CLEANING);
    174 	else
    175 		flags = ip->i_flag & (IN_MODIFIED | IN_CLEANING);
    176 	if (flags == 0)
    177 		return (0);
    178 
    179 	/* If sync, push back the vnode and any dirty blocks it may have. */
    180 	if ((ap->a_flags & (UPDATE_WAIT|UPDATE_DIROP)) == UPDATE_WAIT) {
    181 		/* Avoid flushing VDIROP. */
    182 		simple_lock(&fs->lfs_interlock);
    183 		++fs->lfs_diropwait;
    184 		while (vp->v_flag & VDIROP) {
    185 			DLOG((DLOG_DIROP, "lfs_update: sleeping on inode %d"
    186 			      " (dirops)\n", ip->i_number));
    187 			DLOG((DLOG_DIROP, "lfs_update: vflags 0x%x, iflags"
    188 			      " 0x%x\n", vp->v_flag, ip->i_flag));
    189 			if (fs->lfs_dirops == 0)
    190 				lfs_flush_fs(fs, SEGM_SYNC);
    191 			else
    192 				ltsleep(&fs->lfs_writer, PRIBIO+1, "lfs_fsync",
    193 					0, &fs->lfs_interlock);
    194 			/* XXX KS - by falling out here, are we writing the vn
    195 			twice? */
    196 		}
    197 		--fs->lfs_diropwait;
    198 		simple_unlock(&fs->lfs_interlock);
    199 		return lfs_vflush(vp);
    200 	}
    201 	return 0;
    202 }
    203 
    204 #define	SINGLE	0	/* index of single indirect block */
    205 #define	DOUBLE	1	/* index of double indirect block */
    206 #define	TRIPLE	2	/* index of triple indirect block */
    207 /*
    208  * Truncate the inode oip to at most length size, freeing the
    209  * disk blocks.
    210  */
    211 /* VOP_BWRITE 1 + NIADDR + VOP_BALLOC == 2 + 2*NIADDR times */
    212 
    213 int
    214 lfs_truncate(void *v)
    215 {
    216 	struct vop_truncate_args /* {
    217 		struct vnode *a_vp;
    218 		off_t a_length;
    219 		int a_flags;
    220 		struct ucred *a_cred;
    221 		struct proc *a_p;
    222 	} */ *ap = v;
    223 	struct vnode *ovp = ap->a_vp;
    224 	struct genfs_node *gp = VTOG(ovp);
    225 	daddr_t lastblock;
    226 	struct inode *oip = VTOI(ovp);
    227 	daddr_t bn, lbn, lastiblock[NIADDR], indir_lbn[NIADDR];
    228 	/* XXX ondisk32 */
    229 	int32_t newblks[NDADDR + NIADDR];
    230 	off_t length = ap->a_length;
    231 	struct lfs *fs;
    232 	struct buf *bp;
    233 	int offset, size, level;
    234 	long count, rcount, blocksreleased = 0, real_released = 0;
    235 	int i, ioflag, nblocks;
    236 	int aflags, error, allerror = 0;
    237 	off_t osize;
    238 	long lastseg;
    239 	size_t bc;
    240 	int obufsize, odb;
    241 	int usepc;
    242 	struct ufsmount *ump = oip->i_ump;
    243 
    244 	if (length < 0)
    245 		return (EINVAL);
    246 
    247 	/*
    248 	 * Just return and not update modification times.
    249 	 */
    250 	if (oip->i_size == length)
    251 		return (0);
    252 
    253 	if (ovp->v_type == VLNK &&
    254 	    (oip->i_size < ump->um_maxsymlinklen ||
    255 	     (ump->um_maxsymlinklen == 0 &&
    256 	      oip->i_ffs1_blocks == 0))) {
    257 #ifdef DIAGNOSTIC
    258 		if (length != 0)
    259 			panic("lfs_truncate: partial truncate of symlink");
    260 #endif
    261 		memset((char *)SHORTLINK(oip), 0, (u_int)oip->i_size);
    262 		oip->i_size = oip->i_ffs1_size = 0;
    263 		oip->i_flag |= IN_CHANGE | IN_UPDATE;
    264 		return (VOP_UPDATE(ovp, NULL, NULL, 0));
    265 	}
    266 	if (oip->i_size == length) {
    267 		oip->i_flag |= IN_CHANGE | IN_UPDATE;
    268 		return (VOP_UPDATE(ovp, NULL, NULL, 0));
    269 	}
    270 #ifdef QUOTA
    271 	if ((error = getinoquota(oip)) != 0)
    272 		return (error);
    273 #endif
    274 	fs = oip->i_lfs;
    275 	lfs_imtime(fs);
    276 	osize = oip->i_size;
    277 	ioflag = ap->a_flags;
    278 	usepc = (ovp->v_type == VREG && ovp != fs->lfs_ivnode);
    279 
    280 	ASSERT_NO_SEGLOCK(fs);
    281 	/*
    282 	 * Lengthen the size of the file. We must ensure that the
    283 	 * last byte of the file is allocated. Since the smallest
    284 	 * value of osize is 0, length will be at least 1.
    285 	 */
    286 	if (osize < length) {
    287 		if (length > ump->um_maxfilesize)
    288 			return (EFBIG);
    289 		aflags = B_CLRBUF;
    290 		if (ioflag & IO_SYNC)
    291 			aflags |= B_SYNC;
    292 		if (usepc) {
    293 			if (lblkno(fs, osize) < NDADDR &&
    294 			    lblkno(fs, osize) != lblkno(fs, length) &&
    295 			    blkroundup(fs, osize) != osize) {
    296 				off_t eob;
    297 
    298 				eob = blkroundup(fs, osize);
    299 				error = ufs_balloc_range(ovp, osize,
    300 				    eob - osize, ap->a_cred, aflags);
    301 				if (error)
    302 					return error;
    303 				if (ioflag & IO_SYNC) {
    304 					ovp->v_size = eob;
    305 					simple_lock(&ovp->v_interlock);
    306 					VOP_PUTPAGES(ovp,
    307 					    trunc_page(osize & fs->lfs_bmask),
    308 					    round_page(eob),
    309 					    PGO_CLEANIT | PGO_SYNCIO);
    310 				}
    311 			}
    312 			error = ufs_balloc_range(ovp, length - 1, 1, ap->a_cred,
    313 						 aflags);
    314 			if (error) {
    315 				(void) VOP_TRUNCATE(ovp, osize,
    316 						    ioflag & IO_SYNC,
    317 				    		    ap->a_cred, ap->a_p);
    318 				return error;
    319 			}
    320 			uvm_vnp_setsize(ovp, length);
    321 			oip->i_flag |= IN_CHANGE | IN_UPDATE;
    322 			KASSERT(ovp->v_size == oip->i_size);
    323 			oip->i_lfs_hiblk = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    324 			return (VOP_UPDATE(ovp, NULL, NULL, 0));
    325 		} else {
    326 			error = lfs_reserve(fs, ovp, NULL,
    327 			    btofsb(fs, (NIADDR + 2) << fs->lfs_bshift));
    328 			if (error)
    329 				return (error);
    330 			error = VOP_BALLOC(ovp, length - 1, 1, ap->a_cred,
    331 					   aflags, &bp);
    332 			lfs_reserve(fs, ovp, NULL,
    333 			    -btofsb(fs, (NIADDR + 2) << fs->lfs_bshift));
    334 			if (error)
    335 				return (error);
    336 			oip->i_ffs1_size = oip->i_size = length;
    337 			uvm_vnp_setsize(ovp, length);
    338 			(void) VOP_BWRITE(bp);
    339 			oip->i_flag |= IN_CHANGE | IN_UPDATE;
    340 			oip->i_lfs_hiblk = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    341 			return (VOP_UPDATE(ovp, NULL, NULL, 0));
    342 		}
    343 	}
    344 
    345 	if ((error = lfs_reserve(fs, ovp, NULL,
    346 	    btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift))) != 0)
    347 		return (error);
    348 
    349 	/*
    350 	 * Shorten the size of the file. If the file is not being
    351 	 * truncated to a block boundary, the contents of the
    352 	 * partial block following the end of the file must be
    353 	 * zero'ed in case it ever becomes accessible again because
    354 	 * of subsequent file growth. Directories however are not
    355 	 * zero'ed as they should grow back initialized to empty.
    356 	 */
    357 	offset = blkoff(fs, length);
    358 	lastseg = -1;
    359 	bc = 0;
    360 
    361 	if (ovp != fs->lfs_ivnode)
    362 		lfs_seglock(fs, SEGM_PROT);
    363 	if (offset == 0) {
    364 		oip->i_size = oip->i_ffs1_size = length;
    365 	} else if (!usepc) {
    366 		lbn = lblkno(fs, length);
    367 		aflags = B_CLRBUF;
    368 		if (ioflag & IO_SYNC)
    369 			aflags |= B_SYNC;
    370 		error = VOP_BALLOC(ovp, length - 1, 1, ap->a_cred, aflags, &bp);
    371 		if (error) {
    372 			lfs_reserve(fs, ovp, NULL,
    373 			    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    374 			goto errout;
    375 		}
    376 		obufsize = bp->b_bufsize;
    377 		odb = btofsb(fs, bp->b_bcount);
    378 		oip->i_size = oip->i_ffs1_size = length;
    379 		size = blksize(fs, oip, lbn);
    380 		if (ovp->v_type != VDIR)
    381 			memset((char *)bp->b_data + offset, 0,
    382 			       (u_int)(size - offset));
    383 		allocbuf(bp, size, 1);
    384 		if ((bp->b_flags & (B_LOCKED | B_CALL)) == B_LOCKED) {
    385 			simple_lock(&lfs_subsys_lock);
    386 			locked_queue_bytes -= obufsize - bp->b_bufsize;
    387 			simple_unlock(&lfs_subsys_lock);
    388 		}
    389 		if (bp->b_flags & B_DELWRI)
    390 			fs->lfs_avail += odb - btofsb(fs, size);
    391 		(void) VOP_BWRITE(bp);
    392 	} else { /* vp->v_type == VREG && length < osize && offset != 0 */
    393 		/*
    394 		 * When truncating a regular file down to a non-block-aligned
    395 		 * size, we must zero the part of last block which is past
    396 		 * the new EOF.  We must synchronously flush the zeroed pages
    397 		 * to disk since the new pages will be invalidated as soon
    398 		 * as we inform the VM system of the new, smaller size.
    399 		 * We must do this before acquiring the GLOCK, since fetching
    400 		 * the pages will acquire the GLOCK internally.
    401 		 * So there is a window where another thread could see a whole
    402 		 * zeroed page past EOF, but that's life.
    403 		 */
    404 		daddr_t xlbn;
    405 		voff_t eoz;
    406 
    407 		aflags = ioflag & IO_SYNC ? B_SYNC : 0;
    408 		error = ufs_balloc_range(ovp, length - 1, 1, ap->a_cred,
    409 		    aflags);
    410 		if (error) {
    411 			lfs_reserve(fs, ovp, NULL,
    412 				    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    413 			goto errout;
    414 		}
    415 		xlbn = lblkno(fs, length);
    416 		size = blksize(fs, oip, xlbn);
    417 		eoz = MIN(lblktosize(fs, xlbn) + size, osize);
    418 		uvm_vnp_zerorange(ovp, length, eoz - length);
    419 		if (round_page(eoz) > round_page(length)) {
    420 			simple_lock(&ovp->v_interlock);
    421 			error = VOP_PUTPAGES(ovp, round_page(length),
    422 			    round_page(eoz),
    423 			    PGO_CLEANIT | PGO_DEACTIVATE |
    424 			    ((ioflag & IO_SYNC) ? PGO_SYNCIO : 0));
    425 			if (error) {
    426 				lfs_reserve(fs, ovp, NULL,
    427 					    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    428 				goto errout;
    429 			}
    430 		}
    431 	}
    432 
    433 	lockmgr(&gp->g_glock, LK_EXCLUSIVE, NULL);
    434 
    435 	oip->i_size = oip->i_ffs1_size = length;
    436 	uvm_vnp_setsize(ovp, length);
    437 	/*
    438 	 * Calculate index into inode's block list of
    439 	 * last direct and indirect blocks (if any)
    440 	 * which we want to keep.  Lastblock is -1 when
    441 	 * the file is truncated to 0.
    442 	 */
    443 	/* Avoid sign overflow - XXX assumes that off_t is a quad_t. */
    444 	if (length > QUAD_MAX - fs->lfs_bsize)
    445 		lastblock = lblkno(fs, QUAD_MAX - fs->lfs_bsize);
    446 	else
    447 		lastblock = lblkno(fs, length + fs->lfs_bsize - 1) - 1;
    448 	lastiblock[SINGLE] = lastblock - NDADDR;
    449 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
    450 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
    451 	nblocks = btofsb(fs, fs->lfs_bsize);
    452 	/*
    453 	 * Record changed file and block pointers before we start
    454 	 * freeing blocks.  lastiblock values are also normalized to -1
    455 	 * for calls to lfs_indirtrunc below.
    456 	 */
    457 	memcpy((caddr_t)newblks, (caddr_t)&oip->i_ffs1_db[0], sizeof newblks);
    458 	for (level = TRIPLE; level >= SINGLE; level--)
    459 		if (lastiblock[level] < 0) {
    460 			newblks[NDADDR+level] = 0;
    461 			lastiblock[level] = -1;
    462 		}
    463 	for (i = NDADDR - 1; i > lastblock; i--)
    464 		newblks[i] = 0;
    465 
    466 	oip->i_size = oip->i_ffs1_size = osize;
    467 	error = lfs_vtruncbuf(ovp, lastblock + 1, 0, 0);
    468 	if (error && !allerror)
    469 		allerror = error;
    470 
    471 	/*
    472 	 * Indirect blocks first.
    473 	 */
    474 	indir_lbn[SINGLE] = -NDADDR;
    475 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
    476 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
    477 	for (level = TRIPLE; level >= SINGLE; level--) {
    478 		bn = oip->i_ffs1_ib[level];
    479 		if (bn != 0) {
    480 			error = lfs_indirtrunc(oip, indir_lbn[level],
    481 					       bn, lastiblock[level],
    482 					       level, &count, &rcount,
    483 					       &lastseg, &bc, ap->a_p);
    484 			if (error)
    485 				allerror = error;
    486 			real_released += rcount;
    487 			blocksreleased += count;
    488 			if (lastiblock[level] < 0) {
    489 				if (oip->i_ffs1_ib[level] > 0)
    490 					real_released += nblocks;
    491 				blocksreleased += nblocks;
    492 				oip->i_ffs1_ib[level] = 0;
    493 				lfs_blkfree(fs, bn, fs->lfs_bsize, &lastseg, &bc);
    494         			lfs_deregister_block(ovp, bn);
    495 			}
    496 		}
    497 		if (lastiblock[level] >= 0)
    498 			goto done;
    499 	}
    500 
    501 	/*
    502 	 * All whole direct blocks or frags.
    503 	 */
    504 	for (i = NDADDR - 1; i > lastblock; i--) {
    505 		long bsize, obsize;
    506 
    507 		bn = oip->i_ffs1_db[i];
    508 		if (bn == 0)
    509 			continue;
    510 		bsize = blksize(fs, oip, i);
    511 		if (oip->i_ffs1_db[i] > 0) {
    512 			/* Check for fragment size changes */
    513 			obsize = oip->i_lfs_fragsize[i];
    514 			real_released += btofsb(fs, obsize);
    515 			oip->i_lfs_fragsize[i] = 0;
    516 		} else
    517 			obsize = 0;
    518 		blocksreleased += btofsb(fs, bsize);
    519 		oip->i_ffs1_db[i] = 0;
    520 		lfs_blkfree(fs, bn, obsize, &lastseg, &bc);
    521         	lfs_deregister_block(ovp, bn);
    522 	}
    523 	if (lastblock < 0)
    524 		goto done;
    525 
    526 	/*
    527 	 * Finally, look for a change in size of the
    528 	 * last direct block; release any frags.
    529 	 */
    530 	bn = oip->i_ffs1_db[lastblock];
    531 	if (bn != 0) {
    532 		long oldspace, newspace;
    533 #if 0
    534 		long olddspace;
    535 #endif
    536 
    537 		/*
    538 		 * Calculate amount of space we're giving
    539 		 * back as old block size minus new block size.
    540 		 */
    541 		oldspace = blksize(fs, oip, lastblock);
    542 #if 0
    543 		olddspace = oip->i_lfs_fragsize[lastblock];
    544 #endif
    545 
    546 		oip->i_size = oip->i_ffs1_size = length;
    547 		newspace = blksize(fs, oip, lastblock);
    548 		if (newspace == 0)
    549 			panic("itrunc: newspace");
    550 		if (oldspace - newspace > 0) {
    551 			blocksreleased += btofsb(fs, oldspace - newspace);
    552 		}
    553 #if 0
    554 		if (bn > 0 && olddspace - newspace > 0) {
    555 			/* No segment accounting here, just vnode */
    556 			real_released += btofsb(fs, olddspace - newspace);
    557 		}
    558 #endif
    559 	}
    560 
    561 done:
    562 	/* Finish segment accounting corrections */
    563 	lfs_update_seguse(fs, lastseg, bc);
    564 #ifdef DIAGNOSTIC
    565 	for (level = SINGLE; level <= TRIPLE; level++)
    566 		if ((newblks[NDADDR + level] == 0) !=
    567 		    (oip->i_ffs1_ib[level]) == 0) {
    568 			panic("lfs itrunc1");
    569 		}
    570 	for (i = 0; i < NDADDR; i++)
    571 		if ((newblks[i] == 0) != (oip->i_ffs1_db[i] == 0)) {
    572 			panic("lfs itrunc2");
    573 		}
    574 	if (length == 0 &&
    575 	    (!LIST_EMPTY(&ovp->v_cleanblkhd) || !LIST_EMPTY(&ovp->v_dirtyblkhd)))
    576 		panic("lfs itrunc3");
    577 #endif /* DIAGNOSTIC */
    578 	/*
    579 	 * Put back the real size.
    580 	 */
    581 	oip->i_size = oip->i_ffs1_size = length;
    582 	oip->i_lfs_effnblks -= blocksreleased;
    583 	oip->i_ffs1_blocks -= real_released;
    584 	simple_lock(&fs->lfs_interlock);
    585 	fs->lfs_bfree += blocksreleased;
    586 	simple_unlock(&fs->lfs_interlock);
    587 #ifdef DIAGNOSTIC
    588 	if (oip->i_size == 0 &&
    589 	    (oip->i_ffs1_blocks != 0 || oip->i_lfs_effnblks != 0)) {
    590 		printf("lfs_truncate: truncate to 0 but %d blks/%d effblks\n",
    591 		       oip->i_ffs1_blocks, oip->i_lfs_effnblks);
    592 		panic("lfs_truncate: persistent blocks");
    593 	}
    594 #endif
    595 
    596 	/*
    597 	 * If we truncated to zero, take us off the paging queue.
    598 	 */
    599 	simple_lock(&fs->lfs_interlock);
    600 	if (oip->i_size == 0 && oip->i_flags & IN_PAGING) {
    601 		oip->i_flags &= ~IN_PAGING;
    602 		TAILQ_REMOVE(&fs->lfs_pchainhd, oip, i_lfs_pchain);
    603 	}
    604 	simple_unlock(&fs->lfs_interlock);
    605 
    606 	oip->i_flag |= IN_CHANGE;
    607 #ifdef QUOTA
    608 	(void) chkdq(oip, -blocksreleased, NOCRED, 0);
    609 #endif
    610 	lfs_reserve(fs, ovp, NULL,
    611 	    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    612 	lockmgr(&gp->g_glock, LK_RELEASE, NULL);
    613   errout:
    614 	oip->i_lfs_hiblk = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    615 	if (ovp != fs->lfs_ivnode)
    616 		lfs_segunlock(fs);
    617 	return (allerror ? allerror : error);
    618 }
    619 
    620 /* Update segment and avail usage information when removing a block. */
    621 static int
    622 lfs_blkfree(struct lfs *fs, daddr_t daddr, size_t bsize, long *lastseg,
    623 	    size_t *num)
    624 {
    625 	long seg;
    626 	int error = 0;
    627 
    628 	ASSERT_SEGLOCK(fs);
    629 	bsize = fragroundup(fs, bsize);
    630 	if (daddr > 0) {
    631 		if (*lastseg != (seg = dtosn(fs, daddr))) {
    632 			error = lfs_update_seguse(fs, *lastseg, *num);
    633 			*num = bsize;
    634 			*lastseg = seg;
    635 		} else
    636 			*num += bsize;
    637 	}
    638 
    639 	return error;
    640 }
    641 
    642 /* Finish the accounting updates for a segment. */
    643 static int
    644 lfs_update_seguse(struct lfs *fs, long lastseg, size_t num)
    645 {
    646 	SEGUSE *sup;
    647 	struct buf *bp;
    648 
    649 	ASSERT_SEGLOCK(fs);
    650 	if (lastseg < 0 || num == 0)
    651 		return 0;
    652 
    653 	LFS_SEGENTRY(sup, fs, lastseg, bp);
    654 	if (num > sup->su_nbytes) {
    655 		printf("lfs_truncate: segment %ld short by %ld\n",
    656 		       lastseg, (long)num - sup->su_nbytes);
    657 		panic("lfs_truncate: negative bytes");
    658 		sup->su_nbytes = num;
    659 	}
    660 	sup->su_nbytes -= num;
    661 	LFS_WRITESEGENTRY(sup, fs, lastseg, bp);
    662 
    663 	return 0;
    664 }
    665 
    666 /*
    667  * Release blocks associated with the inode ip and stored in the indirect
    668  * block bn.  Blocks are free'd in LIFO order up to (but not including)
    669  * lastbn.  If level is greater than SINGLE, the block is an indirect block
    670  * and recursive calls to indirtrunc must be used to cleanse other indirect
    671  * blocks.
    672  *
    673  * NB: triple indirect blocks are untested.
    674  */
    675 static int
    676 lfs_indirtrunc(struct inode *ip, daddr_t lbn, daddr_t dbn,
    677 	       daddr_t lastbn, int level, long *countp,
    678 	       long *rcountp, long *lastsegp, size_t *bcp, struct proc *p)
    679 {
    680 	int i;
    681 	struct buf *bp;
    682 	struct lfs *fs = ip->i_lfs;
    683 	int32_t *bap;	/* XXX ondisk32 */
    684 	struct vnode *vp;
    685 	daddr_t nb, nlbn, last;
    686 	int32_t *copy = NULL;	/* XXX ondisk32 */
    687 	long blkcount, rblkcount, factor;
    688 	int nblocks, blocksreleased = 0, real_released = 0;
    689 	int error = 0, allerror = 0;
    690 
    691 	ASSERT_SEGLOCK(fs);
    692 	/*
    693 	 * Calculate index in current block of last
    694 	 * block to be kept.  -1 indicates the entire
    695 	 * block so we need not calculate the index.
    696 	 */
    697 	factor = 1;
    698 	for (i = SINGLE; i < level; i++)
    699 		factor *= NINDIR(fs);
    700 	last = lastbn;
    701 	if (lastbn > 0)
    702 		last /= factor;
    703 	nblocks = btofsb(fs, fs->lfs_bsize);
    704 	/*
    705 	 * Get buffer of block pointers, zero those entries corresponding
    706 	 * to blocks to be free'd, and update on disk copy first.  Since
    707 	 * double(triple) indirect before single(double) indirect, calls
    708 	 * to bmap on these blocks will fail.  However, we already have
    709 	 * the on disk address, so we have to set the b_blkno field
    710 	 * explicitly instead of letting bread do everything for us.
    711 	 */
    712 	vp = ITOV(ip);
    713 	bp = getblk(vp, lbn, (int)fs->lfs_bsize, 0, 0);
    714 	if (bp->b_flags & (B_DONE | B_DELWRI)) {
    715 		/* Braces must be here in case trace evaluates to nothing. */
    716 		trace(TR_BREADHIT, pack(vp, fs->lfs_bsize), lbn);
    717 	} else {
    718 		trace(TR_BREADMISS, pack(vp, fs->lfs_bsize), lbn);
    719 		p->p_stats->p_ru.ru_inblock++;	/* pay for read */
    720 		bp->b_flags |= B_READ;
    721 		if (bp->b_bcount > bp->b_bufsize)
    722 			panic("lfs_indirtrunc: bad buffer size");
    723 		bp->b_blkno = fsbtodb(fs, dbn);
    724 		VOP_STRATEGY(vp, bp);
    725 		error = biowait(bp);
    726 	}
    727 	if (error) {
    728 		brelse(bp);
    729 		*countp = *rcountp = 0;
    730 		return (error);
    731 	}
    732 
    733 	bap = (int32_t *)bp->b_data;	/* XXX ondisk32 */
    734 	if (lastbn >= 0) {
    735 		copy = (int32_t *)lfs_malloc(fs, fs->lfs_bsize, LFS_NB_IBLOCK);
    736 		memcpy((caddr_t)copy, (caddr_t)bap, (u_int)fs->lfs_bsize);
    737 		memset((caddr_t)&bap[last + 1], 0,
    738 		/* XXX ondisk32 */
    739 		  (u_int)(NINDIR(fs) - (last + 1)) * sizeof (int32_t));
    740 		error = VOP_BWRITE(bp);
    741 		if (error)
    742 			allerror = error;
    743 		bap = copy;
    744 	}
    745 
    746 	/*
    747 	 * Recursively free totally unused blocks.
    748 	 */
    749 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
    750 	    i--, nlbn += factor) {
    751 		nb = bap[i];
    752 		if (nb == 0)
    753 			continue;
    754 		if (level > SINGLE) {
    755 			error = lfs_indirtrunc(ip, nlbn, nb,
    756 					       (daddr_t)-1, level - 1,
    757 					       &blkcount, &rblkcount,
    758 					       lastsegp, bcp, p);
    759 			if (error)
    760 				allerror = error;
    761 			blocksreleased += blkcount;
    762 			real_released += rblkcount;
    763 		}
    764 		lfs_blkfree(fs, nb, fs->lfs_bsize, lastsegp, bcp);
    765 		if (bap[i] > 0)
    766 			real_released += nblocks;
    767 		blocksreleased += nblocks;
    768 	}
    769 
    770 	/*
    771 	 * Recursively free last partial block.
    772 	 */
    773 	if (level > SINGLE && lastbn >= 0) {
    774 		last = lastbn % factor;
    775 		nb = bap[i];
    776 		if (nb != 0) {
    777 			error = lfs_indirtrunc(ip, nlbn, nb,
    778 					       last, level - 1, &blkcount,
    779 					       &rblkcount, lastsegp, bcp, p);
    780 			if (error)
    781 				allerror = error;
    782 			real_released += rblkcount;
    783 			blocksreleased += blkcount;
    784 		}
    785 	}
    786 
    787 	if (copy != NULL) {
    788 		lfs_free(fs, copy, LFS_NB_IBLOCK);
    789 	} else {
    790 		if (bp->b_flags & B_DELWRI) {
    791 			LFS_UNLOCK_BUF(bp);
    792 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    793 			wakeup(&fs->lfs_avail);
    794 		}
    795 		bp->b_flags |= B_INVAL;
    796 		brelse(bp);
    797 	}
    798 
    799 	*countp = blocksreleased;
    800 	*rcountp = real_released;
    801 	return (allerror);
    802 }
    803 
    804 /*
    805  * Destroy any in core blocks past the truncation length.
    806  * Inlined from vtruncbuf, so that lfs_avail could be updated.
    807  * We take the seglock to prevent cleaning from occurring while we are
    808  * invalidating blocks.
    809  */
    810 static int
    811 lfs_vtruncbuf(struct vnode *vp, daddr_t lbn, int slpflag, int slptimeo)
    812 {
    813 	struct buf *bp, *nbp;
    814 	int s, error;
    815 	struct lfs *fs;
    816 	voff_t off;
    817 
    818 	off = round_page((voff_t)lbn << vp->v_mount->mnt_fs_bshift);
    819 	simple_lock(&vp->v_interlock);
    820 	error = VOP_PUTPAGES(vp, off, 0, PGO_FREE | PGO_SYNCIO);
    821 	if (error)
    822 		return error;
    823 
    824 	fs = VTOI(vp)->i_lfs;
    825 	s = splbio();
    826 
    827 	ASSERT_SEGLOCK(fs);
    828 restart:
    829 	for (bp = LIST_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
    830 		nbp = LIST_NEXT(bp, b_vnbufs);
    831 		if (bp->b_lblkno < lbn)
    832 			continue;
    833 		simple_lock(&bp->b_interlock);
    834 		if (bp->b_flags & B_BUSY) {
    835 			bp->b_flags |= B_WANTED;
    836 			error = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    837 			    "lfs_vtruncbuf", slptimeo, &bp->b_interlock);
    838 			if (error) {
    839 				splx(s);
    840 				return (error);
    841 			}
    842 			goto restart;
    843 		}
    844 		bp->b_flags |= B_BUSY | B_INVAL | B_VFLUSH;
    845 		if (bp->b_flags & B_DELWRI) {
    846 			bp->b_flags &= ~B_DELWRI;
    847 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    848 			wakeup(&fs->lfs_avail);
    849 		}
    850 		LFS_UNLOCK_BUF(bp);
    851 		simple_unlock(&bp->b_interlock);
    852 		brelse(bp);
    853 	}
    854 
    855 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    856 		nbp = LIST_NEXT(bp, b_vnbufs);
    857 		if (bp->b_lblkno < lbn)
    858 			continue;
    859 		simple_lock(&bp->b_interlock);
    860 		if (bp->b_flags & B_BUSY) {
    861 			bp->b_flags |= B_WANTED;
    862 			error = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    863 			    "lfs_vtruncbuf", slptimeo, &bp->b_interlock);
    864 			if (error) {
    865 				splx(s);
    866 				return (error);
    867 			}
    868 			goto restart;
    869 		}
    870 		bp->b_flags |= B_BUSY | B_INVAL | B_VFLUSH;
    871 		if (bp->b_flags & B_DELWRI) {
    872 			bp->b_flags &= ~B_DELWRI;
    873 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    874 			wakeup(&fs->lfs_avail);
    875 		}
    876 		LFS_UNLOCK_BUF(bp);
    877 		simple_unlock(&bp->b_interlock);
    878 		brelse(bp);
    879 	}
    880 
    881 	splx(s);
    882 
    883 	return (0);
    884 }
    885 
    886