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