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