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