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