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