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