xref: /freebsd/sys/ufs/ffs/ffs_inode.c (revision a0409676120c1e558d0ade943019934e0f15118d)
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 &&
333 	    (ip->i_size < vp->v_mount->mnt_maxsymlinklen ||
334 	     datablocks == 0)) {
335 #ifdef INVARIANTS
336 		if (length != 0)
337 			panic("ffs_truncate: partial truncate of symlink");
338 #endif
339 		bzero(SHORTLINK(ip), (u_int)ip->i_size);
340 		ip->i_size = 0;
341 		DIP_SET(ip, i_size, 0);
342 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
343 		if (needextclean)
344 			goto extclean;
345 		return (ffs_update(vp, waitforupdate));
346 	}
347 	if (ip->i_size == length) {
348 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
349 		if (needextclean)
350 			goto extclean;
351 		return (ffs_update(vp, 0));
352 	}
353 	if (fs->fs_ronly)
354 		panic("ffs_truncate: read-only filesystem");
355 	if (IS_SNAPSHOT(ip))
356 		ffs_snapremove(vp);
357 	cluster_init_vn(&ip->i_clusterw);
358 	osize = ip->i_size;
359 	/*
360 	 * Lengthen the size of the file. We must ensure that the
361 	 * last byte of the file is allocated. Since the smallest
362 	 * value of osize is 0, length will be at least 1.
363 	 */
364 	if (osize < length) {
365 		vnode_pager_setsize(vp, length);
366 		flags |= BA_CLRBUF;
367 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
368 		if (error) {
369 			vnode_pager_setsize(vp, osize);
370 			return (error);
371 		}
372 		ip->i_size = length;
373 		DIP_SET(ip, i_size, length);
374 		if (bp->b_bufsize == fs->fs_bsize)
375 			bp->b_flags |= B_CLUSTEROK;
376 		ffs_inode_bwrite(vp, bp, flags);
377 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
378 		return (ffs_update(vp, waitforupdate));
379 	}
380 	/*
381 	 * Lookup block number for a given offset. Zero length files
382 	 * have no blocks, so return a blkno of -1.
383 	 */
384 	lbn = lblkno(fs, length - 1);
385 	if (length == 0) {
386 		blkno = -1;
387 	} else if (lbn < UFS_NDADDR) {
388 		blkno = DIP(ip, i_db[lbn]);
389 	} else {
390 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
391 		    cred, BA_METAONLY, &bp);
392 		if (error)
393 			return (error);
394 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
395 		if (I_IS_UFS1(ip))
396 			blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
397 		else
398 			blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
399 		/*
400 		 * If the block number is non-zero, then the indirect block
401 		 * must have been previously allocated and need not be written.
402 		 * If the block number is zero, then we may have allocated
403 		 * the indirect block and hence need to write it out.
404 		 */
405 		if (blkno != 0)
406 			brelse(bp);
407 		else if (flags & IO_SYNC)
408 			bwrite(bp);
409 		else
410 			bdwrite(bp);
411 	}
412 	/*
413 	 * If the block number at the new end of the file is zero,
414 	 * then we must allocate it to ensure that the last block of
415 	 * the file is allocated. Soft updates does not handle this
416 	 * case, so here we have to clean up the soft updates data
417 	 * structures describing the allocation past the truncation
418 	 * point. Finding and deallocating those structures is a lot of
419 	 * work. Since partial truncation with a hole at the end occurs
420 	 * rarely, we solve the problem by syncing the file so that it
421 	 * will have no soft updates data structures left.
422 	 */
423 	if (blkno == 0 && (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
424 		return (error);
425 	if (blkno != 0 && DOINGSOFTDEP(vp)) {
426 		if (softdeptrunc == 0 && journaltrunc == 0) {
427 			/*
428 			 * If soft updates cannot handle this truncation,
429 			 * clean up soft dependency data structures and
430 			 * fall through to the synchronous truncation.
431 			 */
432 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
433 				return (error);
434 		} else {
435 			flags = IO_NORMAL | (needextclean ? IO_EXT: 0);
436 			if (journaltrunc)
437 				softdep_journal_freeblocks(ip, cred, length,
438 				    flags);
439 			else
440 				softdep_setup_freeblocks(ip, length, flags);
441 			ASSERT_VOP_LOCKED(vp, "ffs_truncate1");
442 			if (journaltrunc == 0) {
443 				UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
444 				error = ffs_update(vp, 0);
445 			}
446 			return (error);
447 		}
448 	}
449 	/*
450 	 * Shorten the size of the file. If the last block of the
451 	 * shortened file is unallocated, we must allocate it.
452 	 * Additionally, if the file is not being truncated to a
453 	 * block boundary, the contents of the partial block
454 	 * following the end of the file must be zero'ed in
455 	 * case it ever becomes accessible again because of
456 	 * subsequent file growth. Directories however are not
457 	 * zero'ed as they should grow back initialized to empty.
458 	 */
459 	offset = blkoff(fs, length);
460 	if (blkno != 0 && offset == 0) {
461 		ip->i_size = length;
462 		DIP_SET(ip, i_size, length);
463 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
464 #ifdef UFS_DIRHASH
465 		if (vp->v_type == VDIR && ip->i_dirhash != NULL)
466 			ufsdirhash_dirtrunc(ip, length);
467 #endif
468 	} else {
469 		lbn = lblkno(fs, length);
470 		flags |= BA_CLRBUF;
471 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
472 		if (error)
473 			return (error);
474 		ffs_inode_bwrite(vp, bp, flags);
475 
476 		/*
477 		 * When we are doing soft updates and the UFS_BALLOC
478 		 * above fills in a direct block hole with a full sized
479 		 * block that will be truncated down to a fragment below,
480 		 * we must flush out the block dependency with an FSYNC
481 		 * so that we do not get a soft updates inconsistency
482 		 * when we create the fragment below.
483 		 */
484 		if (DOINGSOFTDEP(vp) && lbn < UFS_NDADDR &&
485 		    fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
486 		    (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
487 			return (error);
488 
489 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
490 		if (error)
491 			return (error);
492 		ip->i_size = length;
493 		DIP_SET(ip, i_size, length);
494 #ifdef UFS_DIRHASH
495 		if (vp->v_type == VDIR && ip->i_dirhash != NULL)
496 			ufsdirhash_dirtrunc(ip, length);
497 #endif
498 		size = blksize(fs, ip, lbn);
499 		if (vp->v_type != VDIR && offset != 0)
500 			bzero((char *)bp->b_data + offset,
501 			    (u_int)(size - offset));
502 		/* Kirk's code has reallocbuf(bp, size, 1) here */
503 		allocbuf(bp, size);
504 		if (bp->b_bufsize == fs->fs_bsize)
505 			bp->b_flags |= B_CLUSTEROK;
506 		ffs_inode_bwrite(vp, bp, flags);
507 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
508 	}
509 	/*
510 	 * Calculate index into inode's block list of
511 	 * last direct and indirect blocks (if any)
512 	 * which we want to keep.  Lastblock is -1 when
513 	 * the file is truncated to 0.
514 	 */
515 	lastblock = lblkno(fs, length + fs->fs_bsize - 1) - 1;
516 	lastiblock[SINGLE] = lastblock - UFS_NDADDR;
517 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
518 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
519 	nblocks = btodb(fs->fs_bsize);
520 	/*
521 	 * Update file and block pointers on disk before we start freeing
522 	 * blocks.  If we crash before free'ing blocks below, the blocks
523 	 * will be returned to the free list.  lastiblock values are also
524 	 * normalized to -1 for calls to ffs_indirtrunc below.
525 	 */
526 	for (level = TRIPLE; level >= SINGLE; level--) {
527 		oldblks[UFS_NDADDR + level] = DIP(ip, i_ib[level]);
528 		if (lastiblock[level] < 0) {
529 			DIP_SET(ip, i_ib[level], 0);
530 			lastiblock[level] = -1;
531 		}
532 	}
533 	for (i = 0; i < UFS_NDADDR; i++) {
534 		oldblks[i] = DIP(ip, i_db[i]);
535 		if (i > lastblock)
536 			DIP_SET(ip, i_db[i], 0);
537 	}
538 	UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
539 	allerror = ffs_update(vp, waitforupdate);
540 
541 	/*
542 	 * Having written the new inode to disk, save its new configuration
543 	 * and put back the old block pointers long enough to process them.
544 	 * Note that we save the new block configuration so we can check it
545 	 * when we are done.
546 	 */
547 	for (i = 0; i < UFS_NDADDR; i++) {
548 		newblks[i] = DIP(ip, i_db[i]);
549 		DIP_SET(ip, i_db[i], oldblks[i]);
550 	}
551 	for (i = 0; i < UFS_NIADDR; i++) {
552 		newblks[UFS_NDADDR + i] = DIP(ip, i_ib[i]);
553 		DIP_SET(ip, i_ib[i], oldblks[UFS_NDADDR + i]);
554 	}
555 	ip->i_size = osize;
556 	DIP_SET(ip, i_size, osize);
557 	UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
558 
559 	error = vtruncbuf(vp, length, fs->fs_bsize);
560 	if (error && (allerror == 0))
561 		allerror = error;
562 
563 	/*
564 	 * Indirect blocks first.
565 	 */
566 	indir_lbn[SINGLE] = -UFS_NDADDR;
567 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
568 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
569 	for (level = TRIPLE; level >= SINGLE; level--) {
570 		bn = DIP(ip, i_ib[level]);
571 		if (bn != 0) {
572 			error = ffs_indirtrunc(ip, indir_lbn[level],
573 			    fsbtodb(fs, bn), lastiblock[level], level, &count);
574 			if (error)
575 				allerror = error;
576 			blocksreleased += count;
577 			if (lastiblock[level] < 0) {
578 				DIP_SET(ip, i_ib[level], 0);
579 				ffs_blkfree(ump, fs, ump->um_devvp, bn,
580 				    fs->fs_bsize, ip->i_number,
581 				    vp->v_type, NULL, SINGLETON_KEY);
582 				blocksreleased += nblocks;
583 			}
584 		}
585 		if (lastiblock[level] >= 0)
586 			goto done;
587 	}
588 
589 	/*
590 	 * All whole direct blocks or frags.
591 	 */
592 	key = ffs_blkrelease_start(ump, ump->um_devvp, ip->i_number);
593 	for (i = UFS_NDADDR - 1; i > lastblock; i--) {
594 		long bsize;
595 
596 		bn = DIP(ip, i_db[i]);
597 		if (bn == 0)
598 			continue;
599 		DIP_SET(ip, i_db[i], 0);
600 		bsize = blksize(fs, ip, i);
601 		ffs_blkfree(ump, fs, ump->um_devvp, bn, bsize, ip->i_number,
602 		    vp->v_type, NULL, key);
603 		blocksreleased += btodb(bsize);
604 	}
605 	ffs_blkrelease_finish(ump, key);
606 	if (lastblock < 0)
607 		goto done;
608 
609 	/*
610 	 * Finally, look for a change in size of the
611 	 * last direct block; release any frags.
612 	 */
613 	bn = DIP(ip, i_db[lastblock]);
614 	if (bn != 0) {
615 		long oldspace, newspace;
616 
617 		/*
618 		 * Calculate amount of space we're giving
619 		 * back as old block size minus new block size.
620 		 */
621 		oldspace = blksize(fs, ip, lastblock);
622 		ip->i_size = length;
623 		DIP_SET(ip, i_size, length);
624 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
625 		newspace = blksize(fs, ip, lastblock);
626 		if (newspace == 0)
627 			panic("ffs_truncate: newspace");
628 		if (oldspace - newspace > 0) {
629 			/*
630 			 * Block number of space to be free'd is
631 			 * the old block # plus the number of frags
632 			 * required for the storage we're keeping.
633 			 */
634 			bn += numfrags(fs, newspace);
635 			ffs_blkfree(ump, fs, ump->um_devvp, bn,
636 			   oldspace - newspace, ip->i_number, vp->v_type,
637 			   NULL, SINGLETON_KEY);
638 			blocksreleased += btodb(oldspace - newspace);
639 		}
640 	}
641 done:
642 #ifdef INVARIANTS
643 	for (level = SINGLE; level <= TRIPLE; level++)
644 		if (newblks[UFS_NDADDR + level] != DIP(ip, i_ib[level]))
645 			panic("ffs_truncate1: level %d newblks %jd != i_ib %jd",
646 			    level, (intmax_t)newblks[UFS_NDADDR + level],
647 			    (intmax_t)DIP(ip, i_ib[level]));
648 	for (i = 0; i < UFS_NDADDR; i++)
649 		if (newblks[i] != DIP(ip, i_db[i]))
650 			panic("ffs_truncate2: blkno %d newblks %jd != i_db %jd",
651 			    i, (intmax_t)newblks[UFS_NDADDR + level],
652 			    (intmax_t)DIP(ip, i_ib[level]));
653 	BO_LOCK(bo);
654 	if (length == 0 &&
655 	    (fs->fs_magic != FS_UFS2_MAGIC || ip->i_din2->di_extsize == 0) &&
656 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
657 		panic("ffs_truncate3: vp = %p, buffers: dirty = %d, clean = %d",
658 			vp, bo->bo_dirty.bv_cnt, bo->bo_clean.bv_cnt);
659 	BO_UNLOCK(bo);
660 #endif /* INVARIANTS */
661 	/*
662 	 * Put back the real size.
663 	 */
664 	ip->i_size = length;
665 	DIP_SET(ip, i_size, length);
666 	if (DIP(ip, i_blocks) >= blocksreleased)
667 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - blocksreleased);
668 	else	/* sanity */
669 		DIP_SET(ip, i_blocks, 0);
670 	UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
671 #ifdef QUOTA
672 	(void) chkdq(ip, -blocksreleased, NOCRED, FORCE);
673 #endif
674 	return (allerror);
675 
676 extclean:
677 	if (journaltrunc)
678 		softdep_journal_freeblocks(ip, cred, length, IO_EXT);
679 	else
680 		softdep_setup_freeblocks(ip, length, IO_EXT);
681 	return (ffs_update(vp, waitforupdate));
682 }
683 
684 /*
685  * Release blocks associated with the inode ip and stored in the indirect
686  * block bn.  Blocks are free'd in LIFO order up to (but not including)
687  * lastbn.  If level is greater than SINGLE, the block is an indirect block
688  * and recursive calls to indirtrunc must be used to cleanse other indirect
689  * blocks.
690  */
691 static int
692 ffs_indirtrunc(ip, lbn, dbn, lastbn, level, countp)
693 	struct inode *ip;
694 	ufs2_daddr_t lbn, lastbn;
695 	ufs2_daddr_t dbn;
696 	int level;
697 	ufs2_daddr_t *countp;
698 {
699 	struct buf *bp;
700 	struct fs *fs;
701 	struct ufsmount *ump;
702 	struct vnode *vp;
703 	caddr_t copy = NULL;
704 	u_long key;
705 	int i, nblocks, error = 0, allerror = 0;
706 	ufs2_daddr_t nb, nlbn, last;
707 	ufs2_daddr_t blkcount, factor, blocksreleased = 0;
708 	ufs1_daddr_t *bap1 = NULL;
709 	ufs2_daddr_t *bap2 = NULL;
710 #define BAP(ip, i) (I_IS_UFS1(ip) ? bap1[i] : bap2[i])
711 
712 	fs = ITOFS(ip);
713 	ump = ITOUMP(ip);
714 
715 	/*
716 	 * Calculate index in current block of last
717 	 * block to be kept.  -1 indicates the entire
718 	 * block so we need not calculate the index.
719 	 */
720 	factor = lbn_offset(fs, level);
721 	last = lastbn;
722 	if (lastbn > 0)
723 		last /= factor;
724 	nblocks = btodb(fs->fs_bsize);
725 	/*
726 	 * Get buffer of block pointers, zero those entries corresponding
727 	 * to blocks to be free'd, and update on disk copy first.  Since
728 	 * double(triple) indirect before single(double) indirect, calls
729 	 * to VOP_BMAP() on these blocks will fail.  However, we already
730 	 * have the on-disk address, so we just pass it to bread() instead
731 	 * of having bread() attempt to calculate it using VOP_BMAP().
732 	 */
733 	vp = ITOV(ip);
734 	error = ffs_breadz(ump, vp, lbn, dbn, (int)fs->fs_bsize, NULL, NULL, 0,
735 	    NOCRED, 0, NULL, &bp);
736 	if (error) {
737 		*countp = 0;
738 		return (error);
739 	}
740 
741 	if (I_IS_UFS1(ip))
742 		bap1 = (ufs1_daddr_t *)bp->b_data;
743 	else
744 		bap2 = (ufs2_daddr_t *)bp->b_data;
745 	if (lastbn != -1) {
746 		copy = malloc(fs->fs_bsize, M_TEMP, M_WAITOK);
747 		bcopy((caddr_t)bp->b_data, copy, (u_int)fs->fs_bsize);
748 		for (i = last + 1; i < NINDIR(fs); i++)
749 			if (I_IS_UFS1(ip))
750 				bap1[i] = 0;
751 			else
752 				bap2[i] = 0;
753 		if (DOINGASYNC(vp)) {
754 			bdwrite(bp);
755 		} else {
756 			error = bwrite(bp);
757 			if (error)
758 				allerror = error;
759 		}
760 		if (I_IS_UFS1(ip))
761 			bap1 = (ufs1_daddr_t *)copy;
762 		else
763 			bap2 = (ufs2_daddr_t *)copy;
764 	}
765 
766 	/*
767 	 * Recursively free totally unused blocks.
768 	 */
769 	key = ffs_blkrelease_start(ump, ITODEVVP(ip), ip->i_number);
770 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
771 	    i--, nlbn += factor) {
772 		nb = BAP(ip, i);
773 		if (nb == 0)
774 			continue;
775 		if (level > SINGLE) {
776 			if ((error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
777 			    (ufs2_daddr_t)-1, level - 1, &blkcount)) != 0)
778 				allerror = error;
779 			blocksreleased += blkcount;
780 		}
781 		ffs_blkfree(ump, fs, ITODEVVP(ip), nb, fs->fs_bsize,
782 		    ip->i_number, vp->v_type, NULL, key);
783 		blocksreleased += nblocks;
784 	}
785 	ffs_blkrelease_finish(ump, key);
786 
787 	/*
788 	 * Recursively free last partial block.
789 	 */
790 	if (level > SINGLE && lastbn >= 0) {
791 		last = lastbn % factor;
792 		nb = BAP(ip, i);
793 		if (nb != 0) {
794 			error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
795 			    last, level - 1, &blkcount);
796 			if (error)
797 				allerror = error;
798 			blocksreleased += blkcount;
799 		}
800 	}
801 	if (copy != NULL) {
802 		free(copy, M_TEMP);
803 	} else {
804 		bp->b_flags |= B_INVAL | B_NOCACHE;
805 		brelse(bp);
806 	}
807 
808 	*countp = blocksreleased;
809 	return (allerror);
810 }
811 
812 int
813 ffs_rdonly(struct inode *ip)
814 {
815 
816 	return (ITOFS(ip)->fs_ronly != 0);
817 }
818