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