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