xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision aa0a1e58)
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/systm.h>
69 #include <sys/bio.h>
70 #include <sys/buf.h>
71 #include <sys/conf.h>
72 #include <sys/fcntl.h>
73 #include <sys/file.h>
74 #include <sys/filedesc.h>
75 #include <sys/priv.h>
76 #include <sys/proc.h>
77 #include <sys/vnode.h>
78 #include <sys/mount.h>
79 #include <sys/kernel.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 #include <sys/taskqueue.h>
84 
85 #include <security/audit/audit.h>
86 
87 #include <geom/geom.h>
88 
89 #include <ufs/ufs/dir.h>
90 #include <ufs/ufs/extattr.h>
91 #include <ufs/ufs/quota.h>
92 #include <ufs/ufs/inode.h>
93 #include <ufs/ufs/ufs_extern.h>
94 #include <ufs/ufs/ufsmount.h>
95 
96 #include <ufs/ffs/fs.h>
97 #include <ufs/ffs/ffs_extern.h>
98 #include <ufs/ffs/softdep.h>
99 
100 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
101 				  int size, int rsize);
102 
103 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
104 static ufs2_daddr_t
105 	      ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
106 static void	ffs_blkfree_cg(struct ufsmount *, struct fs *,
107 		    struct vnode *, ufs2_daddr_t, long, ino_t,
108 		    struct workhead *);
109 static void	ffs_blkfree_trim_completed(struct bio *);
110 static void	ffs_blkfree_trim_task(void *ctx, int pending __unused);
111 #ifdef INVARIANTS
112 static int	ffs_checkblk(struct inode *, ufs2_daddr_t, long);
113 #endif
114 static ufs2_daddr_t ffs_clusteralloc(struct inode *, u_int, ufs2_daddr_t, int,
115 		    int);
116 static ino_t	ffs_dirpref(struct inode *);
117 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
118 		    int, int);
119 static void	ffs_fserr(struct fs *, ino_t, char *);
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 (fs->fs_pendingblocks > 0 && reclaimed == 0) {
221 		reclaimed = 1;
222 		softdep_request_cleanup(fs, ITOV(ip));
223 		goto retry;
224 	}
225 	UFS_UNLOCK(ump);
226 	if (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, 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 (fs->fs_pendingblocks > 0 && reclaimed == 0) {
422 		reclaimed = 1;
423 		softdep_request_cleanup(fs, vp);
424 		UFS_UNLOCK(ump);
425 		if (bp) {
426 			brelse(bp);
427 			bp = NULL;
428 		}
429 		UFS_LOCK(ump);
430 		goto retry;
431 	}
432 	UFS_UNLOCK(ump);
433 	if (bp)
434 		brelse(bp);
435 	if (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, 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, 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;
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 	if (fs->fs_cstotal.cs_nifree == 0)
950 		goto noinodes;
951 
952 	if ((mode & IFMT) == IFDIR)
953 		ipref = ffs_dirpref(pip);
954 	else
955 		ipref = pip->i_number;
956 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
957 		ipref = 0;
958 	cg = ino_to_cg(fs, ipref);
959 	/*
960 	 * Track number of dirs created one after another
961 	 * in a same cg without intervening by files.
962 	 */
963 	if ((mode & IFMT) == IFDIR) {
964 		if (fs->fs_contigdirs[cg] < 255)
965 			fs->fs_contigdirs[cg]++;
966 	} else {
967 		if (fs->fs_contigdirs[cg] > 0)
968 			fs->fs_contigdirs[cg]--;
969 	}
970 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
971 					(allocfcn_t *)ffs_nodealloccg);
972 	if (ino == 0)
973 		goto noinodes;
974 	error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
975 	if (error) {
976 		error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
977 		    FFSV_FORCEINSMQ);
978 		ffs_vfree(pvp, ino, mode);
979 		if (error1 == 0) {
980 			ip = VTOI(*vpp);
981 			if (ip->i_mode)
982 				goto dup_alloc;
983 			ip->i_flag |= IN_MODIFIED;
984 			vput(*vpp);
985 		}
986 		return (error);
987 	}
988 	ip = VTOI(*vpp);
989 	if (ip->i_mode) {
990 dup_alloc:
991 		printf("mode = 0%o, inum = %lu, fs = %s\n",
992 		    ip->i_mode, (u_long)ip->i_number, fs->fs_fsmnt);
993 		panic("ffs_valloc: dup alloc");
994 	}
995 	if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) {  /* XXX */
996 		printf("free inode %s/%lu had %ld blocks\n",
997 		    fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
998 		DIP_SET(ip, i_blocks, 0);
999 	}
1000 	ip->i_flags = 0;
1001 	DIP_SET(ip, i_flags, 0);
1002 	/*
1003 	 * Set up a new generation number for this inode.
1004 	 */
1005 	if (ip->i_gen == 0 || ++ip->i_gen == 0)
1006 		ip->i_gen = arc4random() / 2 + 1;
1007 	DIP_SET(ip, i_gen, ip->i_gen);
1008 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1009 		vfs_timestamp(&ts);
1010 		ip->i_din2->di_birthtime = ts.tv_sec;
1011 		ip->i_din2->di_birthnsec = ts.tv_nsec;
1012 	}
1013 	ip->i_flag = 0;
1014 	vnode_destroy_vobject(*vpp);
1015 	(*vpp)->v_type = VNON;
1016 	if (fs->fs_magic == FS_UFS2_MAGIC)
1017 		(*vpp)->v_op = &ffs_vnodeops2;
1018 	else
1019 		(*vpp)->v_op = &ffs_vnodeops1;
1020 	return (0);
1021 noinodes:
1022 	UFS_UNLOCK(ump);
1023 	if (ppsratecheck(&lastfail, &curfail, 1)) {
1024 		ffs_fserr(fs, pip->i_number, "out of inodes");
1025 		uprintf("\n%s: create/symlink failed, no inodes free\n",
1026 		    fs->fs_fsmnt);
1027 	}
1028 	return (ENOSPC);
1029 }
1030 
1031 /*
1032  * Find a cylinder group to place a directory.
1033  *
1034  * The policy implemented by this algorithm is to allocate a
1035  * directory inode in the same cylinder group as its parent
1036  * directory, but also to reserve space for its files inodes
1037  * and data. Restrict the number of directories which may be
1038  * allocated one after another in the same cylinder group
1039  * without intervening allocation of files.
1040  *
1041  * If we allocate a first level directory then force allocation
1042  * in another cylinder group.
1043  */
1044 static ino_t
1045 ffs_dirpref(pip)
1046 	struct inode *pip;
1047 {
1048 	struct fs *fs;
1049 	u_int cg, prefcg, dirsize, cgsize;
1050 	u_int avgifree, avgbfree, avgndir, curdirsize;
1051 	u_int minifree, minbfree, maxndir;
1052 	u_int mincg, minndir;
1053 	u_int maxcontigdirs;
1054 
1055 	mtx_assert(UFS_MTX(pip->i_ump), MA_OWNED);
1056 	fs = pip->i_fs;
1057 
1058 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1059 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1060 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1061 
1062 	/*
1063 	 * Force allocation in another cg if creating a first level dir.
1064 	 */
1065 	ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1066 	if (ITOV(pip)->v_vflag & VV_ROOT) {
1067 		prefcg = arc4random() % fs->fs_ncg;
1068 		mincg = prefcg;
1069 		minndir = fs->fs_ipg;
1070 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
1071 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1072 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1073 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1074 				mincg = cg;
1075 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1076 			}
1077 		for (cg = 0; cg < prefcg; cg++)
1078 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1079 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1080 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1081 				mincg = cg;
1082 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1083 			}
1084 		return ((ino_t)(fs->fs_ipg * mincg));
1085 	}
1086 
1087 	/*
1088 	 * Count various limits which used for
1089 	 * optimal allocation of a directory inode.
1090 	 */
1091 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1092 	minifree = avgifree - avgifree / 4;
1093 	if (minifree < 1)
1094 		minifree = 1;
1095 	minbfree = avgbfree - avgbfree / 4;
1096 	if (minbfree < 1)
1097 		minbfree = 1;
1098 	cgsize = fs->fs_fsize * fs->fs_fpg;
1099 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1100 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1101 	if (dirsize < curdirsize)
1102 		dirsize = curdirsize;
1103 	if (dirsize <= 0)
1104 		maxcontigdirs = 0;		/* dirsize overflowed */
1105 	else
1106 		maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1107 	if (fs->fs_avgfpdir > 0)
1108 		maxcontigdirs = min(maxcontigdirs,
1109 				    fs->fs_ipg / fs->fs_avgfpdir);
1110 	if (maxcontigdirs == 0)
1111 		maxcontigdirs = 1;
1112 
1113 	/*
1114 	 * Limit number of dirs in one cg and reserve space for
1115 	 * regular files, but only if we have no deficit in
1116 	 * inodes or space.
1117 	 */
1118 	prefcg = ino_to_cg(fs, pip->i_number);
1119 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1120 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1121 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1122 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1123 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1124 				return ((ino_t)(fs->fs_ipg * cg));
1125 		}
1126 	for (cg = 0; cg < prefcg; cg++)
1127 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1128 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1129 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1130 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1131 				return ((ino_t)(fs->fs_ipg * cg));
1132 		}
1133 	/*
1134 	 * This is a backstop when we have deficit in space.
1135 	 */
1136 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1137 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1138 			return ((ino_t)(fs->fs_ipg * cg));
1139 	for (cg = 0; cg < prefcg; cg++)
1140 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1141 			break;
1142 	return ((ino_t)(fs->fs_ipg * cg));
1143 }
1144 
1145 /*
1146  * Select the desired position for the next block in a file.  The file is
1147  * logically divided into sections. The first section is composed of the
1148  * direct blocks. Each additional section contains fs_maxbpg blocks.
1149  *
1150  * If no blocks have been allocated in the first section, the policy is to
1151  * request a block in the same cylinder group as the inode that describes
1152  * the file. If no blocks have been allocated in any other section, the
1153  * policy is to place the section in a cylinder group with a greater than
1154  * average number of free blocks.  An appropriate cylinder group is found
1155  * by using a rotor that sweeps the cylinder groups. When a new group of
1156  * blocks is needed, the sweep begins in the cylinder group following the
1157  * cylinder group from which the previous allocation was made. The sweep
1158  * continues until a cylinder group with greater than the average number
1159  * of free blocks is found. If the allocation is for the first block in an
1160  * indirect block, the information on the previous allocation is unavailable;
1161  * here a best guess is made based upon the logical block number being
1162  * allocated.
1163  *
1164  * If a section is already partially allocated, the policy is to
1165  * contiguously allocate fs_maxcontig blocks. The end of one of these
1166  * contiguous blocks and the beginning of the next is laid out
1167  * contiguously if possible.
1168  */
1169 ufs2_daddr_t
1170 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1171 	struct inode *ip;
1172 	ufs_lbn_t lbn;
1173 	int indx;
1174 	ufs1_daddr_t *bap;
1175 {
1176 	struct fs *fs;
1177 	u_int cg;
1178 	u_int avgbfree, startcg;
1179 
1180 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1181 	fs = ip->i_fs;
1182 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1183 		if (lbn < NDADDR + NINDIR(fs)) {
1184 			cg = ino_to_cg(fs, ip->i_number);
1185 			return (cgbase(fs, cg) + fs->fs_frag);
1186 		}
1187 		/*
1188 		 * Find a cylinder with greater than average number of
1189 		 * unused data blocks.
1190 		 */
1191 		if (indx == 0 || bap[indx - 1] == 0)
1192 			startcg =
1193 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1194 		else
1195 			startcg = dtog(fs, bap[indx - 1]) + 1;
1196 		startcg %= fs->fs_ncg;
1197 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1198 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1199 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1200 				fs->fs_cgrotor = cg;
1201 				return (cgbase(fs, cg) + fs->fs_frag);
1202 			}
1203 		for (cg = 0; cg <= startcg; cg++)
1204 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1205 				fs->fs_cgrotor = cg;
1206 				return (cgbase(fs, cg) + fs->fs_frag);
1207 			}
1208 		return (0);
1209 	}
1210 	/*
1211 	 * We just always try to lay things out contiguously.
1212 	 */
1213 	return (bap[indx - 1] + fs->fs_frag);
1214 }
1215 
1216 /*
1217  * Same as above, but for UFS2
1218  */
1219 ufs2_daddr_t
1220 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1221 	struct inode *ip;
1222 	ufs_lbn_t lbn;
1223 	int indx;
1224 	ufs2_daddr_t *bap;
1225 {
1226 	struct fs *fs;
1227 	u_int cg;
1228 	u_int avgbfree, startcg;
1229 
1230 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1231 	fs = ip->i_fs;
1232 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1233 		if (lbn < NDADDR + NINDIR(fs)) {
1234 			cg = ino_to_cg(fs, ip->i_number);
1235 			return (cgbase(fs, cg) + fs->fs_frag);
1236 		}
1237 		/*
1238 		 * Find a cylinder with greater than average number of
1239 		 * unused data blocks.
1240 		 */
1241 		if (indx == 0 || bap[indx - 1] == 0)
1242 			startcg =
1243 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1244 		else
1245 			startcg = dtog(fs, bap[indx - 1]) + 1;
1246 		startcg %= fs->fs_ncg;
1247 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1248 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1249 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1250 				fs->fs_cgrotor = cg;
1251 				return (cgbase(fs, cg) + fs->fs_frag);
1252 			}
1253 		for (cg = 0; cg <= startcg; cg++)
1254 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1255 				fs->fs_cgrotor = cg;
1256 				return (cgbase(fs, cg) + fs->fs_frag);
1257 			}
1258 		return (0);
1259 	}
1260 	/*
1261 	 * We just always try to lay things out contiguously.
1262 	 */
1263 	return (bap[indx - 1] + fs->fs_frag);
1264 }
1265 
1266 /*
1267  * Implement the cylinder overflow algorithm.
1268  *
1269  * The policy implemented by this algorithm is:
1270  *   1) allocate the block in its requested cylinder group.
1271  *   2) quadradically rehash on the cylinder group number.
1272  *   3) brute force search for a free block.
1273  *
1274  * Must be called with the UFS lock held.  Will release the lock on success
1275  * and return with it held on failure.
1276  */
1277 /*VARARGS5*/
1278 static ufs2_daddr_t
1279 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1280 	struct inode *ip;
1281 	u_int cg;
1282 	ufs2_daddr_t pref;
1283 	int size;	/* Search size for data blocks, mode for inodes */
1284 	int rsize;	/* Real allocated size. */
1285 	allocfcn_t *allocator;
1286 {
1287 	struct fs *fs;
1288 	ufs2_daddr_t result;
1289 	u_int i, icg = cg;
1290 
1291 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1292 #ifdef INVARIANTS
1293 	if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1294 		panic("ffs_hashalloc: allocation on suspended filesystem");
1295 #endif
1296 	fs = ip->i_fs;
1297 	/*
1298 	 * 1: preferred cylinder group
1299 	 */
1300 	result = (*allocator)(ip, cg, pref, size, rsize);
1301 	if (result)
1302 		return (result);
1303 	/*
1304 	 * 2: quadratic rehash
1305 	 */
1306 	for (i = 1; i < fs->fs_ncg; i *= 2) {
1307 		cg += i;
1308 		if (cg >= fs->fs_ncg)
1309 			cg -= fs->fs_ncg;
1310 		result = (*allocator)(ip, cg, 0, size, rsize);
1311 		if (result)
1312 			return (result);
1313 	}
1314 	/*
1315 	 * 3: brute force search
1316 	 * Note that we start at i == 2, since 0 was checked initially,
1317 	 * and 1 is always checked in the quadratic rehash.
1318 	 */
1319 	cg = (icg + 2) % fs->fs_ncg;
1320 	for (i = 2; i < fs->fs_ncg; i++) {
1321 		result = (*allocator)(ip, cg, 0, size, rsize);
1322 		if (result)
1323 			return (result);
1324 		cg++;
1325 		if (cg == fs->fs_ncg)
1326 			cg = 0;
1327 	}
1328 	return (0);
1329 }
1330 
1331 /*
1332  * Determine whether a fragment can be extended.
1333  *
1334  * Check to see if the necessary fragments are available, and
1335  * if they are, allocate them.
1336  */
1337 static ufs2_daddr_t
1338 ffs_fragextend(ip, cg, bprev, osize, nsize)
1339 	struct inode *ip;
1340 	u_int cg;
1341 	ufs2_daddr_t bprev;
1342 	int osize, nsize;
1343 {
1344 	struct fs *fs;
1345 	struct cg *cgp;
1346 	struct buf *bp;
1347 	struct ufsmount *ump;
1348 	int nffree;
1349 	long bno;
1350 	int frags, bbase;
1351 	int i, error;
1352 	u_int8_t *blksfree;
1353 
1354 	ump = ip->i_ump;
1355 	fs = ip->i_fs;
1356 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1357 		return (0);
1358 	frags = numfrags(fs, nsize);
1359 	bbase = fragnum(fs, bprev);
1360 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
1361 		/* cannot extend across a block boundary */
1362 		return (0);
1363 	}
1364 	UFS_UNLOCK(ump);
1365 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1366 		(int)fs->fs_cgsize, NOCRED, &bp);
1367 	if (error)
1368 		goto fail;
1369 	cgp = (struct cg *)bp->b_data;
1370 	if (!cg_chkmagic(cgp))
1371 		goto fail;
1372 	bp->b_xflags |= BX_BKGRDWRITE;
1373 	cgp->cg_old_time = cgp->cg_time = time_second;
1374 	bno = dtogd(fs, bprev);
1375 	blksfree = cg_blksfree(cgp);
1376 	for (i = numfrags(fs, osize); i < frags; i++)
1377 		if (isclr(blksfree, bno + i))
1378 			goto fail;
1379 	/*
1380 	 * the current fragment can be extended
1381 	 * deduct the count on fragment being extended into
1382 	 * increase the count on the remaining fragment (if any)
1383 	 * allocate the extended piece
1384 	 */
1385 	for (i = frags; i < fs->fs_frag - bbase; i++)
1386 		if (isclr(blksfree, bno + i))
1387 			break;
1388 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
1389 	if (i != frags)
1390 		cgp->cg_frsum[i - frags]++;
1391 	for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1392 		clrbit(blksfree, bno + i);
1393 		cgp->cg_cs.cs_nffree--;
1394 		nffree++;
1395 	}
1396 	UFS_LOCK(ump);
1397 	fs->fs_cstotal.cs_nffree -= nffree;
1398 	fs->fs_cs(fs, cg).cs_nffree -= nffree;
1399 	fs->fs_fmod = 1;
1400 	ACTIVECLEAR(fs, cg);
1401 	UFS_UNLOCK(ump);
1402 	if (DOINGSOFTDEP(ITOV(ip)))
1403 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1404 		    frags, numfrags(fs, osize));
1405 	bdwrite(bp);
1406 	return (bprev);
1407 
1408 fail:
1409 	brelse(bp);
1410 	UFS_LOCK(ump);
1411 	return (0);
1412 
1413 }
1414 
1415 /*
1416  * Determine whether a block can be allocated.
1417  *
1418  * Check to see if a block of the appropriate size is available,
1419  * and if it is, allocate it.
1420  */
1421 static ufs2_daddr_t
1422 ffs_alloccg(ip, cg, bpref, size, rsize)
1423 	struct inode *ip;
1424 	u_int cg;
1425 	ufs2_daddr_t bpref;
1426 	int size;
1427 	int rsize;
1428 {
1429 	struct fs *fs;
1430 	struct cg *cgp;
1431 	struct buf *bp;
1432 	struct ufsmount *ump;
1433 	ufs1_daddr_t bno;
1434 	ufs2_daddr_t blkno;
1435 	int i, allocsiz, error, frags;
1436 	u_int8_t *blksfree;
1437 
1438 	ump = ip->i_ump;
1439 	fs = ip->i_fs;
1440 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1441 		return (0);
1442 	UFS_UNLOCK(ump);
1443 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1444 		(int)fs->fs_cgsize, NOCRED, &bp);
1445 	if (error)
1446 		goto fail;
1447 	cgp = (struct cg *)bp->b_data;
1448 	if (!cg_chkmagic(cgp) ||
1449 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1450 		goto fail;
1451 	bp->b_xflags |= BX_BKGRDWRITE;
1452 	cgp->cg_old_time = cgp->cg_time = time_second;
1453 	if (size == fs->fs_bsize) {
1454 		UFS_LOCK(ump);
1455 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1456 		ACTIVECLEAR(fs, cg);
1457 		UFS_UNLOCK(ump);
1458 		bdwrite(bp);
1459 		return (blkno);
1460 	}
1461 	/*
1462 	 * check to see if any fragments are already available
1463 	 * allocsiz is the size which will be allocated, hacking
1464 	 * it down to a smaller size if necessary
1465 	 */
1466 	blksfree = cg_blksfree(cgp);
1467 	frags = numfrags(fs, size);
1468 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1469 		if (cgp->cg_frsum[allocsiz] != 0)
1470 			break;
1471 	if (allocsiz == fs->fs_frag) {
1472 		/*
1473 		 * no fragments were available, so a block will be
1474 		 * allocated, and hacked up
1475 		 */
1476 		if (cgp->cg_cs.cs_nbfree == 0)
1477 			goto fail;
1478 		UFS_LOCK(ump);
1479 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1480 		ACTIVECLEAR(fs, cg);
1481 		UFS_UNLOCK(ump);
1482 		bdwrite(bp);
1483 		return (blkno);
1484 	}
1485 	KASSERT(size == rsize,
1486 	    ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1487 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1488 	if (bno < 0)
1489 		goto fail;
1490 	for (i = 0; i < frags; i++)
1491 		clrbit(blksfree, bno + i);
1492 	cgp->cg_cs.cs_nffree -= frags;
1493 	cgp->cg_frsum[allocsiz]--;
1494 	if (frags != allocsiz)
1495 		cgp->cg_frsum[allocsiz - frags]++;
1496 	UFS_LOCK(ump);
1497 	fs->fs_cstotal.cs_nffree -= frags;
1498 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1499 	fs->fs_fmod = 1;
1500 	blkno = cgbase(fs, cg) + bno;
1501 	ACTIVECLEAR(fs, cg);
1502 	UFS_UNLOCK(ump);
1503 	if (DOINGSOFTDEP(ITOV(ip)))
1504 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1505 	bdwrite(bp);
1506 	return (blkno);
1507 
1508 fail:
1509 	brelse(bp);
1510 	UFS_LOCK(ump);
1511 	return (0);
1512 }
1513 
1514 /*
1515  * Allocate a block in a cylinder group.
1516  *
1517  * This algorithm implements the following policy:
1518  *   1) allocate the requested block.
1519  *   2) allocate a rotationally optimal block in the same cylinder.
1520  *   3) allocate the next available block on the block rotor for the
1521  *      specified cylinder group.
1522  * Note that this routine only allocates fs_bsize blocks; these
1523  * blocks may be fragmented by the routine that allocates them.
1524  */
1525 static ufs2_daddr_t
1526 ffs_alloccgblk(ip, bp, bpref, size)
1527 	struct inode *ip;
1528 	struct buf *bp;
1529 	ufs2_daddr_t bpref;
1530 	int size;
1531 {
1532 	struct fs *fs;
1533 	struct cg *cgp;
1534 	struct ufsmount *ump;
1535 	ufs1_daddr_t bno;
1536 	ufs2_daddr_t blkno;
1537 	u_int8_t *blksfree;
1538 	int i;
1539 
1540 	fs = ip->i_fs;
1541 	ump = ip->i_ump;
1542 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1543 	cgp = (struct cg *)bp->b_data;
1544 	blksfree = cg_blksfree(cgp);
1545 	if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
1546 		bpref = cgp->cg_rotor;
1547 	} else {
1548 		bpref = blknum(fs, bpref);
1549 		bno = dtogd(fs, bpref);
1550 		/*
1551 		 * if the requested block is available, use it
1552 		 */
1553 		if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1554 			goto gotit;
1555 	}
1556 	/*
1557 	 * Take the next available block in this cylinder group.
1558 	 */
1559 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1560 	if (bno < 0)
1561 		return (0);
1562 	cgp->cg_rotor = bno;
1563 gotit:
1564 	blkno = fragstoblks(fs, bno);
1565 	ffs_clrblock(fs, blksfree, (long)blkno);
1566 	ffs_clusteracct(fs, cgp, blkno, -1);
1567 	cgp->cg_cs.cs_nbfree--;
1568 	fs->fs_cstotal.cs_nbfree--;
1569 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1570 	fs->fs_fmod = 1;
1571 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1572 	/*
1573 	 * If the caller didn't want the whole block free the frags here.
1574 	 */
1575 	size = numfrags(fs, size);
1576 	if (size != fs->fs_frag) {
1577 		bno = dtogd(fs, blkno);
1578 		for (i = size; i < fs->fs_frag; i++)
1579 			setbit(blksfree, bno + i);
1580 		i = fs->fs_frag - size;
1581 		cgp->cg_cs.cs_nffree += i;
1582 		fs->fs_cstotal.cs_nffree += i;
1583 		fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1584 		fs->fs_fmod = 1;
1585 		cgp->cg_frsum[i]++;
1586 	}
1587 	/* XXX Fixme. */
1588 	UFS_UNLOCK(ump);
1589 	if (DOINGSOFTDEP(ITOV(ip)))
1590 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno,
1591 		    size, 0);
1592 	UFS_LOCK(ump);
1593 	return (blkno);
1594 }
1595 
1596 /*
1597  * Determine whether a cluster can be allocated.
1598  *
1599  * We do not currently check for optimal rotational layout if there
1600  * are multiple choices in the same cylinder group. Instead we just
1601  * take the first one that we find following bpref.
1602  */
1603 static ufs2_daddr_t
1604 ffs_clusteralloc(ip, cg, bpref, len, unused)
1605 	struct inode *ip;
1606 	u_int cg;
1607 	ufs2_daddr_t bpref;
1608 	int len;
1609 	int unused;
1610 {
1611 	struct fs *fs;
1612 	struct cg *cgp;
1613 	struct buf *bp;
1614 	struct ufsmount *ump;
1615 	int i, run, bit, map, got;
1616 	ufs2_daddr_t bno;
1617 	u_char *mapp;
1618 	int32_t *lp;
1619 	u_int8_t *blksfree;
1620 
1621 	fs = ip->i_fs;
1622 	ump = ip->i_ump;
1623 	if (fs->fs_maxcluster[cg] < len)
1624 		return (0);
1625 	UFS_UNLOCK(ump);
1626 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1627 	    NOCRED, &bp))
1628 		goto fail_lock;
1629 	cgp = (struct cg *)bp->b_data;
1630 	if (!cg_chkmagic(cgp))
1631 		goto fail_lock;
1632 	bp->b_xflags |= BX_BKGRDWRITE;
1633 	/*
1634 	 * Check to see if a cluster of the needed size (or bigger) is
1635 	 * available in this cylinder group.
1636 	 */
1637 	lp = &cg_clustersum(cgp)[len];
1638 	for (i = len; i <= fs->fs_contigsumsize; i++)
1639 		if (*lp++ > 0)
1640 			break;
1641 	if (i > fs->fs_contigsumsize) {
1642 		/*
1643 		 * This is the first time looking for a cluster in this
1644 		 * cylinder group. Update the cluster summary information
1645 		 * to reflect the true maximum sized cluster so that
1646 		 * future cluster allocation requests can avoid reading
1647 		 * the cylinder group map only to find no clusters.
1648 		 */
1649 		lp = &cg_clustersum(cgp)[len - 1];
1650 		for (i = len - 1; i > 0; i--)
1651 			if (*lp-- > 0)
1652 				break;
1653 		UFS_LOCK(ump);
1654 		fs->fs_maxcluster[cg] = i;
1655 		goto fail;
1656 	}
1657 	/*
1658 	 * Search the cluster map to find a big enough cluster.
1659 	 * We take the first one that we find, even if it is larger
1660 	 * than we need as we prefer to get one close to the previous
1661 	 * block allocation. We do not search before the current
1662 	 * preference point as we do not want to allocate a block
1663 	 * that is allocated before the previous one (as we will
1664 	 * then have to wait for another pass of the elevator
1665 	 * algorithm before it will be read). We prefer to fail and
1666 	 * be recalled to try an allocation in the next cylinder group.
1667 	 */
1668 	if (dtog(fs, bpref) != cg)
1669 		bpref = 0;
1670 	else
1671 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1672 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1673 	map = *mapp++;
1674 	bit = 1 << (bpref % NBBY);
1675 	for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1676 		if ((map & bit) == 0) {
1677 			run = 0;
1678 		} else {
1679 			run++;
1680 			if (run == len)
1681 				break;
1682 		}
1683 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
1684 			bit <<= 1;
1685 		} else {
1686 			map = *mapp++;
1687 			bit = 1;
1688 		}
1689 	}
1690 	if (got >= cgp->cg_nclusterblks)
1691 		goto fail_lock;
1692 	/*
1693 	 * Allocate the cluster that we have found.
1694 	 */
1695 	blksfree = cg_blksfree(cgp);
1696 	for (i = 1; i <= len; i++)
1697 		if (!ffs_isblock(fs, blksfree, got - run + i))
1698 			panic("ffs_clusteralloc: map mismatch");
1699 	bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1700 	if (dtog(fs, bno) != cg)
1701 		panic("ffs_clusteralloc: allocated out of group");
1702 	len = blkstofrags(fs, len);
1703 	UFS_LOCK(ump);
1704 	for (i = 0; i < len; i += fs->fs_frag)
1705 		if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
1706 			panic("ffs_clusteralloc: lost block");
1707 	ACTIVECLEAR(fs, cg);
1708 	UFS_UNLOCK(ump);
1709 	bdwrite(bp);
1710 	return (bno);
1711 
1712 fail_lock:
1713 	UFS_LOCK(ump);
1714 fail:
1715 	brelse(bp);
1716 	return (0);
1717 }
1718 
1719 /*
1720  * Determine whether an inode can be allocated.
1721  *
1722  * Check to see if an inode is available, and if it is,
1723  * allocate it using the following policy:
1724  *   1) allocate the requested inode.
1725  *   2) allocate the next available inode after the requested
1726  *      inode in the specified cylinder group.
1727  */
1728 static ufs2_daddr_t
1729 ffs_nodealloccg(ip, cg, ipref, mode, unused)
1730 	struct inode *ip;
1731 	u_int cg;
1732 	ufs2_daddr_t ipref;
1733 	int mode;
1734 	int unused;
1735 {
1736 	struct fs *fs;
1737 	struct cg *cgp;
1738 	struct buf *bp, *ibp;
1739 	struct ufsmount *ump;
1740 	u_int8_t *inosused;
1741 	struct ufs2_dinode *dp2;
1742 	int error, start, len, loc, map, i;
1743 
1744 	fs = ip->i_fs;
1745 	ump = ip->i_ump;
1746 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1747 		return (0);
1748 	UFS_UNLOCK(ump);
1749 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1750 		(int)fs->fs_cgsize, NOCRED, &bp);
1751 	if (error) {
1752 		brelse(bp);
1753 		UFS_LOCK(ump);
1754 		return (0);
1755 	}
1756 	cgp = (struct cg *)bp->b_data;
1757 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1758 		brelse(bp);
1759 		UFS_LOCK(ump);
1760 		return (0);
1761 	}
1762 	bp->b_xflags |= BX_BKGRDWRITE;
1763 	cgp->cg_old_time = cgp->cg_time = time_second;
1764 	inosused = cg_inosused(cgp);
1765 	if (ipref) {
1766 		ipref %= fs->fs_ipg;
1767 		if (isclr(inosused, ipref))
1768 			goto gotit;
1769 	}
1770 	start = cgp->cg_irotor / NBBY;
1771 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1772 	loc = skpc(0xff, len, &inosused[start]);
1773 	if (loc == 0) {
1774 		len = start + 1;
1775 		start = 0;
1776 		loc = skpc(0xff, len, &inosused[0]);
1777 		if (loc == 0) {
1778 			printf("cg = %d, irotor = %ld, fs = %s\n",
1779 			    cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
1780 			panic("ffs_nodealloccg: map corrupted");
1781 			/* NOTREACHED */
1782 		}
1783 	}
1784 	i = start + len - loc;
1785 	map = inosused[i] ^ 0xff;
1786 	if (map == 0) {
1787 		printf("fs = %s\n", fs->fs_fsmnt);
1788 		panic("ffs_nodealloccg: block not in map");
1789 	}
1790 	ipref = i * NBBY + ffs(map) - 1;
1791 	cgp->cg_irotor = ipref;
1792 gotit:
1793 	/*
1794 	 * Check to see if we need to initialize more inodes.
1795 	 */
1796 	ibp = NULL;
1797 	if (fs->fs_magic == FS_UFS2_MAGIC &&
1798 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
1799 	    cgp->cg_initediblk < cgp->cg_niblk) {
1800 		ibp = getblk(ip->i_devvp, fsbtodb(fs,
1801 		    ino_to_fsba(fs, cg * fs->fs_ipg + cgp->cg_initediblk)),
1802 		    (int)fs->fs_bsize, 0, 0, 0);
1803 		bzero(ibp->b_data, (int)fs->fs_bsize);
1804 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
1805 		for (i = 0; i < INOPB(fs); i++) {
1806 			dp2->di_gen = arc4random() / 2 + 1;
1807 			dp2++;
1808 		}
1809 		cgp->cg_initediblk += INOPB(fs);
1810 	}
1811 	UFS_LOCK(ump);
1812 	ACTIVECLEAR(fs, cg);
1813 	setbit(inosused, ipref);
1814 	cgp->cg_cs.cs_nifree--;
1815 	fs->fs_cstotal.cs_nifree--;
1816 	fs->fs_cs(fs, cg).cs_nifree--;
1817 	fs->fs_fmod = 1;
1818 	if ((mode & IFMT) == IFDIR) {
1819 		cgp->cg_cs.cs_ndir++;
1820 		fs->fs_cstotal.cs_ndir++;
1821 		fs->fs_cs(fs, cg).cs_ndir++;
1822 	}
1823 	UFS_UNLOCK(ump);
1824 	if (DOINGSOFTDEP(ITOV(ip)))
1825 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
1826 	bdwrite(bp);
1827 	if (ibp != NULL)
1828 		bawrite(ibp);
1829 	return ((ino_t)(cg * fs->fs_ipg + ipref));
1830 }
1831 
1832 /*
1833  * Free a block or fragment.
1834  *
1835  * The specified block or fragment is placed back in the
1836  * free map. If a fragment is deallocated, a possible
1837  * block reassembly is checked.
1838  */
1839 static void
1840 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
1841 	struct ufsmount *ump;
1842 	struct fs *fs;
1843 	struct vnode *devvp;
1844 	ufs2_daddr_t bno;
1845 	long size;
1846 	ino_t inum;
1847 	struct workhead *dephd;
1848 {
1849 	struct mount *mp;
1850 	struct cg *cgp;
1851 	struct buf *bp;
1852 	ufs1_daddr_t fragno, cgbno;
1853 	ufs2_daddr_t cgblkno;
1854 	int i, blk, frags, bbase;
1855 	u_int cg;
1856 	u_int8_t *blksfree;
1857 	struct cdev *dev;
1858 
1859 	cg = dtog(fs, bno);
1860 	if (devvp->v_type == VREG) {
1861 		/* devvp is a snapshot */
1862 		dev = VTOI(devvp)->i_devvp->v_rdev;
1863 		cgblkno = fragstoblks(fs, cgtod(fs, cg));
1864 	} else {
1865 		/* devvp is a normal disk device */
1866 		dev = devvp->v_rdev;
1867 		cgblkno = fsbtodb(fs, cgtod(fs, cg));
1868 		ASSERT_VOP_LOCKED(devvp, "ffs_blkfree");
1869 		if ((devvp->v_vflag & VV_COPYONWRITE) &&
1870 		    ffs_snapblkfree(fs, devvp, bno, size, inum))
1871 			return;
1872 	}
1873 #ifdef INVARIANTS
1874 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1875 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1876 		printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
1877 		    devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
1878 		    size, fs->fs_fsmnt);
1879 		panic("ffs_blkfree: bad size");
1880 	}
1881 #endif
1882 	if ((u_int)bno >= fs->fs_size) {
1883 		printf("bad block %jd, ino %lu\n", (intmax_t)bno,
1884 		    (u_long)inum);
1885 		ffs_fserr(fs, inum, "bad block");
1886 		return;
1887 	}
1888 	if (bread(devvp, cgblkno, (int)fs->fs_cgsize, NOCRED, &bp)) {
1889 		brelse(bp);
1890 		return;
1891 	}
1892 	cgp = (struct cg *)bp->b_data;
1893 	if (!cg_chkmagic(cgp)) {
1894 		brelse(bp);
1895 		return;
1896 	}
1897 	bp->b_xflags |= BX_BKGRDWRITE;
1898 	cgp->cg_old_time = cgp->cg_time = time_second;
1899 	cgbno = dtogd(fs, bno);
1900 	blksfree = cg_blksfree(cgp);
1901 	UFS_LOCK(ump);
1902 	if (size == fs->fs_bsize) {
1903 		fragno = fragstoblks(fs, cgbno);
1904 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
1905 			if (devvp->v_type == VREG) {
1906 				UFS_UNLOCK(ump);
1907 				/* devvp is a snapshot */
1908 				brelse(bp);
1909 				return;
1910 			}
1911 			printf("dev = %s, block = %jd, fs = %s\n",
1912 			    devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
1913 			panic("ffs_blkfree: freeing free block");
1914 		}
1915 		ffs_setblock(fs, blksfree, fragno);
1916 		ffs_clusteracct(fs, cgp, fragno, 1);
1917 		cgp->cg_cs.cs_nbfree++;
1918 		fs->fs_cstotal.cs_nbfree++;
1919 		fs->fs_cs(fs, cg).cs_nbfree++;
1920 	} else {
1921 		bbase = cgbno - fragnum(fs, cgbno);
1922 		/*
1923 		 * decrement the counts associated with the old frags
1924 		 */
1925 		blk = blkmap(fs, blksfree, bbase);
1926 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1927 		/*
1928 		 * deallocate the fragment
1929 		 */
1930 		frags = numfrags(fs, size);
1931 		for (i = 0; i < frags; i++) {
1932 			if (isset(blksfree, cgbno + i)) {
1933 				printf("dev = %s, block = %jd, fs = %s\n",
1934 				    devtoname(dev), (intmax_t)(bno + i),
1935 				    fs->fs_fsmnt);
1936 				panic("ffs_blkfree: freeing free frag");
1937 			}
1938 			setbit(blksfree, cgbno + i);
1939 		}
1940 		cgp->cg_cs.cs_nffree += i;
1941 		fs->fs_cstotal.cs_nffree += i;
1942 		fs->fs_cs(fs, cg).cs_nffree += i;
1943 		/*
1944 		 * add back in counts associated with the new frags
1945 		 */
1946 		blk = blkmap(fs, blksfree, bbase);
1947 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1948 		/*
1949 		 * if a complete block has been reassembled, account for it
1950 		 */
1951 		fragno = fragstoblks(fs, bbase);
1952 		if (ffs_isblock(fs, blksfree, fragno)) {
1953 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
1954 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1955 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1956 			ffs_clusteracct(fs, cgp, fragno, 1);
1957 			cgp->cg_cs.cs_nbfree++;
1958 			fs->fs_cstotal.cs_nbfree++;
1959 			fs->fs_cs(fs, cg).cs_nbfree++;
1960 		}
1961 	}
1962 	fs->fs_fmod = 1;
1963 	ACTIVECLEAR(fs, cg);
1964 	UFS_UNLOCK(ump);
1965 	mp = UFSTOVFS(ump);
1966 	if (mp->mnt_flag & MNT_SOFTDEP && devvp->v_type != VREG)
1967 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
1968 		    numfrags(fs, size), dephd);
1969 	bdwrite(bp);
1970 }
1971 
1972 TASKQUEUE_DEFINE_THREAD(ffs_trim);
1973 
1974 struct ffs_blkfree_trim_params {
1975 	struct task task;
1976 	struct ufsmount *ump;
1977 	struct vnode *devvp;
1978 	ufs2_daddr_t bno;
1979 	long size;
1980 	ino_t inum;
1981 	struct workhead *pdephd;
1982 	struct workhead dephd;
1983 };
1984 
1985 static void
1986 ffs_blkfree_trim_task(ctx, pending)
1987 	void *ctx;
1988 	int pending;
1989 {
1990 	struct ffs_blkfree_trim_params *tp;
1991 
1992 	tp = ctx;
1993 	ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
1994 	    tp->inum, tp->pdephd);
1995 	vn_finished_secondary_write(UFSTOVFS(tp->ump));
1996 	free(tp, M_TEMP);
1997 }
1998 
1999 static void
2000 ffs_blkfree_trim_completed(bip)
2001 	struct bio *bip;
2002 {
2003 	struct ffs_blkfree_trim_params *tp;
2004 
2005 	tp = bip->bio_caller2;
2006 	g_destroy_bio(bip);
2007 	TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2008 	taskqueue_enqueue(taskqueue_ffs_trim, &tp->task);
2009 }
2010 
2011 void
2012 ffs_blkfree(ump, fs, devvp, bno, size, inum, dephd)
2013 	struct ufsmount *ump;
2014 	struct fs *fs;
2015 	struct vnode *devvp;
2016 	ufs2_daddr_t bno;
2017 	long size;
2018 	ino_t inum;
2019 	struct workhead *dephd;
2020 {
2021 	struct mount *mp;
2022 	struct bio *bip;
2023 	struct ffs_blkfree_trim_params *tp;
2024 
2025 	if (!ump->um_candelete) {
2026 		ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2027 		return;
2028 	}
2029 
2030 	/*
2031 	 * Postpone the set of the free bit in the cg bitmap until the
2032 	 * BIO_DELETE is completed.  Otherwise, due to disk queue
2033 	 * reordering, TRIM might be issued after we reuse the block
2034 	 * and write some new data into it.
2035 	 */
2036 	tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2037 	tp->ump = ump;
2038 	tp->devvp = devvp;
2039 	tp->bno = bno;
2040 	tp->size = size;
2041 	tp->inum = inum;
2042 	if (dephd != NULL) {
2043 		LIST_INIT(&tp->dephd);
2044 		LIST_SWAP(dephd, &tp->dephd, worklist, wk_list);
2045 		tp->pdephd = &tp->dephd;
2046 	} else
2047 		tp->pdephd = NULL;
2048 
2049 	bip = g_alloc_bio();
2050 	bip->bio_cmd = BIO_DELETE;
2051 	bip->bio_offset = dbtob(fsbtodb(fs, bno));
2052 	bip->bio_done = ffs_blkfree_trim_completed;
2053 	bip->bio_length = size;
2054 	bip->bio_caller2 = tp;
2055 
2056 	mp = UFSTOVFS(ump);
2057 	vn_start_secondary_write(NULL, &mp, 0);
2058 	g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2059 }
2060 
2061 #ifdef INVARIANTS
2062 /*
2063  * Verify allocation of a block or fragment. Returns true if block or
2064  * fragment is allocated, false if it is free.
2065  */
2066 static int
2067 ffs_checkblk(ip, bno, size)
2068 	struct inode *ip;
2069 	ufs2_daddr_t bno;
2070 	long size;
2071 {
2072 	struct fs *fs;
2073 	struct cg *cgp;
2074 	struct buf *bp;
2075 	ufs1_daddr_t cgbno;
2076 	int i, error, frags, free;
2077 	u_int8_t *blksfree;
2078 
2079 	fs = ip->i_fs;
2080 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2081 		printf("bsize = %ld, size = %ld, fs = %s\n",
2082 		    (long)fs->fs_bsize, size, fs->fs_fsmnt);
2083 		panic("ffs_checkblk: bad size");
2084 	}
2085 	if ((u_int)bno >= fs->fs_size)
2086 		panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2087 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
2088 		(int)fs->fs_cgsize, NOCRED, &bp);
2089 	if (error)
2090 		panic("ffs_checkblk: cg bread failed");
2091 	cgp = (struct cg *)bp->b_data;
2092 	if (!cg_chkmagic(cgp))
2093 		panic("ffs_checkblk: cg magic mismatch");
2094 	bp->b_xflags |= BX_BKGRDWRITE;
2095 	blksfree = cg_blksfree(cgp);
2096 	cgbno = dtogd(fs, bno);
2097 	if (size == fs->fs_bsize) {
2098 		free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2099 	} else {
2100 		frags = numfrags(fs, size);
2101 		for (free = 0, i = 0; i < frags; i++)
2102 			if (isset(blksfree, cgbno + i))
2103 				free++;
2104 		if (free != 0 && free != frags)
2105 			panic("ffs_checkblk: partially free fragment");
2106 	}
2107 	brelse(bp);
2108 	return (!free);
2109 }
2110 #endif /* INVARIANTS */
2111 
2112 /*
2113  * Free an inode.
2114  */
2115 int
2116 ffs_vfree(pvp, ino, mode)
2117 	struct vnode *pvp;
2118 	ino_t ino;
2119 	int mode;
2120 {
2121 	struct inode *ip;
2122 
2123 	if (DOINGSOFTDEP(pvp)) {
2124 		softdep_freefile(pvp, ino, mode);
2125 		return (0);
2126 	}
2127 	ip = VTOI(pvp);
2128 	return (ffs_freefile(ip->i_ump, ip->i_fs, ip->i_devvp, ino, mode,
2129 	    NULL));
2130 }
2131 
2132 /*
2133  * Do the actual free operation.
2134  * The specified inode is placed back in the free map.
2135  */
2136 int
2137 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2138 	struct ufsmount *ump;
2139 	struct fs *fs;
2140 	struct vnode *devvp;
2141 	ino_t ino;
2142 	int mode;
2143 	struct workhead *wkhd;
2144 {
2145 	struct cg *cgp;
2146 	struct buf *bp;
2147 	ufs2_daddr_t cgbno;
2148 	int error;
2149 	u_int cg;
2150 	u_int8_t *inosused;
2151 	struct cdev *dev;
2152 
2153 	cg = ino_to_cg(fs, ino);
2154 	if (devvp->v_type == VREG) {
2155 		/* devvp is a snapshot */
2156 		dev = VTOI(devvp)->i_devvp->v_rdev;
2157 		cgbno = fragstoblks(fs, cgtod(fs, cg));
2158 	} else {
2159 		/* devvp is a normal disk device */
2160 		dev = devvp->v_rdev;
2161 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2162 	}
2163 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2164 		panic("ffs_freefile: range: dev = %s, ino = %lu, fs = %s",
2165 		    devtoname(dev), (u_long)ino, fs->fs_fsmnt);
2166 	if ((error = bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp))) {
2167 		brelse(bp);
2168 		return (error);
2169 	}
2170 	cgp = (struct cg *)bp->b_data;
2171 	if (!cg_chkmagic(cgp)) {
2172 		brelse(bp);
2173 		return (0);
2174 	}
2175 	bp->b_xflags |= BX_BKGRDWRITE;
2176 	cgp->cg_old_time = cgp->cg_time = time_second;
2177 	inosused = cg_inosused(cgp);
2178 	ino %= fs->fs_ipg;
2179 	if (isclr(inosused, ino)) {
2180 		printf("dev = %s, ino = %u, fs = %s\n", devtoname(dev),
2181 		    ino + cg * fs->fs_ipg, fs->fs_fsmnt);
2182 		if (fs->fs_ronly == 0)
2183 			panic("ffs_freefile: freeing free inode");
2184 	}
2185 	clrbit(inosused, ino);
2186 	if (ino < cgp->cg_irotor)
2187 		cgp->cg_irotor = ino;
2188 	cgp->cg_cs.cs_nifree++;
2189 	UFS_LOCK(ump);
2190 	fs->fs_cstotal.cs_nifree++;
2191 	fs->fs_cs(fs, cg).cs_nifree++;
2192 	if ((mode & IFMT) == IFDIR) {
2193 		cgp->cg_cs.cs_ndir--;
2194 		fs->fs_cstotal.cs_ndir--;
2195 		fs->fs_cs(fs, cg).cs_ndir--;
2196 	}
2197 	fs->fs_fmod = 1;
2198 	ACTIVECLEAR(fs, cg);
2199 	UFS_UNLOCK(ump);
2200 	if (UFSTOVFS(ump)->mnt_flag & MNT_SOFTDEP && devvp->v_type != VREG)
2201 		softdep_setup_inofree(UFSTOVFS(ump), bp,
2202 		    ino + cg * fs->fs_ipg, wkhd);
2203 	bdwrite(bp);
2204 	return (0);
2205 }
2206 
2207 /*
2208  * Check to see if a file is free.
2209  */
2210 int
2211 ffs_checkfreefile(fs, devvp, ino)
2212 	struct fs *fs;
2213 	struct vnode *devvp;
2214 	ino_t ino;
2215 {
2216 	struct cg *cgp;
2217 	struct buf *bp;
2218 	ufs2_daddr_t cgbno;
2219 	int ret;
2220 	u_int cg;
2221 	u_int8_t *inosused;
2222 
2223 	cg = ino_to_cg(fs, ino);
2224 	if (devvp->v_type == VREG) {
2225 		/* devvp is a snapshot */
2226 		cgbno = fragstoblks(fs, cgtod(fs, cg));
2227 	} else {
2228 		/* devvp is a normal disk device */
2229 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2230 	}
2231 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2232 		return (1);
2233 	if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2234 		brelse(bp);
2235 		return (1);
2236 	}
2237 	cgp = (struct cg *)bp->b_data;
2238 	if (!cg_chkmagic(cgp)) {
2239 		brelse(bp);
2240 		return (1);
2241 	}
2242 	inosused = cg_inosused(cgp);
2243 	ino %= fs->fs_ipg;
2244 	ret = isclr(inosused, ino);
2245 	brelse(bp);
2246 	return (ret);
2247 }
2248 
2249 /*
2250  * Find a block of the specified size in the specified cylinder group.
2251  *
2252  * It is a panic if a request is made to find a block if none are
2253  * available.
2254  */
2255 static ufs1_daddr_t
2256 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2257 	struct fs *fs;
2258 	struct cg *cgp;
2259 	ufs2_daddr_t bpref;
2260 	int allocsiz;
2261 {
2262 	ufs1_daddr_t bno;
2263 	int start, len, loc, i;
2264 	int blk, field, subfield, pos;
2265 	u_int8_t *blksfree;
2266 
2267 	/*
2268 	 * find the fragment by searching through the free block
2269 	 * map for an appropriate bit pattern
2270 	 */
2271 	if (bpref)
2272 		start = dtogd(fs, bpref) / NBBY;
2273 	else
2274 		start = cgp->cg_frotor / NBBY;
2275 	blksfree = cg_blksfree(cgp);
2276 	len = howmany(fs->fs_fpg, NBBY) - start;
2277 	loc = scanc((u_int)len, (u_char *)&blksfree[start],
2278 		fragtbl[fs->fs_frag],
2279 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2280 	if (loc == 0) {
2281 		len = start + 1;
2282 		start = 0;
2283 		loc = scanc((u_int)len, (u_char *)&blksfree[0],
2284 			fragtbl[fs->fs_frag],
2285 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2286 		if (loc == 0) {
2287 			printf("start = %d, len = %d, fs = %s\n",
2288 			    start, len, fs->fs_fsmnt);
2289 			panic("ffs_alloccg: map corrupted");
2290 			/* NOTREACHED */
2291 		}
2292 	}
2293 	bno = (start + len - loc) * NBBY;
2294 	cgp->cg_frotor = bno;
2295 	/*
2296 	 * found the byte in the map
2297 	 * sift through the bits to find the selected frag
2298 	 */
2299 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2300 		blk = blkmap(fs, blksfree, bno);
2301 		blk <<= 1;
2302 		field = around[allocsiz];
2303 		subfield = inside[allocsiz];
2304 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2305 			if ((blk & field) == subfield)
2306 				return (bno + pos);
2307 			field <<= 1;
2308 			subfield <<= 1;
2309 		}
2310 	}
2311 	printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2312 	panic("ffs_alloccg: block not in map");
2313 	return (-1);
2314 }
2315 
2316 /*
2317  * Fserr prints the name of a filesystem with an error diagnostic.
2318  *
2319  * The form of the error message is:
2320  *	fs: error message
2321  */
2322 static void
2323 ffs_fserr(fs, inum, cp)
2324 	struct fs *fs;
2325 	ino_t inum;
2326 	char *cp;
2327 {
2328 	struct thread *td = curthread;	/* XXX */
2329 	struct proc *p = td->td_proc;
2330 
2331 	log(LOG_ERR, "pid %d (%s), uid %d inumber %d on %s: %s\n",
2332 	    p->p_pid, p->p_comm, td->td_ucred->cr_uid, inum, fs->fs_fsmnt, cp);
2333 }
2334 
2335 /*
2336  * This function provides the capability for the fsck program to
2337  * update an active filesystem. Fourteen operations are provided:
2338  *
2339  * adjrefcnt(inode, amt) - adjusts the reference count on the
2340  *	specified inode by the specified amount. Under normal
2341  *	operation the count should always go down. Decrementing
2342  *	the count to zero will cause the inode to be freed.
2343  * adjblkcnt(inode, amt) - adjust the number of blocks used to
2344  *	by the specifed amount.
2345  * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2346  *	adjust the superblock summary.
2347  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2348  *	are marked as free. Inodes should never have to be marked
2349  *	as in use.
2350  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2351  *	are marked as free. Inodes should never have to be marked
2352  *	as in use.
2353  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2354  *	are marked as free. Blocks should never have to be marked
2355  *	as in use.
2356  * setflags(flags, set/clear) - the fs_flags field has the specified
2357  *	flags set (second parameter +1) or cleared (second parameter -1).
2358  * setcwd(dirinode) - set the current directory to dirinode in the
2359  *	filesystem associated with the snapshot.
2360  * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
2361  *	in the current directory is oldvalue then change it to newvalue.
2362  * unlink(nameptr, oldvalue) - Verify that the inode number associated
2363  *	with nameptr in the current directory is oldvalue then unlink it.
2364  */
2365 
2366 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2367 
2368 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2369 	0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2370 
2371 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2372 	sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2373 
2374 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2375 	sysctl_ffs_fsck, "Adjust number of directories");
2376 
2377 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2378 	sysctl_ffs_fsck, "Adjust number of free blocks");
2379 
2380 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2381 	sysctl_ffs_fsck, "Adjust number of free inodes");
2382 
2383 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2384 	sysctl_ffs_fsck, "Adjust number of free frags");
2385 
2386 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2387 	sysctl_ffs_fsck, "Adjust number of free clusters");
2388 
2389 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2390 	sysctl_ffs_fsck, "Free Range of Directory Inodes");
2391 
2392 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2393 	sysctl_ffs_fsck, "Free Range of File Inodes");
2394 
2395 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2396 	sysctl_ffs_fsck, "Free Range of Blocks");
2397 
2398 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2399 	sysctl_ffs_fsck, "Change Filesystem Flags");
2400 
2401 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd, CTLFLAG_WR,
2402 	sysctl_ffs_fsck, "Set Current Working Directory");
2403 
2404 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot, CTLFLAG_WR,
2405 	sysctl_ffs_fsck, "Change Value of .. Entry");
2406 
2407 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink, CTLFLAG_WR,
2408 	sysctl_ffs_fsck, "Unlink a Duplicate Name");
2409 
2410 #ifdef DEBUG
2411 static int fsckcmds = 0;
2412 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2413 #endif /* DEBUG */
2414 
2415 static int
2416 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2417 {
2418 	struct thread *td = curthread;
2419 	struct fsck_cmd cmd;
2420 	struct ufsmount *ump;
2421 	struct vnode *vp, *vpold, *dvp, *fdvp;
2422 	struct inode *ip, *dp;
2423 	struct mount *mp;
2424 	struct fs *fs;
2425 	ufs2_daddr_t blkno;
2426 	long blkcnt, blksize;
2427 	struct filedesc *fdp;
2428 	struct file *fp;
2429 	int vfslocked, filetype, error;
2430 
2431 	if (req->newlen > sizeof cmd)
2432 		return (EBADRPC);
2433 	if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2434 		return (error);
2435 	if (cmd.version != FFS_CMD_VERSION)
2436 		return (ERPCMISMATCH);
2437 	if ((error = getvnode(curproc->p_fd, cmd.handle, &fp)) != 0)
2438 		return (error);
2439 	vp = fp->f_data;
2440 	if (vp->v_type != VREG && vp->v_type != VDIR) {
2441 		fdrop(fp, td);
2442 		return (EINVAL);
2443 	}
2444 	vn_start_write(vp, &mp, V_WAIT);
2445 	if (mp == 0 || strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2446 		vn_finished_write(mp);
2447 		fdrop(fp, td);
2448 		return (EINVAL);
2449 	}
2450 	if (mp->mnt_flag & MNT_RDONLY) {
2451 		vn_finished_write(mp);
2452 		fdrop(fp, td);
2453 		return (EROFS);
2454 	}
2455 	ump = VFSTOUFS(mp);
2456 	fs = ump->um_fs;
2457 	filetype = IFREG;
2458 
2459 	switch (oidp->oid_number) {
2460 
2461 	case FFS_SET_FLAGS:
2462 #ifdef DEBUG
2463 		if (fsckcmds)
2464 			printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2465 			    cmd.size > 0 ? "set" : "clear");
2466 #endif /* DEBUG */
2467 		if (cmd.size > 0)
2468 			fs->fs_flags |= (long)cmd.value;
2469 		else
2470 			fs->fs_flags &= ~(long)cmd.value;
2471 		break;
2472 
2473 	case FFS_ADJ_REFCNT:
2474 #ifdef DEBUG
2475 		if (fsckcmds) {
2476 			printf("%s: adjust inode %jd count by %jd\n",
2477 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2478 			    (intmax_t)cmd.size);
2479 		}
2480 #endif /* DEBUG */
2481 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2482 			break;
2483 		ip = VTOI(vp);
2484 		ip->i_nlink += cmd.size;
2485 		DIP_SET(ip, i_nlink, ip->i_nlink);
2486 		ip->i_effnlink += cmd.size;
2487 		ip->i_flag |= IN_CHANGE;
2488 		if (DOINGSOFTDEP(vp))
2489 			softdep_change_linkcnt(ip);
2490 		vput(vp);
2491 		break;
2492 
2493 	case FFS_ADJ_BLKCNT:
2494 #ifdef DEBUG
2495 		if (fsckcmds) {
2496 			printf("%s: adjust inode %jd block count by %jd\n",
2497 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2498 			    (intmax_t)cmd.size);
2499 		}
2500 #endif /* DEBUG */
2501 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2502 			break;
2503 		ip = VTOI(vp);
2504 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2505 		ip->i_flag |= IN_CHANGE;
2506 		vput(vp);
2507 		break;
2508 
2509 	case FFS_DIR_FREE:
2510 		filetype = IFDIR;
2511 		/* fall through */
2512 
2513 	case FFS_FILE_FREE:
2514 #ifdef DEBUG
2515 		if (fsckcmds) {
2516 			if (cmd.size == 1)
2517 				printf("%s: free %s inode %d\n",
2518 				    mp->mnt_stat.f_mntonname,
2519 				    filetype == IFDIR ? "directory" : "file",
2520 				    (ino_t)cmd.value);
2521 			else
2522 				printf("%s: free %s inodes %d-%d\n",
2523 				    mp->mnt_stat.f_mntonname,
2524 				    filetype == IFDIR ? "directory" : "file",
2525 				    (ino_t)cmd.value,
2526 				    (ino_t)(cmd.value + cmd.size - 1));
2527 		}
2528 #endif /* DEBUG */
2529 		while (cmd.size > 0) {
2530 			if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2531 			    cmd.value, filetype, NULL)))
2532 				break;
2533 			cmd.size -= 1;
2534 			cmd.value += 1;
2535 		}
2536 		break;
2537 
2538 	case FFS_BLK_FREE:
2539 #ifdef DEBUG
2540 		if (fsckcmds) {
2541 			if (cmd.size == 1)
2542 				printf("%s: free block %jd\n",
2543 				    mp->mnt_stat.f_mntonname,
2544 				    (intmax_t)cmd.value);
2545 			else
2546 				printf("%s: free blocks %jd-%jd\n",
2547 				    mp->mnt_stat.f_mntonname,
2548 				    (intmax_t)cmd.value,
2549 				    (intmax_t)cmd.value + cmd.size - 1);
2550 		}
2551 #endif /* DEBUG */
2552 		blkno = cmd.value;
2553 		blkcnt = cmd.size;
2554 		blksize = fs->fs_frag - (blkno % fs->fs_frag);
2555 		while (blkcnt > 0) {
2556 			if (blksize > blkcnt)
2557 				blksize = blkcnt;
2558 			ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2559 			    blksize * fs->fs_fsize, ROOTINO, NULL);
2560 			blkno += blksize;
2561 			blkcnt -= blksize;
2562 			blksize = fs->fs_frag;
2563 		}
2564 		break;
2565 
2566 	/*
2567 	 * Adjust superblock summaries.  fsck(8) is expected to
2568 	 * submit deltas when necessary.
2569 	 */
2570 	case FFS_ADJ_NDIR:
2571 #ifdef DEBUG
2572 		if (fsckcmds) {
2573 			printf("%s: adjust number of directories by %jd\n",
2574 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2575 		}
2576 #endif /* DEBUG */
2577 		fs->fs_cstotal.cs_ndir += cmd.value;
2578 		break;
2579 
2580 	case FFS_ADJ_NBFREE:
2581 #ifdef DEBUG
2582 		if (fsckcmds) {
2583 			printf("%s: adjust number of free blocks by %+jd\n",
2584 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2585 		}
2586 #endif /* DEBUG */
2587 		fs->fs_cstotal.cs_nbfree += cmd.value;
2588 		break;
2589 
2590 	case FFS_ADJ_NIFREE:
2591 #ifdef DEBUG
2592 		if (fsckcmds) {
2593 			printf("%s: adjust number of free inodes by %+jd\n",
2594 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2595 		}
2596 #endif /* DEBUG */
2597 		fs->fs_cstotal.cs_nifree += cmd.value;
2598 		break;
2599 
2600 	case FFS_ADJ_NFFREE:
2601 #ifdef DEBUG
2602 		if (fsckcmds) {
2603 			printf("%s: adjust number of free frags by %+jd\n",
2604 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2605 		}
2606 #endif /* DEBUG */
2607 		fs->fs_cstotal.cs_nffree += cmd.value;
2608 		break;
2609 
2610 	case FFS_ADJ_NUMCLUSTERS:
2611 #ifdef DEBUG
2612 		if (fsckcmds) {
2613 			printf("%s: adjust number of free clusters by %+jd\n",
2614 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2615 		}
2616 #endif /* DEBUG */
2617 		fs->fs_cstotal.cs_numclusters += cmd.value;
2618 		break;
2619 
2620 	case FFS_SET_CWD:
2621 #ifdef DEBUG
2622 		if (fsckcmds) {
2623 			printf("%s: set current directory to inode %jd\n",
2624 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2625 		}
2626 #endif /* DEBUG */
2627 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
2628 			break;
2629 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2630 		AUDIT_ARG_VNODE1(vp);
2631 		if ((error = change_dir(vp, td)) != 0) {
2632 			vput(vp);
2633 			VFS_UNLOCK_GIANT(vfslocked);
2634 			break;
2635 		}
2636 		VOP_UNLOCK(vp, 0);
2637 		VFS_UNLOCK_GIANT(vfslocked);
2638 		fdp = td->td_proc->p_fd;
2639 		FILEDESC_XLOCK(fdp);
2640 		vpold = fdp->fd_cdir;
2641 		fdp->fd_cdir = vp;
2642 		FILEDESC_XUNLOCK(fdp);
2643 		vfslocked = VFS_LOCK_GIANT(vpold->v_mount);
2644 		vrele(vpold);
2645 		VFS_UNLOCK_GIANT(vfslocked);
2646 		break;
2647 
2648 	case FFS_SET_DOTDOT:
2649 #ifdef DEBUG
2650 		if (fsckcmds) {
2651 			printf("%s: change .. in cwd from %jd to %jd\n",
2652 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2653 			    (intmax_t)cmd.size);
2654 		}
2655 #endif /* DEBUG */
2656 		/*
2657 		 * First we have to get and lock the parent directory
2658 		 * to which ".." points.
2659 		 */
2660 		error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
2661 		if (error)
2662 			break;
2663 		/*
2664 		 * Now we get and lock the child directory containing "..".
2665 		 */
2666 		FILEDESC_SLOCK(td->td_proc->p_fd);
2667 		dvp = td->td_proc->p_fd->fd_cdir;
2668 		FILEDESC_SUNLOCK(td->td_proc->p_fd);
2669 		if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
2670 			vput(fdvp);
2671 			break;
2672 		}
2673 		dp = VTOI(dvp);
2674 		dp->i_offset = 12;	/* XXX mastertemplate.dot_reclen */
2675 		error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
2676 		    DT_DIR, 0);
2677 		cache_purge(fdvp);
2678 		cache_purge(dvp);
2679 		vput(dvp);
2680 		vput(fdvp);
2681 		break;
2682 
2683 	case FFS_UNLINK:
2684 #ifdef DEBUG
2685 		if (fsckcmds) {
2686 			char buf[32];
2687 
2688 			if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
2689 				strncpy(buf, "Name_too_long", 32);
2690 			printf("%s: unlink %s (inode %jd)\n",
2691 			    mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
2692 		}
2693 #endif /* DEBUG */
2694 		/*
2695 		 * kern_unlinkat will do its own start/finish writes and
2696 		 * they do not nest, so drop ours here. Setting mp == NULL
2697 		 * indicates that vn_finished_write is not needed down below.
2698 		 */
2699 		vn_finished_write(mp);
2700 		mp = NULL;
2701 		error = kern_unlinkat(td, AT_FDCWD, (char *)(intptr_t)cmd.value,
2702 		    UIO_USERSPACE, (ino_t)cmd.size);
2703 		break;
2704 
2705 	default:
2706 #ifdef DEBUG
2707 		if (fsckcmds) {
2708 			printf("Invalid request %d from fsck\n",
2709 			    oidp->oid_number);
2710 		}
2711 #endif /* DEBUG */
2712 		error = EINVAL;
2713 		break;
2714 
2715 	}
2716 	fdrop(fp, td);
2717 	vn_finished_write(mp);
2718 	return (error);
2719 }
2720