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