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