xref: /freebsd/sys/ufs/ffs/ffs_inode.c (revision 85732ac8)
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 		/*
152 		 * XXX: FIX? The entropy here is desirable,
153 		 * but the harvesting may be expensive
154 		 */
155 		random_harvest_queue(&(ip->i_din1), sizeof(ip->i_din1), RANDOM_FS_ATIME);
156 	} else {
157 		*((struct ufs2_dinode *)bp->b_data +
158 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
159 		/*
160 		 * XXX: FIX? The entropy here is desirable,
161 		 * but the harvesting may be expensive
162 		 */
163 		random_harvest_queue(&(ip->i_din2), sizeof(ip->i_din2), RANDOM_FS_ATIME);
164 	}
165 	if (waitfor)
166 		error = bwrite(bp);
167 	else if (vm_page_count_severe() || buf_dirty_count_severe()) {
168 		bawrite(bp);
169 		error = 0;
170 	} else {
171 		if (bp->b_bufsize == fs->fs_bsize)
172 			bp->b_flags |= B_CLUSTEROK;
173 		bdwrite(bp);
174 		error = 0;
175 	}
176 	return (error);
177 }
178 
179 #define	SINGLE	0	/* index of single indirect block */
180 #define	DOUBLE	1	/* index of double indirect block */
181 #define	TRIPLE	2	/* index of triple indirect block */
182 /*
183  * Truncate the inode ip to at most length size, freeing the
184  * disk blocks.
185  */
186 int
187 ffs_truncate(vp, length, flags, cred)
188 	struct vnode *vp;
189 	off_t length;
190 	int flags;
191 	struct ucred *cred;
192 {
193 	struct inode *ip;
194 	ufs2_daddr_t bn, lbn, lastblock, lastiblock[UFS_NIADDR];
195 	ufs2_daddr_t indir_lbn[UFS_NIADDR], oldblks[UFS_NDADDR + UFS_NIADDR];
196 	ufs2_daddr_t newblks[UFS_NDADDR + UFS_NIADDR];
197 	ufs2_daddr_t count, blocksreleased = 0, datablocks, blkno;
198 	struct bufobj *bo;
199 	struct fs *fs;
200 	struct buf *bp;
201 	struct ufsmount *ump;
202 	int softdeptrunc, journaltrunc;
203 	int needextclean, extblocks;
204 	int offset, size, level, nblocks;
205 	int i, error, allerror, indiroff, waitforupdate;
206 	u_long key;
207 	off_t osize;
208 
209 	ip = VTOI(vp);
210 	ump = VFSTOUFS(vp->v_mount);
211 	fs = ump->um_fs;
212 	bo = &vp->v_bufobj;
213 
214 	ASSERT_VOP_LOCKED(vp, "ffs_truncate");
215 
216 	if (length < 0)
217 		return (EINVAL);
218 	if (length > fs->fs_maxfilesize)
219 		return (EFBIG);
220 #ifdef QUOTA
221 	error = getinoquota(ip);
222 	if (error)
223 		return (error);
224 #endif
225 	/*
226 	 * Historically clients did not have to specify which data
227 	 * they were truncating. So, if not specified, we assume
228 	 * traditional behavior, e.g., just the normal data.
229 	 */
230 	if ((flags & (IO_EXT | IO_NORMAL)) == 0)
231 		flags |= IO_NORMAL;
232 	if (!DOINGSOFTDEP(vp) && !DOINGASYNC(vp))
233 		flags |= IO_SYNC;
234 	waitforupdate = (flags & IO_SYNC) != 0 || !DOINGASYNC(vp);
235 	/*
236 	 * If we are truncating the extended-attributes, and cannot
237 	 * do it with soft updates, then do it slowly here. If we are
238 	 * truncating both the extended attributes and the file contents
239 	 * (e.g., the file is being unlinked), then pick it off with
240 	 * soft updates below.
241 	 */
242 	allerror = 0;
243 	needextclean = 0;
244 	softdeptrunc = 0;
245 	journaltrunc = DOINGSUJ(vp);
246 	if (journaltrunc == 0 && DOINGSOFTDEP(vp) && length == 0)
247 		softdeptrunc = !softdep_slowdown(vp);
248 	extblocks = 0;
249 	datablocks = DIP(ip, i_blocks);
250 	if (fs->fs_magic == FS_UFS2_MAGIC && ip->i_din2->di_extsize > 0) {
251 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
252 		datablocks -= extblocks;
253 	}
254 	if ((flags & IO_EXT) && extblocks > 0) {
255 		if (length != 0)
256 			panic("ffs_truncate: partial trunc of extdata");
257 		if (softdeptrunc || journaltrunc) {
258 			if ((flags & IO_NORMAL) == 0)
259 				goto extclean;
260 			needextclean = 1;
261 		} else {
262 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
263 				return (error);
264 #ifdef QUOTA
265 			(void) chkdq(ip, -extblocks, NOCRED, 0);
266 #endif
267 			vinvalbuf(vp, V_ALT, 0, 0);
268 			vn_pages_remove(vp,
269 			    OFF_TO_IDX(lblktosize(fs, -extblocks)), 0);
270 			osize = ip->i_din2->di_extsize;
271 			ip->i_din2->di_blocks -= extblocks;
272 			ip->i_din2->di_extsize = 0;
273 			for (i = 0; i < UFS_NXADDR; i++) {
274 				oldblks[i] = ip->i_din2->di_extb[i];
275 				ip->i_din2->di_extb[i] = 0;
276 			}
277 			ip->i_flag |= IN_CHANGE;
278 			if ((error = ffs_update(vp, waitforupdate)))
279 				return (error);
280 			for (i = 0; i < UFS_NXADDR; i++) {
281 				if (oldblks[i] == 0)
282 					continue;
283 				ffs_blkfree(ump, fs, ITODEVVP(ip), oldblks[i],
284 				    sblksize(fs, osize, i), ip->i_number,
285 				    vp->v_type, NULL, SINGLETON_KEY);
286 			}
287 		}
288 	}
289 	if ((flags & IO_NORMAL) == 0)
290 		return (0);
291 	if (vp->v_type == VLNK &&
292 	    (ip->i_size < vp->v_mount->mnt_maxsymlinklen ||
293 	     datablocks == 0)) {
294 #ifdef INVARIANTS
295 		if (length != 0)
296 			panic("ffs_truncate: partial truncate of symlink");
297 #endif
298 		bzero(SHORTLINK(ip), (u_int)ip->i_size);
299 		ip->i_size = 0;
300 		DIP_SET(ip, i_size, 0);
301 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
302 		if (needextclean)
303 			goto extclean;
304 		return (ffs_update(vp, waitforupdate));
305 	}
306 	if (ip->i_size == length) {
307 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
308 		if (needextclean)
309 			goto extclean;
310 		return (ffs_update(vp, 0));
311 	}
312 	if (fs->fs_ronly)
313 		panic("ffs_truncate: read-only filesystem");
314 	if (IS_SNAPSHOT(ip))
315 		ffs_snapremove(vp);
316 	vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
317 	osize = ip->i_size;
318 	/*
319 	 * Lengthen the size of the file. We must ensure that the
320 	 * last byte of the file is allocated. Since the smallest
321 	 * value of osize is 0, length will be at least 1.
322 	 */
323 	if (osize < length) {
324 		vnode_pager_setsize(vp, length);
325 		flags |= BA_CLRBUF;
326 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
327 		if (error) {
328 			vnode_pager_setsize(vp, osize);
329 			return (error);
330 		}
331 		ip->i_size = length;
332 		DIP_SET(ip, i_size, length);
333 		if (bp->b_bufsize == fs->fs_bsize)
334 			bp->b_flags |= B_CLUSTEROK;
335 		if (flags & IO_SYNC)
336 			bwrite(bp);
337 		else if (DOINGASYNC(vp))
338 			bdwrite(bp);
339 		else
340 			bawrite(bp);
341 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
342 		return (ffs_update(vp, waitforupdate));
343 	}
344 	/*
345 	 * Lookup block number for a given offset. Zero length files
346 	 * have no blocks, so return a blkno of -1.
347 	 */
348 	lbn = lblkno(fs, length - 1);
349 	if (length == 0) {
350 		blkno = -1;
351 	} else if (lbn < UFS_NDADDR) {
352 		blkno = DIP(ip, i_db[lbn]);
353 	} else {
354 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
355 		    cred, BA_METAONLY, &bp);
356 		if (error)
357 			return (error);
358 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
359 		if (I_IS_UFS1(ip))
360 			blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
361 		else
362 			blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
363 		/*
364 		 * If the block number is non-zero, then the indirect block
365 		 * must have been previously allocated and need not be written.
366 		 * If the block number is zero, then we may have allocated
367 		 * the indirect block and hence need to write it out.
368 		 */
369 		if (blkno != 0)
370 			brelse(bp);
371 		else if (flags & IO_SYNC)
372 			bwrite(bp);
373 		else
374 			bdwrite(bp);
375 	}
376 	/*
377 	 * If the block number at the new end of the file is zero,
378 	 * then we must allocate it to ensure that the last block of
379 	 * the file is allocated. Soft updates does not handle this
380 	 * case, so here we have to clean up the soft updates data
381 	 * structures describing the allocation past the truncation
382 	 * point. Finding and deallocating those structures is a lot of
383 	 * work. Since partial truncation with a hole at the end occurs
384 	 * rarely, we solve the problem by syncing the file so that it
385 	 * will have no soft updates data structures left.
386 	 */
387 	if (blkno == 0 && (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
388 		return (error);
389 	if (blkno != 0 && DOINGSOFTDEP(vp)) {
390 		if (softdeptrunc == 0 && journaltrunc == 0) {
391 			/*
392 			 * If soft updates cannot handle this truncation,
393 			 * clean up soft dependency data structures and
394 			 * fall through to the synchronous truncation.
395 			 */
396 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
397 				return (error);
398 		} else {
399 			flags = IO_NORMAL | (needextclean ? IO_EXT: 0);
400 			if (journaltrunc)
401 				softdep_journal_freeblocks(ip, cred, length,
402 				    flags);
403 			else
404 				softdep_setup_freeblocks(ip, length, flags);
405 			ASSERT_VOP_LOCKED(vp, "ffs_truncate1");
406 			if (journaltrunc == 0) {
407 				ip->i_flag |= IN_CHANGE | IN_UPDATE;
408 				error = ffs_update(vp, 0);
409 			}
410 			return (error);
411 		}
412 	}
413 	/*
414 	 * Shorten the size of the file. If the last block of the
415 	 * shortened file is unallocated, we must allocate it.
416 	 * Additionally, if the file is not being truncated to a
417 	 * block boundary, the contents of the partial block
418 	 * following the end of the file must be zero'ed in
419 	 * case it ever becomes accessible again because of
420 	 * subsequent file growth. Directories however are not
421 	 * zero'ed as they should grow back initialized to empty.
422 	 */
423 	offset = blkoff(fs, length);
424 	if (blkno != 0 && offset == 0) {
425 		ip->i_size = length;
426 		DIP_SET(ip, i_size, length);
427 	} else {
428 		lbn = lblkno(fs, length);
429 		flags |= BA_CLRBUF;
430 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
431 		if (error)
432 			return (error);
433 		/*
434 		 * When we are doing soft updates and the UFS_BALLOC
435 		 * above fills in a direct block hole with a full sized
436 		 * block that will be truncated down to a fragment below,
437 		 * we must flush out the block dependency with an FSYNC
438 		 * so that we do not get a soft updates inconsistency
439 		 * when we create the fragment below.
440 		 */
441 		if (DOINGSOFTDEP(vp) && lbn < UFS_NDADDR &&
442 		    fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
443 		    (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
444 			return (error);
445 		ip->i_size = length;
446 		DIP_SET(ip, i_size, length);
447 		size = blksize(fs, ip, lbn);
448 		if (vp->v_type != VDIR && offset != 0)
449 			bzero((char *)bp->b_data + offset,
450 			    (u_int)(size - offset));
451 		/* Kirk's code has reallocbuf(bp, size, 1) here */
452 		allocbuf(bp, size);
453 		if (bp->b_bufsize == fs->fs_bsize)
454 			bp->b_flags |= B_CLUSTEROK;
455 		if (flags & IO_SYNC)
456 			bwrite(bp);
457 		else if (DOINGASYNC(vp))
458 			bdwrite(bp);
459 		else
460 			bawrite(bp);
461 	}
462 	/*
463 	 * Calculate index into inode's block list of
464 	 * last direct and indirect blocks (if any)
465 	 * which we want to keep.  Lastblock is -1 when
466 	 * the file is truncated to 0.
467 	 */
468 	lastblock = lblkno(fs, length + fs->fs_bsize - 1) - 1;
469 	lastiblock[SINGLE] = lastblock - UFS_NDADDR;
470 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
471 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
472 	nblocks = btodb(fs->fs_bsize);
473 	/*
474 	 * Update file and block pointers on disk before we start freeing
475 	 * blocks.  If we crash before free'ing blocks below, the blocks
476 	 * will be returned to the free list.  lastiblock values are also
477 	 * normalized to -1 for calls to ffs_indirtrunc below.
478 	 */
479 	for (level = TRIPLE; level >= SINGLE; level--) {
480 		oldblks[UFS_NDADDR + level] = DIP(ip, i_ib[level]);
481 		if (lastiblock[level] < 0) {
482 			DIP_SET(ip, i_ib[level], 0);
483 			lastiblock[level] = -1;
484 		}
485 	}
486 	for (i = 0; i < UFS_NDADDR; i++) {
487 		oldblks[i] = DIP(ip, i_db[i]);
488 		if (i > lastblock)
489 			DIP_SET(ip, i_db[i], 0);
490 	}
491 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
492 	allerror = ffs_update(vp, waitforupdate);
493 
494 	/*
495 	 * Having written the new inode to disk, save its new configuration
496 	 * and put back the old block pointers long enough to process them.
497 	 * Note that we save the new block configuration so we can check it
498 	 * when we are done.
499 	 */
500 	for (i = 0; i < UFS_NDADDR; i++) {
501 		newblks[i] = DIP(ip, i_db[i]);
502 		DIP_SET(ip, i_db[i], oldblks[i]);
503 	}
504 	for (i = 0; i < UFS_NIADDR; i++) {
505 		newblks[UFS_NDADDR + i] = DIP(ip, i_ib[i]);
506 		DIP_SET(ip, i_ib[i], oldblks[UFS_NDADDR + i]);
507 	}
508 	ip->i_size = osize;
509 	DIP_SET(ip, i_size, osize);
510 
511 	error = vtruncbuf(vp, cred, length, fs->fs_bsize);
512 	if (error && (allerror == 0))
513 		allerror = error;
514 
515 	/*
516 	 * Indirect blocks first.
517 	 */
518 	indir_lbn[SINGLE] = -UFS_NDADDR;
519 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
520 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
521 	for (level = TRIPLE; level >= SINGLE; level--) {
522 		bn = DIP(ip, i_ib[level]);
523 		if (bn != 0) {
524 			error = ffs_indirtrunc(ip, indir_lbn[level],
525 			    fsbtodb(fs, bn), lastiblock[level], level, &count);
526 			if (error)
527 				allerror = error;
528 			blocksreleased += count;
529 			if (lastiblock[level] < 0) {
530 				DIP_SET(ip, i_ib[level], 0);
531 				ffs_blkfree(ump, fs, ump->um_devvp, bn,
532 				    fs->fs_bsize, ip->i_number,
533 				    vp->v_type, NULL, SINGLETON_KEY);
534 				blocksreleased += nblocks;
535 			}
536 		}
537 		if (lastiblock[level] >= 0)
538 			goto done;
539 	}
540 
541 	/*
542 	 * All whole direct blocks or frags.
543 	 */
544 	key = ffs_blkrelease_start(ump, ump->um_devvp, ip->i_number);
545 	for (i = UFS_NDADDR - 1; i > lastblock; i--) {
546 		long bsize;
547 
548 		bn = DIP(ip, i_db[i]);
549 		if (bn == 0)
550 			continue;
551 		DIP_SET(ip, i_db[i], 0);
552 		bsize = blksize(fs, ip, i);
553 		ffs_blkfree(ump, fs, ump->um_devvp, bn, bsize, ip->i_number,
554 		    vp->v_type, NULL, key);
555 		blocksreleased += btodb(bsize);
556 	}
557 	ffs_blkrelease_finish(ump, key);
558 	if (lastblock < 0)
559 		goto done;
560 
561 	/*
562 	 * Finally, look for a change in size of the
563 	 * last direct block; release any frags.
564 	 */
565 	bn = DIP(ip, i_db[lastblock]);
566 	if (bn != 0) {
567 		long oldspace, newspace;
568 
569 		/*
570 		 * Calculate amount of space we're giving
571 		 * back as old block size minus new block size.
572 		 */
573 		oldspace = blksize(fs, ip, lastblock);
574 		ip->i_size = length;
575 		DIP_SET(ip, i_size, length);
576 		newspace = blksize(fs, ip, lastblock);
577 		if (newspace == 0)
578 			panic("ffs_truncate: newspace");
579 		if (oldspace - newspace > 0) {
580 			/*
581 			 * Block number of space to be free'd is
582 			 * the old block # plus the number of frags
583 			 * required for the storage we're keeping.
584 			 */
585 			bn += numfrags(fs, newspace);
586 			ffs_blkfree(ump, fs, ump->um_devvp, bn,
587 			   oldspace - newspace, ip->i_number, vp->v_type,
588 			   NULL, SINGLETON_KEY);
589 			blocksreleased += btodb(oldspace - newspace);
590 		}
591 	}
592 done:
593 #ifdef INVARIANTS
594 	for (level = SINGLE; level <= TRIPLE; level++)
595 		if (newblks[UFS_NDADDR + level] != DIP(ip, i_ib[level]))
596 			panic("ffs_truncate1");
597 	for (i = 0; i < UFS_NDADDR; i++)
598 		if (newblks[i] != DIP(ip, i_db[i]))
599 			panic("ffs_truncate2");
600 	BO_LOCK(bo);
601 	if (length == 0 &&
602 	    (fs->fs_magic != FS_UFS2_MAGIC || ip->i_din2->di_extsize == 0) &&
603 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
604 		panic("ffs_truncate3");
605 	BO_UNLOCK(bo);
606 #endif /* INVARIANTS */
607 	/*
608 	 * Put back the real size.
609 	 */
610 	ip->i_size = length;
611 	DIP_SET(ip, i_size, length);
612 	if (DIP(ip, i_blocks) >= blocksreleased)
613 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - blocksreleased);
614 	else	/* sanity */
615 		DIP_SET(ip, i_blocks, 0);
616 	ip->i_flag |= IN_CHANGE;
617 #ifdef QUOTA
618 	(void) chkdq(ip, -blocksreleased, NOCRED, 0);
619 #endif
620 	return (allerror);
621 
622 extclean:
623 	if (journaltrunc)
624 		softdep_journal_freeblocks(ip, cred, length, IO_EXT);
625 	else
626 		softdep_setup_freeblocks(ip, length, IO_EXT);
627 	return (ffs_update(vp, waitforupdate));
628 }
629 
630 /*
631  * Release blocks associated with the inode ip and stored in the indirect
632  * block bn.  Blocks are free'd in LIFO order up to (but not including)
633  * lastbn.  If level is greater than SINGLE, the block is an indirect block
634  * and recursive calls to indirtrunc must be used to cleanse other indirect
635  * blocks.
636  */
637 static int
638 ffs_indirtrunc(ip, lbn, dbn, lastbn, level, countp)
639 	struct inode *ip;
640 	ufs2_daddr_t lbn, lastbn;
641 	ufs2_daddr_t dbn;
642 	int level;
643 	ufs2_daddr_t *countp;
644 {
645 	struct buf *bp;
646 	struct fs *fs;
647 	struct ufsmount *ump;
648 	struct vnode *vp;
649 	caddr_t copy = NULL;
650 	u_long key;
651 	int i, nblocks, error = 0, allerror = 0;
652 	ufs2_daddr_t nb, nlbn, last;
653 	ufs2_daddr_t blkcount, factor, blocksreleased = 0;
654 	ufs1_daddr_t *bap1 = NULL;
655 	ufs2_daddr_t *bap2 = NULL;
656 #define BAP(ip, i) (I_IS_UFS1(ip) ? bap1[i] : bap2[i])
657 
658 	fs = ITOFS(ip);
659 	ump = ITOUMP(ip);
660 
661 	/*
662 	 * Calculate index in current block of last
663 	 * block to be kept.  -1 indicates the entire
664 	 * block so we need not calculate the index.
665 	 */
666 	factor = lbn_offset(fs, level);
667 	last = lastbn;
668 	if (lastbn > 0)
669 		last /= factor;
670 	nblocks = btodb(fs->fs_bsize);
671 	/*
672 	 * Get buffer of block pointers, zero those entries corresponding
673 	 * to blocks to be free'd, and update on disk copy first.  Since
674 	 * double(triple) indirect before single(double) indirect, calls
675 	 * to bmap on these blocks will fail.  However, we already have
676 	 * the on disk address, so we have to set the b_blkno field
677 	 * explicitly instead of letting bread do everything for us.
678 	 */
679 	vp = ITOV(ip);
680 	bp = getblk(vp, lbn, (int)fs->fs_bsize, 0, 0, 0);
681 	if ((bp->b_flags & B_CACHE) == 0) {
682 #ifdef RACCT
683 		if (racct_enable) {
684 			PROC_LOCK(curproc);
685 			racct_add_buf(curproc, bp, 0);
686 			PROC_UNLOCK(curproc);
687 		}
688 #endif /* RACCT */
689 		curthread->td_ru.ru_inblock++;	/* pay for read */
690 		bp->b_iocmd = BIO_READ;
691 		bp->b_flags &= ~B_INVAL;
692 		bp->b_ioflags &= ~BIO_ERROR;
693 		if (bp->b_bcount > bp->b_bufsize)
694 			panic("ffs_indirtrunc: bad buffer size");
695 		bp->b_blkno = dbn;
696 		vfs_busy_pages(bp, 0);
697 		bp->b_iooffset = dbtob(bp->b_blkno);
698 		bstrategy(bp);
699 		error = bufwait(bp);
700 	}
701 	if (error) {
702 		brelse(bp);
703 		*countp = 0;
704 		return (error);
705 	}
706 
707 	if (I_IS_UFS1(ip))
708 		bap1 = (ufs1_daddr_t *)bp->b_data;
709 	else
710 		bap2 = (ufs2_daddr_t *)bp->b_data;
711 	if (lastbn != -1) {
712 		copy = malloc(fs->fs_bsize, M_TEMP, M_WAITOK);
713 		bcopy((caddr_t)bp->b_data, copy, (u_int)fs->fs_bsize);
714 		for (i = last + 1; i < NINDIR(fs); i++)
715 			if (I_IS_UFS1(ip))
716 				bap1[i] = 0;
717 			else
718 				bap2[i] = 0;
719 		if (DOINGASYNC(vp)) {
720 			bdwrite(bp);
721 		} else {
722 			error = bwrite(bp);
723 			if (error)
724 				allerror = error;
725 		}
726 		if (I_IS_UFS1(ip))
727 			bap1 = (ufs1_daddr_t *)copy;
728 		else
729 			bap2 = (ufs2_daddr_t *)copy;
730 	}
731 
732 	/*
733 	 * Recursively free totally unused blocks.
734 	 */
735 	key = ffs_blkrelease_start(ump, ITODEVVP(ip), ip->i_number);
736 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
737 	    i--, nlbn += factor) {
738 		nb = BAP(ip, i);
739 		if (nb == 0)
740 			continue;
741 		if (level > SINGLE) {
742 			if ((error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
743 			    (ufs2_daddr_t)-1, level - 1, &blkcount)) != 0)
744 				allerror = error;
745 			blocksreleased += blkcount;
746 		}
747 		ffs_blkfree(ump, fs, ITODEVVP(ip), nb, fs->fs_bsize,
748 		    ip->i_number, vp->v_type, NULL, key);
749 		blocksreleased += nblocks;
750 	}
751 	ffs_blkrelease_finish(ump, key);
752 
753 	/*
754 	 * Recursively free last partial block.
755 	 */
756 	if (level > SINGLE && lastbn >= 0) {
757 		last = lastbn % factor;
758 		nb = BAP(ip, i);
759 		if (nb != 0) {
760 			error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
761 			    last, level - 1, &blkcount);
762 			if (error)
763 				allerror = error;
764 			blocksreleased += blkcount;
765 		}
766 	}
767 	if (copy != NULL) {
768 		free(copy, M_TEMP);
769 	} else {
770 		bp->b_flags |= B_INVAL | B_NOCACHE;
771 		brelse(bp);
772 	}
773 
774 	*countp = blocksreleased;
775 	return (allerror);
776 }
777 
778 int
779 ffs_rdonly(struct inode *ip)
780 {
781 
782 	return (ITOFS(ip)->fs_ronly != 0);
783 }
784 
785