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