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