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