Home | History | Annotate | Line # | Download | only in lfs
lfs_inode.c revision 1.109
      1 /*	$NetBSD: lfs_inode.c,v 1.109 2007/05/16 19:11:37 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.109 2007/05/16 19:11:37 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/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, int, 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 	simple_lock(&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 		ltsleep(vp, (PRIBIO+1), "lfs_update", 0, &vp->v_interlock);
    160 	}
    161 	simple_unlock(&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 		simple_lock(&fs->lfs_interlock);
    175 		++fs->lfs_diropwait;
    176 		while (vp->v_flag & VDIROP) {
    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", vp->v_flag, ip->i_flag));
    181 			if (fs->lfs_dirops == 0)
    182 				lfs_flush_fs(fs, SEGM_SYNC);
    183 			else
    184 				ltsleep(&fs->lfs_writer, PRIBIO+1, "lfs_fsync",
    185 					0, &fs->lfs_interlock);
    186 			/* XXX KS - by falling out here, are we writing the vn
    187 			twice? */
    188 		}
    189 		--fs->lfs_diropwait;
    190 		simple_unlock(&fs->lfs_interlock);
    191 		return lfs_vflush(vp);
    192 	}
    193 	return 0;
    194 }
    195 
    196 #define	SINGLE	0	/* index of single indirect block */
    197 #define	DOUBLE	1	/* index of double indirect block */
    198 #define	TRIPLE	2	/* index of triple indirect block */
    199 /*
    200  * Truncate the inode oip to at most length size, freeing the
    201  * disk blocks.
    202  */
    203 /* VOP_BWRITE 1 + NIADDR + lfs_balloc == 2 + 2*NIADDR times */
    204 
    205 int
    206 lfs_truncate(struct vnode *ovp, off_t length, int ioflag,
    207     kauth_cred_t cred, struct lwp *l)
    208 {
    209 	daddr_t lastblock;
    210 	struct inode *oip = VTOI(ovp);
    211 	daddr_t bn, lbn, lastiblock[NIADDR], indir_lbn[NIADDR];
    212 	/* XXX ondisk32 */
    213 	int32_t newblks[NDADDR + NIADDR];
    214 	struct lfs *fs;
    215 	struct buf *bp;
    216 	int offset, size, level;
    217 	long count, rcount, blocksreleased = 0, real_released = 0;
    218 	int i, nblocks;
    219 	int aflags, error, allerror = 0;
    220 	off_t osize;
    221 	long lastseg;
    222 	size_t bc;
    223 	int obufsize, odb;
    224 	int usepc;
    225 	struct ufsmount *ump = oip->i_ump;
    226 
    227 	if (ovp->v_type == VCHR || ovp->v_type == VBLK ||
    228 	    ovp->v_type == VFIFO || ovp->v_type == VSOCK) {
    229 		KASSERT(oip->i_size == 0);
    230 		return 0;
    231 	}
    232 
    233 	if (length < 0)
    234 		return (EINVAL);
    235 
    236 	/*
    237 	 * Just return and not update modification times.
    238 	 */
    239 	if (oip->i_size == length)
    240 		return (0);
    241 
    242 	if (ovp->v_type == VLNK &&
    243 	    (oip->i_size < ump->um_maxsymlinklen ||
    244 	     (ump->um_maxsymlinklen == 0 &&
    245 	      oip->i_ffs1_blocks == 0))) {
    246 #ifdef DIAGNOSTIC
    247 		if (length != 0)
    248 			panic("lfs_truncate: partial truncate of symlink");
    249 #endif
    250 		memset((char *)SHORTLINK(oip), 0, (u_int)oip->i_size);
    251 		oip->i_size = oip->i_ffs1_size = 0;
    252 		oip->i_flag |= IN_CHANGE | IN_UPDATE;
    253 		return (lfs_update(ovp, NULL, NULL, 0));
    254 	}
    255 	if (oip->i_size == length) {
    256 		oip->i_flag |= IN_CHANGE | IN_UPDATE;
    257 		return (lfs_update(ovp, NULL, NULL, 0));
    258 	}
    259 #ifdef QUOTA
    260 	if ((error = getinoquota(oip)) != 0)
    261 		return (error);
    262 #endif
    263 	fs = oip->i_lfs;
    264 	lfs_imtime(fs);
    265 	osize = oip->i_size;
    266 	usepc = (ovp->v_type == VREG && ovp != fs->lfs_ivnode);
    267 
    268 	ASSERT_NO_SEGLOCK(fs);
    269 	/*
    270 	 * Lengthen the size of the file. We must ensure that the
    271 	 * last byte of the file is allocated. Since the smallest
    272 	 * value of osize is 0, length will be at least 1.
    273 	 */
    274 	if (osize < length) {
    275 		if (length > ump->um_maxfilesize)
    276 			return (EFBIG);
    277 		aflags = B_CLRBUF;
    278 		if (ioflag & IO_SYNC)
    279 			aflags |= B_SYNC;
    280 		if (usepc) {
    281 			if (lblkno(fs, osize) < NDADDR &&
    282 			    lblkno(fs, osize) != lblkno(fs, length) &&
    283 			    blkroundup(fs, osize) != osize) {
    284 				off_t eob;
    285 
    286 				eob = blkroundup(fs, osize);
    287 				error = ufs_balloc_range(ovp, osize,
    288 				    eob - osize, cred, aflags);
    289 				if (error)
    290 					return error;
    291 				if (ioflag & IO_SYNC) {
    292 					ovp->v_size = eob;
    293 					simple_lock(&ovp->v_interlock);
    294 					VOP_PUTPAGES(ovp,
    295 					    trunc_page(osize & fs->lfs_bmask),
    296 					    round_page(eob),
    297 					    PGO_CLEANIT | PGO_SYNCIO);
    298 				}
    299 			}
    300 			error = ufs_balloc_range(ovp, length - 1, 1, cred,
    301 						 aflags);
    302 			if (error) {
    303 				(void) lfs_truncate(ovp, osize,
    304 						    ioflag & IO_SYNC, cred, l);
    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 = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    311 			return (lfs_update(ovp, NULL, NULL, 0));
    312 		} else {
    313 			error = lfs_reserve(fs, ovp, NULL,
    314 			    btofsb(fs, (NIADDR + 2) << fs->lfs_bshift));
    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 			    -btofsb(fs, (NIADDR + 2) << fs->lfs_bshift));
    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);
    326 			oip->i_flag |= IN_CHANGE | IN_UPDATE;
    327 			oip->i_lfs_hiblk = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    328 			return (lfs_update(ovp, NULL, NULL, 0));
    329 		}
    330 	}
    331 
    332 	if ((error = lfs_reserve(fs, ovp, NULL,
    333 	    btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift))) != 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 = 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 = 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 			    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    361 			goto errout;
    362 		}
    363 		obufsize = bp->b_bufsize;
    364 		odb = btofsb(fs, bp->b_bcount);
    365 		oip->i_size = oip->i_ffs1_size = length;
    366 		size = 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 | B_CALL)) == B_LOCKED) {
    372 			simple_lock(&lfs_subsys_lock);
    373 			locked_queue_bytes -= obufsize - bp->b_bufsize;
    374 			simple_unlock(&lfs_subsys_lock);
    375 		}
    376 		if (bp->b_flags & B_DELWRI)
    377 			fs->lfs_avail += odb - btofsb(fs, size);
    378 		(void) VOP_BWRITE(bp);
    379 	} else { /* vp->v_type == VREG && length < osize && offset != 0 */
    380 		/*
    381 		 * When truncating a regular file down to a non-block-aligned
    382 		 * size, we must zero the part of last block which is past
    383 		 * the new EOF.  We must synchronously flush the zeroed pages
    384 		 * to disk since the new pages will be invalidated as soon
    385 		 * as we inform the VM system of the new, smaller size.
    386 		 * We must do this before acquiring the GLOCK, since fetching
    387 		 * the pages will acquire the GLOCK internally.
    388 		 * So there is a window where another thread could see a whole
    389 		 * zeroed page past EOF, but that's life.
    390 		 */
    391 		daddr_t xlbn;
    392 		voff_t eoz;
    393 
    394 		aflags = ioflag & IO_SYNC ? B_SYNC : 0;
    395 		error = ufs_balloc_range(ovp, length - 1, 1, cred, aflags);
    396 		if (error) {
    397 			lfs_reserve(fs, ovp, NULL,
    398 				    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    399 			goto errout;
    400 		}
    401 		xlbn = lblkno(fs, length);
    402 		size = blksize(fs, oip, xlbn);
    403 		eoz = MIN(lblktosize(fs, xlbn) + size, osize);
    404 		uvm_vnp_zerorange(ovp, length, eoz - length);
    405 		if (round_page(eoz) > round_page(length)) {
    406 			simple_lock(&ovp->v_interlock);
    407 			error = VOP_PUTPAGES(ovp, round_page(length),
    408 			    round_page(eoz),
    409 			    PGO_CLEANIT | PGO_DEACTIVATE |
    410 			    ((ioflag & IO_SYNC) ? PGO_SYNCIO : 0));
    411 			if (error) {
    412 				lfs_reserve(fs, ovp, NULL,
    413 					    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    414 				goto errout;
    415 			}
    416 		}
    417 	}
    418 
    419 	genfs_node_wrlock(ovp);
    420 
    421 	oip->i_size = oip->i_ffs1_size = length;
    422 	uvm_vnp_setsize(ovp, length);
    423 	/*
    424 	 * Calculate index into inode's block list of
    425 	 * last direct and indirect blocks (if any)
    426 	 * which we want to keep.  Lastblock is -1 when
    427 	 * the file is truncated to 0.
    428 	 */
    429 	/* Avoid sign overflow - XXX assumes that off_t is a quad_t. */
    430 	if (length > QUAD_MAX - fs->lfs_bsize)
    431 		lastblock = lblkno(fs, QUAD_MAX - fs->lfs_bsize);
    432 	else
    433 		lastblock = lblkno(fs, length + fs->lfs_bsize - 1) - 1;
    434 	lastiblock[SINGLE] = lastblock - NDADDR;
    435 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
    436 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
    437 	nblocks = btofsb(fs, fs->lfs_bsize);
    438 	/*
    439 	 * Record changed file and block pointers before we start
    440 	 * freeing blocks.  lastiblock values are also normalized to -1
    441 	 * for calls to lfs_indirtrunc below.
    442 	 */
    443 	memcpy((void *)newblks, (void *)&oip->i_ffs1_db[0], sizeof newblks);
    444 	for (level = TRIPLE; level >= SINGLE; level--)
    445 		if (lastiblock[level] < 0) {
    446 			newblks[NDADDR+level] = 0;
    447 			lastiblock[level] = -1;
    448 		}
    449 	for (i = NDADDR - 1; i > lastblock; i--)
    450 		newblks[i] = 0;
    451 
    452 	oip->i_size = oip->i_ffs1_size = osize;
    453 	error = lfs_vtruncbuf(ovp, lastblock + 1, 0, 0);
    454 	if (error && !allerror)
    455 		allerror = error;
    456 
    457 	/*
    458 	 * Indirect blocks first.
    459 	 */
    460 	indir_lbn[SINGLE] = -NDADDR;
    461 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
    462 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
    463 	for (level = TRIPLE; level >= SINGLE; level--) {
    464 		bn = oip->i_ffs1_ib[level];
    465 		if (bn != 0) {
    466 			error = lfs_indirtrunc(oip, indir_lbn[level],
    467 					       bn, lastiblock[level],
    468 					       level, &count, &rcount,
    469 					       &lastseg, &bc, l);
    470 			if (error)
    471 				allerror = error;
    472 			real_released += rcount;
    473 			blocksreleased += count;
    474 			if (lastiblock[level] < 0) {
    475 				if (oip->i_ffs1_ib[level] > 0)
    476 					real_released += nblocks;
    477 				blocksreleased += nblocks;
    478 				oip->i_ffs1_ib[level] = 0;
    479 				lfs_blkfree(fs, oip, bn, fs->lfs_bsize,
    480 					    &lastseg, &bc);
    481         			lfs_deregister_block(ovp, bn);
    482 			}
    483 		}
    484 		if (lastiblock[level] >= 0)
    485 			goto done;
    486 	}
    487 
    488 	/*
    489 	 * All whole direct blocks or frags.
    490 	 */
    491 	for (i = NDADDR - 1; i > lastblock; i--) {
    492 		long bsize, obsize;
    493 
    494 		bn = oip->i_ffs1_db[i];
    495 		if (bn == 0)
    496 			continue;
    497 		bsize = blksize(fs, oip, i);
    498 		if (oip->i_ffs1_db[i] > 0) {
    499 			/* Check for fragment size changes */
    500 			obsize = oip->i_lfs_fragsize[i];
    501 			real_released += btofsb(fs, obsize);
    502 			oip->i_lfs_fragsize[i] = 0;
    503 		} else
    504 			obsize = 0;
    505 		blocksreleased += btofsb(fs, bsize);
    506 		oip->i_ffs1_db[i] = 0;
    507 		lfs_blkfree(fs, oip, bn, obsize, &lastseg, &bc);
    508         	lfs_deregister_block(ovp, bn);
    509 	}
    510 	if (lastblock < 0)
    511 		goto done;
    512 
    513 	/*
    514 	 * Finally, look for a change in size of the
    515 	 * last direct block; release any frags.
    516 	 */
    517 	bn = oip->i_ffs1_db[lastblock];
    518 	if (bn != 0) {
    519 		long oldspace, newspace;
    520 #if 0
    521 		long olddspace;
    522 #endif
    523 
    524 		/*
    525 		 * Calculate amount of space we're giving
    526 		 * back as old block size minus new block size.
    527 		 */
    528 		oldspace = blksize(fs, oip, lastblock);
    529 #if 0
    530 		olddspace = oip->i_lfs_fragsize[lastblock];
    531 #endif
    532 
    533 		oip->i_size = oip->i_ffs1_size = length;
    534 		newspace = blksize(fs, oip, lastblock);
    535 		if (newspace == 0)
    536 			panic("itrunc: newspace");
    537 		if (oldspace - newspace > 0) {
    538 			blocksreleased += btofsb(fs, oldspace - newspace);
    539 		}
    540 #if 0
    541 		if (bn > 0 && olddspace - newspace > 0) {
    542 			/* No segment accounting here, just vnode */
    543 			real_released += btofsb(fs, olddspace - newspace);
    544 		}
    545 #endif
    546 	}
    547 
    548 done:
    549 	/* Finish segment accounting corrections */
    550 	lfs_update_seguse(fs, oip, lastseg, bc);
    551 #ifdef DIAGNOSTIC
    552 	for (level = SINGLE; level <= TRIPLE; level++)
    553 		if ((newblks[NDADDR + level] == 0) !=
    554 		    ((oip->i_ffs1_ib[level]) == 0)) {
    555 			panic("lfs itrunc1");
    556 		}
    557 	for (i = 0; i < NDADDR; i++)
    558 		if ((newblks[i] == 0) != (oip->i_ffs1_db[i] == 0)) {
    559 			panic("lfs itrunc2");
    560 		}
    561 	if (length == 0 &&
    562 	    (!LIST_EMPTY(&ovp->v_cleanblkhd) || !LIST_EMPTY(&ovp->v_dirtyblkhd)))
    563 		panic("lfs itrunc3");
    564 #endif /* DIAGNOSTIC */
    565 	/*
    566 	 * Put back the real size.
    567 	 */
    568 	oip->i_size = oip->i_ffs1_size = length;
    569 	oip->i_lfs_effnblks -= blocksreleased;
    570 	oip->i_ffs1_blocks -= real_released;
    571 	simple_lock(&fs->lfs_interlock);
    572 	fs->lfs_bfree += blocksreleased;
    573 	simple_unlock(&fs->lfs_interlock);
    574 #ifdef DIAGNOSTIC
    575 	if (oip->i_size == 0 &&
    576 	    (oip->i_ffs1_blocks != 0 || oip->i_lfs_effnblks != 0)) {
    577 		printf("lfs_truncate: truncate to 0 but %d blks/%d effblks\n",
    578 		       oip->i_ffs1_blocks, oip->i_lfs_effnblks);
    579 		panic("lfs_truncate: persistent blocks");
    580 	}
    581 #endif
    582 
    583 	/*
    584 	 * If we truncated to zero, take us off the paging queue.
    585 	 */
    586 	simple_lock(&fs->lfs_interlock);
    587 	if (oip->i_size == 0 && oip->i_flags & IN_PAGING) {
    588 		oip->i_flags &= ~IN_PAGING;
    589 		TAILQ_REMOVE(&fs->lfs_pchainhd, oip, i_lfs_pchain);
    590 	}
    591 	simple_unlock(&fs->lfs_interlock);
    592 
    593 	oip->i_flag |= IN_CHANGE;
    594 #ifdef QUOTA
    595 	(void) chkdq(oip, -blocksreleased, NOCRED, 0);
    596 #endif
    597 	lfs_reserve(fs, ovp, NULL,
    598 	    -btofsb(fs, (2 * NIADDR + 3) << fs->lfs_bshift));
    599 	genfs_node_unlock(ovp);
    600   errout:
    601 	oip->i_lfs_hiblk = lblkno(fs, oip->i_size + fs->lfs_bsize - 1) - 1;
    602 	if (ovp != fs->lfs_ivnode)
    603 		lfs_segunlock(fs);
    604 	return (allerror ? allerror : error);
    605 }
    606 
    607 /* Update segment and avail usage information when removing a block. */
    608 static int
    609 lfs_blkfree(struct lfs *fs, struct inode *ip, daddr_t daddr,
    610 	    size_t bsize, long *lastseg, size_t *num)
    611 {
    612 	long seg;
    613 	int error = 0;
    614 
    615 	ASSERT_SEGLOCK(fs);
    616 	bsize = fragroundup(fs, bsize);
    617 	if (daddr > 0) {
    618 		if (*lastseg != (seg = dtosn(fs, daddr))) {
    619 			error = lfs_update_seguse(fs, ip, *lastseg, *num);
    620 			*num = bsize;
    621 			*lastseg = seg;
    622 		} else
    623 			*num += bsize;
    624 	}
    625 
    626 	return error;
    627 }
    628 
    629 /* Finish the accounting updates for a segment. */
    630 static int
    631 lfs_update_seguse(struct lfs *fs, struct inode *ip, long lastseg, size_t num)
    632 {
    633 	struct segdelta *sd;
    634 	struct vnode *vp;
    635 
    636 	ASSERT_SEGLOCK(fs);
    637 	if (lastseg < 0 || num == 0)
    638 		return 0;
    639 
    640 	vp = ITOV(ip);
    641 	LIST_FOREACH(sd, &ip->i_lfs_segdhd, list)
    642 		if (sd->segnum == lastseg)
    643 			break;
    644 	if (sd == NULL) {
    645 		sd = malloc(sizeof(*sd), M_SEGMENT, M_WAITOK);
    646 		sd->segnum = lastseg;
    647 		sd->num = 0;
    648 		LIST_INSERT_HEAD(&ip->i_lfs_segdhd, sd, list);
    649 	}
    650 	sd->num += num;
    651 
    652 	return 0;
    653 }
    654 
    655 static void
    656 lfs_finalize_seguse(struct lfs *fs, void *v)
    657 {
    658 	SEGUSE *sup;
    659 	struct buf *bp;
    660 	struct segdelta *sd;
    661 	LIST_HEAD(, segdelta) *hd = v;
    662 
    663 	ASSERT_SEGLOCK(fs);
    664 	while((sd = LIST_FIRST(hd)) != NULL) {
    665 		LIST_REMOVE(sd, list);
    666 		LFS_SEGENTRY(sup, fs, sd->segnum, bp);
    667 		if (sd->num > sup->su_nbytes) {
    668 			printf("lfs_finalize_seguse: segment %ld short by %ld\n",
    669 				sd->segnum, (long)(sd->num - sup->su_nbytes));
    670 			panic("lfs_finalize_seguse: negative bytes");
    671 			sup->su_nbytes = sd->num;
    672 		}
    673 		sup->su_nbytes -= sd->num;
    674 		LFS_WRITESEGENTRY(sup, fs, sd->segnum, bp);
    675 		free(sd, M_SEGMENT);
    676 	}
    677 }
    678 
    679 /* Finish the accounting updates for a segment. */
    680 void
    681 lfs_finalize_ino_seguse(struct lfs *fs, struct inode *ip)
    682 {
    683 	ASSERT_SEGLOCK(fs);
    684 	lfs_finalize_seguse(fs, &ip->i_lfs_segdhd);
    685 }
    686 
    687 /* Finish the accounting updates for a segment. */
    688 void
    689 lfs_finalize_fs_seguse(struct lfs *fs)
    690 {
    691 	ASSERT_SEGLOCK(fs);
    692 	lfs_finalize_seguse(fs, &fs->lfs_segdhd);
    693 }
    694 
    695 /*
    696  * Release blocks associated with the inode ip and stored in the indirect
    697  * block bn.  Blocks are free'd in LIFO order up to (but not including)
    698  * lastbn.  If level is greater than SINGLE, the block is an indirect block
    699  * and recursive calls to indirtrunc must be used to cleanse other indirect
    700  * blocks.
    701  *
    702  * NB: triple indirect blocks are untested.
    703  */
    704 static int
    705 lfs_indirtrunc(struct inode *ip, daddr_t lbn, daddr_t dbn,
    706 	       daddr_t lastbn, int level, long *countp,
    707 	       long *rcountp, long *lastsegp, size_t *bcp, struct lwp *l)
    708 {
    709 	int i;
    710 	struct buf *bp;
    711 	struct lfs *fs = ip->i_lfs;
    712 	int32_t *bap;	/* XXX ondisk32 */
    713 	struct vnode *vp;
    714 	daddr_t nb, nlbn, last;
    715 	int32_t *copy = NULL;	/* XXX ondisk32 */
    716 	long blkcount, rblkcount, factor;
    717 	int nblocks, blocksreleased = 0, real_released = 0;
    718 	int error = 0, allerror = 0;
    719 
    720 	ASSERT_SEGLOCK(fs);
    721 	/*
    722 	 * Calculate index in current block of last
    723 	 * block to be kept.  -1 indicates the entire
    724 	 * block so we need not calculate the index.
    725 	 */
    726 	factor = 1;
    727 	for (i = SINGLE; i < level; i++)
    728 		factor *= NINDIR(fs);
    729 	last = lastbn;
    730 	if (lastbn > 0)
    731 		last /= factor;
    732 	nblocks = btofsb(fs, fs->lfs_bsize);
    733 	/*
    734 	 * Get buffer of block pointers, zero those entries corresponding
    735 	 * to blocks to be free'd, and update on disk copy first.  Since
    736 	 * double(triple) indirect before single(double) indirect, calls
    737 	 * to bmap on these blocks will fail.  However, we already have
    738 	 * the on disk address, so we have to set the b_blkno field
    739 	 * explicitly instead of letting bread do everything for us.
    740 	 */
    741 	vp = ITOV(ip);
    742 	bp = getblk(vp, lbn, (int)fs->lfs_bsize, 0, 0);
    743 	if (bp->b_flags & (B_DONE | B_DELWRI)) {
    744 		/* Braces must be here in case trace evaluates to nothing. */
    745 		trace(TR_BREADHIT, pack(vp, fs->lfs_bsize), lbn);
    746 	} else {
    747 		trace(TR_BREADMISS, pack(vp, fs->lfs_bsize), lbn);
    748 		l->l_proc->p_stats->p_ru.ru_inblock++;	/* pay for read */
    749 		bp->b_flags |= B_READ;
    750 		if (bp->b_bcount > bp->b_bufsize)
    751 			panic("lfs_indirtrunc: bad buffer size");
    752 		bp->b_blkno = fsbtodb(fs, dbn);
    753 		VOP_STRATEGY(vp, bp);
    754 		error = biowait(bp);
    755 	}
    756 	if (error) {
    757 		brelse(bp);
    758 		*countp = *rcountp = 0;
    759 		return (error);
    760 	}
    761 
    762 	bap = (int32_t *)bp->b_data;	/* XXX ondisk32 */
    763 	if (lastbn >= 0) {
    764 		copy = (int32_t *)lfs_malloc(fs, fs->lfs_bsize, LFS_NB_IBLOCK);
    765 		memcpy((void *)copy, (void *)bap, (u_int)fs->lfs_bsize);
    766 		memset((void *)&bap[last + 1], 0,
    767 		/* XXX ondisk32 */
    768 		  (u_int)(NINDIR(fs) - (last + 1)) * sizeof (int32_t));
    769 		error = VOP_BWRITE(bp);
    770 		if (error)
    771 			allerror = error;
    772 		bap = copy;
    773 	}
    774 
    775 	/*
    776 	 * Recursively free totally unused blocks.
    777 	 */
    778 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
    779 	    i--, nlbn += factor) {
    780 		nb = bap[i];
    781 		if (nb == 0)
    782 			continue;
    783 		if (level > SINGLE) {
    784 			error = lfs_indirtrunc(ip, nlbn, nb,
    785 					       (daddr_t)-1, level - 1,
    786 					       &blkcount, &rblkcount,
    787 					       lastsegp, bcp, l);
    788 			if (error)
    789 				allerror = error;
    790 			blocksreleased += blkcount;
    791 			real_released += rblkcount;
    792 		}
    793 		lfs_blkfree(fs, ip, nb, fs->lfs_bsize, lastsegp, bcp);
    794 		if (bap[i] > 0)
    795 			real_released += nblocks;
    796 		blocksreleased += nblocks;
    797 	}
    798 
    799 	/*
    800 	 * Recursively free last partial block.
    801 	 */
    802 	if (level > SINGLE && lastbn >= 0) {
    803 		last = lastbn % factor;
    804 		nb = bap[i];
    805 		if (nb != 0) {
    806 			error = lfs_indirtrunc(ip, nlbn, nb,
    807 					       last, level - 1, &blkcount,
    808 					       &rblkcount, lastsegp, bcp, l);
    809 			if (error)
    810 				allerror = error;
    811 			real_released += rblkcount;
    812 			blocksreleased += blkcount;
    813 		}
    814 	}
    815 
    816 	if (copy != NULL) {
    817 		lfs_free(fs, copy, LFS_NB_IBLOCK);
    818 	} else {
    819 		if (bp->b_flags & B_DELWRI) {
    820 			LFS_UNLOCK_BUF(bp);
    821 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    822 			wakeup(&fs->lfs_avail);
    823 		}
    824 		bp->b_flags |= B_INVAL;
    825 		brelse(bp);
    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, int slpflag, int slptimeo)
    841 {
    842 	struct buf *bp, *nbp;
    843 	int s, error;
    844 	struct lfs *fs;
    845 	voff_t off;
    846 
    847 	off = round_page((voff_t)lbn << vp->v_mount->mnt_fs_bshift);
    848 	simple_lock(&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 	s = splbio();
    855 
    856 	ASSERT_SEGLOCK(fs);
    857 restart:
    858 	for (bp = LIST_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
    859 		nbp = LIST_NEXT(bp, b_vnbufs);
    860 		if (bp->b_lblkno < lbn)
    861 			continue;
    862 		simple_lock(&bp->b_interlock);
    863 		if (bp->b_flags & B_BUSY) {
    864 			bp->b_flags |= B_WANTED;
    865 			error = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    866 			    "lfs_vtruncbuf", slptimeo, &bp->b_interlock);
    867 			if (error) {
    868 				splx(s);
    869 				return (error);
    870 			}
    871 			goto restart;
    872 		}
    873 		bp->b_flags |= B_BUSY | B_INVAL | B_VFLUSH;
    874 		if (bp->b_flags & B_DELWRI) {
    875 			bp->b_flags &= ~B_DELWRI;
    876 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    877 			wakeup(&fs->lfs_avail);
    878 		}
    879 		LFS_UNLOCK_BUF(bp);
    880 		simple_unlock(&bp->b_interlock);
    881 		brelse(bp);
    882 	}
    883 
    884 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    885 		nbp = LIST_NEXT(bp, b_vnbufs);
    886 		if (bp->b_lblkno < lbn)
    887 			continue;
    888 		simple_lock(&bp->b_interlock);
    889 		if (bp->b_flags & B_BUSY) {
    890 			bp->b_flags |= B_WANTED;
    891 			error = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
    892 			    "lfs_vtruncbuf", slptimeo, &bp->b_interlock);
    893 			if (error) {
    894 				splx(s);
    895 				return (error);
    896 			}
    897 			goto restart;
    898 		}
    899 		bp->b_flags |= B_BUSY | B_INVAL | B_VFLUSH;
    900 		if (bp->b_flags & B_DELWRI) {
    901 			bp->b_flags &= ~B_DELWRI;
    902 			fs->lfs_avail += btofsb(fs, bp->b_bcount);
    903 			wakeup(&fs->lfs_avail);
    904 		}
    905 		LFS_UNLOCK_BUF(bp);
    906 		simple_unlock(&bp->b_interlock);
    907 		brelse(bp);
    908 	}
    909 
    910 	splx(s);
    911 
    912 	return (0);
    913 }
    914 
    915