xref: /freebsd/sys/ufs/ffs/ffs_inode.c (revision 63a938566d524836885917d95bd491aa4400b181)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ffs_inode.c	8.13 (Berkeley) 4/21/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_quota.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bio.h>
42 #include <sys/buf.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/proc.h>
46 #include <sys/racct.h>
47 #include <sys/random.h>
48 #include <sys/resourcevar.h>
49 #include <sys/rwlock.h>
50 #include <sys/stat.h>
51 #include <sys/vmmeter.h>
52 #include <sys/vnode.h>
53 
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_object.h>
57 
58 #include <ufs/ufs/extattr.h>
59 #include <ufs/ufs/quota.h>
60 #include <ufs/ufs/ufsmount.h>
61 #include <ufs/ufs/inode.h>
62 #include <ufs/ufs/ufs_extern.h>
63 
64 #include <ufs/ffs/fs.h>
65 #include <ufs/ffs/ffs_extern.h>
66 
67 static int ffs_indirtrunc(struct inode *, ufs2_daddr_t, ufs2_daddr_t,
68 	    ufs2_daddr_t, int, ufs2_daddr_t *);
69 
70 /*
71  * Update the access, modified, and inode change times as specified by the
72  * IN_ACCESS, IN_UPDATE, and IN_CHANGE flags respectively.  Write the inode
73  * to disk if the IN_MODIFIED flag is set (it may be set initially, or by
74  * the timestamp update).  The IN_LAZYMOD flag is set to force a write
75  * later if not now.  The IN_LAZYACCESS is set instead of IN_MODIFIED if the fs
76  * is currently being suspended (or is suspended) and vnode has been accessed.
77  * If we write now, then clear IN_MODIFIED, IN_LAZYACCESS and IN_LAZYMOD to
78  * reflect the presumably successful write, and if waitfor is set, then wait
79  * for the write to complete.
80  */
81 int
82 ffs_update(vp, waitfor)
83 	struct vnode *vp;
84 	int waitfor;
85 {
86 	struct fs *fs;
87 	struct buf *bp;
88 	struct inode *ip;
89 	int flags, error;
90 
91 	ASSERT_VOP_ELOCKED(vp, "ffs_update");
92 	ufs_itimes(vp);
93 	ip = VTOI(vp);
94 	if ((ip->i_flag & IN_MODIFIED) == 0 && waitfor == 0)
95 		return (0);
96 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
97 	fs = ITOFS(ip);
98 	if (fs->fs_ronly && ITOUMP(ip)->um_fsckpid == 0)
99 		return (0);
100 	/*
101 	 * If we are updating a snapshot and another process is currently
102 	 * writing the buffer containing the inode for this snapshot then
103 	 * a deadlock can occur when it tries to check the snapshot to see
104 	 * if that block needs to be copied. Thus when updating a snapshot
105 	 * we check to see if the buffer is already locked, and if it is
106 	 * we drop the snapshot lock until the buffer has been written
107 	 * and is available to us. We have to grab a reference to the
108 	 * snapshot vnode to prevent it from being removed while we are
109 	 * waiting for the buffer.
110 	 */
111 	flags = 0;
112 	if (IS_SNAPSHOT(ip))
113 		flags = GB_LOCK_NOWAIT;
114 loop:
115 	error = bread_gb(ITODEVVP(ip),
116 	     fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
117 	     (int) fs->fs_bsize, NOCRED, flags, &bp);
118 	if (error != 0) {
119 		if (error != EBUSY)
120 			return (error);
121 		KASSERT((IS_SNAPSHOT(ip)), ("EBUSY from non-snapshot"));
122 		/*
123 		 * Wait for our inode block to become available.
124 		 *
125 		 * Hold a reference to the vnode to protect against
126 		 * ffs_snapgone(). Since we hold a reference, it can only
127 		 * get reclaimed (VI_DOOMED flag) in a forcible downgrade
128 		 * or unmount. For an unmount, the entire filesystem will be
129 		 * gone, so we cannot attempt to touch anything associated
130 		 * with it while the vnode is unlocked; all we can do is
131 		 * pause briefly and try again. If when we relock the vnode
132 		 * we discover that it has been reclaimed, updating it is no
133 		 * longer necessary and we can just return an error.
134 		 */
135 		vref(vp);
136 		VOP_UNLOCK(vp, 0);
137 		pause("ffsupd", 1);
138 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
139 		vrele(vp);
140 		if ((vp->v_iflag & VI_DOOMED) != 0)
141 			return (ENOENT);
142 		goto loop;
143 	}
144 	if (DOINGSOFTDEP(vp))
145 		softdep_update_inodeblock(ip, bp, waitfor);
146 	else if (ip->i_effnlink != ip->i_nlink)
147 		panic("ffs_update: bad link cnt");
148 	if (I_IS_UFS1(ip)) {
149 		*((struct ufs1_dinode *)bp->b_data +
150 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
151 		/* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
152 		random_harvest_queue(&(ip->i_din1), sizeof(ip->i_din1), 1, RANDOM_FS_ATIME);
153 	} else {
154 		*((struct ufs2_dinode *)bp->b_data +
155 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
156 		/* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
157 		random_harvest_queue(&(ip->i_din2), sizeof(ip->i_din2), 1, RANDOM_FS_ATIME);
158 	}
159 	if (waitfor)
160 		error = bwrite(bp);
161 	else if (vm_page_count_severe() || buf_dirty_count_severe()) {
162 		bawrite(bp);
163 		error = 0;
164 	} else {
165 		if (bp->b_bufsize == fs->fs_bsize)
166 			bp->b_flags |= B_CLUSTEROK;
167 		bdwrite(bp);
168 		error = 0;
169 	}
170 	return (error);
171 }
172 
173 #define	SINGLE	0	/* index of single indirect block */
174 #define	DOUBLE	1	/* index of double indirect block */
175 #define	TRIPLE	2	/* index of triple indirect block */
176 /*
177  * Truncate the inode ip to at most length size, freeing the
178  * disk blocks.
179  */
180 int
181 ffs_truncate(vp, length, flags, cred)
182 	struct vnode *vp;
183 	off_t length;
184 	int flags;
185 	struct ucred *cred;
186 {
187 	struct inode *ip;
188 	ufs2_daddr_t bn, lbn, lastblock, lastiblock[UFS_NIADDR];
189 	ufs2_daddr_t indir_lbn[UFS_NIADDR], oldblks[UFS_NDADDR + UFS_NIADDR];
190 	ufs2_daddr_t newblks[UFS_NDADDR + UFS_NIADDR];
191 	ufs2_daddr_t count, blocksreleased = 0, datablocks, blkno;
192 	struct bufobj *bo;
193 	struct fs *fs;
194 	struct buf *bp;
195 	struct ufsmount *ump;
196 	int softdeptrunc, journaltrunc;
197 	int needextclean, extblocks;
198 	int offset, size, level, nblocks;
199 	int i, error, allerror, indiroff, waitforupdate;
200 	off_t osize;
201 
202 	ip = VTOI(vp);
203 	ump = VFSTOUFS(vp->v_mount);
204 	fs = ump->um_fs;
205 	bo = &vp->v_bufobj;
206 
207 	ASSERT_VOP_LOCKED(vp, "ffs_truncate");
208 
209 	if (length < 0)
210 		return (EINVAL);
211 	if (length > fs->fs_maxfilesize)
212 		return (EFBIG);
213 #ifdef QUOTA
214 	error = getinoquota(ip);
215 	if (error)
216 		return (error);
217 #endif
218 	/*
219 	 * Historically clients did not have to specify which data
220 	 * they were truncating. So, if not specified, we assume
221 	 * traditional behavior, e.g., just the normal data.
222 	 */
223 	if ((flags & (IO_EXT | IO_NORMAL)) == 0)
224 		flags |= IO_NORMAL;
225 	if (!DOINGSOFTDEP(vp) && !DOINGASYNC(vp))
226 		flags |= IO_SYNC;
227 	waitforupdate = (flags & IO_SYNC) != 0 || !DOINGASYNC(vp);
228 	/*
229 	 * If we are truncating the extended-attributes, and cannot
230 	 * do it with soft updates, then do it slowly here. If we are
231 	 * truncating both the extended attributes and the file contents
232 	 * (e.g., the file is being unlinked), then pick it off with
233 	 * soft updates below.
234 	 */
235 	allerror = 0;
236 	needextclean = 0;
237 	softdeptrunc = 0;
238 	journaltrunc = DOINGSUJ(vp);
239 	if (journaltrunc == 0 && DOINGSOFTDEP(vp) && length == 0)
240 		softdeptrunc = !softdep_slowdown(vp);
241 	extblocks = 0;
242 	datablocks = DIP(ip, i_blocks);
243 	if (fs->fs_magic == FS_UFS2_MAGIC && ip->i_din2->di_extsize > 0) {
244 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
245 		datablocks -= extblocks;
246 	}
247 	if ((flags & IO_EXT) && extblocks > 0) {
248 		if (length != 0)
249 			panic("ffs_truncate: partial trunc of extdata");
250 		if (softdeptrunc || journaltrunc) {
251 			if ((flags & IO_NORMAL) == 0)
252 				goto extclean;
253 			needextclean = 1;
254 		} else {
255 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
256 				return (error);
257 #ifdef QUOTA
258 			(void) chkdq(ip, -extblocks, NOCRED, 0);
259 #endif
260 			vinvalbuf(vp, V_ALT, 0, 0);
261 			vn_pages_remove(vp,
262 			    OFF_TO_IDX(lblktosize(fs, -extblocks)), 0);
263 			osize = ip->i_din2->di_extsize;
264 			ip->i_din2->di_blocks -= extblocks;
265 			ip->i_din2->di_extsize = 0;
266 			for (i = 0; i < UFS_NXADDR; i++) {
267 				oldblks[i] = ip->i_din2->di_extb[i];
268 				ip->i_din2->di_extb[i] = 0;
269 			}
270 			ip->i_flag |= IN_CHANGE;
271 			if ((error = ffs_update(vp, waitforupdate)))
272 				return (error);
273 			for (i = 0; i < UFS_NXADDR; i++) {
274 				if (oldblks[i] == 0)
275 					continue;
276 				ffs_blkfree(ump, fs, ITODEVVP(ip), oldblks[i],
277 				    sblksize(fs, osize, i), ip->i_number,
278 				    vp->v_type, NULL);
279 			}
280 		}
281 	}
282 	if ((flags & IO_NORMAL) == 0)
283 		return (0);
284 	if (vp->v_type == VLNK &&
285 	    (ip->i_size < vp->v_mount->mnt_maxsymlinklen ||
286 	     datablocks == 0)) {
287 #ifdef INVARIANTS
288 		if (length != 0)
289 			panic("ffs_truncate: partial truncate of symlink");
290 #endif
291 		bzero(SHORTLINK(ip), (u_int)ip->i_size);
292 		ip->i_size = 0;
293 		DIP_SET(ip, i_size, 0);
294 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
295 		if (needextclean)
296 			goto extclean;
297 		return (ffs_update(vp, waitforupdate));
298 	}
299 	if (ip->i_size == length) {
300 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
301 		if (needextclean)
302 			goto extclean;
303 		return (ffs_update(vp, 0));
304 	}
305 	if (fs->fs_ronly)
306 		panic("ffs_truncate: read-only filesystem");
307 	if (IS_SNAPSHOT(ip))
308 		ffs_snapremove(vp);
309 	vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
310 	osize = ip->i_size;
311 	/*
312 	 * Lengthen the size of the file. We must ensure that the
313 	 * last byte of the file is allocated. Since the smallest
314 	 * value of osize is 0, length will be at least 1.
315 	 */
316 	if (osize < length) {
317 		vnode_pager_setsize(vp, length);
318 		flags |= BA_CLRBUF;
319 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
320 		if (error) {
321 			vnode_pager_setsize(vp, osize);
322 			return (error);
323 		}
324 		ip->i_size = length;
325 		DIP_SET(ip, i_size, length);
326 		if (bp->b_bufsize == fs->fs_bsize)
327 			bp->b_flags |= B_CLUSTEROK;
328 		if (flags & IO_SYNC)
329 			bwrite(bp);
330 		else if (DOINGASYNC(vp))
331 			bdwrite(bp);
332 		else
333 			bawrite(bp);
334 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
335 		return (ffs_update(vp, waitforupdate));
336 	}
337 	/*
338 	 * Lookup block number for a given offset. Zero length files
339 	 * have no blocks, so return a blkno of -1.
340 	 */
341 	lbn = lblkno(fs, length - 1);
342 	if (length == 0) {
343 		blkno = -1;
344 	} else if (lbn < UFS_NDADDR) {
345 		blkno = DIP(ip, i_db[lbn]);
346 	} else {
347 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
348 		    cred, BA_METAONLY, &bp);
349 		if (error)
350 			return (error);
351 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
352 		if (I_IS_UFS1(ip))
353 			blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
354 		else
355 			blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
356 		/*
357 		 * If the block number is non-zero, then the indirect block
358 		 * must have been previously allocated and need not be written.
359 		 * If the block number is zero, then we may have allocated
360 		 * the indirect block and hence need to write it out.
361 		 */
362 		if (blkno != 0)
363 			brelse(bp);
364 		else if (flags & IO_SYNC)
365 			bwrite(bp);
366 		else
367 			bdwrite(bp);
368 	}
369 	/*
370 	 * If the block number at the new end of the file is zero,
371 	 * then we must allocate it to ensure that the last block of
372 	 * the file is allocated. Soft updates does not handle this
373 	 * case, so here we have to clean up the soft updates data
374 	 * structures describing the allocation past the truncation
375 	 * point. Finding and deallocating those structures is a lot of
376 	 * work. Since partial truncation with a hole at the end occurs
377 	 * rarely, we solve the problem by syncing the file so that it
378 	 * will have no soft updates data structures left.
379 	 */
380 	if (blkno == 0 && (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
381 		return (error);
382 	if (blkno != 0 && DOINGSOFTDEP(vp)) {
383 		if (softdeptrunc == 0 && journaltrunc == 0) {
384 			/*
385 			 * If soft updates cannot handle this truncation,
386 			 * clean up soft dependency data structures and
387 			 * fall through to the synchronous truncation.
388 			 */
389 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
390 				return (error);
391 		} else {
392 			flags = IO_NORMAL | (needextclean ? IO_EXT: 0);
393 			if (journaltrunc)
394 				softdep_journal_freeblocks(ip, cred, length,
395 				    flags);
396 			else
397 				softdep_setup_freeblocks(ip, length, flags);
398 			ASSERT_VOP_LOCKED(vp, "ffs_truncate1");
399 			if (journaltrunc == 0) {
400 				ip->i_flag |= IN_CHANGE | IN_UPDATE;
401 				error = ffs_update(vp, 0);
402 			}
403 			return (error);
404 		}
405 	}
406 	/*
407 	 * Shorten the size of the file. If the last block of the
408 	 * shortened file is unallocated, we must allocate it.
409 	 * Additionally, if the file is not being truncated to a
410 	 * block boundary, the contents of the partial block
411 	 * following the end of the file must be zero'ed in
412 	 * case it ever becomes accessible again because of
413 	 * subsequent file growth. Directories however are not
414 	 * zero'ed as they should grow back initialized to empty.
415 	 */
416 	offset = blkoff(fs, length);
417 	if (blkno != 0 && offset == 0) {
418 		ip->i_size = length;
419 		DIP_SET(ip, i_size, length);
420 	} else {
421 		lbn = lblkno(fs, length);
422 		flags |= BA_CLRBUF;
423 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
424 		if (error)
425 			return (error);
426 		/*
427 		 * When we are doing soft updates and the UFS_BALLOC
428 		 * above fills in a direct block hole with a full sized
429 		 * block that will be truncated down to a fragment below,
430 		 * we must flush out the block dependency with an FSYNC
431 		 * so that we do not get a soft updates inconsistency
432 		 * when we create the fragment below.
433 		 */
434 		if (DOINGSOFTDEP(vp) && lbn < UFS_NDADDR &&
435 		    fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
436 		    (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
437 			return (error);
438 		ip->i_size = length;
439 		DIP_SET(ip, i_size, length);
440 		size = blksize(fs, ip, lbn);
441 		if (vp->v_type != VDIR && offset != 0)
442 			bzero((char *)bp->b_data + offset,
443 			    (u_int)(size - offset));
444 		/* Kirk's code has reallocbuf(bp, size, 1) here */
445 		allocbuf(bp, size);
446 		if (bp->b_bufsize == fs->fs_bsize)
447 			bp->b_flags |= B_CLUSTEROK;
448 		if (flags & IO_SYNC)
449 			bwrite(bp);
450 		else if (DOINGASYNC(vp))
451 			bdwrite(bp);
452 		else
453 			bawrite(bp);
454 	}
455 	/*
456 	 * Calculate index into inode's block list of
457 	 * last direct and indirect blocks (if any)
458 	 * which we want to keep.  Lastblock is -1 when
459 	 * the file is truncated to 0.
460 	 */
461 	lastblock = lblkno(fs, length + fs->fs_bsize - 1) - 1;
462 	lastiblock[SINGLE] = lastblock - UFS_NDADDR;
463 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
464 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
465 	nblocks = btodb(fs->fs_bsize);
466 	/*
467 	 * Update file and block pointers on disk before we start freeing
468 	 * blocks.  If we crash before free'ing blocks below, the blocks
469 	 * will be returned to the free list.  lastiblock values are also
470 	 * normalized to -1 for calls to ffs_indirtrunc below.
471 	 */
472 	for (level = TRIPLE; level >= SINGLE; level--) {
473 		oldblks[UFS_NDADDR + level] = DIP(ip, i_ib[level]);
474 		if (lastiblock[level] < 0) {
475 			DIP_SET(ip, i_ib[level], 0);
476 			lastiblock[level] = -1;
477 		}
478 	}
479 	for (i = 0; i < UFS_NDADDR; i++) {
480 		oldblks[i] = DIP(ip, i_db[i]);
481 		if (i > lastblock)
482 			DIP_SET(ip, i_db[i], 0);
483 	}
484 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
485 	allerror = ffs_update(vp, waitforupdate);
486 
487 	/*
488 	 * Having written the new inode to disk, save its new configuration
489 	 * and put back the old block pointers long enough to process them.
490 	 * Note that we save the new block configuration so we can check it
491 	 * when we are done.
492 	 */
493 	for (i = 0; i < UFS_NDADDR; i++) {
494 		newblks[i] = DIP(ip, i_db[i]);
495 		DIP_SET(ip, i_db[i], oldblks[i]);
496 	}
497 	for (i = 0; i < UFS_NIADDR; i++) {
498 		newblks[UFS_NDADDR + i] = DIP(ip, i_ib[i]);
499 		DIP_SET(ip, i_ib[i], oldblks[UFS_NDADDR + i]);
500 	}
501 	ip->i_size = osize;
502 	DIP_SET(ip, i_size, osize);
503 
504 	error = vtruncbuf(vp, cred, length, fs->fs_bsize);
505 	if (error && (allerror == 0))
506 		allerror = error;
507 
508 	/*
509 	 * Indirect blocks first.
510 	 */
511 	indir_lbn[SINGLE] = -UFS_NDADDR;
512 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
513 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
514 	for (level = TRIPLE; level >= SINGLE; level--) {
515 		bn = DIP(ip, i_ib[level]);
516 		if (bn != 0) {
517 			error = ffs_indirtrunc(ip, indir_lbn[level],
518 			    fsbtodb(fs, bn), lastiblock[level], level, &count);
519 			if (error)
520 				allerror = error;
521 			blocksreleased += count;
522 			if (lastiblock[level] < 0) {
523 				DIP_SET(ip, i_ib[level], 0);
524 				ffs_blkfree(ump, fs, ump->um_devvp, bn,
525 				    fs->fs_bsize, ip->i_number,
526 				    vp->v_type, NULL);
527 				blocksreleased += nblocks;
528 			}
529 		}
530 		if (lastiblock[level] >= 0)
531 			goto done;
532 	}
533 
534 	/*
535 	 * All whole direct blocks or frags.
536 	 */
537 	for (i = UFS_NDADDR - 1; i > lastblock; i--) {
538 		long bsize;
539 
540 		bn = DIP(ip, i_db[i]);
541 		if (bn == 0)
542 			continue;
543 		DIP_SET(ip, i_db[i], 0);
544 		bsize = blksize(fs, ip, i);
545 		ffs_blkfree(ump, fs, ump->um_devvp, bn, bsize, ip->i_number,
546 		    vp->v_type, NULL);
547 		blocksreleased += btodb(bsize);
548 	}
549 	if (lastblock < 0)
550 		goto done;
551 
552 	/*
553 	 * Finally, look for a change in size of the
554 	 * last direct block; release any frags.
555 	 */
556 	bn = DIP(ip, i_db[lastblock]);
557 	if (bn != 0) {
558 		long oldspace, newspace;
559 
560 		/*
561 		 * Calculate amount of space we're giving
562 		 * back as old block size minus new block size.
563 		 */
564 		oldspace = blksize(fs, ip, lastblock);
565 		ip->i_size = length;
566 		DIP_SET(ip, i_size, length);
567 		newspace = blksize(fs, ip, lastblock);
568 		if (newspace == 0)
569 			panic("ffs_truncate: newspace");
570 		if (oldspace - newspace > 0) {
571 			/*
572 			 * Block number of space to be free'd is
573 			 * the old block # plus the number of frags
574 			 * required for the storage we're keeping.
575 			 */
576 			bn += numfrags(fs, newspace);
577 			ffs_blkfree(ump, fs, ump->um_devvp, bn,
578 			   oldspace - newspace, ip->i_number, vp->v_type, NULL);
579 			blocksreleased += btodb(oldspace - newspace);
580 		}
581 	}
582 done:
583 #ifdef INVARIANTS
584 	for (level = SINGLE; level <= TRIPLE; level++)
585 		if (newblks[UFS_NDADDR + level] != DIP(ip, i_ib[level]))
586 			panic("ffs_truncate1");
587 	for (i = 0; i < UFS_NDADDR; i++)
588 		if (newblks[i] != DIP(ip, i_db[i]))
589 			panic("ffs_truncate2");
590 	BO_LOCK(bo);
591 	if (length == 0 &&
592 	    (fs->fs_magic != FS_UFS2_MAGIC || ip->i_din2->di_extsize == 0) &&
593 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
594 		panic("ffs_truncate3");
595 	BO_UNLOCK(bo);
596 #endif /* INVARIANTS */
597 	/*
598 	 * Put back the real size.
599 	 */
600 	ip->i_size = length;
601 	DIP_SET(ip, i_size, length);
602 	if (DIP(ip, i_blocks) >= blocksreleased)
603 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - blocksreleased);
604 	else	/* sanity */
605 		DIP_SET(ip, i_blocks, 0);
606 	ip->i_flag |= IN_CHANGE;
607 #ifdef QUOTA
608 	(void) chkdq(ip, -blocksreleased, NOCRED, 0);
609 #endif
610 	return (allerror);
611 
612 extclean:
613 	if (journaltrunc)
614 		softdep_journal_freeblocks(ip, cred, length, IO_EXT);
615 	else
616 		softdep_setup_freeblocks(ip, length, IO_EXT);
617 	return (ffs_update(vp, waitforupdate));
618 }
619 
620 /*
621  * Release blocks associated with the inode ip and stored in the indirect
622  * block bn.  Blocks are free'd in LIFO order up to (but not including)
623  * lastbn.  If level is greater than SINGLE, the block is an indirect block
624  * and recursive calls to indirtrunc must be used to cleanse other indirect
625  * blocks.
626  */
627 static int
628 ffs_indirtrunc(ip, lbn, dbn, lastbn, level, countp)
629 	struct inode *ip;
630 	ufs2_daddr_t lbn, lastbn;
631 	ufs2_daddr_t dbn;
632 	int level;
633 	ufs2_daddr_t *countp;
634 {
635 	struct buf *bp;
636 	struct fs *fs;
637 	struct vnode *vp;
638 	caddr_t copy = NULL;
639 	int i, nblocks, error = 0, allerror = 0;
640 	ufs2_daddr_t nb, nlbn, last;
641 	ufs2_daddr_t blkcount, factor, blocksreleased = 0;
642 	ufs1_daddr_t *bap1 = NULL;
643 	ufs2_daddr_t *bap2 = NULL;
644 #define BAP(ip, i) (I_IS_UFS1(ip) ? bap1[i] : bap2[i])
645 
646 	fs = ITOFS(ip);
647 
648 	/*
649 	 * Calculate index in current block of last
650 	 * block to be kept.  -1 indicates the entire
651 	 * block so we need not calculate the index.
652 	 */
653 	factor = lbn_offset(fs, level);
654 	last = lastbn;
655 	if (lastbn > 0)
656 		last /= factor;
657 	nblocks = btodb(fs->fs_bsize);
658 	/*
659 	 * Get buffer of block pointers, zero those entries corresponding
660 	 * to blocks to be free'd, and update on disk copy first.  Since
661 	 * double(triple) indirect before single(double) indirect, calls
662 	 * to bmap on these blocks will fail.  However, we already have
663 	 * the on disk address, so we have to set the b_blkno field
664 	 * explicitly instead of letting bread do everything for us.
665 	 */
666 	vp = ITOV(ip);
667 	bp = getblk(vp, lbn, (int)fs->fs_bsize, 0, 0, 0);
668 	if ((bp->b_flags & B_CACHE) == 0) {
669 #ifdef RACCT
670 		if (racct_enable) {
671 			PROC_LOCK(curproc);
672 			racct_add_buf(curproc, bp, 0);
673 			PROC_UNLOCK(curproc);
674 		}
675 #endif /* RACCT */
676 		curthread->td_ru.ru_inblock++;	/* pay for read */
677 		bp->b_iocmd = BIO_READ;
678 		bp->b_flags &= ~B_INVAL;
679 		bp->b_ioflags &= ~BIO_ERROR;
680 		if (bp->b_bcount > bp->b_bufsize)
681 			panic("ffs_indirtrunc: bad buffer size");
682 		bp->b_blkno = dbn;
683 		vfs_busy_pages(bp, 0);
684 		bp->b_iooffset = dbtob(bp->b_blkno);
685 		bstrategy(bp);
686 		error = bufwait(bp);
687 	}
688 	if (error) {
689 		brelse(bp);
690 		*countp = 0;
691 		return (error);
692 	}
693 
694 	if (I_IS_UFS1(ip))
695 		bap1 = (ufs1_daddr_t *)bp->b_data;
696 	else
697 		bap2 = (ufs2_daddr_t *)bp->b_data;
698 	if (lastbn != -1) {
699 		copy = malloc(fs->fs_bsize, M_TEMP, M_WAITOK);
700 		bcopy((caddr_t)bp->b_data, copy, (u_int)fs->fs_bsize);
701 		for (i = last + 1; i < NINDIR(fs); i++)
702 			if (I_IS_UFS1(ip))
703 				bap1[i] = 0;
704 			else
705 				bap2[i] = 0;
706 		if (DOINGASYNC(vp)) {
707 			bdwrite(bp);
708 		} else {
709 			error = bwrite(bp);
710 			if (error)
711 				allerror = error;
712 		}
713 		if (I_IS_UFS1(ip))
714 			bap1 = (ufs1_daddr_t *)copy;
715 		else
716 			bap2 = (ufs2_daddr_t *)copy;
717 	}
718 
719 	/*
720 	 * Recursively free totally unused blocks.
721 	 */
722 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
723 	    i--, nlbn += factor) {
724 		nb = BAP(ip, i);
725 		if (nb == 0)
726 			continue;
727 		if (level > SINGLE) {
728 			if ((error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
729 			    (ufs2_daddr_t)-1, level - 1, &blkcount)) != 0)
730 				allerror = error;
731 			blocksreleased += blkcount;
732 		}
733 		ffs_blkfree(ITOUMP(ip), fs, ITODEVVP(ip), nb, fs->fs_bsize,
734 		    ip->i_number, vp->v_type, NULL);
735 		blocksreleased += nblocks;
736 	}
737 
738 	/*
739 	 * Recursively free last partial block.
740 	 */
741 	if (level > SINGLE && lastbn >= 0) {
742 		last = lastbn % factor;
743 		nb = BAP(ip, i);
744 		if (nb != 0) {
745 			error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
746 			    last, level - 1, &blkcount);
747 			if (error)
748 				allerror = error;
749 			blocksreleased += blkcount;
750 		}
751 	}
752 	if (copy != NULL) {
753 		free(copy, M_TEMP);
754 	} else {
755 		bp->b_flags |= B_INVAL | B_NOCACHE;
756 		brelse(bp);
757 	}
758 
759 	*countp = blocksreleased;
760 	return (allerror);
761 }
762 
763 int
764 ffs_rdonly(struct inode *ip)
765 {
766 
767 	return (ITOFS(ip)->fs_ronly != 0);
768 }
769 
770