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