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