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