xref: /freebsd/sys/ufs/ffs/ffs_inode.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ffs_inode.c	8.13 (Berkeley) 4/21/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_quota.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bio.h>
42 #include <sys/buf.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/proc.h>
46 #include <sys/racct.h>
47 #include <sys/random.h>
48 #include <sys/resourcevar.h>
49 #include <sys/rwlock.h>
50 #include <sys/stat.h>
51 #include <sys/vmmeter.h>
52 #include <sys/vnode.h>
53 
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_object.h>
57 
58 #include <ufs/ufs/extattr.h>
59 #include <ufs/ufs/quota.h>
60 #include <ufs/ufs/ufsmount.h>
61 #include <ufs/ufs/inode.h>
62 #include <ufs/ufs/ufs_extern.h>
63 
64 #include <ufs/ffs/fs.h>
65 #include <ufs/ffs/ffs_extern.h>
66 
67 static int ffs_indirtrunc(struct inode *, ufs2_daddr_t, ufs2_daddr_t,
68 	    ufs2_daddr_t, int, ufs2_daddr_t *);
69 
70 /*
71  * Update the access, modified, and inode change times as specified by the
72  * IN_ACCESS, IN_UPDATE, and IN_CHANGE flags respectively.  Write the inode
73  * to disk if the IN_MODIFIED flag is set (it may be set initially, or by
74  * the timestamp update).  The IN_LAZYMOD flag is set to force a write
75  * later if not now.  The IN_LAZYACCESS is set instead of IN_MODIFIED if the fs
76  * is currently being suspended (or is suspended) and vnode has been accessed.
77  * If we write now, then clear IN_MODIFIED, IN_LAZYACCESS and IN_LAZYMOD to
78  * reflect the presumably successful write, and if waitfor is set, then wait
79  * for the write to complete.
80  */
81 int
82 ffs_update(vp, waitfor)
83 	struct vnode *vp;
84 	int waitfor;
85 {
86 	struct fs *fs;
87 	struct buf *bp;
88 	struct inode *ip;
89 	int flags, error;
90 
91 	ASSERT_VOP_ELOCKED(vp, "ffs_update");
92 	ufs_itimes(vp);
93 	ip = VTOI(vp);
94 	if ((ip->i_flag & IN_MODIFIED) == 0 && waitfor == 0)
95 		return (0);
96 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
97 	fs = ITOFS(ip);
98 	if (fs->fs_ronly && ITOUMP(ip)->um_fsckpid == 0)
99 		return (0);
100 	/*
101 	 * If we are updating a snapshot and another process is currently
102 	 * writing the buffer containing the inode for this snapshot then
103 	 * a deadlock can occur when it tries to check the snapshot to see
104 	 * if that block needs to be copied. Thus when updating a snapshot
105 	 * we check to see if the buffer is already locked, and if it is
106 	 * we drop the snapshot lock until the buffer has been written
107 	 * and is available to us. We have to grab a reference to the
108 	 * snapshot vnode to prevent it from being removed while we are
109 	 * waiting for the buffer.
110 	 */
111 	flags = 0;
112 	if (IS_SNAPSHOT(ip))
113 		flags = GB_LOCK_NOWAIT;
114 loop:
115 	error = bread_gb(ITODEVVP(ip),
116 	     fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
117 	     (int) fs->fs_bsize, NOCRED, flags, &bp);
118 	if (error != 0) {
119 		if (error != EBUSY)
120 			return (error);
121 		KASSERT((IS_SNAPSHOT(ip)), ("EBUSY from non-snapshot"));
122 		/*
123 		 * Wait for our inode block to become available.
124 		 *
125 		 * Hold a reference to the vnode to protect against
126 		 * ffs_snapgone(). Since we hold a reference, it can only
127 		 * get reclaimed (VI_DOOMED flag) in a forcible downgrade
128 		 * or unmount. For an unmount, the entire filesystem will be
129 		 * gone, so we cannot attempt to touch anything associated
130 		 * with it while the vnode is unlocked; all we can do is
131 		 * pause briefly and try again. If when we relock the vnode
132 		 * we discover that it has been reclaimed, updating it is no
133 		 * longer necessary and we can just return an error.
134 		 */
135 		vref(vp);
136 		VOP_UNLOCK(vp, 0);
137 		pause("ffsupd", 1);
138 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
139 		vrele(vp);
140 		if ((vp->v_iflag & VI_DOOMED) != 0)
141 			return (ENOENT);
142 		goto loop;
143 	}
144 	if (DOINGSOFTDEP(vp))
145 		softdep_update_inodeblock(ip, bp, waitfor);
146 	else if (ip->i_effnlink != ip->i_nlink)
147 		panic("ffs_update: bad link cnt");
148 	if (I_IS_UFS1(ip)) {
149 		*((struct ufs1_dinode *)bp->b_data +
150 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
151 		/*
152 		 * XXX: FIX? The entropy here is desirable,
153 		 * but the harvesting may be expensive
154 		 */
155 		random_harvest_queue(&(ip->i_din1), sizeof(ip->i_din1), RANDOM_FS_ATIME);
156 	} else {
157 		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 	if (journaltrunc == 0 && DOINGSOFTDEP(vp) && length == 0)
248 		softdeptrunc = !softdep_slowdown(vp);
249 	extblocks = 0;
250 	datablocks = DIP(ip, i_blocks);
251 	if (fs->fs_magic == FS_UFS2_MAGIC && ip->i_din2->di_extsize > 0) {
252 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
253 		datablocks -= extblocks;
254 	}
255 	if ((flags & IO_EXT) && extblocks > 0) {
256 		if (length != 0)
257 			panic("ffs_truncate: partial trunc of extdata");
258 		if (softdeptrunc || journaltrunc) {
259 			if ((flags & IO_NORMAL) == 0)
260 				goto extclean;
261 			needextclean = 1;
262 		} else {
263 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
264 				return (error);
265 #ifdef QUOTA
266 			(void) chkdq(ip, -extblocks, NOCRED, 0);
267 #endif
268 			vinvalbuf(vp, V_ALT, 0, 0);
269 			vn_pages_remove(vp,
270 			    OFF_TO_IDX(lblktosize(fs, -extblocks)), 0);
271 			osize = ip->i_din2->di_extsize;
272 			ip->i_din2->di_blocks -= extblocks;
273 			ip->i_din2->di_extsize = 0;
274 			for (i = 0; i < UFS_NXADDR; i++) {
275 				oldblks[i] = ip->i_din2->di_extb[i];
276 				ip->i_din2->di_extb[i] = 0;
277 			}
278 			ip->i_flag |= IN_CHANGE;
279 			if ((error = ffs_update(vp, waitforupdate)))
280 				return (error);
281 			for (i = 0; i < UFS_NXADDR; i++) {
282 				if (oldblks[i] == 0)
283 					continue;
284 				ffs_blkfree(ump, fs, ITODEVVP(ip), oldblks[i],
285 				    sblksize(fs, osize, i), ip->i_number,
286 				    vp->v_type, NULL, SINGLETON_KEY);
287 			}
288 		}
289 	}
290 	if ((flags & IO_NORMAL) == 0)
291 		return (0);
292 	if (vp->v_type == VLNK &&
293 	    (ip->i_size < vp->v_mount->mnt_maxsymlinklen ||
294 	     datablocks == 0)) {
295 #ifdef INVARIANTS
296 		if (length != 0)
297 			panic("ffs_truncate: partial truncate of symlink");
298 #endif
299 		bzero(SHORTLINK(ip), (u_int)ip->i_size);
300 		ip->i_size = 0;
301 		DIP_SET(ip, i_size, 0);
302 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
303 		if (needextclean)
304 			goto extclean;
305 		return (ffs_update(vp, waitforupdate));
306 	}
307 	if (ip->i_size == length) {
308 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
309 		if (needextclean)
310 			goto extclean;
311 		return (ffs_update(vp, 0));
312 	}
313 	if (fs->fs_ronly)
314 		panic("ffs_truncate: read-only filesystem");
315 	if (IS_SNAPSHOT(ip))
316 		ffs_snapremove(vp);
317 	vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
318 	osize = ip->i_size;
319 	/*
320 	 * Lengthen the size of the file. We must ensure that the
321 	 * last byte of the file is allocated. Since the smallest
322 	 * value of osize is 0, length will be at least 1.
323 	 */
324 	if (osize < length) {
325 		vnode_pager_setsize(vp, length);
326 		flags |= BA_CLRBUF;
327 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
328 		if (error) {
329 			vnode_pager_setsize(vp, osize);
330 			return (error);
331 		}
332 		ip->i_size = length;
333 		DIP_SET(ip, i_size, length);
334 		if (bp->b_bufsize == fs->fs_bsize)
335 			bp->b_flags |= B_CLUSTEROK;
336 		if (flags & IO_SYNC)
337 			bwrite(bp);
338 		else if (DOINGASYNC(vp))
339 			bdwrite(bp);
340 		else
341 			bawrite(bp);
342 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
343 		return (ffs_update(vp, waitforupdate));
344 	}
345 	/*
346 	 * Lookup block number for a given offset. Zero length files
347 	 * have no blocks, so return a blkno of -1.
348 	 */
349 	lbn = lblkno(fs, length - 1);
350 	if (length == 0) {
351 		blkno = -1;
352 	} else if (lbn < UFS_NDADDR) {
353 		blkno = DIP(ip, i_db[lbn]);
354 	} else {
355 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
356 		    cred, BA_METAONLY, &bp);
357 		if (error)
358 			return (error);
359 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
360 		if (I_IS_UFS1(ip))
361 			blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
362 		else
363 			blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
364 		/*
365 		 * If the block number is non-zero, then the indirect block
366 		 * must have been previously allocated and need not be written.
367 		 * If the block number is zero, then we may have allocated
368 		 * the indirect block and hence need to write it out.
369 		 */
370 		if (blkno != 0)
371 			brelse(bp);
372 		else if (flags & IO_SYNC)
373 			bwrite(bp);
374 		else
375 			bdwrite(bp);
376 	}
377 	/*
378 	 * If the block number at the new end of the file is zero,
379 	 * then we must allocate it to ensure that the last block of
380 	 * the file is allocated. Soft updates does not handle this
381 	 * case, so here we have to clean up the soft updates data
382 	 * structures describing the allocation past the truncation
383 	 * point. Finding and deallocating those structures is a lot of
384 	 * work. Since partial truncation with a hole at the end occurs
385 	 * rarely, we solve the problem by syncing the file so that it
386 	 * will have no soft updates data structures left.
387 	 */
388 	if (blkno == 0 && (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
389 		return (error);
390 	if (blkno != 0 && DOINGSOFTDEP(vp)) {
391 		if (softdeptrunc == 0 && journaltrunc == 0) {
392 			/*
393 			 * If soft updates cannot handle this truncation,
394 			 * clean up soft dependency data structures and
395 			 * fall through to the synchronous truncation.
396 			 */
397 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
398 				return (error);
399 		} else {
400 			flags = IO_NORMAL | (needextclean ? IO_EXT: 0);
401 			if (journaltrunc)
402 				softdep_journal_freeblocks(ip, cred, length,
403 				    flags);
404 			else
405 				softdep_setup_freeblocks(ip, length, flags);
406 			ASSERT_VOP_LOCKED(vp, "ffs_truncate1");
407 			if (journaltrunc == 0) {
408 				ip->i_flag |= IN_CHANGE | IN_UPDATE;
409 				error = ffs_update(vp, 0);
410 			}
411 			return (error);
412 		}
413 	}
414 	/*
415 	 * Shorten the size of the file. If the last block of the
416 	 * shortened file is unallocated, we must allocate it.
417 	 * Additionally, if the file is not being truncated to a
418 	 * block boundary, the contents of the partial block
419 	 * following the end of the file must be zero'ed in
420 	 * case it ever becomes accessible again because of
421 	 * subsequent file growth. Directories however are not
422 	 * zero'ed as they should grow back initialized to empty.
423 	 */
424 	offset = blkoff(fs, length);
425 	if (blkno != 0 && offset == 0) {
426 		ip->i_size = length;
427 		DIP_SET(ip, i_size, length);
428 	} else {
429 		lbn = lblkno(fs, length);
430 		flags |= BA_CLRBUF;
431 		error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
432 		if (error)
433 			return (error);
434 		/*
435 		 * When we are doing soft updates and the UFS_BALLOC
436 		 * above fills in a direct block hole with a full sized
437 		 * block that will be truncated down to a fragment below,
438 		 * we must flush out the block dependency with an FSYNC
439 		 * so that we do not get a soft updates inconsistency
440 		 * when we create the fragment below.
441 		 */
442 		if (DOINGSOFTDEP(vp) && lbn < UFS_NDADDR &&
443 		    fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
444 		    (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
445 			return (error);
446 		ip->i_size = length;
447 		DIP_SET(ip, i_size, length);
448 		size = blksize(fs, ip, lbn);
449 		if (vp->v_type != VDIR && offset != 0)
450 			bzero((char *)bp->b_data + offset,
451 			    (u_int)(size - offset));
452 		/* Kirk's code has reallocbuf(bp, size, 1) here */
453 		allocbuf(bp, size);
454 		if (bp->b_bufsize == fs->fs_bsize)
455 			bp->b_flags |= B_CLUSTEROK;
456 		if (flags & IO_SYNC)
457 			bwrite(bp);
458 		else if (DOINGASYNC(vp))
459 			bdwrite(bp);
460 		else
461 			bawrite(bp);
462 	}
463 	/*
464 	 * Calculate index into inode's block list of
465 	 * last direct and indirect blocks (if any)
466 	 * which we want to keep.  Lastblock is -1 when
467 	 * the file is truncated to 0.
468 	 */
469 	lastblock = lblkno(fs, length + fs->fs_bsize - 1) - 1;
470 	lastiblock[SINGLE] = lastblock - UFS_NDADDR;
471 	lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
472 	lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
473 	nblocks = btodb(fs->fs_bsize);
474 	/*
475 	 * Update file and block pointers on disk before we start freeing
476 	 * blocks.  If we crash before free'ing blocks below, the blocks
477 	 * will be returned to the free list.  lastiblock values are also
478 	 * normalized to -1 for calls to ffs_indirtrunc below.
479 	 */
480 	for (level = TRIPLE; level >= SINGLE; level--) {
481 		oldblks[UFS_NDADDR + level] = DIP(ip, i_ib[level]);
482 		if (lastiblock[level] < 0) {
483 			DIP_SET(ip, i_ib[level], 0);
484 			lastiblock[level] = -1;
485 		}
486 	}
487 	for (i = 0; i < UFS_NDADDR; i++) {
488 		oldblks[i] = DIP(ip, i_db[i]);
489 		if (i > lastblock)
490 			DIP_SET(ip, i_db[i], 0);
491 	}
492 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
493 	allerror = ffs_update(vp, waitforupdate);
494 
495 	/*
496 	 * Having written the new inode to disk, save its new configuration
497 	 * and put back the old block pointers long enough to process them.
498 	 * Note that we save the new block configuration so we can check it
499 	 * when we are done.
500 	 */
501 	for (i = 0; i < UFS_NDADDR; i++) {
502 		newblks[i] = DIP(ip, i_db[i]);
503 		DIP_SET(ip, i_db[i], oldblks[i]);
504 	}
505 	for (i = 0; i < UFS_NIADDR; i++) {
506 		newblks[UFS_NDADDR + i] = DIP(ip, i_ib[i]);
507 		DIP_SET(ip, i_ib[i], oldblks[UFS_NDADDR + i]);
508 	}
509 	ip->i_size = osize;
510 	DIP_SET(ip, i_size, osize);
511 
512 	error = vtruncbuf(vp, cred, length, fs->fs_bsize);
513 	if (error && (allerror == 0))
514 		allerror = error;
515 
516 	/*
517 	 * Indirect blocks first.
518 	 */
519 	indir_lbn[SINGLE] = -UFS_NDADDR;
520 	indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
521 	indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
522 	for (level = TRIPLE; level >= SINGLE; level--) {
523 		bn = DIP(ip, i_ib[level]);
524 		if (bn != 0) {
525 			error = ffs_indirtrunc(ip, indir_lbn[level],
526 			    fsbtodb(fs, bn), lastiblock[level], level, &count);
527 			if (error)
528 				allerror = error;
529 			blocksreleased += count;
530 			if (lastiblock[level] < 0) {
531 				DIP_SET(ip, i_ib[level], 0);
532 				ffs_blkfree(ump, fs, ump->um_devvp, bn,
533 				    fs->fs_bsize, ip->i_number,
534 				    vp->v_type, NULL, SINGLETON_KEY);
535 				blocksreleased += nblocks;
536 			}
537 		}
538 		if (lastiblock[level] >= 0)
539 			goto done;
540 	}
541 
542 	/*
543 	 * All whole direct blocks or frags.
544 	 */
545 	key = ffs_blkrelease_start(ump, ump->um_devvp, ip->i_number);
546 	for (i = UFS_NDADDR - 1; i > lastblock; i--) {
547 		long bsize;
548 
549 		bn = DIP(ip, i_db[i]);
550 		if (bn == 0)
551 			continue;
552 		DIP_SET(ip, i_db[i], 0);
553 		bsize = blksize(fs, ip, i);
554 		ffs_blkfree(ump, fs, ump->um_devvp, bn, bsize, ip->i_number,
555 		    vp->v_type, NULL, key);
556 		blocksreleased += btodb(bsize);
557 	}
558 	ffs_blkrelease_finish(ump, key);
559 	if (lastblock < 0)
560 		goto done;
561 
562 	/*
563 	 * Finally, look for a change in size of the
564 	 * last direct block; release any frags.
565 	 */
566 	bn = DIP(ip, i_db[lastblock]);
567 	if (bn != 0) {
568 		long oldspace, newspace;
569 
570 		/*
571 		 * Calculate amount of space we're giving
572 		 * back as old block size minus new block size.
573 		 */
574 		oldspace = blksize(fs, ip, lastblock);
575 		ip->i_size = length;
576 		DIP_SET(ip, i_size, length);
577 		newspace = blksize(fs, ip, lastblock);
578 		if (newspace == 0)
579 			panic("ffs_truncate: newspace");
580 		if (oldspace - newspace > 0) {
581 			/*
582 			 * Block number of space to be free'd is
583 			 * the old block # plus the number of frags
584 			 * required for the storage we're keeping.
585 			 */
586 			bn += numfrags(fs, newspace);
587 			ffs_blkfree(ump, fs, ump->um_devvp, bn,
588 			   oldspace - newspace, ip->i_number, vp->v_type,
589 			   NULL, SINGLETON_KEY);
590 			blocksreleased += btodb(oldspace - newspace);
591 		}
592 	}
593 done:
594 #ifdef INVARIANTS
595 	for (level = SINGLE; level <= TRIPLE; level++)
596 		if (newblks[UFS_NDADDR + level] != DIP(ip, i_ib[level]))
597 			panic("ffs_truncate1");
598 	for (i = 0; i < UFS_NDADDR; i++)
599 		if (newblks[i] != DIP(ip, i_db[i]))
600 			panic("ffs_truncate2");
601 	BO_LOCK(bo);
602 	if (length == 0 &&
603 	    (fs->fs_magic != FS_UFS2_MAGIC || ip->i_din2->di_extsize == 0) &&
604 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
605 		panic("ffs_truncate3");
606 	BO_UNLOCK(bo);
607 #endif /* INVARIANTS */
608 	/*
609 	 * Put back the real size.
610 	 */
611 	ip->i_size = length;
612 	DIP_SET(ip, i_size, length);
613 	if (DIP(ip, i_blocks) >= blocksreleased)
614 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - blocksreleased);
615 	else	/* sanity */
616 		DIP_SET(ip, i_blocks, 0);
617 	ip->i_flag |= IN_CHANGE;
618 #ifdef QUOTA
619 	(void) chkdq(ip, -blocksreleased, NOCRED, 0);
620 #endif
621 	return (allerror);
622 
623 extclean:
624 	if (journaltrunc)
625 		softdep_journal_freeblocks(ip, cred, length, IO_EXT);
626 	else
627 		softdep_setup_freeblocks(ip, length, IO_EXT);
628 	return (ffs_update(vp, waitforupdate));
629 }
630 
631 /*
632  * Release blocks associated with the inode ip and stored in the indirect
633  * block bn.  Blocks are free'd in LIFO order up to (but not including)
634  * lastbn.  If level is greater than SINGLE, the block is an indirect block
635  * and recursive calls to indirtrunc must be used to cleanse other indirect
636  * blocks.
637  */
638 static int
639 ffs_indirtrunc(ip, lbn, dbn, lastbn, level, countp)
640 	struct inode *ip;
641 	ufs2_daddr_t lbn, lastbn;
642 	ufs2_daddr_t dbn;
643 	int level;
644 	ufs2_daddr_t *countp;
645 {
646 	struct buf *bp;
647 	struct fs *fs;
648 	struct ufsmount *ump;
649 	struct vnode *vp;
650 	caddr_t copy = NULL;
651 	u_long key;
652 	int i, nblocks, error = 0, allerror = 0;
653 	ufs2_daddr_t nb, nlbn, last;
654 	ufs2_daddr_t blkcount, factor, blocksreleased = 0;
655 	ufs1_daddr_t *bap1 = NULL;
656 	ufs2_daddr_t *bap2 = NULL;
657 #define BAP(ip, i) (I_IS_UFS1(ip) ? bap1[i] : bap2[i])
658 
659 	fs = ITOFS(ip);
660 	ump = ITOUMP(ip);
661 
662 	/*
663 	 * Calculate index in current block of last
664 	 * block to be kept.  -1 indicates the entire
665 	 * block so we need not calculate the index.
666 	 */
667 	factor = lbn_offset(fs, level);
668 	last = lastbn;
669 	if (lastbn > 0)
670 		last /= factor;
671 	nblocks = btodb(fs->fs_bsize);
672 	/*
673 	 * Get buffer of block pointers, zero those entries corresponding
674 	 * to blocks to be free'd, and update on disk copy first.  Since
675 	 * double(triple) indirect before single(double) indirect, calls
676 	 * to bmap on these blocks will fail.  However, we already have
677 	 * the on disk address, so we have to set the b_blkno field
678 	 * explicitly instead of letting bread do everything for us.
679 	 */
680 	vp = ITOV(ip);
681 	bp = getblk(vp, lbn, (int)fs->fs_bsize, 0, 0, 0);
682 	if ((bp->b_flags & B_CACHE) == 0) {
683 #ifdef RACCT
684 		if (racct_enable) {
685 			PROC_LOCK(curproc);
686 			racct_add_buf(curproc, bp, 0);
687 			PROC_UNLOCK(curproc);
688 		}
689 #endif /* RACCT */
690 		curthread->td_ru.ru_inblock++;	/* pay for read */
691 		bp->b_iocmd = BIO_READ;
692 		bp->b_flags &= ~B_INVAL;
693 		bp->b_ioflags &= ~BIO_ERROR;
694 		if (bp->b_bcount > bp->b_bufsize)
695 			panic("ffs_indirtrunc: bad buffer size");
696 		bp->b_blkno = dbn;
697 		vfs_busy_pages(bp, 0);
698 		bp->b_iooffset = dbtob(bp->b_blkno);
699 		bstrategy(bp);
700 		error = bufwait(bp);
701 	}
702 	if (error) {
703 		brelse(bp);
704 		*countp = 0;
705 		return (error);
706 	}
707 
708 	if (I_IS_UFS1(ip))
709 		bap1 = (ufs1_daddr_t *)bp->b_data;
710 	else
711 		bap2 = (ufs2_daddr_t *)bp->b_data;
712 	if (lastbn != -1) {
713 		copy = malloc(fs->fs_bsize, M_TEMP, M_WAITOK);
714 		bcopy((caddr_t)bp->b_data, copy, (u_int)fs->fs_bsize);
715 		for (i = last + 1; i < NINDIR(fs); i++)
716 			if (I_IS_UFS1(ip))
717 				bap1[i] = 0;
718 			else
719 				bap2[i] = 0;
720 		if (DOINGASYNC(vp)) {
721 			bdwrite(bp);
722 		} else {
723 			error = bwrite(bp);
724 			if (error)
725 				allerror = error;
726 		}
727 		if (I_IS_UFS1(ip))
728 			bap1 = (ufs1_daddr_t *)copy;
729 		else
730 			bap2 = (ufs2_daddr_t *)copy;
731 	}
732 
733 	/*
734 	 * Recursively free totally unused blocks.
735 	 */
736 	key = ffs_blkrelease_start(ump, ITODEVVP(ip), ip->i_number);
737 	for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
738 	    i--, nlbn += factor) {
739 		nb = BAP(ip, i);
740 		if (nb == 0)
741 			continue;
742 		if (level > SINGLE) {
743 			if ((error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
744 			    (ufs2_daddr_t)-1, level - 1, &blkcount)) != 0)
745 				allerror = error;
746 			blocksreleased += blkcount;
747 		}
748 		ffs_blkfree(ump, fs, ITODEVVP(ip), nb, fs->fs_bsize,
749 		    ip->i_number, vp->v_type, NULL, key);
750 		blocksreleased += nblocks;
751 	}
752 	ffs_blkrelease_finish(ump, key);
753 
754 	/*
755 	 * Recursively free last partial block.
756 	 */
757 	if (level > SINGLE && lastbn >= 0) {
758 		last = lastbn % factor;
759 		nb = BAP(ip, i);
760 		if (nb != 0) {
761 			error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
762 			    last, level - 1, &blkcount);
763 			if (error)
764 				allerror = error;
765 			blocksreleased += blkcount;
766 		}
767 	}
768 	if (copy != NULL) {
769 		free(copy, M_TEMP);
770 	} else {
771 		bp->b_flags |= B_INVAL | B_NOCACHE;
772 		brelse(bp);
773 	}
774 
775 	*countp = blocksreleased;
776 	return (allerror);
777 }
778 
779 int
780 ffs_rdonly(struct inode *ip)
781 {
782 
783 	return (ITOFS(ip)->fs_ronly != 0);
784 }
785 
786