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