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