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