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