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