xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision e9e8876a4d6afc1ad5315faaa191b25121a813d7)
1 /*-
2  * SPDX-License-Identifier: (BSD-2-Clause-FreeBSD AND BSD-3-Clause)
3  *
4  * Copyright (c) 2002 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project by Marshall
8  * Kirk McKusick and Network Associates Laboratories, the Security
9  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
10  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
11  * research program
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Copyright (c) 1982, 1986, 1989, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)ffs_alloc.c	8.18 (Berkeley) 5/26/95
62  */
63 
64 #include <sys/cdefs.h>
65 __FBSDID("$FreeBSD$");
66 
67 #include "opt_quota.h"
68 
69 #include <sys/param.h>
70 #include <sys/capsicum.h>
71 #include <sys/gsb_crc32.h>
72 #include <sys/systm.h>
73 #include <sys/bio.h>
74 #include <sys/buf.h>
75 #include <sys/conf.h>
76 #include <sys/fcntl.h>
77 #include <sys/file.h>
78 #include <sys/filedesc.h>
79 #include <sys/priv.h>
80 #include <sys/proc.h>
81 #include <sys/vnode.h>
82 #include <sys/mount.h>
83 #include <sys/kernel.h>
84 #include <sys/syscallsubr.h>
85 #include <sys/sysctl.h>
86 #include <sys/syslog.h>
87 #include <sys/taskqueue.h>
88 
89 #include <security/audit/audit.h>
90 
91 #include <geom/geom.h>
92 #include <geom/geom_vfs.h>
93 
94 #include <ufs/ufs/dir.h>
95 #include <ufs/ufs/extattr.h>
96 #include <ufs/ufs/quota.h>
97 #include <ufs/ufs/inode.h>
98 #include <ufs/ufs/ufs_extern.h>
99 #include <ufs/ufs/ufsmount.h>
100 
101 #include <ufs/ffs/fs.h>
102 #include <ufs/ffs/ffs_extern.h>
103 #include <ufs/ffs/softdep.h>
104 
105 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
106 				  int size, int rsize);
107 
108 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
109 static ufs2_daddr_t
110 	      ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
111 static void	ffs_blkfree_cg(struct ufsmount *, struct fs *,
112 		    struct vnode *, ufs2_daddr_t, long, ino_t,
113 		    struct workhead *);
114 #ifdef INVARIANTS
115 static int	ffs_checkblk(struct inode *, ufs2_daddr_t, long);
116 #endif
117 static ufs2_daddr_t ffs_clusteralloc(struct inode *, u_int, ufs2_daddr_t, int);
118 static ino_t	ffs_dirpref(struct inode *);
119 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
120 		    int, int);
121 static ufs2_daddr_t	ffs_hashalloc
122 		(struct inode *, u_int, ufs2_daddr_t, int, int, allocfcn_t *);
123 static ufs2_daddr_t ffs_nodealloccg(struct inode *, u_int, ufs2_daddr_t, int,
124 		    int);
125 static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
126 static int	ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
127 static int	ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
128 static void	ffs_ckhash_cg(struct buf *);
129 
130 /*
131  * Allocate a block in the filesystem.
132  *
133  * The size of the requested block is given, which must be some
134  * multiple of fs_fsize and <= fs_bsize.
135  * A preference may be optionally specified. If a preference is given
136  * the following hierarchy is used to allocate a block:
137  *   1) allocate the requested block.
138  *   2) allocate a rotationally optimal block in the same cylinder.
139  *   3) allocate a block in the same cylinder group.
140  *   4) quadradically rehash into other cylinder groups, until an
141  *      available block is located.
142  * If no block preference is given the following hierarchy is used
143  * to allocate a block:
144  *   1) allocate a block in the cylinder group that contains the
145  *      inode for the file.
146  *   2) quadradically rehash into other cylinder groups, until an
147  *      available block is located.
148  */
149 int
150 ffs_alloc(ip, lbn, bpref, size, flags, cred, bnp)
151 	struct inode *ip;
152 	ufs2_daddr_t lbn, bpref;
153 	int size, flags;
154 	struct ucred *cred;
155 	ufs2_daddr_t *bnp;
156 {
157 	struct fs *fs;
158 	struct ufsmount *ump;
159 	ufs2_daddr_t bno;
160 	u_int cg, reclaimed;
161 	int64_t delta;
162 #ifdef QUOTA
163 	int error;
164 #endif
165 
166 	*bnp = 0;
167 	ump = ITOUMP(ip);
168 	fs = ump->um_fs;
169 	mtx_assert(UFS_MTX(ump), MA_OWNED);
170 #ifdef INVARIANTS
171 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
172 		printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
173 		    devtoname(ump->um_dev), (long)fs->fs_bsize, size,
174 		    fs->fs_fsmnt);
175 		panic("ffs_alloc: bad size");
176 	}
177 	if (cred == NOCRED)
178 		panic("ffs_alloc: missing credential");
179 #endif /* INVARIANTS */
180 	reclaimed = 0;
181 retry:
182 #ifdef QUOTA
183 	UFS_UNLOCK(ump);
184 	error = chkdq(ip, btodb(size), cred, 0);
185 	if (error)
186 		return (error);
187 	UFS_LOCK(ump);
188 #endif
189 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
190 		goto nospace;
191 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
192 	    freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
193 		goto nospace;
194 	if (bpref >= fs->fs_size)
195 		bpref = 0;
196 	if (bpref == 0)
197 		cg = ino_to_cg(fs, ip->i_number);
198 	else
199 		cg = dtog(fs, bpref);
200 	bno = ffs_hashalloc(ip, cg, bpref, size, size, ffs_alloccg);
201 	if (bno > 0) {
202 		delta = btodb(size);
203 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
204 		if (flags & IO_EXT)
205 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
206 		else
207 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
208 		*bnp = bno;
209 		return (0);
210 	}
211 nospace:
212 #ifdef QUOTA
213 	UFS_UNLOCK(ump);
214 	/*
215 	 * Restore user's disk quota because allocation failed.
216 	 */
217 	(void) chkdq(ip, -btodb(size), cred, FORCE);
218 	UFS_LOCK(ump);
219 #endif
220 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
221 		reclaimed = 1;
222 		softdep_request_cleanup(fs, ITOV(ip), cred, FLUSH_BLOCKS_WAIT);
223 		goto retry;
224 	}
225 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
226 		UFS_UNLOCK(ump);
227 		return (ENXIO);
228 	}
229 	if (reclaimed > 0 &&
230 	    ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
231 		UFS_UNLOCK(ump);
232 		ffs_fserr(fs, ip->i_number, "filesystem full");
233 		uprintf("\n%s: write failed, filesystem is full\n",
234 		    fs->fs_fsmnt);
235 	} else {
236 		UFS_UNLOCK(ump);
237 	}
238 	return (ENOSPC);
239 }
240 
241 /*
242  * Reallocate a fragment to a bigger size
243  *
244  * The number and size of the old block is given, and a preference
245  * and new size is also specified. The allocator attempts to extend
246  * the original block. Failing that, the regular block allocator is
247  * invoked to get an appropriate block.
248  */
249 int
250 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
251 	struct inode *ip;
252 	ufs2_daddr_t lbprev;
253 	ufs2_daddr_t bprev;
254 	ufs2_daddr_t bpref;
255 	int osize, nsize, flags;
256 	struct ucred *cred;
257 	struct buf **bpp;
258 {
259 	struct vnode *vp;
260 	struct fs *fs;
261 	struct buf *bp;
262 	struct ufsmount *ump;
263 	u_int cg, request, reclaimed;
264 	int error, gbflags;
265 	ufs2_daddr_t bno;
266 	int64_t delta;
267 
268 	vp = ITOV(ip);
269 	ump = ITOUMP(ip);
270 	fs = ump->um_fs;
271 	bp = NULL;
272 	gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
273 
274 	mtx_assert(UFS_MTX(ump), MA_OWNED);
275 #ifdef INVARIANTS
276 	if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
277 		panic("ffs_realloccg: allocation on suspended filesystem");
278 	if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
279 	    (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
280 		printf(
281 		"dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
282 		    devtoname(ump->um_dev), (long)fs->fs_bsize, osize,
283 		    nsize, fs->fs_fsmnt);
284 		panic("ffs_realloccg: bad size");
285 	}
286 	if (cred == NOCRED)
287 		panic("ffs_realloccg: missing credential");
288 #endif /* INVARIANTS */
289 	reclaimed = 0;
290 retry:
291 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
292 	    freespace(fs, fs->fs_minfree) -  numfrags(fs, nsize - osize) < 0) {
293 		goto nospace;
294 	}
295 	if (bprev == 0) {
296 		printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
297 		    devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
298 		    fs->fs_fsmnt);
299 		panic("ffs_realloccg: bad bprev");
300 	}
301 	UFS_UNLOCK(ump);
302 	/*
303 	 * Allocate the extra space in the buffer.
304 	 */
305 	error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
306 	if (error) {
307 		return (error);
308 	}
309 
310 	if (bp->b_blkno == bp->b_lblkno) {
311 		if (lbprev >= UFS_NDADDR)
312 			panic("ffs_realloccg: lbprev out of range");
313 		bp->b_blkno = fsbtodb(fs, bprev);
314 	}
315 
316 #ifdef QUOTA
317 	error = chkdq(ip, btodb(nsize - osize), cred, 0);
318 	if (error) {
319 		brelse(bp);
320 		return (error);
321 	}
322 #endif
323 	/*
324 	 * Check for extension in the existing location.
325 	 */
326 	*bpp = NULL;
327 	cg = dtog(fs, bprev);
328 	UFS_LOCK(ump);
329 	bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
330 	if (bno) {
331 		if (bp->b_blkno != fsbtodb(fs, bno))
332 			panic("ffs_realloccg: bad blockno");
333 		delta = btodb(nsize - osize);
334 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
335 		if (flags & IO_EXT)
336 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
337 		else
338 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
339 		allocbuf(bp, nsize);
340 		bp->b_flags |= B_DONE;
341 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
342 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
343 			vfs_bio_set_valid(bp, osize, nsize - osize);
344 		*bpp = bp;
345 		return (0);
346 	}
347 	/*
348 	 * Allocate a new disk location.
349 	 */
350 	if (bpref >= fs->fs_size)
351 		bpref = 0;
352 	switch ((int)fs->fs_optim) {
353 	case FS_OPTSPACE:
354 		/*
355 		 * Allocate an exact sized fragment. Although this makes
356 		 * best use of space, we will waste time relocating it if
357 		 * the file continues to grow. If the fragmentation is
358 		 * less than half of the minimum free reserve, we choose
359 		 * to begin optimizing for time.
360 		 */
361 		request = nsize;
362 		if (fs->fs_minfree <= 5 ||
363 		    fs->fs_cstotal.cs_nffree >
364 		    (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
365 			break;
366 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
367 			fs->fs_fsmnt);
368 		fs->fs_optim = FS_OPTTIME;
369 		break;
370 	case FS_OPTTIME:
371 		/*
372 		 * At this point we have discovered a file that is trying to
373 		 * grow a small fragment to a larger fragment. To save time,
374 		 * we allocate a full sized block, then free the unused portion.
375 		 * If the file continues to grow, the `ffs_fragextend' call
376 		 * above will be able to grow it in place without further
377 		 * copying. If aberrant programs cause disk fragmentation to
378 		 * grow within 2% of the free reserve, we choose to begin
379 		 * optimizing for space.
380 		 */
381 		request = fs->fs_bsize;
382 		if (fs->fs_cstotal.cs_nffree <
383 		    (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
384 			break;
385 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
386 			fs->fs_fsmnt);
387 		fs->fs_optim = FS_OPTSPACE;
388 		break;
389 	default:
390 		printf("dev = %s, optim = %ld, fs = %s\n",
391 		    devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
392 		panic("ffs_realloccg: bad optim");
393 		/* NOTREACHED */
394 	}
395 	bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
396 	if (bno > 0) {
397 		bp->b_blkno = fsbtodb(fs, bno);
398 		if (!DOINGSOFTDEP(vp))
399 			/*
400 			 * The usual case is that a smaller fragment that
401 			 * was just allocated has been replaced with a bigger
402 			 * fragment or a full-size block. If it is marked as
403 			 * B_DELWRI, the current contents have not been written
404 			 * to disk. It is possible that the block was written
405 			 * earlier, but very uncommon. If the block has never
406 			 * been written, there is no need to send a BIO_DELETE
407 			 * for it when it is freed. The gain from avoiding the
408 			 * TRIMs for the common case of unwritten blocks far
409 			 * exceeds the cost of the write amplification for the
410 			 * uncommon case of failing to send a TRIM for a block
411 			 * that had been written.
412 			 */
413 			ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
414 			    ip->i_number, vp->v_type, NULL,
415 			    (bp->b_flags & B_DELWRI) != 0 ?
416 			    NOTRIM_KEY : SINGLETON_KEY);
417 		delta = btodb(nsize - osize);
418 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
419 		if (flags & IO_EXT)
420 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
421 		else
422 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
423 		allocbuf(bp, nsize);
424 		bp->b_flags |= B_DONE;
425 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
426 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
427 			vfs_bio_set_valid(bp, osize, nsize - osize);
428 		*bpp = bp;
429 		return (0);
430 	}
431 #ifdef QUOTA
432 	UFS_UNLOCK(ump);
433 	/*
434 	 * Restore user's disk quota because allocation failed.
435 	 */
436 	(void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
437 	UFS_LOCK(ump);
438 #endif
439 nospace:
440 	/*
441 	 * no space available
442 	 */
443 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
444 		reclaimed = 1;
445 		UFS_UNLOCK(ump);
446 		if (bp) {
447 			brelse(bp);
448 			bp = NULL;
449 		}
450 		UFS_LOCK(ump);
451 		softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
452 		goto retry;
453 	}
454 	if (bp)
455 		brelse(bp);
456 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
457 		UFS_UNLOCK(ump);
458 		return (ENXIO);
459 	}
460 	if (reclaimed > 0 &&
461 	    ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
462 		UFS_UNLOCK(ump);
463 		ffs_fserr(fs, ip->i_number, "filesystem full");
464 		uprintf("\n%s: write failed, filesystem is full\n",
465 		    fs->fs_fsmnt);
466 	} else {
467 		UFS_UNLOCK(ump);
468 	}
469 	return (ENOSPC);
470 }
471 
472 /*
473  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
474  *
475  * The vnode and an array of buffer pointers for a range of sequential
476  * logical blocks to be made contiguous is given. The allocator attempts
477  * to find a range of sequential blocks starting as close as possible
478  * from the end of the allocation for the logical block immediately
479  * preceding the current range. If successful, the physical block numbers
480  * in the buffer pointers and in the inode are changed to reflect the new
481  * allocation. If unsuccessful, the allocation is left unchanged. The
482  * success in doing the reallocation is returned. Note that the error
483  * return is not reflected back to the user. Rather the previous block
484  * allocation will be used.
485  */
486 
487 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
488     "FFS filesystem");
489 
490 static int doasyncfree = 1;
491 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
492 "do not force synchronous writes when blocks are reallocated");
493 
494 static int doreallocblks = 1;
495 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
496 "enable block reallocation");
497 
498 static int dotrimcons = 1;
499 SYSCTL_INT(_vfs_ffs, OID_AUTO, dotrimcons, CTLFLAG_RWTUN, &dotrimcons, 0,
500 "enable BIO_DELETE / TRIM consolidation");
501 
502 static int maxclustersearch = 10;
503 SYSCTL_INT(_vfs_ffs, OID_AUTO, maxclustersearch, CTLFLAG_RW, &maxclustersearch,
504 0, "max number of cylinder group to search for contigous blocks");
505 
506 #ifdef DIAGNOSTIC
507 static int prtrealloc = 0;
508 SYSCTL_INT(_debug, OID_AUTO, ffs_prtrealloc, CTLFLAG_RW, &prtrealloc, 0,
509 	"print out FFS filesystem block reallocation operations");
510 #endif
511 
512 int
513 ffs_reallocblks(ap)
514 	struct vop_reallocblks_args /* {
515 		struct vnode *a_vp;
516 		struct cluster_save *a_buflist;
517 	} */ *ap;
518 {
519 	struct ufsmount *ump;
520 	int error;
521 
522 	/*
523 	 * We used to skip reallocating the blocks of a file into a
524 	 * contiguous sequence if the underlying flash device requested
525 	 * BIO_DELETE notifications, because devices that benefit from
526 	 * BIO_DELETE also benefit from not moving the data. However,
527 	 * the destination for the data is usually moved before the data
528 	 * is written to the initially allocated location, so we rarely
529 	 * suffer the penalty of extra writes. With the addition of the
530 	 * consolidation of contiguous blocks into single BIO_DELETE
531 	 * operations, having fewer but larger contiguous blocks reduces
532 	 * the number of (slow and expensive) BIO_DELETE operations. So
533 	 * when doing BIO_DELETE consolidation, we do block reallocation.
534 	 *
535 	 * Skip if reallocblks has been disabled globally.
536 	 */
537 	ump = ap->a_vp->v_mount->mnt_data;
538 	if ((((ump->um_flags) & UM_CANDELETE) != 0 && dotrimcons == 0) ||
539 	    doreallocblks == 0)
540 		return (ENOSPC);
541 
542 	/*
543 	 * We can't wait in softdep prealloc as it may fsync and recurse
544 	 * here.  Instead we simply fail to reallocate blocks if this
545 	 * rare condition arises.
546 	 */
547 	if (DOINGSUJ(ap->a_vp))
548 		if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
549 			return (ENOSPC);
550 	vn_seqc_write_begin(ap->a_vp);
551 	error = ump->um_fstype == UFS1 ? ffs_reallocblks_ufs1(ap) :
552 	    ffs_reallocblks_ufs2(ap);
553 	vn_seqc_write_end(ap->a_vp);
554 	return (error);
555 }
556 
557 static int
558 ffs_reallocblks_ufs1(ap)
559 	struct vop_reallocblks_args /* {
560 		struct vnode *a_vp;
561 		struct cluster_save *a_buflist;
562 	} */ *ap;
563 {
564 	struct fs *fs;
565 	struct inode *ip;
566 	struct vnode *vp;
567 	struct buf *sbp, *ebp, *bp;
568 	ufs1_daddr_t *bap, *sbap, *ebap;
569 	struct cluster_save *buflist;
570 	struct ufsmount *ump;
571 	ufs_lbn_t start_lbn, end_lbn;
572 	ufs1_daddr_t soff, newblk, blkno;
573 	ufs2_daddr_t pref;
574 	struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
575 	int i, cg, len, start_lvl, end_lvl, ssize;
576 
577 	vp = ap->a_vp;
578 	ip = VTOI(vp);
579 	ump = ITOUMP(ip);
580 	fs = ump->um_fs;
581 	/*
582 	 * If we are not tracking block clusters or if we have less than 4%
583 	 * free blocks left, then do not attempt to cluster. Running with
584 	 * less than 5% free block reserve is not recommended and those that
585 	 * choose to do so do not expect to have good file layout.
586 	 */
587 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
588 		return (ENOSPC);
589 	buflist = ap->a_buflist;
590 	len = buflist->bs_nchildren;
591 	start_lbn = buflist->bs_children[0]->b_lblkno;
592 	end_lbn = start_lbn + len - 1;
593 #ifdef INVARIANTS
594 	for (i = 0; i < len; i++)
595 		if (!ffs_checkblk(ip,
596 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
597 			panic("ffs_reallocblks: unallocated block 1");
598 	for (i = 1; i < len; i++)
599 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
600 			panic("ffs_reallocblks: non-logical cluster");
601 	blkno = buflist->bs_children[0]->b_blkno;
602 	ssize = fsbtodb(fs, fs->fs_frag);
603 	for (i = 1; i < len - 1; i++)
604 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
605 			panic("ffs_reallocblks: non-physical cluster %d", i);
606 #endif
607 	/*
608 	 * If the cluster crosses the boundary for the first indirect
609 	 * block, leave space for the indirect block. Indirect blocks
610 	 * are initially laid out in a position after the last direct
611 	 * block. Block reallocation would usually destroy locality by
612 	 * moving the indirect block out of the way to make room for
613 	 * data blocks if we didn't compensate here. We should also do
614 	 * this for other indirect block boundaries, but it is only
615 	 * important for the first one.
616 	 */
617 	if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
618 		return (ENOSPC);
619 	/*
620 	 * If the latest allocation is in a new cylinder group, assume that
621 	 * the filesystem has decided to move and do not force it back to
622 	 * the previous cylinder group.
623 	 */
624 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
625 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
626 		return (ENOSPC);
627 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
628 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
629 		return (ENOSPC);
630 	/*
631 	 * Get the starting offset and block map for the first block.
632 	 */
633 	if (start_lvl == 0) {
634 		sbap = &ip->i_din1->di_db[0];
635 		soff = start_lbn;
636 	} else {
637 		idp = &start_ap[start_lvl - 1];
638 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
639 			brelse(sbp);
640 			return (ENOSPC);
641 		}
642 		sbap = (ufs1_daddr_t *)sbp->b_data;
643 		soff = idp->in_off;
644 	}
645 	/*
646 	 * If the block range spans two block maps, get the second map.
647 	 */
648 	ebap = NULL;
649 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
650 		ssize = len;
651 	} else {
652 #ifdef INVARIANTS
653 		if (start_lvl > 0 &&
654 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
655 			panic("ffs_reallocblk: start == end");
656 #endif
657 		ssize = len - (idp->in_off + 1);
658 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
659 			goto fail;
660 		ebap = (ufs1_daddr_t *)ebp->b_data;
661 	}
662 	/*
663 	 * Find the preferred location for the cluster. If we have not
664 	 * previously failed at this endeavor, then follow our standard
665 	 * preference calculation. If we have failed at it, then pick up
666 	 * where we last ended our search.
667 	 */
668 	UFS_LOCK(ump);
669 	if (ip->i_nextclustercg == -1)
670 		pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
671 	else
672 		pref = cgdata(fs, ip->i_nextclustercg);
673 	/*
674 	 * Search the block map looking for an allocation of the desired size.
675 	 * To avoid wasting too much time, we limit the number of cylinder
676 	 * groups that we will search.
677 	 */
678 	cg = dtog(fs, pref);
679 	for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
680 		if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
681 			break;
682 		cg += 1;
683 		if (cg >= fs->fs_ncg)
684 			cg = 0;
685 	}
686 	/*
687 	 * If we have failed in our search, record where we gave up for
688 	 * next time. Otherwise, fall back to our usual search citerion.
689 	 */
690 	if (newblk == 0) {
691 		ip->i_nextclustercg = cg;
692 		UFS_UNLOCK(ump);
693 		goto fail;
694 	}
695 	ip->i_nextclustercg = -1;
696 	/*
697 	 * We have found a new contiguous block.
698 	 *
699 	 * First we have to replace the old block pointers with the new
700 	 * block pointers in the inode and indirect blocks associated
701 	 * with the file.
702 	 */
703 #ifdef DIAGNOSTIC
704 	if (prtrealloc)
705 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
706 		    (uintmax_t)ip->i_number,
707 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
708 #endif
709 	blkno = newblk;
710 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
711 		if (i == ssize) {
712 			bap = ebap;
713 			soff = -i;
714 		}
715 #ifdef INVARIANTS
716 		if (!ffs_checkblk(ip,
717 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
718 			panic("ffs_reallocblks: unallocated block 2");
719 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
720 			panic("ffs_reallocblks: alloc mismatch");
721 #endif
722 #ifdef DIAGNOSTIC
723 		if (prtrealloc)
724 			printf(" %d,", *bap);
725 #endif
726 		if (DOINGSOFTDEP(vp)) {
727 			if (sbap == &ip->i_din1->di_db[0] && i < ssize)
728 				softdep_setup_allocdirect(ip, start_lbn + i,
729 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
730 				    buflist->bs_children[i]);
731 			else
732 				softdep_setup_allocindir_page(ip, start_lbn + i,
733 				    i < ssize ? sbp : ebp, soff + i, blkno,
734 				    *bap, buflist->bs_children[i]);
735 		}
736 		*bap++ = blkno;
737 	}
738 	/*
739 	 * Next we must write out the modified inode and indirect blocks.
740 	 * For strict correctness, the writes should be synchronous since
741 	 * the old block values may have been written to disk. In practise
742 	 * they are almost never written, but if we are concerned about
743 	 * strict correctness, the `doasyncfree' flag should be set to zero.
744 	 *
745 	 * The test on `doasyncfree' should be changed to test a flag
746 	 * that shows whether the associated buffers and inodes have
747 	 * been written. The flag should be set when the cluster is
748 	 * started and cleared whenever the buffer or inode is flushed.
749 	 * We can then check below to see if it is set, and do the
750 	 * synchronous write only when it has been cleared.
751 	 */
752 	if (sbap != &ip->i_din1->di_db[0]) {
753 		if (doasyncfree)
754 			bdwrite(sbp);
755 		else
756 			bwrite(sbp);
757 	} else {
758 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
759 		if (!doasyncfree)
760 			ffs_update(vp, 1);
761 	}
762 	if (ssize < len) {
763 		if (doasyncfree)
764 			bdwrite(ebp);
765 		else
766 			bwrite(ebp);
767 	}
768 	/*
769 	 * Last, free the old blocks and assign the new blocks to the buffers.
770 	 */
771 #ifdef DIAGNOSTIC
772 	if (prtrealloc)
773 		printf("\n\tnew:");
774 #endif
775 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
776 		bp = buflist->bs_children[i];
777 		if (!DOINGSOFTDEP(vp))
778 			/*
779 			 * The usual case is that a set of N-contiguous blocks
780 			 * that was just allocated has been replaced with a
781 			 * set of N+1-contiguous blocks. If they are marked as
782 			 * B_DELWRI, the current contents have not been written
783 			 * to disk. It is possible that the blocks were written
784 			 * earlier, but very uncommon. If the blocks have never
785 			 * been written, there is no need to send a BIO_DELETE
786 			 * for them when they are freed. The gain from avoiding
787 			 * the TRIMs for the common case of unwritten blocks
788 			 * far exceeds the cost of the write amplification for
789 			 * the uncommon case of failing to send a TRIM for the
790 			 * blocks that had been written.
791 			 */
792 			ffs_blkfree(ump, fs, ump->um_devvp,
793 			    dbtofsb(fs, bp->b_blkno),
794 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL,
795 			    (bp->b_flags & B_DELWRI) != 0 ?
796 			    NOTRIM_KEY : SINGLETON_KEY);
797 		bp->b_blkno = fsbtodb(fs, blkno);
798 #ifdef INVARIANTS
799 		if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
800 			panic("ffs_reallocblks: unallocated block 3");
801 #endif
802 #ifdef DIAGNOSTIC
803 		if (prtrealloc)
804 			printf(" %d,", blkno);
805 #endif
806 	}
807 #ifdef DIAGNOSTIC
808 	if (prtrealloc) {
809 		prtrealloc--;
810 		printf("\n");
811 	}
812 #endif
813 	return (0);
814 
815 fail:
816 	if (ssize < len)
817 		brelse(ebp);
818 	if (sbap != &ip->i_din1->di_db[0])
819 		brelse(sbp);
820 	return (ENOSPC);
821 }
822 
823 static int
824 ffs_reallocblks_ufs2(ap)
825 	struct vop_reallocblks_args /* {
826 		struct vnode *a_vp;
827 		struct cluster_save *a_buflist;
828 	} */ *ap;
829 {
830 	struct fs *fs;
831 	struct inode *ip;
832 	struct vnode *vp;
833 	struct buf *sbp, *ebp, *bp;
834 	ufs2_daddr_t *bap, *sbap, *ebap;
835 	struct cluster_save *buflist;
836 	struct ufsmount *ump;
837 	ufs_lbn_t start_lbn, end_lbn;
838 	ufs2_daddr_t soff, newblk, blkno, pref;
839 	struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
840 	int i, cg, len, start_lvl, end_lvl, ssize;
841 
842 	vp = ap->a_vp;
843 	ip = VTOI(vp);
844 	ump = ITOUMP(ip);
845 	fs = ump->um_fs;
846 	/*
847 	 * If we are not tracking block clusters or if we have less than 4%
848 	 * free blocks left, then do not attempt to cluster. Running with
849 	 * less than 5% free block reserve is not recommended and those that
850 	 * choose to do so do not expect to have good file layout.
851 	 */
852 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
853 		return (ENOSPC);
854 	buflist = ap->a_buflist;
855 	len = buflist->bs_nchildren;
856 	start_lbn = buflist->bs_children[0]->b_lblkno;
857 	end_lbn = start_lbn + len - 1;
858 #ifdef INVARIANTS
859 	for (i = 0; i < len; i++)
860 		if (!ffs_checkblk(ip,
861 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
862 			panic("ffs_reallocblks: unallocated block 1");
863 	for (i = 1; i < len; i++)
864 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
865 			panic("ffs_reallocblks: non-logical cluster");
866 	blkno = buflist->bs_children[0]->b_blkno;
867 	ssize = fsbtodb(fs, fs->fs_frag);
868 	for (i = 1; i < len - 1; i++)
869 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
870 			panic("ffs_reallocblks: non-physical cluster %d", i);
871 #endif
872 	/*
873 	 * If the cluster crosses the boundary for the first indirect
874 	 * block, do not move anything in it. Indirect blocks are
875 	 * usually initially laid out in a position between the data
876 	 * blocks. Block reallocation would usually destroy locality by
877 	 * moving the indirect block out of the way to make room for
878 	 * data blocks if we didn't compensate here. We should also do
879 	 * this for other indirect block boundaries, but it is only
880 	 * important for the first one.
881 	 */
882 	if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
883 		return (ENOSPC);
884 	/*
885 	 * If the latest allocation is in a new cylinder group, assume that
886 	 * the filesystem has decided to move and do not force it back to
887 	 * the previous cylinder group.
888 	 */
889 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
890 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
891 		return (ENOSPC);
892 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
893 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
894 		return (ENOSPC);
895 	/*
896 	 * Get the starting offset and block map for the first block.
897 	 */
898 	if (start_lvl == 0) {
899 		sbap = &ip->i_din2->di_db[0];
900 		soff = start_lbn;
901 	} else {
902 		idp = &start_ap[start_lvl - 1];
903 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
904 			brelse(sbp);
905 			return (ENOSPC);
906 		}
907 		sbap = (ufs2_daddr_t *)sbp->b_data;
908 		soff = idp->in_off;
909 	}
910 	/*
911 	 * If the block range spans two block maps, get the second map.
912 	 */
913 	ebap = NULL;
914 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
915 		ssize = len;
916 	} else {
917 #ifdef INVARIANTS
918 		if (start_lvl > 0 &&
919 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
920 			panic("ffs_reallocblk: start == end");
921 #endif
922 		ssize = len - (idp->in_off + 1);
923 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
924 			goto fail;
925 		ebap = (ufs2_daddr_t *)ebp->b_data;
926 	}
927 	/*
928 	 * Find the preferred location for the cluster. If we have not
929 	 * previously failed at this endeavor, then follow our standard
930 	 * preference calculation. If we have failed at it, then pick up
931 	 * where we last ended our search.
932 	 */
933 	UFS_LOCK(ump);
934 	if (ip->i_nextclustercg == -1)
935 		pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
936 	else
937 		pref = cgdata(fs, ip->i_nextclustercg);
938 	/*
939 	 * Search the block map looking for an allocation of the desired size.
940 	 * To avoid wasting too much time, we limit the number of cylinder
941 	 * groups that we will search.
942 	 */
943 	cg = dtog(fs, pref);
944 	for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
945 		if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
946 			break;
947 		cg += 1;
948 		if (cg >= fs->fs_ncg)
949 			cg = 0;
950 	}
951 	/*
952 	 * If we have failed in our search, record where we gave up for
953 	 * next time. Otherwise, fall back to our usual search citerion.
954 	 */
955 	if (newblk == 0) {
956 		ip->i_nextclustercg = cg;
957 		UFS_UNLOCK(ump);
958 		goto fail;
959 	}
960 	ip->i_nextclustercg = -1;
961 	/*
962 	 * We have found a new contiguous block.
963 	 *
964 	 * First we have to replace the old block pointers with the new
965 	 * block pointers in the inode and indirect blocks associated
966 	 * with the file.
967 	 */
968 #ifdef DIAGNOSTIC
969 	if (prtrealloc)
970 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
971 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
972 #endif
973 	blkno = newblk;
974 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
975 		if (i == ssize) {
976 			bap = ebap;
977 			soff = -i;
978 		}
979 #ifdef INVARIANTS
980 		if (!ffs_checkblk(ip,
981 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
982 			panic("ffs_reallocblks: unallocated block 2");
983 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
984 			panic("ffs_reallocblks: alloc mismatch");
985 #endif
986 #ifdef DIAGNOSTIC
987 		if (prtrealloc)
988 			printf(" %jd,", (intmax_t)*bap);
989 #endif
990 		if (DOINGSOFTDEP(vp)) {
991 			if (sbap == &ip->i_din2->di_db[0] && i < ssize)
992 				softdep_setup_allocdirect(ip, start_lbn + i,
993 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
994 				    buflist->bs_children[i]);
995 			else
996 				softdep_setup_allocindir_page(ip, start_lbn + i,
997 				    i < ssize ? sbp : ebp, soff + i, blkno,
998 				    *bap, buflist->bs_children[i]);
999 		}
1000 		*bap++ = blkno;
1001 	}
1002 	/*
1003 	 * Next we must write out the modified inode and indirect blocks.
1004 	 * For strict correctness, the writes should be synchronous since
1005 	 * the old block values may have been written to disk. In practise
1006 	 * they are almost never written, but if we are concerned about
1007 	 * strict correctness, the `doasyncfree' flag should be set to zero.
1008 	 *
1009 	 * The test on `doasyncfree' should be changed to test a flag
1010 	 * that shows whether the associated buffers and inodes have
1011 	 * been written. The flag should be set when the cluster is
1012 	 * started and cleared whenever the buffer or inode is flushed.
1013 	 * We can then check below to see if it is set, and do the
1014 	 * synchronous write only when it has been cleared.
1015 	 */
1016 	if (sbap != &ip->i_din2->di_db[0]) {
1017 		if (doasyncfree)
1018 			bdwrite(sbp);
1019 		else
1020 			bwrite(sbp);
1021 	} else {
1022 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1023 		if (!doasyncfree)
1024 			ffs_update(vp, 1);
1025 	}
1026 	if (ssize < len) {
1027 		if (doasyncfree)
1028 			bdwrite(ebp);
1029 		else
1030 			bwrite(ebp);
1031 	}
1032 	/*
1033 	 * Last, free the old blocks and assign the new blocks to the buffers.
1034 	 */
1035 #ifdef DIAGNOSTIC
1036 	if (prtrealloc)
1037 		printf("\n\tnew:");
1038 #endif
1039 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
1040 		bp = buflist->bs_children[i];
1041 		if (!DOINGSOFTDEP(vp))
1042 			/*
1043 			 * The usual case is that a set of N-contiguous blocks
1044 			 * that was just allocated has been replaced with a
1045 			 * set of N+1-contiguous blocks. If they are marked as
1046 			 * B_DELWRI, the current contents have not been written
1047 			 * to disk. It is possible that the blocks were written
1048 			 * earlier, but very uncommon. If the blocks have never
1049 			 * been written, there is no need to send a BIO_DELETE
1050 			 * for them when they are freed. The gain from avoiding
1051 			 * the TRIMs for the common case of unwritten blocks
1052 			 * far exceeds the cost of the write amplification for
1053 			 * the uncommon case of failing to send a TRIM for the
1054 			 * blocks that had been written.
1055 			 */
1056 			ffs_blkfree(ump, fs, ump->um_devvp,
1057 			    dbtofsb(fs, bp->b_blkno),
1058 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL,
1059 			    (bp->b_flags & B_DELWRI) != 0 ?
1060 			    NOTRIM_KEY : SINGLETON_KEY);
1061 		bp->b_blkno = fsbtodb(fs, blkno);
1062 #ifdef INVARIANTS
1063 		if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
1064 			panic("ffs_reallocblks: unallocated block 3");
1065 #endif
1066 #ifdef DIAGNOSTIC
1067 		if (prtrealloc)
1068 			printf(" %jd,", (intmax_t)blkno);
1069 #endif
1070 	}
1071 #ifdef DIAGNOSTIC
1072 	if (prtrealloc) {
1073 		prtrealloc--;
1074 		printf("\n");
1075 	}
1076 #endif
1077 	return (0);
1078 
1079 fail:
1080 	if (ssize < len)
1081 		brelse(ebp);
1082 	if (sbap != &ip->i_din2->di_db[0])
1083 		brelse(sbp);
1084 	return (ENOSPC);
1085 }
1086 
1087 /*
1088  * Allocate an inode in the filesystem.
1089  *
1090  * If allocating a directory, use ffs_dirpref to select the inode.
1091  * If allocating in a directory, the following hierarchy is followed:
1092  *   1) allocate the preferred inode.
1093  *   2) allocate an inode in the same cylinder group.
1094  *   3) quadradically rehash into other cylinder groups, until an
1095  *      available inode is located.
1096  * If no inode preference is given the following hierarchy is used
1097  * to allocate an inode:
1098  *   1) allocate an inode in cylinder group 0.
1099  *   2) quadradically rehash into other cylinder groups, until an
1100  *      available inode is located.
1101  */
1102 int
1103 ffs_valloc(pvp, mode, cred, vpp)
1104 	struct vnode *pvp;
1105 	int mode;
1106 	struct ucred *cred;
1107 	struct vnode **vpp;
1108 {
1109 	struct inode *pip;
1110 	struct fs *fs;
1111 	struct inode *ip;
1112 	struct timespec ts;
1113 	struct ufsmount *ump;
1114 	ino_t ino, ipref;
1115 	u_int cg;
1116 	int error, reclaimed;
1117 
1118 	*vpp = NULL;
1119 	pip = VTOI(pvp);
1120 	ump = ITOUMP(pip);
1121 	fs = ump->um_fs;
1122 
1123 	UFS_LOCK(ump);
1124 	reclaimed = 0;
1125 retry:
1126 	if (fs->fs_cstotal.cs_nifree == 0)
1127 		goto noinodes;
1128 
1129 	if ((mode & IFMT) == IFDIR)
1130 		ipref = ffs_dirpref(pip);
1131 	else
1132 		ipref = pip->i_number;
1133 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
1134 		ipref = 0;
1135 	cg = ino_to_cg(fs, ipref);
1136 	/*
1137 	 * Track number of dirs created one after another
1138 	 * in a same cg without intervening by files.
1139 	 */
1140 	if ((mode & IFMT) == IFDIR) {
1141 		if (fs->fs_contigdirs[cg] < 255)
1142 			fs->fs_contigdirs[cg]++;
1143 	} else {
1144 		if (fs->fs_contigdirs[cg] > 0)
1145 			fs->fs_contigdirs[cg]--;
1146 	}
1147 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1148 					(allocfcn_t *)ffs_nodealloccg);
1149 	if (ino == 0)
1150 		goto noinodes;
1151 	/*
1152 	 * Get rid of the cached old vnode, force allocation of a new vnode
1153 	 * for this inode. If this fails, release the allocated ino and
1154 	 * return the error.
1155 	 */
1156 	if ((error = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1157 	    FFSV_FORCEINSMQ | FFSV_REPLACE)) != 0) {
1158 		ffs_vfree(pvp, ino, mode);
1159 		return (error);
1160 	}
1161 	/*
1162 	 * We got an inode, so check mode and panic if it is already allocated.
1163 	 */
1164 	ip = VTOI(*vpp);
1165 	if (ip->i_mode) {
1166 		printf("mode = 0%o, inum = %ju, fs = %s\n",
1167 		    ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1168 		panic("ffs_valloc: dup alloc");
1169 	}
1170 	if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) {  /* XXX */
1171 		printf("free inode %s/%lu had %ld blocks\n",
1172 		    fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1173 		DIP_SET(ip, i_blocks, 0);
1174 	}
1175 	ip->i_flags = 0;
1176 	DIP_SET(ip, i_flags, 0);
1177 	/*
1178 	 * Set up a new generation number for this inode.
1179 	 */
1180 	while (ip->i_gen == 0 || ++ip->i_gen == 0)
1181 		ip->i_gen = arc4random();
1182 	DIP_SET(ip, i_gen, ip->i_gen);
1183 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1184 		vfs_timestamp(&ts);
1185 		ip->i_din2->di_birthtime = ts.tv_sec;
1186 		ip->i_din2->di_birthnsec = ts.tv_nsec;
1187 	}
1188 	ip->i_flag = 0;
1189 	(*vpp)->v_vflag = 0;
1190 	(*vpp)->v_type = VNON;
1191 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1192 		(*vpp)->v_op = &ffs_vnodeops2;
1193 		UFS_INODE_SET_FLAG(ip, IN_UFS2);
1194 	} else {
1195 		(*vpp)->v_op = &ffs_vnodeops1;
1196 	}
1197 	return (0);
1198 noinodes:
1199 	if (reclaimed == 0) {
1200 		reclaimed = 1;
1201 		softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1202 		goto retry;
1203 	}
1204 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
1205 		UFS_UNLOCK(ump);
1206 		return (ENXIO);
1207 	}
1208 	if (ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
1209 		UFS_UNLOCK(ump);
1210 		ffs_fserr(fs, pip->i_number, "out of inodes");
1211 		uprintf("\n%s: create/symlink failed, no inodes free\n",
1212 		    fs->fs_fsmnt);
1213 	} else {
1214 		UFS_UNLOCK(ump);
1215 	}
1216 	return (ENOSPC);
1217 }
1218 
1219 /*
1220  * Find a cylinder group to place a directory.
1221  *
1222  * The policy implemented by this algorithm is to allocate a
1223  * directory inode in the same cylinder group as its parent
1224  * directory, but also to reserve space for its files inodes
1225  * and data. Restrict the number of directories which may be
1226  * allocated one after another in the same cylinder group
1227  * without intervening allocation of files.
1228  *
1229  * If we allocate a first level directory then force allocation
1230  * in another cylinder group.
1231  */
1232 static ino_t
1233 ffs_dirpref(pip)
1234 	struct inode *pip;
1235 {
1236 	struct fs *fs;
1237 	int cg, prefcg, dirsize, cgsize;
1238 	u_int avgifree, avgbfree, avgndir, curdirsize;
1239 	u_int minifree, minbfree, maxndir;
1240 	u_int mincg, minndir;
1241 	u_int maxcontigdirs;
1242 
1243 	mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1244 	fs = ITOFS(pip);
1245 
1246 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1247 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1248 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1249 
1250 	/*
1251 	 * Force allocation in another cg if creating a first level dir.
1252 	 */
1253 	ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1254 	if (ITOV(pip)->v_vflag & VV_ROOT) {
1255 		prefcg = arc4random() % fs->fs_ncg;
1256 		mincg = prefcg;
1257 		minndir = fs->fs_ipg;
1258 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
1259 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1260 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1261 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1262 				mincg = cg;
1263 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1264 			}
1265 		for (cg = 0; cg < prefcg; cg++)
1266 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1267 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1268 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1269 				mincg = cg;
1270 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1271 			}
1272 		return ((ino_t)(fs->fs_ipg * mincg));
1273 	}
1274 
1275 	/*
1276 	 * Count various limits which used for
1277 	 * optimal allocation of a directory inode.
1278 	 */
1279 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1280 	minifree = avgifree - avgifree / 4;
1281 	if (minifree < 1)
1282 		minifree = 1;
1283 	minbfree = avgbfree - avgbfree / 4;
1284 	if (minbfree < 1)
1285 		minbfree = 1;
1286 	cgsize = fs->fs_fsize * fs->fs_fpg;
1287 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1288 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1289 	if (dirsize < curdirsize)
1290 		dirsize = curdirsize;
1291 	if (dirsize <= 0)
1292 		maxcontigdirs = 0;		/* dirsize overflowed */
1293 	else
1294 		maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1295 	if (fs->fs_avgfpdir > 0)
1296 		maxcontigdirs = min(maxcontigdirs,
1297 				    fs->fs_ipg / fs->fs_avgfpdir);
1298 	if (maxcontigdirs == 0)
1299 		maxcontigdirs = 1;
1300 
1301 	/*
1302 	 * Limit number of dirs in one cg and reserve space for
1303 	 * regular files, but only if we have no deficit in
1304 	 * inodes or space.
1305 	 *
1306 	 * We are trying to find a suitable cylinder group nearby
1307 	 * our preferred cylinder group to place a new directory.
1308 	 * We scan from our preferred cylinder group forward looking
1309 	 * for a cylinder group that meets our criterion. If we get
1310 	 * to the final cylinder group and do not find anything,
1311 	 * we start scanning forwards from the beginning of the
1312 	 * filesystem. While it might seem sensible to start scanning
1313 	 * backwards or even to alternate looking forward and backward,
1314 	 * this approach fails badly when the filesystem is nearly full.
1315 	 * Specifically, we first search all the areas that have no space
1316 	 * and finally try the one preceding that. We repeat this on
1317 	 * every request and in the case of the final block end up
1318 	 * searching the entire filesystem. By jumping to the front
1319 	 * of the filesystem, our future forward searches always look
1320 	 * in new cylinder groups so finds every possible block after
1321 	 * one pass over the filesystem.
1322 	 */
1323 	prefcg = ino_to_cg(fs, pip->i_number);
1324 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1325 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1326 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1327 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1328 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1329 				return ((ino_t)(fs->fs_ipg * cg));
1330 		}
1331 	for (cg = 0; cg < prefcg; cg++)
1332 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1333 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1334 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1335 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1336 				return ((ino_t)(fs->fs_ipg * cg));
1337 		}
1338 	/*
1339 	 * This is a backstop when we have deficit in space.
1340 	 */
1341 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1342 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1343 			return ((ino_t)(fs->fs_ipg * cg));
1344 	for (cg = 0; cg < prefcg; cg++)
1345 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1346 			break;
1347 	return ((ino_t)(fs->fs_ipg * cg));
1348 }
1349 
1350 /*
1351  * Select the desired position for the next block in a file.  The file is
1352  * logically divided into sections. The first section is composed of the
1353  * direct blocks and the next fs_maxbpg blocks. Each additional section
1354  * contains fs_maxbpg blocks.
1355  *
1356  * If no blocks have been allocated in the first section, the policy is to
1357  * request a block in the same cylinder group as the inode that describes
1358  * the file. The first indirect is allocated immediately following the last
1359  * direct block and the data blocks for the first indirect immediately
1360  * follow it.
1361  *
1362  * If no blocks have been allocated in any other section, the indirect
1363  * block(s) are allocated in the same cylinder group as its inode in an
1364  * area reserved immediately following the inode blocks. The policy for
1365  * the data blocks is to place them in a cylinder group with a greater than
1366  * average number of free blocks. An appropriate cylinder group is found
1367  * by using a rotor that sweeps the cylinder groups. When a new group of
1368  * blocks is needed, the sweep begins in the cylinder group following the
1369  * cylinder group from which the previous allocation was made. The sweep
1370  * continues until a cylinder group with greater than the average number
1371  * of free blocks is found. If the allocation is for the first block in an
1372  * indirect block or the previous block is a hole, then the information on
1373  * the previous allocation is unavailable; here a best guess is made based
1374  * on the logical block number being allocated.
1375  *
1376  * If a section is already partially allocated, the policy is to
1377  * allocate blocks contiguously within the section if possible.
1378  */
1379 ufs2_daddr_t
1380 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1381 	struct inode *ip;
1382 	ufs_lbn_t lbn;
1383 	int indx;
1384 	ufs1_daddr_t *bap;
1385 {
1386 	struct fs *fs;
1387 	u_int cg, inocg;
1388 	u_int avgbfree, startcg;
1389 	ufs2_daddr_t pref, prevbn;
1390 
1391 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1392 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1393 	fs = ITOFS(ip);
1394 	/*
1395 	 * Allocation of indirect blocks is indicated by passing negative
1396 	 * values in indx: -1 for single indirect, -2 for double indirect,
1397 	 * -3 for triple indirect. As noted below, we attempt to allocate
1398 	 * the first indirect inline with the file data. For all later
1399 	 * indirect blocks, the data is often allocated in other cylinder
1400 	 * groups. However to speed random file access and to speed up
1401 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1402 	 * (typically half of fs_minfree) of the data area of each cylinder
1403 	 * group to hold these later indirect blocks.
1404 	 */
1405 	inocg = ino_to_cg(fs, ip->i_number);
1406 	if (indx < 0) {
1407 		/*
1408 		 * Our preference for indirect blocks is the zone at the
1409 		 * beginning of the inode's cylinder group data area that
1410 		 * we try to reserve for indirect blocks.
1411 		 */
1412 		pref = cgmeta(fs, inocg);
1413 		/*
1414 		 * If we are allocating the first indirect block, try to
1415 		 * place it immediately following the last direct block.
1416 		 */
1417 		if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1418 		    ip->i_din1->di_db[UFS_NDADDR - 1] != 0)
1419 			pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1420 		return (pref);
1421 	}
1422 	/*
1423 	 * If we are allocating the first data block in the first indirect
1424 	 * block and the indirect has been allocated in the data block area,
1425 	 * try to place it immediately following the indirect block.
1426 	 */
1427 	if (lbn == UFS_NDADDR) {
1428 		pref = ip->i_din1->di_ib[0];
1429 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1430 		    pref < cgbase(fs, inocg + 1))
1431 			return (pref + fs->fs_frag);
1432 	}
1433 	/*
1434 	 * If we are at the beginning of a file, or we have already allocated
1435 	 * the maximum number of blocks per cylinder group, or we do not
1436 	 * have a block allocated immediately preceding us, then we need
1437 	 * to decide where to start allocating new blocks.
1438 	 */
1439 	if (indx ==  0) {
1440 		prevbn = 0;
1441 	} else {
1442 		prevbn = bap[indx - 1];
1443 		if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1444 		    fs->fs_bsize) != 0)
1445 			prevbn = 0;
1446 	}
1447 	if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1448 		/*
1449 		 * If we are allocating a directory data block, we want
1450 		 * to place it in the metadata area.
1451 		 */
1452 		if ((ip->i_mode & IFMT) == IFDIR)
1453 			return (cgmeta(fs, inocg));
1454 		/*
1455 		 * Until we fill all the direct and all the first indirect's
1456 		 * blocks, we try to allocate in the data area of the inode's
1457 		 * cylinder group.
1458 		 */
1459 		if (lbn < UFS_NDADDR + NINDIR(fs))
1460 			return (cgdata(fs, inocg));
1461 		/*
1462 		 * Find a cylinder with greater than average number of
1463 		 * unused data blocks.
1464 		 */
1465 		if (indx == 0 || prevbn == 0)
1466 			startcg = inocg + lbn / fs->fs_maxbpg;
1467 		else
1468 			startcg = dtog(fs, prevbn) + 1;
1469 		startcg %= fs->fs_ncg;
1470 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1471 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1472 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1473 				fs->fs_cgrotor = cg;
1474 				return (cgdata(fs, cg));
1475 			}
1476 		for (cg = 0; cg <= startcg; cg++)
1477 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1478 				fs->fs_cgrotor = cg;
1479 				return (cgdata(fs, cg));
1480 			}
1481 		return (0);
1482 	}
1483 	/*
1484 	 * Otherwise, we just always try to lay things out contiguously.
1485 	 */
1486 	return (prevbn + fs->fs_frag);
1487 }
1488 
1489 /*
1490  * Same as above, but for UFS2
1491  */
1492 ufs2_daddr_t
1493 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1494 	struct inode *ip;
1495 	ufs_lbn_t lbn;
1496 	int indx;
1497 	ufs2_daddr_t *bap;
1498 {
1499 	struct fs *fs;
1500 	u_int cg, inocg;
1501 	u_int avgbfree, startcg;
1502 	ufs2_daddr_t pref, prevbn;
1503 
1504 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1505 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1506 	fs = ITOFS(ip);
1507 	/*
1508 	 * Allocation of indirect blocks is indicated by passing negative
1509 	 * values in indx: -1 for single indirect, -2 for double indirect,
1510 	 * -3 for triple indirect. As noted below, we attempt to allocate
1511 	 * the first indirect inline with the file data. For all later
1512 	 * indirect blocks, the data is often allocated in other cylinder
1513 	 * groups. However to speed random file access and to speed up
1514 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1515 	 * (typically half of fs_minfree) of the data area of each cylinder
1516 	 * group to hold these later indirect blocks.
1517 	 */
1518 	inocg = ino_to_cg(fs, ip->i_number);
1519 	if (indx < 0) {
1520 		/*
1521 		 * Our preference for indirect blocks is the zone at the
1522 		 * beginning of the inode's cylinder group data area that
1523 		 * we try to reserve for indirect blocks.
1524 		 */
1525 		pref = cgmeta(fs, inocg);
1526 		/*
1527 		 * If we are allocating the first indirect block, try to
1528 		 * place it immediately following the last direct block.
1529 		 */
1530 		if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1531 		    ip->i_din2->di_db[UFS_NDADDR - 1] != 0)
1532 			pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1533 		return (pref);
1534 	}
1535 	/*
1536 	 * If we are allocating the first data block in the first indirect
1537 	 * block and the indirect has been allocated in the data block area,
1538 	 * try to place it immediately following the indirect block.
1539 	 */
1540 	if (lbn == UFS_NDADDR) {
1541 		pref = ip->i_din2->di_ib[0];
1542 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1543 		    pref < cgbase(fs, inocg + 1))
1544 			return (pref + fs->fs_frag);
1545 	}
1546 	/*
1547 	 * If we are at the beginning of a file, or we have already allocated
1548 	 * the maximum number of blocks per cylinder group, or we do not
1549 	 * have a block allocated immediately preceding us, then we need
1550 	 * to decide where to start allocating new blocks.
1551 	 */
1552 	if (indx ==  0) {
1553 		prevbn = 0;
1554 	} else {
1555 		prevbn = bap[indx - 1];
1556 		if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1557 		    fs->fs_bsize) != 0)
1558 			prevbn = 0;
1559 	}
1560 	if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1561 		/*
1562 		 * If we are allocating a directory data block, we want
1563 		 * to place it in the metadata area.
1564 		 */
1565 		if ((ip->i_mode & IFMT) == IFDIR)
1566 			return (cgmeta(fs, inocg));
1567 		/*
1568 		 * Until we fill all the direct and all the first indirect's
1569 		 * blocks, we try to allocate in the data area of the inode's
1570 		 * cylinder group.
1571 		 */
1572 		if (lbn < UFS_NDADDR + NINDIR(fs))
1573 			return (cgdata(fs, inocg));
1574 		/*
1575 		 * Find a cylinder with greater than average number of
1576 		 * unused data blocks.
1577 		 */
1578 		if (indx == 0 || prevbn == 0)
1579 			startcg = inocg + lbn / fs->fs_maxbpg;
1580 		else
1581 			startcg = dtog(fs, prevbn) + 1;
1582 		startcg %= fs->fs_ncg;
1583 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1584 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1585 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1586 				fs->fs_cgrotor = cg;
1587 				return (cgdata(fs, cg));
1588 			}
1589 		for (cg = 0; cg <= startcg; cg++)
1590 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1591 				fs->fs_cgrotor = cg;
1592 				return (cgdata(fs, cg));
1593 			}
1594 		return (0);
1595 	}
1596 	/*
1597 	 * Otherwise, we just always try to lay things out contiguously.
1598 	 */
1599 	return (prevbn + fs->fs_frag);
1600 }
1601 
1602 /*
1603  * Implement the cylinder overflow algorithm.
1604  *
1605  * The policy implemented by this algorithm is:
1606  *   1) allocate the block in its requested cylinder group.
1607  *   2) quadradically rehash on the cylinder group number.
1608  *   3) brute force search for a free block.
1609  *
1610  * Must be called with the UFS lock held.  Will release the lock on success
1611  * and return with it held on failure.
1612  */
1613 /*VARARGS5*/
1614 static ufs2_daddr_t
1615 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1616 	struct inode *ip;
1617 	u_int cg;
1618 	ufs2_daddr_t pref;
1619 	int size;	/* Search size for data blocks, mode for inodes */
1620 	int rsize;	/* Real allocated size. */
1621 	allocfcn_t *allocator;
1622 {
1623 	struct fs *fs;
1624 	ufs2_daddr_t result;
1625 	u_int i, icg = cg;
1626 
1627 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1628 #ifdef INVARIANTS
1629 	if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1630 		panic("ffs_hashalloc: allocation on suspended filesystem");
1631 #endif
1632 	fs = ITOFS(ip);
1633 	/*
1634 	 * 1: preferred cylinder group
1635 	 */
1636 	result = (*allocator)(ip, cg, pref, size, rsize);
1637 	if (result)
1638 		return (result);
1639 	/*
1640 	 * 2: quadratic rehash
1641 	 */
1642 	for (i = 1; i < fs->fs_ncg; i *= 2) {
1643 		cg += i;
1644 		if (cg >= fs->fs_ncg)
1645 			cg -= fs->fs_ncg;
1646 		result = (*allocator)(ip, cg, 0, size, rsize);
1647 		if (result)
1648 			return (result);
1649 	}
1650 	/*
1651 	 * 3: brute force search
1652 	 * Note that we start at i == 2, since 0 was checked initially,
1653 	 * and 1 is always checked in the quadratic rehash.
1654 	 */
1655 	cg = (icg + 2) % fs->fs_ncg;
1656 	for (i = 2; i < fs->fs_ncg; i++) {
1657 		result = (*allocator)(ip, cg, 0, size, rsize);
1658 		if (result)
1659 			return (result);
1660 		cg++;
1661 		if (cg == fs->fs_ncg)
1662 			cg = 0;
1663 	}
1664 	return (0);
1665 }
1666 
1667 /*
1668  * Determine whether a fragment can be extended.
1669  *
1670  * Check to see if the necessary fragments are available, and
1671  * if they are, allocate them.
1672  */
1673 static ufs2_daddr_t
1674 ffs_fragextend(ip, cg, bprev, osize, nsize)
1675 	struct inode *ip;
1676 	u_int cg;
1677 	ufs2_daddr_t bprev;
1678 	int osize, nsize;
1679 {
1680 	struct fs *fs;
1681 	struct cg *cgp;
1682 	struct buf *bp;
1683 	struct ufsmount *ump;
1684 	int nffree;
1685 	long bno;
1686 	int frags, bbase;
1687 	int i, error;
1688 	u_int8_t *blksfree;
1689 
1690 	ump = ITOUMP(ip);
1691 	fs = ump->um_fs;
1692 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1693 		return (0);
1694 	frags = numfrags(fs, nsize);
1695 	bbase = fragnum(fs, bprev);
1696 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
1697 		/* cannot extend across a block boundary */
1698 		return (0);
1699 	}
1700 	UFS_UNLOCK(ump);
1701 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0)
1702 		goto fail;
1703 	bno = dtogd(fs, bprev);
1704 	blksfree = cg_blksfree(cgp);
1705 	for (i = numfrags(fs, osize); i < frags; i++)
1706 		if (isclr(blksfree, bno + i))
1707 			goto fail;
1708 	/*
1709 	 * the current fragment can be extended
1710 	 * deduct the count on fragment being extended into
1711 	 * increase the count on the remaining fragment (if any)
1712 	 * allocate the extended piece
1713 	 */
1714 	for (i = frags; i < fs->fs_frag - bbase; i++)
1715 		if (isclr(blksfree, bno + i))
1716 			break;
1717 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
1718 	if (i != frags)
1719 		cgp->cg_frsum[i - frags]++;
1720 	for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1721 		clrbit(blksfree, bno + i);
1722 		cgp->cg_cs.cs_nffree--;
1723 		nffree++;
1724 	}
1725 	UFS_LOCK(ump);
1726 	fs->fs_cstotal.cs_nffree -= nffree;
1727 	fs->fs_cs(fs, cg).cs_nffree -= nffree;
1728 	fs->fs_fmod = 1;
1729 	ACTIVECLEAR(fs, cg);
1730 	UFS_UNLOCK(ump);
1731 	if (DOINGSOFTDEP(ITOV(ip)))
1732 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1733 		    frags, numfrags(fs, osize));
1734 	bdwrite(bp);
1735 	return (bprev);
1736 
1737 fail:
1738 	brelse(bp);
1739 	UFS_LOCK(ump);
1740 	return (0);
1741 
1742 }
1743 
1744 /*
1745  * Determine whether a block can be allocated.
1746  *
1747  * Check to see if a block of the appropriate size is available,
1748  * and if it is, allocate it.
1749  */
1750 static ufs2_daddr_t
1751 ffs_alloccg(ip, cg, bpref, size, rsize)
1752 	struct inode *ip;
1753 	u_int cg;
1754 	ufs2_daddr_t bpref;
1755 	int size;
1756 	int rsize;
1757 {
1758 	struct fs *fs;
1759 	struct cg *cgp;
1760 	struct buf *bp;
1761 	struct ufsmount *ump;
1762 	ufs1_daddr_t bno;
1763 	ufs2_daddr_t blkno;
1764 	int i, allocsiz, error, frags;
1765 	u_int8_t *blksfree;
1766 
1767 	ump = ITOUMP(ip);
1768 	fs = ump->um_fs;
1769 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1770 		return (0);
1771 	UFS_UNLOCK(ump);
1772 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0 ||
1773 	   (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1774 		goto fail;
1775 	if (size == fs->fs_bsize) {
1776 		UFS_LOCK(ump);
1777 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1778 		ACTIVECLEAR(fs, cg);
1779 		UFS_UNLOCK(ump);
1780 		bdwrite(bp);
1781 		return (blkno);
1782 	}
1783 	/*
1784 	 * check to see if any fragments are already available
1785 	 * allocsiz is the size which will be allocated, hacking
1786 	 * it down to a smaller size if necessary
1787 	 */
1788 	blksfree = cg_blksfree(cgp);
1789 	frags = numfrags(fs, size);
1790 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1791 		if (cgp->cg_frsum[allocsiz] != 0)
1792 			break;
1793 	if (allocsiz == fs->fs_frag) {
1794 		/*
1795 		 * no fragments were available, so a block will be
1796 		 * allocated, and hacked up
1797 		 */
1798 		if (cgp->cg_cs.cs_nbfree == 0)
1799 			goto fail;
1800 		UFS_LOCK(ump);
1801 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1802 		ACTIVECLEAR(fs, cg);
1803 		UFS_UNLOCK(ump);
1804 		bdwrite(bp);
1805 		return (blkno);
1806 	}
1807 	KASSERT(size == rsize,
1808 	    ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1809 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1810 	if (bno < 0)
1811 		goto fail;
1812 	for (i = 0; i < frags; i++)
1813 		clrbit(blksfree, bno + i);
1814 	cgp->cg_cs.cs_nffree -= frags;
1815 	cgp->cg_frsum[allocsiz]--;
1816 	if (frags != allocsiz)
1817 		cgp->cg_frsum[allocsiz - frags]++;
1818 	UFS_LOCK(ump);
1819 	fs->fs_cstotal.cs_nffree -= frags;
1820 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1821 	fs->fs_fmod = 1;
1822 	blkno = cgbase(fs, cg) + bno;
1823 	ACTIVECLEAR(fs, cg);
1824 	UFS_UNLOCK(ump);
1825 	if (DOINGSOFTDEP(ITOV(ip)))
1826 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1827 	bdwrite(bp);
1828 	return (blkno);
1829 
1830 fail:
1831 	brelse(bp);
1832 	UFS_LOCK(ump);
1833 	return (0);
1834 }
1835 
1836 /*
1837  * Allocate a block in a cylinder group.
1838  *
1839  * This algorithm implements the following policy:
1840  *   1) allocate the requested block.
1841  *   2) allocate a rotationally optimal block in the same cylinder.
1842  *   3) allocate the next available block on the block rotor for the
1843  *      specified cylinder group.
1844  * Note that this routine only allocates fs_bsize blocks; these
1845  * blocks may be fragmented by the routine that allocates them.
1846  */
1847 static ufs2_daddr_t
1848 ffs_alloccgblk(ip, bp, bpref, size)
1849 	struct inode *ip;
1850 	struct buf *bp;
1851 	ufs2_daddr_t bpref;
1852 	int size;
1853 {
1854 	struct fs *fs;
1855 	struct cg *cgp;
1856 	struct ufsmount *ump;
1857 	ufs1_daddr_t bno;
1858 	ufs2_daddr_t blkno;
1859 	u_int8_t *blksfree;
1860 	int i, cgbpref;
1861 
1862 	ump = ITOUMP(ip);
1863 	fs = ump->um_fs;
1864 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1865 	cgp = (struct cg *)bp->b_data;
1866 	blksfree = cg_blksfree(cgp);
1867 	if (bpref == 0) {
1868 		bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1869 	} else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1870 		/* map bpref to correct zone in this cg */
1871 		if (bpref < cgdata(fs, cgbpref))
1872 			bpref = cgmeta(fs, cgp->cg_cgx);
1873 		else
1874 			bpref = cgdata(fs, cgp->cg_cgx);
1875 	}
1876 	/*
1877 	 * if the requested block is available, use it
1878 	 */
1879 	bno = dtogd(fs, blknum(fs, bpref));
1880 	if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1881 		goto gotit;
1882 	/*
1883 	 * Take the next available block in this cylinder group.
1884 	 */
1885 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1886 	if (bno < 0)
1887 		return (0);
1888 	/* Update cg_rotor only if allocated from the data zone */
1889 	if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1890 		cgp->cg_rotor = bno;
1891 gotit:
1892 	blkno = fragstoblks(fs, bno);
1893 	ffs_clrblock(fs, blksfree, (long)blkno);
1894 	ffs_clusteracct(fs, cgp, blkno, -1);
1895 	cgp->cg_cs.cs_nbfree--;
1896 	fs->fs_cstotal.cs_nbfree--;
1897 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1898 	fs->fs_fmod = 1;
1899 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1900 	/*
1901 	 * If the caller didn't want the whole block free the frags here.
1902 	 */
1903 	size = numfrags(fs, size);
1904 	if (size != fs->fs_frag) {
1905 		bno = dtogd(fs, blkno);
1906 		for (i = size; i < fs->fs_frag; i++)
1907 			setbit(blksfree, bno + i);
1908 		i = fs->fs_frag - size;
1909 		cgp->cg_cs.cs_nffree += i;
1910 		fs->fs_cstotal.cs_nffree += i;
1911 		fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1912 		fs->fs_fmod = 1;
1913 		cgp->cg_frsum[i]++;
1914 	}
1915 	/* XXX Fixme. */
1916 	UFS_UNLOCK(ump);
1917 	if (DOINGSOFTDEP(ITOV(ip)))
1918 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, size, 0);
1919 	UFS_LOCK(ump);
1920 	return (blkno);
1921 }
1922 
1923 /*
1924  * Determine whether a cluster can be allocated.
1925  *
1926  * We do not currently check for optimal rotational layout if there
1927  * are multiple choices in the same cylinder group. Instead we just
1928  * take the first one that we find following bpref.
1929  */
1930 static ufs2_daddr_t
1931 ffs_clusteralloc(ip, cg, bpref, len)
1932 	struct inode *ip;
1933 	u_int cg;
1934 	ufs2_daddr_t bpref;
1935 	int len;
1936 {
1937 	struct fs *fs;
1938 	struct cg *cgp;
1939 	struct buf *bp;
1940 	struct ufsmount *ump;
1941 	int i, run, bit, map, got, error;
1942 	ufs2_daddr_t bno;
1943 	u_char *mapp;
1944 	int32_t *lp;
1945 	u_int8_t *blksfree;
1946 
1947 	ump = ITOUMP(ip);
1948 	fs = ump->um_fs;
1949 	if (fs->fs_maxcluster[cg] < len)
1950 		return (0);
1951 	UFS_UNLOCK(ump);
1952 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
1953 		UFS_LOCK(ump);
1954 		return (0);
1955 	}
1956 	/*
1957 	 * Check to see if a cluster of the needed size (or bigger) is
1958 	 * available in this cylinder group.
1959 	 */
1960 	lp = &cg_clustersum(cgp)[len];
1961 	for (i = len; i <= fs->fs_contigsumsize; i++)
1962 		if (*lp++ > 0)
1963 			break;
1964 	if (i > fs->fs_contigsumsize) {
1965 		/*
1966 		 * This is the first time looking for a cluster in this
1967 		 * cylinder group. Update the cluster summary information
1968 		 * to reflect the true maximum sized cluster so that
1969 		 * future cluster allocation requests can avoid reading
1970 		 * the cylinder group map only to find no clusters.
1971 		 */
1972 		lp = &cg_clustersum(cgp)[len - 1];
1973 		for (i = len - 1; i > 0; i--)
1974 			if (*lp-- > 0)
1975 				break;
1976 		UFS_LOCK(ump);
1977 		fs->fs_maxcluster[cg] = i;
1978 		brelse(bp);
1979 		return (0);
1980 	}
1981 	/*
1982 	 * Search the cluster map to find a big enough cluster.
1983 	 * We take the first one that we find, even if it is larger
1984 	 * than we need as we prefer to get one close to the previous
1985 	 * block allocation. We do not search before the current
1986 	 * preference point as we do not want to allocate a block
1987 	 * that is allocated before the previous one (as we will
1988 	 * then have to wait for another pass of the elevator
1989 	 * algorithm before it will be read). We prefer to fail and
1990 	 * be recalled to try an allocation in the next cylinder group.
1991 	 */
1992 	if (dtog(fs, bpref) != cg)
1993 		bpref = cgdata(fs, cg);
1994 	else
1995 		bpref = blknum(fs, bpref);
1996 	bpref = fragstoblks(fs, dtogd(fs, bpref));
1997 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1998 	map = *mapp++;
1999 	bit = 1 << (bpref % NBBY);
2000 	for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
2001 		if ((map & bit) == 0) {
2002 			run = 0;
2003 		} else {
2004 			run++;
2005 			if (run == len)
2006 				break;
2007 		}
2008 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
2009 			bit <<= 1;
2010 		} else {
2011 			map = *mapp++;
2012 			bit = 1;
2013 		}
2014 	}
2015 	if (got >= cgp->cg_nclusterblks) {
2016 		UFS_LOCK(ump);
2017 		brelse(bp);
2018 		return (0);
2019 	}
2020 	/*
2021 	 * Allocate the cluster that we have found.
2022 	 */
2023 	blksfree = cg_blksfree(cgp);
2024 	for (i = 1; i <= len; i++)
2025 		if (!ffs_isblock(fs, blksfree, got - run + i))
2026 			panic("ffs_clusteralloc: map mismatch");
2027 	bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
2028 	if (dtog(fs, bno) != cg)
2029 		panic("ffs_clusteralloc: allocated out of group");
2030 	len = blkstofrags(fs, len);
2031 	UFS_LOCK(ump);
2032 	for (i = 0; i < len; i += fs->fs_frag)
2033 		if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
2034 			panic("ffs_clusteralloc: lost block");
2035 	ACTIVECLEAR(fs, cg);
2036 	UFS_UNLOCK(ump);
2037 	bdwrite(bp);
2038 	return (bno);
2039 }
2040 
2041 static inline struct buf *
2042 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
2043 {
2044 	struct fs *fs;
2045 
2046 	fs = ITOFS(ip);
2047 	return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
2048 	    cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
2049 	    gbflags));
2050 }
2051 
2052 /*
2053  * Synchronous inode initialization is needed only when barrier writes do not
2054  * work as advertised, and will impose a heavy cost on file creation in a newly
2055  * created filesystem.
2056  */
2057 static int doasyncinodeinit = 1;
2058 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncinodeinit, CTLFLAG_RWTUN,
2059     &doasyncinodeinit, 0,
2060     "Perform inode block initialization using asynchronous writes");
2061 
2062 /*
2063  * Determine whether an inode can be allocated.
2064  *
2065  * Check to see if an inode is available, and if it is,
2066  * allocate it using the following policy:
2067  *   1) allocate the requested inode.
2068  *   2) allocate the next available inode after the requested
2069  *      inode in the specified cylinder group.
2070  */
2071 static ufs2_daddr_t
2072 ffs_nodealloccg(ip, cg, ipref, mode, unused)
2073 	struct inode *ip;
2074 	u_int cg;
2075 	ufs2_daddr_t ipref;
2076 	int mode;
2077 	int unused;
2078 {
2079 	struct fs *fs;
2080 	struct cg *cgp;
2081 	struct buf *bp, *ibp;
2082 	struct ufsmount *ump;
2083 	u_int8_t *inosused, *loc;
2084 	struct ufs2_dinode *dp2;
2085 	int error, start, len, i;
2086 	u_int32_t old_initediblk;
2087 
2088 	ump = ITOUMP(ip);
2089 	fs = ump->um_fs;
2090 check_nifree:
2091 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
2092 		return (0);
2093 	UFS_UNLOCK(ump);
2094 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
2095 		UFS_LOCK(ump);
2096 		return (0);
2097 	}
2098 restart:
2099 	if (cgp->cg_cs.cs_nifree == 0) {
2100 		brelse(bp);
2101 		UFS_LOCK(ump);
2102 		return (0);
2103 	}
2104 	inosused = cg_inosused(cgp);
2105 	if (ipref) {
2106 		ipref %= fs->fs_ipg;
2107 		if (isclr(inosused, ipref))
2108 			goto gotit;
2109 	}
2110 	start = cgp->cg_irotor / NBBY;
2111 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
2112 	loc = memcchr(&inosused[start], 0xff, len);
2113 	if (loc == NULL) {
2114 		len = start + 1;
2115 		start = 0;
2116 		loc = memcchr(&inosused[start], 0xff, len);
2117 		if (loc == NULL) {
2118 			printf("cg = %d, irotor = %ld, fs = %s\n",
2119 			    cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2120 			panic("ffs_nodealloccg: map corrupted");
2121 			/* NOTREACHED */
2122 		}
2123 	}
2124 	ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2125 gotit:
2126 	/*
2127 	 * Check to see if we need to initialize more inodes.
2128 	 */
2129 	if (fs->fs_magic == FS_UFS2_MAGIC &&
2130 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
2131 	    cgp->cg_initediblk < cgp->cg_niblk) {
2132 		old_initediblk = cgp->cg_initediblk;
2133 
2134 		/*
2135 		 * Free the cylinder group lock before writing the
2136 		 * initialized inode block.  Entering the
2137 		 * babarrierwrite() with the cylinder group lock
2138 		 * causes lock order violation between the lock and
2139 		 * snaplk.
2140 		 *
2141 		 * Another thread can decide to initialize the same
2142 		 * inode block, but whichever thread first gets the
2143 		 * cylinder group lock after writing the newly
2144 		 * allocated inode block will update it and the other
2145 		 * will realize that it has lost and leave the
2146 		 * cylinder group unchanged.
2147 		 */
2148 		ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2149 		brelse(bp);
2150 		if (ibp == NULL) {
2151 			/*
2152 			 * The inode block buffer is already owned by
2153 			 * another thread, which must initialize it.
2154 			 * Wait on the buffer to allow another thread
2155 			 * to finish the updates, with dropped cg
2156 			 * buffer lock, then retry.
2157 			 */
2158 			ibp = getinobuf(ip, cg, old_initediblk, 0);
2159 			brelse(ibp);
2160 			UFS_LOCK(ump);
2161 			goto check_nifree;
2162 		}
2163 		bzero(ibp->b_data, (int)fs->fs_bsize);
2164 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
2165 		for (i = 0; i < INOPB(fs); i++) {
2166 			while (dp2->di_gen == 0)
2167 				dp2->di_gen = arc4random();
2168 			dp2++;
2169 		}
2170 
2171 		/*
2172 		 * Rather than adding a soft updates dependency to ensure
2173 		 * that the new inode block is written before it is claimed
2174 		 * by the cylinder group map, we just do a barrier write
2175 		 * here. The barrier write will ensure that the inode block
2176 		 * gets written before the updated cylinder group map can be
2177 		 * written. The barrier write should only slow down bulk
2178 		 * loading of newly created filesystems.
2179 		 */
2180 		if (doasyncinodeinit)
2181 			babarrierwrite(ibp);
2182 		else
2183 			bwrite(ibp);
2184 
2185 		/*
2186 		 * After the inode block is written, try to update the
2187 		 * cg initediblk pointer.  If another thread beat us
2188 		 * to it, then leave it unchanged as the other thread
2189 		 * has already set it correctly.
2190 		 */
2191 		error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp);
2192 		UFS_LOCK(ump);
2193 		ACTIVECLEAR(fs, cg);
2194 		UFS_UNLOCK(ump);
2195 		if (error != 0)
2196 			return (error);
2197 		if (cgp->cg_initediblk == old_initediblk)
2198 			cgp->cg_initediblk += INOPB(fs);
2199 		goto restart;
2200 	}
2201 	cgp->cg_irotor = ipref;
2202 	UFS_LOCK(ump);
2203 	ACTIVECLEAR(fs, cg);
2204 	setbit(inosused, ipref);
2205 	cgp->cg_cs.cs_nifree--;
2206 	fs->fs_cstotal.cs_nifree--;
2207 	fs->fs_cs(fs, cg).cs_nifree--;
2208 	fs->fs_fmod = 1;
2209 	if ((mode & IFMT) == IFDIR) {
2210 		cgp->cg_cs.cs_ndir++;
2211 		fs->fs_cstotal.cs_ndir++;
2212 		fs->fs_cs(fs, cg).cs_ndir++;
2213 	}
2214 	UFS_UNLOCK(ump);
2215 	if (DOINGSOFTDEP(ITOV(ip)))
2216 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2217 	bdwrite(bp);
2218 	return ((ino_t)(cg * fs->fs_ipg + ipref));
2219 }
2220 
2221 /*
2222  * Free a block or fragment.
2223  *
2224  * The specified block or fragment is placed back in the
2225  * free map. If a fragment is deallocated, a possible
2226  * block reassembly is checked.
2227  */
2228 static void
2229 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2230 	struct ufsmount *ump;
2231 	struct fs *fs;
2232 	struct vnode *devvp;
2233 	ufs2_daddr_t bno;
2234 	long size;
2235 	ino_t inum;
2236 	struct workhead *dephd;
2237 {
2238 	struct mount *mp;
2239 	struct cg *cgp;
2240 	struct buf *bp;
2241 	daddr_t dbn;
2242 	ufs1_daddr_t fragno, cgbno;
2243 	int i, blk, frags, bbase, error;
2244 	u_int cg;
2245 	u_int8_t *blksfree;
2246 	struct cdev *dev;
2247 
2248 	cg = dtog(fs, bno);
2249 	if (devvp->v_type == VREG) {
2250 		/* devvp is a snapshot */
2251 		MPASS(devvp->v_mount->mnt_data == ump);
2252 		dev = ump->um_devvp->v_rdev;
2253 	} else if (devvp->v_type == VCHR) {
2254 		/*
2255 		 * devvp is a normal disk device
2256 		 * XXXKIB: devvp is not locked there, v_rdev access depends on
2257 		 * busy mount, which prevents mntfs devvp from reclamation.
2258 		 */
2259 		dev = devvp->v_rdev;
2260 	} else
2261 		return;
2262 #ifdef INVARIANTS
2263 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2264 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2265 		printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2266 		    devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2267 		    size, fs->fs_fsmnt);
2268 		panic("ffs_blkfree_cg: bad size");
2269 	}
2270 #endif
2271 	if ((u_int)bno >= fs->fs_size) {
2272 		printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2273 		    (u_long)inum);
2274 		ffs_fserr(fs, inum, "bad block");
2275 		return;
2276 	}
2277 	if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2278 		if (!ffs_fsfail_cleanup(ump, error) ||
2279 		    !MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2280 			return;
2281 		if (devvp->v_type == VREG)
2282 			dbn = fragstoblks(fs, cgtod(fs, cg));
2283 		else
2284 			dbn = fsbtodb(fs, cgtod(fs, cg));
2285 		error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2286 		KASSERT(error == 0, ("getblkx failed"));
2287 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2288 		    numfrags(fs, size), dephd);
2289 		bp->b_flags |= B_RELBUF | B_NOCACHE;
2290 		bp->b_flags &= ~B_CACHE;
2291 		bawrite(bp);
2292 		return;
2293 	}
2294 	cgbno = dtogd(fs, bno);
2295 	blksfree = cg_blksfree(cgp);
2296 	UFS_LOCK(ump);
2297 	if (size == fs->fs_bsize) {
2298 		fragno = fragstoblks(fs, cgbno);
2299 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2300 			if (devvp->v_type == VREG) {
2301 				UFS_UNLOCK(ump);
2302 				/* devvp is a snapshot */
2303 				brelse(bp);
2304 				return;
2305 			}
2306 			printf("dev = %s, block = %jd, fs = %s\n",
2307 			    devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2308 			panic("ffs_blkfree_cg: freeing free block");
2309 		}
2310 		ffs_setblock(fs, blksfree, fragno);
2311 		ffs_clusteracct(fs, cgp, fragno, 1);
2312 		cgp->cg_cs.cs_nbfree++;
2313 		fs->fs_cstotal.cs_nbfree++;
2314 		fs->fs_cs(fs, cg).cs_nbfree++;
2315 	} else {
2316 		bbase = cgbno - fragnum(fs, cgbno);
2317 		/*
2318 		 * decrement the counts associated with the old frags
2319 		 */
2320 		blk = blkmap(fs, blksfree, bbase);
2321 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2322 		/*
2323 		 * deallocate the fragment
2324 		 */
2325 		frags = numfrags(fs, size);
2326 		for (i = 0; i < frags; i++) {
2327 			if (isset(blksfree, cgbno + i)) {
2328 				printf("dev = %s, block = %jd, fs = %s\n",
2329 				    devtoname(dev), (intmax_t)(bno + i),
2330 				    fs->fs_fsmnt);
2331 				panic("ffs_blkfree_cg: freeing free frag");
2332 			}
2333 			setbit(blksfree, cgbno + i);
2334 		}
2335 		cgp->cg_cs.cs_nffree += i;
2336 		fs->fs_cstotal.cs_nffree += i;
2337 		fs->fs_cs(fs, cg).cs_nffree += i;
2338 		/*
2339 		 * add back in counts associated with the new frags
2340 		 */
2341 		blk = blkmap(fs, blksfree, bbase);
2342 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2343 		/*
2344 		 * if a complete block has been reassembled, account for it
2345 		 */
2346 		fragno = fragstoblks(fs, bbase);
2347 		if (ffs_isblock(fs, blksfree, fragno)) {
2348 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
2349 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2350 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2351 			ffs_clusteracct(fs, cgp, fragno, 1);
2352 			cgp->cg_cs.cs_nbfree++;
2353 			fs->fs_cstotal.cs_nbfree++;
2354 			fs->fs_cs(fs, cg).cs_nbfree++;
2355 		}
2356 	}
2357 	fs->fs_fmod = 1;
2358 	ACTIVECLEAR(fs, cg);
2359 	UFS_UNLOCK(ump);
2360 	mp = UFSTOVFS(ump);
2361 	if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2362 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2363 		    numfrags(fs, size), dephd);
2364 	bdwrite(bp);
2365 }
2366 
2367 /*
2368  * Structures and routines associated with trim management.
2369  *
2370  * The following requests are passed to trim_lookup to indicate
2371  * the actions that should be taken.
2372  */
2373 #define	NEW	1	/* if found, error else allocate and hash it */
2374 #define	OLD	2	/* if not found, error, else return it */
2375 #define	REPLACE	3	/* if not found, error else unhash and reallocate it */
2376 #define	DONE	4	/* if not found, error else unhash and return it */
2377 #define	SINGLE	5	/* don't look up, just allocate it and don't hash it */
2378 
2379 MALLOC_DEFINE(M_TRIM, "ufs_trim", "UFS trim structures");
2380 
2381 #define	TRIMLIST_HASH(ump, key) \
2382 	(&(ump)->um_trimhash[(key) & (ump)->um_trimlisthashsize])
2383 
2384 /*
2385  * These structures describe each of the block free requests aggregated
2386  * together to make up a trim request.
2387  */
2388 struct trim_blkreq {
2389 	TAILQ_ENTRY(trim_blkreq) blkreqlist;
2390 	ufs2_daddr_t bno;
2391 	long size;
2392 	struct workhead *pdephd;
2393 	struct workhead dephd;
2394 };
2395 
2396 /*
2397  * Description of a trim request.
2398  */
2399 struct ffs_blkfree_trim_params {
2400 	TAILQ_HEAD(, trim_blkreq) blklist;
2401 	LIST_ENTRY(ffs_blkfree_trim_params) hashlist;
2402 	struct task task;
2403 	struct ufsmount *ump;
2404 	struct vnode *devvp;
2405 	ino_t inum;
2406 	ufs2_daddr_t bno;
2407 	long size;
2408 	long key;
2409 };
2410 
2411 static void	ffs_blkfree_trim_completed(struct buf *);
2412 static void	ffs_blkfree_trim_task(void *ctx, int pending __unused);
2413 static struct	ffs_blkfree_trim_params *trim_lookup(struct ufsmount *,
2414 		    struct vnode *, ufs2_daddr_t, long, ino_t, u_long, int);
2415 static void	ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params *);
2416 
2417 /*
2418  * Called on trim completion to start a task to free the associated block(s).
2419  */
2420 static void
2421 ffs_blkfree_trim_completed(bp)
2422 	struct buf *bp;
2423 {
2424 	struct ffs_blkfree_trim_params *tp;
2425 
2426 	tp = bp->b_fsprivate1;
2427 	free(bp, M_TRIM);
2428 	TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2429 	taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
2430 }
2431 
2432 /*
2433  * Trim completion task that free associated block(s).
2434  */
2435 static void
2436 ffs_blkfree_trim_task(ctx, pending)
2437 	void *ctx;
2438 	int pending;
2439 {
2440 	struct ffs_blkfree_trim_params *tp;
2441 	struct trim_blkreq *blkelm;
2442 	struct ufsmount *ump;
2443 
2444 	tp = ctx;
2445 	ump = tp->ump;
2446 	while ((blkelm = TAILQ_FIRST(&tp->blklist)) != NULL) {
2447 		ffs_blkfree_cg(ump, ump->um_fs, tp->devvp, blkelm->bno,
2448 		    blkelm->size, tp->inum, blkelm->pdephd);
2449 		TAILQ_REMOVE(&tp->blklist, blkelm, blkreqlist);
2450 		free(blkelm, M_TRIM);
2451 	}
2452 	vn_finished_secondary_write(UFSTOVFS(ump));
2453 	UFS_LOCK(ump);
2454 	ump->um_trim_inflight -= 1;
2455 	ump->um_trim_inflight_blks -= numfrags(ump->um_fs, tp->size);
2456 	UFS_UNLOCK(ump);
2457 	free(tp, M_TRIM);
2458 }
2459 
2460 /*
2461  * Lookup a trim request by inode number.
2462  * Allocate if requested (NEW, REPLACE, SINGLE).
2463  */
2464 static struct ffs_blkfree_trim_params *
2465 trim_lookup(ump, devvp, bno, size, inum, key, alloctype)
2466 	struct ufsmount *ump;
2467 	struct vnode *devvp;
2468 	ufs2_daddr_t bno;
2469 	long size;
2470 	ino_t inum;
2471 	u_long key;
2472 	int alloctype;
2473 {
2474 	struct trimlist_hashhead *tphashhead;
2475 	struct ffs_blkfree_trim_params *tp, *ntp;
2476 
2477 	ntp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TRIM, M_WAITOK);
2478 	if (alloctype != SINGLE) {
2479 		KASSERT(key >= FIRST_VALID_KEY, ("trim_lookup: invalid key"));
2480 		UFS_LOCK(ump);
2481 		tphashhead = TRIMLIST_HASH(ump, key);
2482 		LIST_FOREACH(tp, tphashhead, hashlist)
2483 			if (key == tp->key)
2484 				break;
2485 	}
2486 	switch (alloctype) {
2487 	case NEW:
2488 		KASSERT(tp == NULL, ("trim_lookup: found trim"));
2489 		break;
2490 	case OLD:
2491 		KASSERT(tp != NULL,
2492 		    ("trim_lookup: missing call to ffs_blkrelease_start()"));
2493 		UFS_UNLOCK(ump);
2494 		free(ntp, M_TRIM);
2495 		return (tp);
2496 	case REPLACE:
2497 		KASSERT(tp != NULL, ("trim_lookup: missing REPLACE trim"));
2498 		LIST_REMOVE(tp, hashlist);
2499 		/* tp will be freed by caller */
2500 		break;
2501 	case DONE:
2502 		KASSERT(tp != NULL, ("trim_lookup: missing DONE trim"));
2503 		LIST_REMOVE(tp, hashlist);
2504 		UFS_UNLOCK(ump);
2505 		free(ntp, M_TRIM);
2506 		return (tp);
2507 	}
2508 	TAILQ_INIT(&ntp->blklist);
2509 	ntp->ump = ump;
2510 	ntp->devvp = devvp;
2511 	ntp->bno = bno;
2512 	ntp->size = size;
2513 	ntp->inum = inum;
2514 	ntp->key = key;
2515 	if (alloctype != SINGLE) {
2516 		LIST_INSERT_HEAD(tphashhead, ntp, hashlist);
2517 		UFS_UNLOCK(ump);
2518 	}
2519 	return (ntp);
2520 }
2521 
2522 /*
2523  * Dispatch a trim request.
2524  */
2525 static void
2526 ffs_blkfree_sendtrim(tp)
2527 	struct ffs_blkfree_trim_params *tp;
2528 {
2529 	struct ufsmount *ump;
2530 	struct mount *mp;
2531 	struct buf *bp;
2532 
2533 	/*
2534 	 * Postpone the set of the free bit in the cg bitmap until the
2535 	 * BIO_DELETE is completed.  Otherwise, due to disk queue
2536 	 * reordering, TRIM might be issued after we reuse the block
2537 	 * and write some new data into it.
2538 	 */
2539 	ump = tp->ump;
2540 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
2541 	bp->b_iocmd = BIO_DELETE;
2542 	bp->b_iooffset = dbtob(fsbtodb(ump->um_fs, tp->bno));
2543 	bp->b_iodone = ffs_blkfree_trim_completed;
2544 	bp->b_bcount = tp->size;
2545 	bp->b_fsprivate1 = tp;
2546 	UFS_LOCK(ump);
2547 	ump->um_trim_total += 1;
2548 	ump->um_trim_inflight += 1;
2549 	ump->um_trim_inflight_blks += numfrags(ump->um_fs, tp->size);
2550 	ump->um_trim_total_blks += numfrags(ump->um_fs, tp->size);
2551 	UFS_UNLOCK(ump);
2552 
2553 	mp = UFSTOVFS(ump);
2554 	vn_start_secondary_write(NULL, &mp, 0);
2555 	g_vfs_strategy(ump->um_bo, bp);
2556 }
2557 
2558 /*
2559  * Allocate a new key to use to identify a range of blocks.
2560  */
2561 u_long
2562 ffs_blkrelease_start(ump, devvp, inum)
2563 	struct ufsmount *ump;
2564 	struct vnode *devvp;
2565 	ino_t inum;
2566 {
2567 	static u_long masterkey;
2568 	u_long key;
2569 
2570 	if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2571 		return (SINGLETON_KEY);
2572 	do {
2573 		key = atomic_fetchadd_long(&masterkey, 1);
2574 	} while (key < FIRST_VALID_KEY);
2575 	(void) trim_lookup(ump, devvp, 0, 0, inum, key, NEW);
2576 	return (key);
2577 }
2578 
2579 /*
2580  * Deallocate a key that has been used to identify a range of blocks.
2581  */
2582 void
2583 ffs_blkrelease_finish(ump, key)
2584 	struct ufsmount *ump;
2585 	u_long key;
2586 {
2587 	struct ffs_blkfree_trim_params *tp;
2588 
2589 	if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2590 		return;
2591 	/*
2592 	 * If the vfs.ffs.dotrimcons sysctl option is enabled while
2593 	 * a file deletion is active, specifically after a call
2594 	 * to ffs_blkrelease_start() but before the call to
2595 	 * ffs_blkrelease_finish(), ffs_blkrelease_start() will
2596 	 * have handed out SINGLETON_KEY rather than starting a
2597 	 * collection sequence. Thus if we get a SINGLETON_KEY
2598 	 * passed to ffs_blkrelease_finish(), we just return rather
2599 	 * than trying to finish the nonexistent sequence.
2600 	 */
2601 	if (key == SINGLETON_KEY) {
2602 #ifdef INVARIANTS
2603 		printf("%s: vfs.ffs.dotrimcons enabled on active filesystem\n",
2604 		    ump->um_mountp->mnt_stat.f_mntonname);
2605 #endif
2606 		return;
2607 	}
2608 	/*
2609 	 * We are done with sending blocks using this key. Look up the key
2610 	 * using the DONE alloctype (in tp) to request that it be unhashed
2611 	 * as we will not be adding to it. If the key has never been used,
2612 	 * tp->size will be zero, so we can just free tp. Otherwise the call
2613 	 * to ffs_blkfree_sendtrim(tp) causes the block range described by
2614 	 * tp to be issued (and then tp to be freed).
2615 	 */
2616 	tp = trim_lookup(ump, NULL, 0, 0, 0, key, DONE);
2617 	if (tp->size == 0)
2618 		free(tp, M_TRIM);
2619 	else
2620 		ffs_blkfree_sendtrim(tp);
2621 }
2622 
2623 /*
2624  * Setup to free a block or fragment.
2625  *
2626  * Check for snapshots that might want to claim the block.
2627  * If trims are requested, prepare a trim request. Attempt to
2628  * aggregate consecutive blocks into a single trim request.
2629  */
2630 void
2631 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd, key)
2632 	struct ufsmount *ump;
2633 	struct fs *fs;
2634 	struct vnode *devvp;
2635 	ufs2_daddr_t bno;
2636 	long size;
2637 	ino_t inum;
2638 	enum vtype vtype;
2639 	struct workhead *dephd;
2640 	u_long key;
2641 {
2642 	struct ffs_blkfree_trim_params *tp, *ntp;
2643 	struct trim_blkreq *blkelm;
2644 
2645 	/*
2646 	 * Check to see if a snapshot wants to claim the block.
2647 	 * Check that devvp is a normal disk device, not a snapshot,
2648 	 * it has a snapshot(s) associated with it, and one of the
2649 	 * snapshots wants to claim the block.
2650 	 */
2651 	if (devvp->v_type == VCHR &&
2652 	    (devvp->v_vflag & VV_COPYONWRITE) &&
2653 	    ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2654 		return;
2655 	}
2656 	/*
2657 	 * Nothing to delay if TRIM is not required for this block or TRIM
2658 	 * is disabled or the operation is performed on a snapshot.
2659 	 */
2660 	if (key == NOTRIM_KEY || ((ump->um_flags & UM_CANDELETE) == 0) ||
2661 	    devvp->v_type == VREG) {
2662 		ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2663 		return;
2664 	}
2665 	blkelm = malloc(sizeof(struct trim_blkreq), M_TRIM, M_WAITOK);
2666 	blkelm->bno = bno;
2667 	blkelm->size = size;
2668 	if (dephd == NULL) {
2669 		blkelm->pdephd = NULL;
2670 	} else {
2671 		LIST_INIT(&blkelm->dephd);
2672 		LIST_SWAP(dephd, &blkelm->dephd, worklist, wk_list);
2673 		blkelm->pdephd = &blkelm->dephd;
2674 	}
2675 	if (key == SINGLETON_KEY) {
2676 		/*
2677 		 * Just a single non-contiguous piece. Use the SINGLE
2678 		 * alloctype to return a trim request that will not be
2679 		 * hashed for future lookup.
2680 		 */
2681 		tp = trim_lookup(ump, devvp, bno, size, inum, key, SINGLE);
2682 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2683 		ffs_blkfree_sendtrim(tp);
2684 		return;
2685 	}
2686 	/*
2687 	 * The callers of this function are not tracking whether or not
2688 	 * the blocks are contiguous. They are just saying that they
2689 	 * are freeing a set of blocks. It is this code that determines
2690 	 * the pieces of that range that are actually contiguous.
2691 	 *
2692 	 * Calling ffs_blkrelease_start() will have created an entry
2693 	 * that we will use.
2694 	 */
2695 	tp = trim_lookup(ump, devvp, bno, size, inum, key, OLD);
2696 	if (tp->size == 0) {
2697 		/*
2698 		 * First block of a potential range, set block and size
2699 		 * for the trim block.
2700 		 */
2701 		tp->bno = bno;
2702 		tp->size = size;
2703 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2704 		return;
2705 	}
2706 	/*
2707 	 * If this block is a continuation of the range (either
2708 	 * follows at the end or preceeds in the front) then we
2709 	 * add it to the front or back of the list and return.
2710 	 *
2711 	 * If it is not a continuation of the trim that we were
2712 	 * building, using the REPLACE alloctype, we request that
2713 	 * the old trim request (still in tp) be unhashed and a
2714 	 * new range started (in ntp). The ffs_blkfree_sendtrim(tp)
2715 	 * call causes the block range described by tp to be issued
2716 	 * (and then tp to be freed).
2717 	 */
2718 	if (bno + numfrags(fs, size) == tp->bno) {
2719 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2720 		tp->bno = bno;
2721 		tp->size += size;
2722 		return;
2723 	} else if (bno == tp->bno + numfrags(fs, tp->size)) {
2724 		TAILQ_INSERT_TAIL(&tp->blklist, blkelm, blkreqlist);
2725 		tp->size += size;
2726 		return;
2727 	}
2728 	ntp = trim_lookup(ump, devvp, bno, size, inum, key, REPLACE);
2729 	TAILQ_INSERT_HEAD(&ntp->blklist, blkelm, blkreqlist);
2730 	ffs_blkfree_sendtrim(tp);
2731 }
2732 
2733 #ifdef INVARIANTS
2734 /*
2735  * Verify allocation of a block or fragment. Returns true if block or
2736  * fragment is allocated, false if it is free.
2737  */
2738 static int
2739 ffs_checkblk(ip, bno, size)
2740 	struct inode *ip;
2741 	ufs2_daddr_t bno;
2742 	long size;
2743 {
2744 	struct fs *fs;
2745 	struct cg *cgp;
2746 	struct buf *bp;
2747 	ufs1_daddr_t cgbno;
2748 	int i, error, frags, free;
2749 	u_int8_t *blksfree;
2750 
2751 	fs = ITOFS(ip);
2752 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2753 		printf("bsize = %ld, size = %ld, fs = %s\n",
2754 		    (long)fs->fs_bsize, size, fs->fs_fsmnt);
2755 		panic("ffs_checkblk: bad size");
2756 	}
2757 	if ((u_int)bno >= fs->fs_size)
2758 		panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2759 	error = ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), 0, &bp, &cgp);
2760 	if (error)
2761 		panic("ffs_checkblk: cylinder group read failed");
2762 	blksfree = cg_blksfree(cgp);
2763 	cgbno = dtogd(fs, bno);
2764 	if (size == fs->fs_bsize) {
2765 		free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2766 	} else {
2767 		frags = numfrags(fs, size);
2768 		for (free = 0, i = 0; i < frags; i++)
2769 			if (isset(blksfree, cgbno + i))
2770 				free++;
2771 		if (free != 0 && free != frags)
2772 			panic("ffs_checkblk: partially free fragment");
2773 	}
2774 	brelse(bp);
2775 	return (!free);
2776 }
2777 #endif /* INVARIANTS */
2778 
2779 /*
2780  * Free an inode.
2781  */
2782 int
2783 ffs_vfree(pvp, ino, mode)
2784 	struct vnode *pvp;
2785 	ino_t ino;
2786 	int mode;
2787 {
2788 	struct ufsmount *ump;
2789 
2790 	if (DOINGSOFTDEP(pvp)) {
2791 		softdep_freefile(pvp, ino, mode);
2792 		return (0);
2793 	}
2794 	ump = VFSTOUFS(pvp->v_mount);
2795 	return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2796 }
2797 
2798 /*
2799  * Do the actual free operation.
2800  * The specified inode is placed back in the free map.
2801  */
2802 int
2803 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2804 	struct ufsmount *ump;
2805 	struct fs *fs;
2806 	struct vnode *devvp;
2807 	ino_t ino;
2808 	int mode;
2809 	struct workhead *wkhd;
2810 {
2811 	struct cg *cgp;
2812 	struct buf *bp;
2813 	daddr_t dbn;
2814 	int error;
2815 	u_int cg;
2816 	u_int8_t *inosused;
2817 	struct cdev *dev;
2818 	ino_t cgino;
2819 
2820 	cg = ino_to_cg(fs, ino);
2821 	if (devvp->v_type == VREG) {
2822 		/* devvp is a snapshot */
2823 		MPASS(devvp->v_mount->mnt_data == ump);
2824 		dev = ump->um_devvp->v_rdev;
2825 	} else if (devvp->v_type == VCHR) {
2826 		/* devvp is a normal disk device */
2827 		dev = devvp->v_rdev;
2828 	} else {
2829 		bp = NULL;
2830 		return (0);
2831 	}
2832 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2833 		panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2834 		    devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2835 	if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2836 		if (!ffs_fsfail_cleanup(ump, error) ||
2837 		    !MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2838 			return (error);
2839 		if (devvp->v_type == VREG)
2840 			dbn = fragstoblks(fs, cgtod(fs, cg));
2841 		else
2842 			dbn = fsbtodb(fs, cgtod(fs, cg));
2843 		error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2844 		KASSERT(error == 0, ("getblkx failed"));
2845 		softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd);
2846 		bp->b_flags |= B_RELBUF | B_NOCACHE;
2847 		bp->b_flags &= ~B_CACHE;
2848 		bawrite(bp);
2849 		return (error);
2850 	}
2851 	inosused = cg_inosused(cgp);
2852 	cgino = ino % fs->fs_ipg;
2853 	if (isclr(inosused, cgino)) {
2854 		printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2855 		    (uintmax_t)ino, fs->fs_fsmnt);
2856 		if (fs->fs_ronly == 0)
2857 			panic("ffs_freefile: freeing free inode");
2858 	}
2859 	clrbit(inosused, cgino);
2860 	if (cgino < cgp->cg_irotor)
2861 		cgp->cg_irotor = cgino;
2862 	cgp->cg_cs.cs_nifree++;
2863 	UFS_LOCK(ump);
2864 	fs->fs_cstotal.cs_nifree++;
2865 	fs->fs_cs(fs, cg).cs_nifree++;
2866 	if ((mode & IFMT) == IFDIR) {
2867 		cgp->cg_cs.cs_ndir--;
2868 		fs->fs_cstotal.cs_ndir--;
2869 		fs->fs_cs(fs, cg).cs_ndir--;
2870 	}
2871 	fs->fs_fmod = 1;
2872 	ACTIVECLEAR(fs, cg);
2873 	UFS_UNLOCK(ump);
2874 	if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2875 		softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd);
2876 	bdwrite(bp);
2877 	return (0);
2878 }
2879 
2880 /*
2881  * Check to see if a file is free.
2882  * Used to check for allocated files in snapshots.
2883  */
2884 int
2885 ffs_checkfreefile(fs, devvp, ino)
2886 	struct fs *fs;
2887 	struct vnode *devvp;
2888 	ino_t ino;
2889 {
2890 	struct cg *cgp;
2891 	struct buf *bp;
2892 	int ret, error;
2893 	u_int cg;
2894 	u_int8_t *inosused;
2895 
2896 	cg = ino_to_cg(fs, ino);
2897 	if ((devvp->v_type != VREG) && (devvp->v_type != VCHR))
2898 		return (1);
2899 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2900 		return (1);
2901 	if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
2902 		return (1);
2903 	inosused = cg_inosused(cgp);
2904 	ino %= fs->fs_ipg;
2905 	ret = isclr(inosused, ino);
2906 	brelse(bp);
2907 	return (ret);
2908 }
2909 
2910 /*
2911  * Find a block of the specified size in the specified cylinder group.
2912  *
2913  * It is a panic if a request is made to find a block if none are
2914  * available.
2915  */
2916 static ufs1_daddr_t
2917 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2918 	struct fs *fs;
2919 	struct cg *cgp;
2920 	ufs2_daddr_t bpref;
2921 	int allocsiz;
2922 {
2923 	ufs1_daddr_t bno;
2924 	int start, len, loc, i;
2925 	int blk, field, subfield, pos;
2926 	u_int8_t *blksfree;
2927 
2928 	/*
2929 	 * find the fragment by searching through the free block
2930 	 * map for an appropriate bit pattern
2931 	 */
2932 	if (bpref)
2933 		start = dtogd(fs, bpref) / NBBY;
2934 	else
2935 		start = cgp->cg_frotor / NBBY;
2936 	blksfree = cg_blksfree(cgp);
2937 	len = howmany(fs->fs_fpg, NBBY) - start;
2938 	loc = scanc((u_int)len, (u_char *)&blksfree[start],
2939 		fragtbl[fs->fs_frag],
2940 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2941 	if (loc == 0) {
2942 		len = start + 1;
2943 		start = 0;
2944 		loc = scanc((u_int)len, (u_char *)&blksfree[0],
2945 			fragtbl[fs->fs_frag],
2946 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2947 		if (loc == 0) {
2948 			printf("start = %d, len = %d, fs = %s\n",
2949 			    start, len, fs->fs_fsmnt);
2950 			panic("ffs_alloccg: map corrupted");
2951 			/* NOTREACHED */
2952 		}
2953 	}
2954 	bno = (start + len - loc) * NBBY;
2955 	cgp->cg_frotor = bno;
2956 	/*
2957 	 * found the byte in the map
2958 	 * sift through the bits to find the selected frag
2959 	 */
2960 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2961 		blk = blkmap(fs, blksfree, bno);
2962 		blk <<= 1;
2963 		field = around[allocsiz];
2964 		subfield = inside[allocsiz];
2965 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2966 			if ((blk & field) == subfield)
2967 				return (bno + pos);
2968 			field <<= 1;
2969 			subfield <<= 1;
2970 		}
2971 	}
2972 	printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2973 	panic("ffs_alloccg: block not in map");
2974 	return (-1);
2975 }
2976 
2977 static const struct statfs *
2978 ffs_getmntstat(struct vnode *devvp)
2979 {
2980 
2981 	if (devvp->v_type == VCHR)
2982 		return (&devvp->v_rdev->si_mountpt->mnt_stat);
2983 	return (ffs_getmntstat(VFSTOUFS(devvp->v_mount)->um_devvp));
2984 }
2985 
2986 /*
2987  * Fetch and verify a cylinder group.
2988  */
2989 int
2990 ffs_getcg(fs, devvp, cg, flags, bpp, cgpp)
2991 	struct fs *fs;
2992 	struct vnode *devvp;
2993 	u_int cg;
2994 	int flags;
2995 	struct buf **bpp;
2996 	struct cg **cgpp;
2997 {
2998 	struct buf *bp;
2999 	struct cg *cgp;
3000 	const struct statfs *sfs;
3001 	daddr_t blkno;
3002 	int error;
3003 
3004 	*bpp = NULL;
3005 	*cgpp = NULL;
3006 	if ((fs->fs_metackhash & CK_CYLGRP) != 0)
3007 		flags |= GB_CKHASH;
3008 	if (devvp->v_type == VREG)
3009 		blkno = fragstoblks(fs, cgtod(fs, cg));
3010 	else
3011 		blkno = fsbtodb(fs, cgtod(fs, cg));
3012 	error = breadn_flags(devvp, blkno, blkno, (int)fs->fs_cgsize, NULL,
3013 	    NULL, 0, NOCRED, flags, ffs_ckhash_cg, &bp);
3014 	if (error != 0)
3015 		return (error);
3016 	cgp = (struct cg *)bp->b_data;
3017 	if ((fs->fs_metackhash & CK_CYLGRP) != 0 &&
3018 	    (bp->b_flags & B_CKHASH) != 0 &&
3019 	    cgp->cg_ckhash != bp->b_ckhash) {
3020 		sfs = ffs_getmntstat(devvp);
3021 		printf("UFS %s%s (%s) cylinder checksum failed: cg %u, cgp: "
3022 		    "0x%x != bp: 0x%jx\n",
3023 		    devvp->v_type == VCHR ? "" : "snapshot of ",
3024 		    sfs->f_mntfromname, sfs->f_mntonname,
3025 		    cg, cgp->cg_ckhash, (uintmax_t)bp->b_ckhash);
3026 		bp->b_flags &= ~B_CKHASH;
3027 		bp->b_flags |= B_INVAL | B_NOCACHE;
3028 		brelse(bp);
3029 		return (EIO);
3030 	}
3031 	if (!cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
3032 		sfs = ffs_getmntstat(devvp);
3033 		printf("UFS %s%s (%s)",
3034 		    devvp->v_type == VCHR ? "" : "snapshot of ",
3035 		    sfs->f_mntfromname, sfs->f_mntonname);
3036 		if (!cg_chkmagic(cgp))
3037 			printf(" cg %u: bad magic number 0x%x should be 0x%x\n",
3038 			    cg, cgp->cg_magic, CG_MAGIC);
3039 		else
3040 			printf(": wrong cylinder group cg %u != cgx %u\n", cg,
3041 			    cgp->cg_cgx);
3042 		bp->b_flags &= ~B_CKHASH;
3043 		bp->b_flags |= B_INVAL | B_NOCACHE;
3044 		brelse(bp);
3045 		return (EIO);
3046 	}
3047 	bp->b_flags &= ~B_CKHASH;
3048 	bp->b_xflags |= BX_BKGRDWRITE;
3049 	/*
3050 	 * If we are using check hashes on the cylinder group then we want
3051 	 * to limit changing the cylinder group time to when we are actually
3052 	 * going to write it to disk so that its check hash remains correct
3053 	 * in memory. If the CK_CYLGRP flag is set the time is updated in
3054 	 * ffs_bufwrite() as the buffer is queued for writing. Otherwise we
3055 	 * update the time here as we have done historically.
3056 	 */
3057 	if ((fs->fs_metackhash & CK_CYLGRP) != 0)
3058 		bp->b_xflags |= BX_CYLGRP;
3059 	else
3060 		cgp->cg_old_time = cgp->cg_time = time_second;
3061 	*bpp = bp;
3062 	*cgpp = cgp;
3063 	return (0);
3064 }
3065 
3066 static void
3067 ffs_ckhash_cg(bp)
3068 	struct buf *bp;
3069 {
3070 	uint32_t ckhash;
3071 	struct cg *cgp;
3072 
3073 	cgp = (struct cg *)bp->b_data;
3074 	ckhash = cgp->cg_ckhash;
3075 	cgp->cg_ckhash = 0;
3076 	bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
3077 	cgp->cg_ckhash = ckhash;
3078 }
3079 
3080 /*
3081  * Fserr prints the name of a filesystem with an error diagnostic.
3082  *
3083  * The form of the error message is:
3084  *	fs: error message
3085  */
3086 void
3087 ffs_fserr(fs, inum, cp)
3088 	struct fs *fs;
3089 	ino_t inum;
3090 	char *cp;
3091 {
3092 	struct thread *td = curthread;	/* XXX */
3093 	struct proc *p = td->td_proc;
3094 
3095 	log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
3096 	    p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
3097 	    fs->fs_fsmnt, cp);
3098 }
3099 
3100 /*
3101  * This function provides the capability for the fsck program to
3102  * update an active filesystem. Fourteen operations are provided:
3103  *
3104  * adjrefcnt(inode, amt) - adjusts the reference count on the
3105  *	specified inode by the specified amount. Under normal
3106  *	operation the count should always go down. Decrementing
3107  *	the count to zero will cause the inode to be freed.
3108  * adjblkcnt(inode, amt) - adjust the number of blocks used by the
3109  *	inode by the specified amount.
3110  * setsize(inode, size) - set the size of the inode to the
3111  *	specified size.
3112  * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
3113  *	adjust the superblock summary.
3114  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
3115  *	are marked as free. Inodes should never have to be marked
3116  *	as in use.
3117  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
3118  *	are marked as free. Inodes should never have to be marked
3119  *	as in use.
3120  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
3121  *	are marked as free. Blocks should never have to be marked
3122  *	as in use.
3123  * setflags(flags, set/clear) - the fs_flags field has the specified
3124  *	flags set (second parameter +1) or cleared (second parameter -1).
3125  * setcwd(dirinode) - set the current directory to dirinode in the
3126  *	filesystem associated with the snapshot.
3127  * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
3128  *	in the current directory is oldvalue then change it to newvalue.
3129  * unlink(nameptr, oldvalue) - Verify that the inode number associated
3130  *	with nameptr in the current directory is oldvalue then unlink it.
3131  */
3132 
3133 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
3134 
3135 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt,
3136     CTLFLAG_WR | CTLTYPE_STRUCT | CTLFLAG_NEEDGIANT,
3137     0, 0, sysctl_ffs_fsck, "S,fsck",
3138     "Adjust Inode Reference Count");
3139 
3140 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt,
3141     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3142     "Adjust Inode Used Blocks Count");
3143 
3144 static SYSCTL_NODE(_vfs_ffs, FFS_SET_SIZE, setsize,
3145     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3146     "Set the inode size");
3147 
3148 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir,
3149     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3150     "Adjust number of directories");
3151 
3152 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree,
3153     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3154     "Adjust number of free blocks");
3155 
3156 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree,
3157     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3158     "Adjust number of free inodes");
3159 
3160 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree,
3161     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3162     "Adjust number of free frags");
3163 
3164 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters,
3165     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3166     "Adjust number of free clusters");
3167 
3168 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs,
3169     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3170     "Free Range of Directory Inodes");
3171 
3172 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles,
3173     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3174     "Free Range of File Inodes");
3175 
3176 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks,
3177     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3178     "Free Range of Blocks");
3179 
3180 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags,
3181     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3182     "Change Filesystem Flags");
3183 
3184 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd,
3185     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3186     "Set Current Working Directory");
3187 
3188 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot,
3189     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3190     "Change Value of .. Entry");
3191 
3192 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink,
3193     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3194     "Unlink a Duplicate Name");
3195 
3196 #ifdef DIAGNOSTIC
3197 static int fsckcmds = 0;
3198 SYSCTL_INT(_debug, OID_AUTO, ffs_fsckcmds, CTLFLAG_RW, &fsckcmds, 0,
3199 	"print out fsck_ffs-based filesystem update commands");
3200 #endif /* DIAGNOSTIC */
3201 
3202 static int
3203 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
3204 {
3205 	struct thread *td = curthread;
3206 	struct fsck_cmd cmd;
3207 	struct ufsmount *ump;
3208 	struct vnode *vp, *dvp, *fdvp;
3209 	struct inode *ip, *dp;
3210 	struct mount *mp;
3211 	struct fs *fs;
3212 	struct pwd *pwd;
3213 	ufs2_daddr_t blkno;
3214 	long blkcnt, blksize;
3215 	u_long key;
3216 	struct file *fp;
3217 	cap_rights_t rights;
3218 	int filetype, error;
3219 
3220 	if (req->newptr == NULL || req->newlen > sizeof(cmd))
3221 		return (EBADRPC);
3222 	if ((error = SYSCTL_IN(req, &cmd, sizeof(cmd))) != 0)
3223 		return (error);
3224 	if (cmd.version != FFS_CMD_VERSION)
3225 		return (ERPCMISMATCH);
3226 	if ((error = getvnode(td, cmd.handle,
3227 	    cap_rights_init_one(&rights, CAP_FSCK), &fp)) != 0)
3228 		return (error);
3229 	vp = fp->f_vnode;
3230 	if (vp->v_type != VREG && vp->v_type != VDIR) {
3231 		fdrop(fp, td);
3232 		return (EINVAL);
3233 	}
3234 	vn_start_write(vp, &mp, V_WAIT);
3235 	if (mp == NULL ||
3236 	    strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
3237 		vn_finished_write(mp);
3238 		fdrop(fp, td);
3239 		return (EINVAL);
3240 	}
3241 	ump = VFSTOUFS(mp);
3242 	if (mp->mnt_flag & MNT_RDONLY) {
3243 		vn_finished_write(mp);
3244 		fdrop(fp, td);
3245 		return (EROFS);
3246 	}
3247 	fs = ump->um_fs;
3248 	filetype = IFREG;
3249 
3250 	switch (oidp->oid_number) {
3251 	case FFS_SET_FLAGS:
3252 #ifdef DIAGNOSTIC
3253 		if (fsckcmds)
3254 			printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
3255 			    cmd.size > 0 ? "set" : "clear");
3256 #endif /* DIAGNOSTIC */
3257 		if (cmd.size > 0)
3258 			fs->fs_flags |= (long)cmd.value;
3259 		else
3260 			fs->fs_flags &= ~(long)cmd.value;
3261 		break;
3262 
3263 	case FFS_ADJ_REFCNT:
3264 #ifdef DIAGNOSTIC
3265 		if (fsckcmds) {
3266 			printf("%s: adjust inode %jd link count by %jd\n",
3267 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3268 			    (intmax_t)cmd.size);
3269 		}
3270 #endif /* DIAGNOSTIC */
3271 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3272 			break;
3273 		ip = VTOI(vp);
3274 		ip->i_nlink += cmd.size;
3275 		DIP_SET(ip, i_nlink, ip->i_nlink);
3276 		ip->i_effnlink += cmd.size;
3277 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3278 		error = ffs_update(vp, 1);
3279 		if (DOINGSOFTDEP(vp))
3280 			softdep_change_linkcnt(ip);
3281 		vput(vp);
3282 		break;
3283 
3284 	case FFS_ADJ_BLKCNT:
3285 #ifdef DIAGNOSTIC
3286 		if (fsckcmds) {
3287 			printf("%s: adjust inode %jd block count by %jd\n",
3288 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3289 			    (intmax_t)cmd.size);
3290 		}
3291 #endif /* DIAGNOSTIC */
3292 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3293 			break;
3294 		ip = VTOI(vp);
3295 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
3296 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3297 		error = ffs_update(vp, 1);
3298 		vput(vp);
3299 		break;
3300 
3301 	case FFS_SET_SIZE:
3302 #ifdef DIAGNOSTIC
3303 		if (fsckcmds) {
3304 			printf("%s: set inode %jd size to %jd\n",
3305 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3306 			    (intmax_t)cmd.size);
3307 		}
3308 #endif /* DIAGNOSTIC */
3309 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3310 			break;
3311 		ip = VTOI(vp);
3312 		DIP_SET(ip, i_size, cmd.size);
3313 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_MODIFIED);
3314 		error = ffs_update(vp, 1);
3315 		vput(vp);
3316 		break;
3317 
3318 	case FFS_DIR_FREE:
3319 		filetype = IFDIR;
3320 		/* fall through */
3321 
3322 	case FFS_FILE_FREE:
3323 #ifdef DIAGNOSTIC
3324 		if (fsckcmds) {
3325 			if (cmd.size == 1)
3326 				printf("%s: free %s inode %ju\n",
3327 				    mp->mnt_stat.f_mntonname,
3328 				    filetype == IFDIR ? "directory" : "file",
3329 				    (uintmax_t)cmd.value);
3330 			else
3331 				printf("%s: free %s inodes %ju-%ju\n",
3332 				    mp->mnt_stat.f_mntonname,
3333 				    filetype == IFDIR ? "directory" : "file",
3334 				    (uintmax_t)cmd.value,
3335 				    (uintmax_t)(cmd.value + cmd.size - 1));
3336 		}
3337 #endif /* DIAGNOSTIC */
3338 		while (cmd.size > 0) {
3339 			if ((error = ffs_freefile(ump, fs, ump->um_devvp,
3340 			    cmd.value, filetype, NULL)))
3341 				break;
3342 			cmd.size -= 1;
3343 			cmd.value += 1;
3344 		}
3345 		break;
3346 
3347 	case FFS_BLK_FREE:
3348 #ifdef DIAGNOSTIC
3349 		if (fsckcmds) {
3350 			if (cmd.size == 1)
3351 				printf("%s: free block %jd\n",
3352 				    mp->mnt_stat.f_mntonname,
3353 				    (intmax_t)cmd.value);
3354 			else
3355 				printf("%s: free blocks %jd-%jd\n",
3356 				    mp->mnt_stat.f_mntonname,
3357 				    (intmax_t)cmd.value,
3358 				    (intmax_t)cmd.value + cmd.size - 1);
3359 		}
3360 #endif /* DIAGNOSTIC */
3361 		blkno = cmd.value;
3362 		blkcnt = cmd.size;
3363 		blksize = fs->fs_frag - (blkno % fs->fs_frag);
3364 		key = ffs_blkrelease_start(ump, ump->um_devvp, UFS_ROOTINO);
3365 		while (blkcnt > 0) {
3366 			if (blkcnt < blksize)
3367 				blksize = blkcnt;
3368 			ffs_blkfree(ump, fs, ump->um_devvp, blkno,
3369 			    blksize * fs->fs_fsize, UFS_ROOTINO,
3370 			    VDIR, NULL, key);
3371 			blkno += blksize;
3372 			blkcnt -= blksize;
3373 			blksize = fs->fs_frag;
3374 		}
3375 		ffs_blkrelease_finish(ump, key);
3376 		break;
3377 
3378 	/*
3379 	 * Adjust superblock summaries.  fsck(8) is expected to
3380 	 * submit deltas when necessary.
3381 	 */
3382 	case FFS_ADJ_NDIR:
3383 #ifdef DIAGNOSTIC
3384 		if (fsckcmds) {
3385 			printf("%s: adjust number of directories by %jd\n",
3386 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3387 		}
3388 #endif /* DIAGNOSTIC */
3389 		fs->fs_cstotal.cs_ndir += cmd.value;
3390 		break;
3391 
3392 	case FFS_ADJ_NBFREE:
3393 #ifdef DIAGNOSTIC
3394 		if (fsckcmds) {
3395 			printf("%s: adjust number of free blocks by %+jd\n",
3396 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3397 		}
3398 #endif /* DIAGNOSTIC */
3399 		fs->fs_cstotal.cs_nbfree += cmd.value;
3400 		break;
3401 
3402 	case FFS_ADJ_NIFREE:
3403 #ifdef DIAGNOSTIC
3404 		if (fsckcmds) {
3405 			printf("%s: adjust number of free inodes by %+jd\n",
3406 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3407 		}
3408 #endif /* DIAGNOSTIC */
3409 		fs->fs_cstotal.cs_nifree += cmd.value;
3410 		break;
3411 
3412 	case FFS_ADJ_NFFREE:
3413 #ifdef DIAGNOSTIC
3414 		if (fsckcmds) {
3415 			printf("%s: adjust number of free frags by %+jd\n",
3416 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3417 		}
3418 #endif /* DIAGNOSTIC */
3419 		fs->fs_cstotal.cs_nffree += cmd.value;
3420 		break;
3421 
3422 	case FFS_ADJ_NUMCLUSTERS:
3423 #ifdef DIAGNOSTIC
3424 		if (fsckcmds) {
3425 			printf("%s: adjust number of free clusters by %+jd\n",
3426 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3427 		}
3428 #endif /* DIAGNOSTIC */
3429 		fs->fs_cstotal.cs_numclusters += cmd.value;
3430 		break;
3431 
3432 	case FFS_SET_CWD:
3433 #ifdef DIAGNOSTIC
3434 		if (fsckcmds) {
3435 			printf("%s: set current directory to inode %jd\n",
3436 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3437 		}
3438 #endif /* DIAGNOSTIC */
3439 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
3440 			break;
3441 		AUDIT_ARG_VNODE1(vp);
3442 		if ((error = change_dir(vp, td)) != 0) {
3443 			vput(vp);
3444 			break;
3445 		}
3446 		VOP_UNLOCK(vp);
3447 		pwd_chdir(td, vp);
3448 		break;
3449 
3450 	case FFS_SET_DOTDOT:
3451 #ifdef DIAGNOSTIC
3452 		if (fsckcmds) {
3453 			printf("%s: change .. in cwd from %jd to %jd\n",
3454 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3455 			    (intmax_t)cmd.size);
3456 		}
3457 #endif /* DIAGNOSTIC */
3458 		/*
3459 		 * First we have to get and lock the parent directory
3460 		 * to which ".." points.
3461 		 */
3462 		error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3463 		if (error)
3464 			break;
3465 		/*
3466 		 * Now we get and lock the child directory containing "..".
3467 		 */
3468 		pwd = pwd_hold(td);
3469 		dvp = pwd->pwd_cdir;
3470 		if ((error = vget(dvp, LK_EXCLUSIVE)) != 0) {
3471 			vput(fdvp);
3472 			pwd_drop(pwd);
3473 			break;
3474 		}
3475 		dp = VTOI(dvp);
3476 		SET_I_OFFSET(dp, 12);	/* XXX mastertemplate.dot_reclen */
3477 		error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3478 		    DT_DIR, 0);
3479 		cache_purge(fdvp);
3480 		cache_purge(dvp);
3481 		vput(dvp);
3482 		vput(fdvp);
3483 		pwd_drop(pwd);
3484 		break;
3485 
3486 	case FFS_UNLINK:
3487 #ifdef DIAGNOSTIC
3488 		if (fsckcmds) {
3489 			char buf[32];
3490 
3491 			if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3492 				strncpy(buf, "Name_too_long", 32);
3493 			printf("%s: unlink %s (inode %jd)\n",
3494 			    mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3495 		}
3496 #endif /* DIAGNOSTIC */
3497 		/*
3498 		 * kern_funlinkat will do its own start/finish writes and
3499 		 * they do not nest, so drop ours here. Setting mp == NULL
3500 		 * indicates that vn_finished_write is not needed down below.
3501 		 */
3502 		vn_finished_write(mp);
3503 		mp = NULL;
3504 		error = kern_funlinkat(td, AT_FDCWD,
3505 		    (char *)(intptr_t)cmd.value, FD_NONE, UIO_USERSPACE,
3506 		    0, (ino_t)cmd.size);
3507 		break;
3508 
3509 	default:
3510 #ifdef DIAGNOSTIC
3511 		if (fsckcmds) {
3512 			printf("Invalid request %d from fsck\n",
3513 			    oidp->oid_number);
3514 		}
3515 #endif /* DIAGNOSTIC */
3516 		error = EINVAL;
3517 		break;
3518 	}
3519 	fdrop(fp, td);
3520 	vn_finished_write(mp);
3521 	return (error);
3522 }
3523