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