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