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