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