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