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