xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision 6b806d21d144c25f4fad714e1c0cf780f5e27d7e)
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 	return (0);
954 noinodes:
955 	UFS_UNLOCK(ump);
956 	ffs_fserr(fs, pip->i_number, "out of inodes");
957 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
958 	return (ENOSPC);
959 }
960 
961 /*
962  * Find a cylinder group to place a directory.
963  *
964  * The policy implemented by this algorithm is to allocate a
965  * directory inode in the same cylinder group as its parent
966  * directory, but also to reserve space for its files inodes
967  * and data. Restrict the number of directories which may be
968  * allocated one after another in the same cylinder group
969  * without intervening allocation of files.
970  *
971  * If we allocate a first level directory then force allocation
972  * in another cylinder group.
973  */
974 static ino_t
975 ffs_dirpref(pip)
976 	struct inode *pip;
977 {
978 	struct fs *fs;
979 	int cg, prefcg, dirsize, cgsize;
980 	int avgifree, avgbfree, avgndir, curdirsize;
981 	int minifree, minbfree, maxndir;
982 	int mincg, minndir;
983 	int maxcontigdirs;
984 
985 	mtx_assert(UFS_MTX(pip->i_ump), MA_OWNED);
986 	fs = pip->i_fs;
987 
988 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
989 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
990 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
991 
992 	/*
993 	 * Force allocation in another cg if creating a first level dir.
994 	 */
995 	ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
996 	if (ITOV(pip)->v_vflag & VV_ROOT) {
997 		prefcg = arc4random() % fs->fs_ncg;
998 		mincg = prefcg;
999 		minndir = fs->fs_ipg;
1000 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
1001 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1002 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1003 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1004 				mincg = cg;
1005 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1006 			}
1007 		for (cg = 0; cg < prefcg; 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 		return ((ino_t)(fs->fs_ipg * mincg));
1015 	}
1016 
1017 	/*
1018 	 * Count various limits which used for
1019 	 * optimal allocation of a directory inode.
1020 	 */
1021 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1022 	minifree = avgifree - avgifree / 4;
1023 	if (minifree < 1)
1024 		minifree = 1;
1025 	minbfree = avgbfree - avgbfree / 4;
1026 	if (minbfree < 1)
1027 		minbfree = 1;
1028 	cgsize = fs->fs_fsize * fs->fs_fpg;
1029 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1030 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1031 	if (dirsize < curdirsize)
1032 		dirsize = curdirsize;
1033 	maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1034 	if (fs->fs_avgfpdir > 0)
1035 		maxcontigdirs = min(maxcontigdirs,
1036 				    fs->fs_ipg / fs->fs_avgfpdir);
1037 	if (maxcontigdirs == 0)
1038 		maxcontigdirs = 1;
1039 
1040 	/*
1041 	 * Limit number of dirs in one cg and reserve space for
1042 	 * regular files, but only if we have no deficit in
1043 	 * inodes or space.
1044 	 */
1045 	prefcg = ino_to_cg(fs, pip->i_number);
1046 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1047 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1048 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1049 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1050 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1051 				return ((ino_t)(fs->fs_ipg * cg));
1052 		}
1053 	for (cg = 0; cg < prefcg; 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 	/*
1061 	 * This is a backstop when we have deficit in space.
1062 	 */
1063 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1064 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1065 			return ((ino_t)(fs->fs_ipg * cg));
1066 	for (cg = 0; cg < prefcg; cg++)
1067 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1068 			break;
1069 	return ((ino_t)(fs->fs_ipg * cg));
1070 }
1071 
1072 /*
1073  * Select the desired position for the next block in a file.  The file is
1074  * logically divided into sections. The first section is composed of the
1075  * direct blocks. Each additional section contains fs_maxbpg blocks.
1076  *
1077  * If no blocks have been allocated in the first section, the policy is to
1078  * request a block in the same cylinder group as the inode that describes
1079  * the file. If no blocks have been allocated in any other section, the
1080  * policy is to place the section in a cylinder group with a greater than
1081  * average number of free blocks.  An appropriate cylinder group is found
1082  * by using a rotor that sweeps the cylinder groups. When a new group of
1083  * blocks is needed, the sweep begins in the cylinder group following the
1084  * cylinder group from which the previous allocation was made. The sweep
1085  * continues until a cylinder group with greater than the average number
1086  * of free blocks is found. If the allocation is for the first block in an
1087  * indirect block, the information on the previous allocation is unavailable;
1088  * here a best guess is made based upon the logical block number being
1089  * allocated.
1090  *
1091  * If a section is already partially allocated, the policy is to
1092  * contiguously allocate fs_maxcontig blocks. The end of one of these
1093  * contiguous blocks and the beginning of the next is laid out
1094  * contiguously if possible.
1095  */
1096 ufs2_daddr_t
1097 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1098 	struct inode *ip;
1099 	ufs_lbn_t lbn;
1100 	int indx;
1101 	ufs1_daddr_t *bap;
1102 {
1103 	struct fs *fs;
1104 	int cg;
1105 	int avgbfree, startcg;
1106 
1107 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1108 	fs = ip->i_fs;
1109 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1110 		if (lbn < NDADDR + NINDIR(fs)) {
1111 			cg = ino_to_cg(fs, ip->i_number);
1112 			return (cgbase(fs, cg) + fs->fs_frag);
1113 		}
1114 		/*
1115 		 * Find a cylinder with greater than average number of
1116 		 * unused data blocks.
1117 		 */
1118 		if (indx == 0 || bap[indx - 1] == 0)
1119 			startcg =
1120 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1121 		else
1122 			startcg = dtog(fs, bap[indx - 1]) + 1;
1123 		startcg %= fs->fs_ncg;
1124 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1125 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1126 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1127 				fs->fs_cgrotor = cg;
1128 				return (cgbase(fs, cg) + fs->fs_frag);
1129 			}
1130 		for (cg = 0; cg <= startcg; cg++)
1131 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1132 				fs->fs_cgrotor = cg;
1133 				return (cgbase(fs, cg) + fs->fs_frag);
1134 			}
1135 		return (0);
1136 	}
1137 	/*
1138 	 * We just always try to lay things out contiguously.
1139 	 */
1140 	return (bap[indx - 1] + fs->fs_frag);
1141 }
1142 
1143 /*
1144  * Same as above, but for UFS2
1145  */
1146 ufs2_daddr_t
1147 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1148 	struct inode *ip;
1149 	ufs_lbn_t lbn;
1150 	int indx;
1151 	ufs2_daddr_t *bap;
1152 {
1153 	struct fs *fs;
1154 	int cg;
1155 	int avgbfree, startcg;
1156 
1157 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1158 	fs = ip->i_fs;
1159 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1160 		if (lbn < NDADDR + NINDIR(fs)) {
1161 			cg = ino_to_cg(fs, ip->i_number);
1162 			return (cgbase(fs, cg) + fs->fs_frag);
1163 		}
1164 		/*
1165 		 * Find a cylinder with greater than average number of
1166 		 * unused data blocks.
1167 		 */
1168 		if (indx == 0 || bap[indx - 1] == 0)
1169 			startcg =
1170 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1171 		else
1172 			startcg = dtog(fs, bap[indx - 1]) + 1;
1173 		startcg %= fs->fs_ncg;
1174 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1175 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1176 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1177 				fs->fs_cgrotor = cg;
1178 				return (cgbase(fs, cg) + fs->fs_frag);
1179 			}
1180 		for (cg = 0; cg <= startcg; cg++)
1181 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1182 				fs->fs_cgrotor = cg;
1183 				return (cgbase(fs, cg) + fs->fs_frag);
1184 			}
1185 		return (0);
1186 	}
1187 	/*
1188 	 * We just always try to lay things out contiguously.
1189 	 */
1190 	return (bap[indx - 1] + fs->fs_frag);
1191 }
1192 
1193 /*
1194  * Implement the cylinder overflow algorithm.
1195  *
1196  * The policy implemented by this algorithm is:
1197  *   1) allocate the block in its requested cylinder group.
1198  *   2) quadradically rehash on the cylinder group number.
1199  *   3) brute force search for a free block.
1200  *
1201  * Must be called with the UFS lock held.  Will release the lock on success
1202  * and return with it held on failure.
1203  */
1204 /*VARARGS5*/
1205 static ufs2_daddr_t
1206 ffs_hashalloc(ip, cg, pref, size, allocator)
1207 	struct inode *ip;
1208 	int cg;
1209 	ufs2_daddr_t pref;
1210 	int size;	/* size for data blocks, mode for inodes */
1211 	allocfcn_t *allocator;
1212 {
1213 	struct fs *fs;
1214 	ufs2_daddr_t result;
1215 	int i, icg = cg;
1216 
1217 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1218 #ifdef DIAGNOSTIC
1219 	if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1220 		panic("ffs_hashalloc: allocation on suspended filesystem");
1221 #endif
1222 	fs = ip->i_fs;
1223 	/*
1224 	 * 1: preferred cylinder group
1225 	 */
1226 	result = (*allocator)(ip, cg, pref, size);
1227 	if (result)
1228 		return (result);
1229 	/*
1230 	 * 2: quadratic rehash
1231 	 */
1232 	for (i = 1; i < fs->fs_ncg; i *= 2) {
1233 		cg += i;
1234 		if (cg >= fs->fs_ncg)
1235 			cg -= fs->fs_ncg;
1236 		result = (*allocator)(ip, cg, 0, size);
1237 		if (result)
1238 			return (result);
1239 	}
1240 	/*
1241 	 * 3: brute force search
1242 	 * Note that we start at i == 2, since 0 was checked initially,
1243 	 * and 1 is always checked in the quadratic rehash.
1244 	 */
1245 	cg = (icg + 2) % fs->fs_ncg;
1246 	for (i = 2; i < fs->fs_ncg; i++) {
1247 		result = (*allocator)(ip, cg, 0, size);
1248 		if (result)
1249 			return (result);
1250 		cg++;
1251 		if (cg == fs->fs_ncg)
1252 			cg = 0;
1253 	}
1254 	return (0);
1255 }
1256 
1257 /*
1258  * Determine whether a fragment can be extended.
1259  *
1260  * Check to see if the necessary fragments are available, and
1261  * if they are, allocate them.
1262  */
1263 static ufs2_daddr_t
1264 ffs_fragextend(ip, cg, bprev, osize, nsize)
1265 	struct inode *ip;
1266 	int cg;
1267 	ufs2_daddr_t bprev;
1268 	int osize, nsize;
1269 {
1270 	struct fs *fs;
1271 	struct cg *cgp;
1272 	struct buf *bp;
1273 	struct ufsmount *ump;
1274 	int nffree;
1275 	long bno;
1276 	int frags, bbase;
1277 	int i, error;
1278 	u_int8_t *blksfree;
1279 
1280 	ump = ip->i_ump;
1281 	fs = ip->i_fs;
1282 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1283 		return (0);
1284 	frags = numfrags(fs, nsize);
1285 	bbase = fragnum(fs, bprev);
1286 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
1287 		/* cannot extend across a block boundary */
1288 		return (0);
1289 	}
1290 	UFS_UNLOCK(ump);
1291 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1292 		(int)fs->fs_cgsize, NOCRED, &bp);
1293 	if (error)
1294 		goto fail;
1295 	cgp = (struct cg *)bp->b_data;
1296 	if (!cg_chkmagic(cgp))
1297 		goto fail;
1298 	bp->b_xflags |= BX_BKGRDWRITE;
1299 	cgp->cg_old_time = cgp->cg_time = time_second;
1300 	bno = dtogd(fs, bprev);
1301 	blksfree = cg_blksfree(cgp);
1302 	for (i = numfrags(fs, osize); i < frags; i++)
1303 		if (isclr(blksfree, bno + i))
1304 			goto fail;
1305 	/*
1306 	 * the current fragment can be extended
1307 	 * deduct the count on fragment being extended into
1308 	 * increase the count on the remaining fragment (if any)
1309 	 * allocate the extended piece
1310 	 */
1311 	for (i = frags; i < fs->fs_frag - bbase; i++)
1312 		if (isclr(blksfree, bno + i))
1313 			break;
1314 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
1315 	if (i != frags)
1316 		cgp->cg_frsum[i - frags]++;
1317 	for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1318 		clrbit(blksfree, bno + i);
1319 		cgp->cg_cs.cs_nffree--;
1320 		nffree++;
1321 	}
1322 	UFS_LOCK(ump);
1323 	fs->fs_cstotal.cs_nffree -= nffree;
1324 	fs->fs_cs(fs, cg).cs_nffree -= nffree;
1325 	fs->fs_fmod = 1;
1326 	ACTIVECLEAR(fs, cg);
1327 	UFS_UNLOCK(ump);
1328 	if (DOINGSOFTDEP(ITOV(ip)))
1329 		softdep_setup_blkmapdep(bp, fs, bprev);
1330 	bdwrite(bp);
1331 	return (bprev);
1332 
1333 fail:
1334 	brelse(bp);
1335 	UFS_LOCK(ump);
1336 	return (0);
1337 
1338 }
1339 
1340 /*
1341  * Determine whether a block can be allocated.
1342  *
1343  * Check to see if a block of the appropriate size is available,
1344  * and if it is, allocate it.
1345  */
1346 static ufs2_daddr_t
1347 ffs_alloccg(ip, cg, bpref, size)
1348 	struct inode *ip;
1349 	int cg;
1350 	ufs2_daddr_t bpref;
1351 	int size;
1352 {
1353 	struct fs *fs;
1354 	struct cg *cgp;
1355 	struct buf *bp;
1356 	struct ufsmount *ump;
1357 	ufs1_daddr_t bno;
1358 	ufs2_daddr_t blkno;
1359 	int i, allocsiz, error, frags;
1360 	u_int8_t *blksfree;
1361 
1362 	ump = ip->i_ump;
1363 	fs = ip->i_fs;
1364 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1365 		return (0);
1366 	UFS_UNLOCK(ump);
1367 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1368 		(int)fs->fs_cgsize, NOCRED, &bp);
1369 	if (error)
1370 		goto fail;
1371 	cgp = (struct cg *)bp->b_data;
1372 	if (!cg_chkmagic(cgp) ||
1373 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1374 		goto fail;
1375 	bp->b_xflags |= BX_BKGRDWRITE;
1376 	cgp->cg_old_time = cgp->cg_time = time_second;
1377 	if (size == fs->fs_bsize) {
1378 		UFS_LOCK(ump);
1379 		blkno = ffs_alloccgblk(ip, bp, bpref);
1380 		ACTIVECLEAR(fs, cg);
1381 		UFS_UNLOCK(ump);
1382 		bdwrite(bp);
1383 		return (blkno);
1384 	}
1385 	/*
1386 	 * check to see if any fragments are already available
1387 	 * allocsiz is the size which will be allocated, hacking
1388 	 * it down to a smaller size if necessary
1389 	 */
1390 	blksfree = cg_blksfree(cgp);
1391 	frags = numfrags(fs, size);
1392 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1393 		if (cgp->cg_frsum[allocsiz] != 0)
1394 			break;
1395 	if (allocsiz == fs->fs_frag) {
1396 		/*
1397 		 * no fragments were available, so a block will be
1398 		 * allocated, and hacked up
1399 		 */
1400 		if (cgp->cg_cs.cs_nbfree == 0)
1401 			goto fail;
1402 		UFS_LOCK(ump);
1403 		blkno = ffs_alloccgblk(ip, bp, bpref);
1404 		bno = dtogd(fs, blkno);
1405 		for (i = frags; i < fs->fs_frag; i++)
1406 			setbit(blksfree, bno + i);
1407 		i = fs->fs_frag - frags;
1408 		cgp->cg_cs.cs_nffree += i;
1409 		fs->fs_cstotal.cs_nffree += i;
1410 		fs->fs_cs(fs, cg).cs_nffree += i;
1411 		fs->fs_fmod = 1;
1412 		cgp->cg_frsum[i]++;
1413 		ACTIVECLEAR(fs, cg);
1414 		UFS_UNLOCK(ump);
1415 		bdwrite(bp);
1416 		return (blkno);
1417 	}
1418 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1419 	if (bno < 0)
1420 		goto fail;
1421 	for (i = 0; i < frags; i++)
1422 		clrbit(blksfree, bno + i);
1423 	cgp->cg_cs.cs_nffree -= frags;
1424 	cgp->cg_frsum[allocsiz]--;
1425 	if (frags != allocsiz)
1426 		cgp->cg_frsum[allocsiz - frags]++;
1427 	UFS_LOCK(ump);
1428 	fs->fs_cstotal.cs_nffree -= frags;
1429 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1430 	fs->fs_fmod = 1;
1431 	blkno = cgbase(fs, cg) + bno;
1432 	ACTIVECLEAR(fs, cg);
1433 	UFS_UNLOCK(ump);
1434 	if (DOINGSOFTDEP(ITOV(ip)))
1435 		softdep_setup_blkmapdep(bp, fs, blkno);
1436 	bdwrite(bp);
1437 	return (blkno);
1438 
1439 fail:
1440 	brelse(bp);
1441 	UFS_LOCK(ump);
1442 	return (0);
1443 }
1444 
1445 /*
1446  * Allocate a block in a cylinder group.
1447  *
1448  * This algorithm implements the following policy:
1449  *   1) allocate the requested block.
1450  *   2) allocate a rotationally optimal block in the same cylinder.
1451  *   3) allocate the next available block on the block rotor for the
1452  *      specified cylinder group.
1453  * Note that this routine only allocates fs_bsize blocks; these
1454  * blocks may be fragmented by the routine that allocates them.
1455  */
1456 static ufs2_daddr_t
1457 ffs_alloccgblk(ip, bp, bpref)
1458 	struct inode *ip;
1459 	struct buf *bp;
1460 	ufs2_daddr_t bpref;
1461 {
1462 	struct fs *fs;
1463 	struct cg *cgp;
1464 	struct ufsmount *ump;
1465 	ufs1_daddr_t bno;
1466 	ufs2_daddr_t blkno;
1467 	u_int8_t *blksfree;
1468 
1469 	fs = ip->i_fs;
1470 	ump = ip->i_ump;
1471 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1472 	cgp = (struct cg *)bp->b_data;
1473 	blksfree = cg_blksfree(cgp);
1474 	if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
1475 		bpref = cgp->cg_rotor;
1476 	} else {
1477 		bpref = blknum(fs, bpref);
1478 		bno = dtogd(fs, bpref);
1479 		/*
1480 		 * if the requested block is available, use it
1481 		 */
1482 		if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1483 			goto gotit;
1484 	}
1485 	/*
1486 	 * Take the next available block in this cylinder group.
1487 	 */
1488 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1489 	if (bno < 0)
1490 		return (0);
1491 	cgp->cg_rotor = bno;
1492 gotit:
1493 	blkno = fragstoblks(fs, bno);
1494 	ffs_clrblock(fs, blksfree, (long)blkno);
1495 	ffs_clusteracct(ump, fs, cgp, blkno, -1);
1496 	cgp->cg_cs.cs_nbfree--;
1497 	fs->fs_cstotal.cs_nbfree--;
1498 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1499 	fs->fs_fmod = 1;
1500 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1501 	/* XXX Fixme. */
1502 	UFS_UNLOCK(ump);
1503 	if (DOINGSOFTDEP(ITOV(ip)))
1504 		softdep_setup_blkmapdep(bp, fs, blkno);
1505 	UFS_LOCK(ump);
1506 	return (blkno);
1507 }
1508 
1509 /*
1510  * Determine whether a cluster can be allocated.
1511  *
1512  * We do not currently check for optimal rotational layout if there
1513  * are multiple choices in the same cylinder group. Instead we just
1514  * take the first one that we find following bpref.
1515  */
1516 static ufs2_daddr_t
1517 ffs_clusteralloc(ip, cg, bpref, len)
1518 	struct inode *ip;
1519 	int cg;
1520 	ufs2_daddr_t bpref;
1521 	int len;
1522 {
1523 	struct fs *fs;
1524 	struct cg *cgp;
1525 	struct buf *bp;
1526 	struct ufsmount *ump;
1527 	int i, run, bit, map, got;
1528 	ufs2_daddr_t bno;
1529 	u_char *mapp;
1530 	int32_t *lp;
1531 	u_int8_t *blksfree;
1532 
1533 	fs = ip->i_fs;
1534 	ump = ip->i_ump;
1535 	if (fs->fs_maxcluster[cg] < len)
1536 		return (0);
1537 	UFS_UNLOCK(ump);
1538 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1539 	    NOCRED, &bp))
1540 		goto fail_lock;
1541 	cgp = (struct cg *)bp->b_data;
1542 	if (!cg_chkmagic(cgp))
1543 		goto fail_lock;
1544 	bp->b_xflags |= BX_BKGRDWRITE;
1545 	/*
1546 	 * Check to see if a cluster of the needed size (or bigger) is
1547 	 * available in this cylinder group.
1548 	 */
1549 	lp = &cg_clustersum(cgp)[len];
1550 	for (i = len; i <= fs->fs_contigsumsize; i++)
1551 		if (*lp++ > 0)
1552 			break;
1553 	if (i > fs->fs_contigsumsize) {
1554 		/*
1555 		 * This is the first time looking for a cluster in this
1556 		 * cylinder group. Update the cluster summary information
1557 		 * to reflect the true maximum sized cluster so that
1558 		 * future cluster allocation requests can avoid reading
1559 		 * the cylinder group map only to find no clusters.
1560 		 */
1561 		lp = &cg_clustersum(cgp)[len - 1];
1562 		for (i = len - 1; i > 0; i--)
1563 			if (*lp-- > 0)
1564 				break;
1565 		UFS_LOCK(ump);
1566 		fs->fs_maxcluster[cg] = i;
1567 		goto fail;
1568 	}
1569 	/*
1570 	 * Search the cluster map to find a big enough cluster.
1571 	 * We take the first one that we find, even if it is larger
1572 	 * than we need as we prefer to get one close to the previous
1573 	 * block allocation. We do not search before the current
1574 	 * preference point as we do not want to allocate a block
1575 	 * that is allocated before the previous one (as we will
1576 	 * then have to wait for another pass of the elevator
1577 	 * algorithm before it will be read). We prefer to fail and
1578 	 * be recalled to try an allocation in the next cylinder group.
1579 	 */
1580 	if (dtog(fs, bpref) != cg)
1581 		bpref = 0;
1582 	else
1583 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1584 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1585 	map = *mapp++;
1586 	bit = 1 << (bpref % NBBY);
1587 	for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1588 		if ((map & bit) == 0) {
1589 			run = 0;
1590 		} else {
1591 			run++;
1592 			if (run == len)
1593 				break;
1594 		}
1595 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
1596 			bit <<= 1;
1597 		} else {
1598 			map = *mapp++;
1599 			bit = 1;
1600 		}
1601 	}
1602 	if (got >= cgp->cg_nclusterblks)
1603 		goto fail_lock;
1604 	/*
1605 	 * Allocate the cluster that we have found.
1606 	 */
1607 	blksfree = cg_blksfree(cgp);
1608 	for (i = 1; i <= len; i++)
1609 		if (!ffs_isblock(fs, blksfree, got - run + i))
1610 			panic("ffs_clusteralloc: map mismatch");
1611 	bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1612 	if (dtog(fs, bno) != cg)
1613 		panic("ffs_clusteralloc: allocated out of group");
1614 	len = blkstofrags(fs, len);
1615 	UFS_LOCK(ump);
1616 	for (i = 0; i < len; i += fs->fs_frag)
1617 		if (ffs_alloccgblk(ip, bp, bno + i) != bno + i)
1618 			panic("ffs_clusteralloc: lost block");
1619 	ACTIVECLEAR(fs, cg);
1620 	UFS_UNLOCK(ump);
1621 	bdwrite(bp);
1622 	return (bno);
1623 
1624 fail_lock:
1625 	UFS_LOCK(ump);
1626 fail:
1627 	brelse(bp);
1628 	return (0);
1629 }
1630 
1631 /*
1632  * Determine whether an inode can be allocated.
1633  *
1634  * Check to see if an inode is available, and if it is,
1635  * allocate it using the following policy:
1636  *   1) allocate the requested inode.
1637  *   2) allocate the next available inode after the requested
1638  *      inode in the specified cylinder group.
1639  */
1640 static ufs2_daddr_t
1641 ffs_nodealloccg(ip, cg, ipref, mode)
1642 	struct inode *ip;
1643 	int cg;
1644 	ufs2_daddr_t ipref;
1645 	int mode;
1646 {
1647 	struct fs *fs;
1648 	struct cg *cgp;
1649 	struct buf *bp, *ibp;
1650 	struct ufsmount *ump;
1651 	u_int8_t *inosused;
1652 	struct ufs2_dinode *dp2;
1653 	int error, start, len, loc, map, i;
1654 
1655 	fs = ip->i_fs;
1656 	ump = ip->i_ump;
1657 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1658 		return (0);
1659 	UFS_UNLOCK(ump);
1660 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1661 		(int)fs->fs_cgsize, NOCRED, &bp);
1662 	if (error) {
1663 		brelse(bp);
1664 		UFS_LOCK(ump);
1665 		return (0);
1666 	}
1667 	cgp = (struct cg *)bp->b_data;
1668 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1669 		brelse(bp);
1670 		UFS_LOCK(ump);
1671 		return (0);
1672 	}
1673 	bp->b_xflags |= BX_BKGRDWRITE;
1674 	cgp->cg_old_time = cgp->cg_time = time_second;
1675 	inosused = cg_inosused(cgp);
1676 	if (ipref) {
1677 		ipref %= fs->fs_ipg;
1678 		if (isclr(inosused, ipref))
1679 			goto gotit;
1680 	}
1681 	start = cgp->cg_irotor / NBBY;
1682 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1683 	loc = skpc(0xff, len, &inosused[start]);
1684 	if (loc == 0) {
1685 		len = start + 1;
1686 		start = 0;
1687 		loc = skpc(0xff, len, &inosused[0]);
1688 		if (loc == 0) {
1689 			printf("cg = %d, irotor = %ld, fs = %s\n",
1690 			    cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
1691 			panic("ffs_nodealloccg: map corrupted");
1692 			/* NOTREACHED */
1693 		}
1694 	}
1695 	i = start + len - loc;
1696 	map = inosused[i];
1697 	ipref = i * NBBY;
1698 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
1699 		if ((map & i) == 0) {
1700 			cgp->cg_irotor = ipref;
1701 			goto gotit;
1702 		}
1703 	}
1704 	printf("fs = %s\n", fs->fs_fsmnt);
1705 	panic("ffs_nodealloccg: block not in map");
1706 	/* NOTREACHED */
1707 gotit:
1708 	/*
1709 	 * Check to see if we need to initialize more inodes.
1710 	 */
1711 	ibp = NULL;
1712 	if (fs->fs_magic == FS_UFS2_MAGIC &&
1713 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
1714 	    cgp->cg_initediblk < cgp->cg_niblk) {
1715 		ibp = getblk(ip->i_devvp, fsbtodb(fs,
1716 		    ino_to_fsba(fs, cg * fs->fs_ipg + cgp->cg_initediblk)),
1717 		    (int)fs->fs_bsize, 0, 0, 0);
1718 		bzero(ibp->b_data, (int)fs->fs_bsize);
1719 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
1720 		for (i = 0; i < INOPB(fs); i++) {
1721 			dp2->di_gen = arc4random() / 2 + 1;
1722 			dp2++;
1723 		}
1724 		cgp->cg_initediblk += INOPB(fs);
1725 	}
1726 	UFS_LOCK(ump);
1727 	ACTIVECLEAR(fs, cg);
1728 	setbit(inosused, ipref);
1729 	cgp->cg_cs.cs_nifree--;
1730 	fs->fs_cstotal.cs_nifree--;
1731 	fs->fs_cs(fs, cg).cs_nifree--;
1732 	fs->fs_fmod = 1;
1733 	if ((mode & IFMT) == IFDIR) {
1734 		cgp->cg_cs.cs_ndir++;
1735 		fs->fs_cstotal.cs_ndir++;
1736 		fs->fs_cs(fs, cg).cs_ndir++;
1737 	}
1738 	UFS_UNLOCK(ump);
1739 	if (DOINGSOFTDEP(ITOV(ip)))
1740 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
1741 	bdwrite(bp);
1742 	if (ibp != NULL)
1743 		bawrite(ibp);
1744 	return (cg * fs->fs_ipg + ipref);
1745 }
1746 
1747 /*
1748  * check if a block is free
1749  */
1750 static int
1751 ffs_isfreeblock(struct fs *fs, u_char *cp, ufs1_daddr_t h)
1752 {
1753 
1754 	switch ((int)fs->fs_frag) {
1755 	case 8:
1756 		return (cp[h] == 0);
1757 	case 4:
1758 		return ((cp[h >> 1] & (0x0f << ((h & 0x1) << 2))) == 0);
1759 	case 2:
1760 		return ((cp[h >> 2] & (0x03 << ((h & 0x3) << 1))) == 0);
1761 	case 1:
1762 		return ((cp[h >> 3] & (0x01 << (h & 0x7))) == 0);
1763 	default:
1764 		panic("ffs_isfreeblock");
1765 	}
1766 	return (0);
1767 }
1768 
1769 /*
1770  * Free a block or fragment.
1771  *
1772  * The specified block or fragment is placed back in the
1773  * free map. If a fragment is deallocated, a possible
1774  * block reassembly is checked.
1775  */
1776 void
1777 ffs_blkfree(ump, fs, devvp, bno, size, inum)
1778 	struct ufsmount *ump;
1779 	struct fs *fs;
1780 	struct vnode *devvp;
1781 	ufs2_daddr_t bno;
1782 	long size;
1783 	ino_t inum;
1784 {
1785 	struct cg *cgp;
1786 	struct buf *bp;
1787 	ufs1_daddr_t fragno, cgbno;
1788 	ufs2_daddr_t cgblkno;
1789 	int i, cg, blk, frags, bbase;
1790 	u_int8_t *blksfree;
1791 	struct cdev *dev;
1792 
1793 	cg = dtog(fs, bno);
1794 	if (devvp->v_type != VCHR) {
1795 		/* devvp is a snapshot */
1796 		dev = VTOI(devvp)->i_devvp->v_rdev;
1797 		cgblkno = fragstoblks(fs, cgtod(fs, cg));
1798 	} else {
1799 		/* devvp is a normal disk device */
1800 		dev = devvp->v_rdev;
1801 		cgblkno = fsbtodb(fs, cgtod(fs, cg));
1802 		ASSERT_VOP_LOCKED(devvp, "ffs_blkfree");
1803 		if ((devvp->v_vflag & VV_COPYONWRITE) &&
1804 		    ffs_snapblkfree(fs, devvp, bno, size, inum))
1805 			return;
1806 	}
1807 #ifdef DIAGNOSTIC
1808 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1809 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1810 		printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
1811 		    devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
1812 		    size, fs->fs_fsmnt);
1813 		panic("ffs_blkfree: bad size");
1814 	}
1815 #endif
1816 	if ((u_int)bno >= fs->fs_size) {
1817 		printf("bad block %jd, ino %lu\n", (intmax_t)bno,
1818 		    (u_long)inum);
1819 		ffs_fserr(fs, inum, "bad block");
1820 		return;
1821 	}
1822 	if (bread(devvp, cgblkno, (int)fs->fs_cgsize, NOCRED, &bp)) {
1823 		brelse(bp);
1824 		return;
1825 	}
1826 	cgp = (struct cg *)bp->b_data;
1827 	if (!cg_chkmagic(cgp)) {
1828 		brelse(bp);
1829 		return;
1830 	}
1831 	bp->b_xflags |= BX_BKGRDWRITE;
1832 	cgp->cg_old_time = cgp->cg_time = time_second;
1833 	cgbno = dtogd(fs, bno);
1834 	blksfree = cg_blksfree(cgp);
1835 	UFS_LOCK(ump);
1836 	if (size == fs->fs_bsize) {
1837 		fragno = fragstoblks(fs, cgbno);
1838 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
1839 			if (devvp->v_type != VCHR) {
1840 				UFS_UNLOCK(ump);
1841 				/* devvp is a snapshot */
1842 				brelse(bp);
1843 				return;
1844 			}
1845 			printf("dev = %s, block = %jd, fs = %s\n",
1846 			    devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
1847 			panic("ffs_blkfree: freeing free block");
1848 		}
1849 		ffs_setblock(fs, blksfree, fragno);
1850 		ffs_clusteracct(ump, fs, cgp, fragno, 1);
1851 		cgp->cg_cs.cs_nbfree++;
1852 		fs->fs_cstotal.cs_nbfree++;
1853 		fs->fs_cs(fs, cg).cs_nbfree++;
1854 	} else {
1855 		bbase = cgbno - fragnum(fs, cgbno);
1856 		/*
1857 		 * decrement the counts associated with the old frags
1858 		 */
1859 		blk = blkmap(fs, blksfree, bbase);
1860 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1861 		/*
1862 		 * deallocate the fragment
1863 		 */
1864 		frags = numfrags(fs, size);
1865 		for (i = 0; i < frags; i++) {
1866 			if (isset(blksfree, cgbno + i)) {
1867 				printf("dev = %s, block = %jd, fs = %s\n",
1868 				    devtoname(dev), (intmax_t)(bno + i),
1869 				    fs->fs_fsmnt);
1870 				panic("ffs_blkfree: freeing free frag");
1871 			}
1872 			setbit(blksfree, cgbno + i);
1873 		}
1874 		cgp->cg_cs.cs_nffree += i;
1875 		fs->fs_cstotal.cs_nffree += i;
1876 		fs->fs_cs(fs, cg).cs_nffree += i;
1877 		/*
1878 		 * add back in counts associated with the new frags
1879 		 */
1880 		blk = blkmap(fs, blksfree, bbase);
1881 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1882 		/*
1883 		 * if a complete block has been reassembled, account for it
1884 		 */
1885 		fragno = fragstoblks(fs, bbase);
1886 		if (ffs_isblock(fs, blksfree, fragno)) {
1887 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
1888 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1889 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1890 			ffs_clusteracct(ump, fs, cgp, fragno, 1);
1891 			cgp->cg_cs.cs_nbfree++;
1892 			fs->fs_cstotal.cs_nbfree++;
1893 			fs->fs_cs(fs, cg).cs_nbfree++;
1894 		}
1895 	}
1896 	fs->fs_fmod = 1;
1897 	ACTIVECLEAR(fs, cg);
1898 	UFS_UNLOCK(ump);
1899 	bdwrite(bp);
1900 }
1901 
1902 #ifdef DIAGNOSTIC
1903 /*
1904  * Verify allocation of a block or fragment. Returns true if block or
1905  * fragment is allocated, false if it is free.
1906  */
1907 static int
1908 ffs_checkblk(ip, bno, size)
1909 	struct inode *ip;
1910 	ufs2_daddr_t bno;
1911 	long size;
1912 {
1913 	struct fs *fs;
1914 	struct cg *cgp;
1915 	struct buf *bp;
1916 	ufs1_daddr_t cgbno;
1917 	int i, error, frags, free;
1918 	u_int8_t *blksfree;
1919 
1920 	fs = ip->i_fs;
1921 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
1922 		printf("bsize = %ld, size = %ld, fs = %s\n",
1923 		    (long)fs->fs_bsize, size, fs->fs_fsmnt);
1924 		panic("ffs_checkblk: bad size");
1925 	}
1926 	if ((u_int)bno >= fs->fs_size)
1927 		panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
1928 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
1929 		(int)fs->fs_cgsize, NOCRED, &bp);
1930 	if (error)
1931 		panic("ffs_checkblk: cg bread failed");
1932 	cgp = (struct cg *)bp->b_data;
1933 	if (!cg_chkmagic(cgp))
1934 		panic("ffs_checkblk: cg magic mismatch");
1935 	bp->b_xflags |= BX_BKGRDWRITE;
1936 	blksfree = cg_blksfree(cgp);
1937 	cgbno = dtogd(fs, bno);
1938 	if (size == fs->fs_bsize) {
1939 		free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
1940 	} else {
1941 		frags = numfrags(fs, size);
1942 		for (free = 0, i = 0; i < frags; i++)
1943 			if (isset(blksfree, cgbno + i))
1944 				free++;
1945 		if (free != 0 && free != frags)
1946 			panic("ffs_checkblk: partially free fragment");
1947 	}
1948 	brelse(bp);
1949 	return (!free);
1950 }
1951 #endif /* DIAGNOSTIC */
1952 
1953 /*
1954  * Free an inode.
1955  */
1956 int
1957 ffs_vfree(pvp, ino, mode)
1958 	struct vnode *pvp;
1959 	ino_t ino;
1960 	int mode;
1961 {
1962 	struct inode *ip;
1963 
1964 	if (DOINGSOFTDEP(pvp)) {
1965 		softdep_freefile(pvp, ino, mode);
1966 		return (0);
1967 	}
1968 	ip = VTOI(pvp);
1969 	return (ffs_freefile(ip->i_ump, ip->i_fs, ip->i_devvp, ino, mode));
1970 }
1971 
1972 /*
1973  * Do the actual free operation.
1974  * The specified inode is placed back in the free map.
1975  */
1976 int
1977 ffs_freefile(ump, fs, devvp, ino, mode)
1978 	struct ufsmount *ump;
1979 	struct fs *fs;
1980 	struct vnode *devvp;
1981 	ino_t ino;
1982 	int mode;
1983 {
1984 	struct cg *cgp;
1985 	struct buf *bp;
1986 	ufs2_daddr_t cgbno;
1987 	int error, cg;
1988 	u_int8_t *inosused;
1989 	struct cdev *dev;
1990 
1991 	cg = ino_to_cg(fs, ino);
1992 	if (devvp->v_type != VCHR) {
1993 		/* devvp is a snapshot */
1994 		dev = VTOI(devvp)->i_devvp->v_rdev;
1995 		cgbno = fragstoblks(fs, cgtod(fs, cg));
1996 	} else {
1997 		/* devvp is a normal disk device */
1998 		dev = devvp->v_rdev;
1999 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2000 	}
2001 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
2002 		panic("ffs_freefile: range: dev = %s, ino = %lu, fs = %s",
2003 		    devtoname(dev), (u_long)ino, fs->fs_fsmnt);
2004 	if ((error = bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp))) {
2005 		brelse(bp);
2006 		return (error);
2007 	}
2008 	cgp = (struct cg *)bp->b_data;
2009 	if (!cg_chkmagic(cgp)) {
2010 		brelse(bp);
2011 		return (0);
2012 	}
2013 	bp->b_xflags |= BX_BKGRDWRITE;
2014 	cgp->cg_old_time = cgp->cg_time = time_second;
2015 	inosused = cg_inosused(cgp);
2016 	ino %= fs->fs_ipg;
2017 	if (isclr(inosused, ino)) {
2018 		printf("dev = %s, ino = %lu, fs = %s\n", devtoname(dev),
2019 		    (u_long)ino + cg * fs->fs_ipg, fs->fs_fsmnt);
2020 		if (fs->fs_ronly == 0)
2021 			panic("ffs_freefile: freeing free inode");
2022 	}
2023 	clrbit(inosused, ino);
2024 	if (ino < cgp->cg_irotor)
2025 		cgp->cg_irotor = ino;
2026 	cgp->cg_cs.cs_nifree++;
2027 	UFS_LOCK(ump);
2028 	fs->fs_cstotal.cs_nifree++;
2029 	fs->fs_cs(fs, cg).cs_nifree++;
2030 	if ((mode & IFMT) == IFDIR) {
2031 		cgp->cg_cs.cs_ndir--;
2032 		fs->fs_cstotal.cs_ndir--;
2033 		fs->fs_cs(fs, cg).cs_ndir--;
2034 	}
2035 	fs->fs_fmod = 1;
2036 	ACTIVECLEAR(fs, cg);
2037 	UFS_UNLOCK(ump);
2038 	bdwrite(bp);
2039 	return (0);
2040 }
2041 
2042 /*
2043  * Check to see if a file is free.
2044  */
2045 int
2046 ffs_checkfreefile(fs, devvp, ino)
2047 	struct fs *fs;
2048 	struct vnode *devvp;
2049 	ino_t ino;
2050 {
2051 	struct cg *cgp;
2052 	struct buf *bp;
2053 	ufs2_daddr_t cgbno;
2054 	int ret, cg;
2055 	u_int8_t *inosused;
2056 
2057 	cg = ino_to_cg(fs, ino);
2058 	if (devvp->v_type != VCHR) {
2059 		/* devvp is a snapshot */
2060 		cgbno = fragstoblks(fs, cgtod(fs, cg));
2061 	} else {
2062 		/* devvp is a normal disk device */
2063 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2064 	}
2065 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
2066 		return (1);
2067 	if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2068 		brelse(bp);
2069 		return (1);
2070 	}
2071 	cgp = (struct cg *)bp->b_data;
2072 	if (!cg_chkmagic(cgp)) {
2073 		brelse(bp);
2074 		return (1);
2075 	}
2076 	inosused = cg_inosused(cgp);
2077 	ino %= fs->fs_ipg;
2078 	ret = isclr(inosused, ino);
2079 	brelse(bp);
2080 	return (ret);
2081 }
2082 
2083 /*
2084  * Find a block of the specified size in the specified cylinder group.
2085  *
2086  * It is a panic if a request is made to find a block if none are
2087  * available.
2088  */
2089 static ufs1_daddr_t
2090 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2091 	struct fs *fs;
2092 	struct cg *cgp;
2093 	ufs2_daddr_t bpref;
2094 	int allocsiz;
2095 {
2096 	ufs1_daddr_t bno;
2097 	int start, len, loc, i;
2098 	int blk, field, subfield, pos;
2099 	u_int8_t *blksfree;
2100 
2101 	/*
2102 	 * find the fragment by searching through the free block
2103 	 * map for an appropriate bit pattern
2104 	 */
2105 	if (bpref)
2106 		start = dtogd(fs, bpref) / NBBY;
2107 	else
2108 		start = cgp->cg_frotor / NBBY;
2109 	blksfree = cg_blksfree(cgp);
2110 	len = howmany(fs->fs_fpg, NBBY) - start;
2111 	loc = scanc((u_int)len, (u_char *)&blksfree[start],
2112 		(u_char *)fragtbl[fs->fs_frag],
2113 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2114 	if (loc == 0) {
2115 		len = start + 1;
2116 		start = 0;
2117 		loc = scanc((u_int)len, (u_char *)&blksfree[0],
2118 			(u_char *)fragtbl[fs->fs_frag],
2119 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2120 		if (loc == 0) {
2121 			printf("start = %d, len = %d, fs = %s\n",
2122 			    start, len, fs->fs_fsmnt);
2123 			panic("ffs_alloccg: map corrupted");
2124 			/* NOTREACHED */
2125 		}
2126 	}
2127 	bno = (start + len - loc) * NBBY;
2128 	cgp->cg_frotor = bno;
2129 	/*
2130 	 * found the byte in the map
2131 	 * sift through the bits to find the selected frag
2132 	 */
2133 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2134 		blk = blkmap(fs, blksfree, bno);
2135 		blk <<= 1;
2136 		field = around[allocsiz];
2137 		subfield = inside[allocsiz];
2138 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2139 			if ((blk & field) == subfield)
2140 				return (bno + pos);
2141 			field <<= 1;
2142 			subfield <<= 1;
2143 		}
2144 	}
2145 	printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2146 	panic("ffs_alloccg: block not in map");
2147 	return (-1);
2148 }
2149 
2150 /*
2151  * Update the cluster map because of an allocation or free.
2152  *
2153  * Cnt == 1 means free; cnt == -1 means allocating.
2154  */
2155 void
2156 ffs_clusteracct(ump, fs, cgp, blkno, cnt)
2157 	struct ufsmount *ump;
2158 	struct fs *fs;
2159 	struct cg *cgp;
2160 	ufs1_daddr_t blkno;
2161 	int cnt;
2162 {
2163 	int32_t *sump;
2164 	int32_t *lp;
2165 	u_char *freemapp, *mapp;
2166 	int i, start, end, forw, back, map, bit;
2167 
2168 	mtx_assert(UFS_MTX(ump), MA_OWNED);
2169 
2170 	if (fs->fs_contigsumsize <= 0)
2171 		return;
2172 	freemapp = cg_clustersfree(cgp);
2173 	sump = cg_clustersum(cgp);
2174 	/*
2175 	 * Allocate or clear the actual block.
2176 	 */
2177 	if (cnt > 0)
2178 		setbit(freemapp, blkno);
2179 	else
2180 		clrbit(freemapp, blkno);
2181 	/*
2182 	 * Find the size of the cluster going forward.
2183 	 */
2184 	start = blkno + 1;
2185 	end = start + fs->fs_contigsumsize;
2186 	if (end >= cgp->cg_nclusterblks)
2187 		end = cgp->cg_nclusterblks;
2188 	mapp = &freemapp[start / NBBY];
2189 	map = *mapp++;
2190 	bit = 1 << (start % NBBY);
2191 	for (i = start; i < end; i++) {
2192 		if ((map & bit) == 0)
2193 			break;
2194 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
2195 			bit <<= 1;
2196 		} else {
2197 			map = *mapp++;
2198 			bit = 1;
2199 		}
2200 	}
2201 	forw = i - start;
2202 	/*
2203 	 * Find the size of the cluster going backward.
2204 	 */
2205 	start = blkno - 1;
2206 	end = start - fs->fs_contigsumsize;
2207 	if (end < 0)
2208 		end = -1;
2209 	mapp = &freemapp[start / NBBY];
2210 	map = *mapp--;
2211 	bit = 1 << (start % NBBY);
2212 	for (i = start; i > end; i--) {
2213 		if ((map & bit) == 0)
2214 			break;
2215 		if ((i & (NBBY - 1)) != 0) {
2216 			bit >>= 1;
2217 		} else {
2218 			map = *mapp--;
2219 			bit = 1 << (NBBY - 1);
2220 		}
2221 	}
2222 	back = start - i;
2223 	/*
2224 	 * Account for old cluster and the possibly new forward and
2225 	 * back clusters.
2226 	 */
2227 	i = back + forw + 1;
2228 	if (i > fs->fs_contigsumsize)
2229 		i = fs->fs_contigsumsize;
2230 	sump[i] += cnt;
2231 	if (back > 0)
2232 		sump[back] -= cnt;
2233 	if (forw > 0)
2234 		sump[forw] -= cnt;
2235 	/*
2236 	 * Update cluster summary information.
2237 	 */
2238 	lp = &sump[fs->fs_contigsumsize];
2239 	for (i = fs->fs_contigsumsize; i > 0; i--)
2240 		if (*lp-- > 0)
2241 			break;
2242 	fs->fs_maxcluster[cgp->cg_cgx] = i;
2243 }
2244 
2245 /*
2246  * Fserr prints the name of a filesystem with an error diagnostic.
2247  *
2248  * The form of the error message is:
2249  *	fs: error message
2250  */
2251 static void
2252 ffs_fserr(fs, inum, cp)
2253 	struct fs *fs;
2254 	ino_t inum;
2255 	char *cp;
2256 {
2257 	struct thread *td = curthread;	/* XXX */
2258 	struct proc *p = td->td_proc;
2259 
2260 	log(LOG_ERR, "pid %d (%s), uid %d inumber %d on %s: %s\n",
2261 	    p->p_pid, p->p_comm, td->td_ucred->cr_uid, inum, fs->fs_fsmnt, cp);
2262 }
2263 
2264 /*
2265  * This function provides the capability for the fsck program to
2266  * update an active filesystem. Six operations are provided:
2267  *
2268  * adjrefcnt(inode, amt) - adjusts the reference count on the
2269  *	specified inode by the specified amount. Under normal
2270  *	operation the count should always go down. Decrementing
2271  *	the count to zero will cause the inode to be freed.
2272  * adjblkcnt(inode, amt) - adjust the number of blocks used to
2273  *	by the specifed amount.
2274  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2275  *	are marked as free. Inodes should never have to be marked
2276  *	as in use.
2277  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2278  *	are marked as free. Inodes should never have to be marked
2279  *	as in use.
2280  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2281  *	are marked as free. Blocks should never have to be marked
2282  *	as in use.
2283  * setflags(flags, set/clear) - the fs_flags field has the specified
2284  *	flags set (second parameter +1) or cleared (second parameter -1).
2285  */
2286 
2287 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2288 
2289 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2290 	0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2291 
2292 SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2293 	sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2294 
2295 SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2296 	sysctl_ffs_fsck, "Free Range of Directory Inodes");
2297 
2298 SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2299 	sysctl_ffs_fsck, "Free Range of File Inodes");
2300 
2301 SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2302 	sysctl_ffs_fsck, "Free Range of Blocks");
2303 
2304 SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2305 	sysctl_ffs_fsck, "Change Filesystem Flags");
2306 
2307 #ifdef DEBUG
2308 static int fsckcmds = 0;
2309 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2310 #endif /* DEBUG */
2311 
2312 static int
2313 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2314 {
2315 	struct fsck_cmd cmd;
2316 	struct ufsmount *ump;
2317 	struct vnode *vp;
2318 	struct inode *ip;
2319 	struct mount *mp;
2320 	struct fs *fs;
2321 	ufs2_daddr_t blkno;
2322 	long blkcnt, blksize;
2323 	struct file *fp;
2324 	int filetype, error;
2325 
2326 	if (req->newlen > sizeof cmd)
2327 		return (EBADRPC);
2328 	if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2329 		return (error);
2330 	if (cmd.version != FFS_CMD_VERSION)
2331 		return (ERPCMISMATCH);
2332 	if ((error = getvnode(curproc->p_fd, cmd.handle, &fp)) != 0)
2333 		return (error);
2334 	vn_start_write(fp->f_data, &mp, V_WAIT);
2335 	if (mp == 0 || strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2336 		vn_finished_write(mp);
2337 		fdrop(fp, curthread);
2338 		return (EINVAL);
2339 	}
2340 	if (mp->mnt_flag & MNT_RDONLY) {
2341 		vn_finished_write(mp);
2342 		fdrop(fp, curthread);
2343 		return (EROFS);
2344 	}
2345 	ump = VFSTOUFS(mp);
2346 	fs = ump->um_fs;
2347 	filetype = IFREG;
2348 
2349 	switch (oidp->oid_number) {
2350 
2351 	case FFS_SET_FLAGS:
2352 #ifdef DEBUG
2353 		if (fsckcmds)
2354 			printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2355 			    cmd.size > 0 ? "set" : "clear");
2356 #endif /* DEBUG */
2357 		if (cmd.size > 0)
2358 			fs->fs_flags |= (long)cmd.value;
2359 		else
2360 			fs->fs_flags &= ~(long)cmd.value;
2361 		break;
2362 
2363 	case FFS_ADJ_REFCNT:
2364 #ifdef DEBUG
2365 		if (fsckcmds) {
2366 			printf("%s: adjust inode %jd count by %jd\n",
2367 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2368 			    (intmax_t)cmd.size);
2369 		}
2370 #endif /* DEBUG */
2371 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2372 			break;
2373 		ip = VTOI(vp);
2374 		ip->i_nlink += cmd.size;
2375 		DIP_SET(ip, i_nlink, ip->i_nlink);
2376 		ip->i_effnlink += cmd.size;
2377 		ip->i_flag |= IN_CHANGE;
2378 		if (DOINGSOFTDEP(vp))
2379 			softdep_change_linkcnt(ip);
2380 		vput(vp);
2381 		break;
2382 
2383 	case FFS_ADJ_BLKCNT:
2384 #ifdef DEBUG
2385 		if (fsckcmds) {
2386 			printf("%s: adjust inode %jd block count by %jd\n",
2387 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2388 			    (intmax_t)cmd.size);
2389 		}
2390 #endif /* DEBUG */
2391 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2392 			break;
2393 		ip = VTOI(vp);
2394 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2395 		ip->i_flag |= IN_CHANGE;
2396 		vput(vp);
2397 		break;
2398 
2399 	case FFS_DIR_FREE:
2400 		filetype = IFDIR;
2401 		/* fall through */
2402 
2403 	case FFS_FILE_FREE:
2404 #ifdef DEBUG
2405 		if (fsckcmds) {
2406 			if (cmd.size == 1)
2407 				printf("%s: free %s inode %d\n",
2408 				    mp->mnt_stat.f_mntonname,
2409 				    filetype == IFDIR ? "directory" : "file",
2410 				    (ino_t)cmd.value);
2411 			else
2412 				printf("%s: free %s inodes %d-%d\n",
2413 				    mp->mnt_stat.f_mntonname,
2414 				    filetype == IFDIR ? "directory" : "file",
2415 				    (ino_t)cmd.value,
2416 				    (ino_t)(cmd.value + cmd.size - 1));
2417 		}
2418 #endif /* DEBUG */
2419 		while (cmd.size > 0) {
2420 			if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2421 			    cmd.value, filetype)))
2422 				break;
2423 			cmd.size -= 1;
2424 			cmd.value += 1;
2425 		}
2426 		break;
2427 
2428 	case FFS_BLK_FREE:
2429 #ifdef DEBUG
2430 		if (fsckcmds) {
2431 			if (cmd.size == 1)
2432 				printf("%s: free block %jd\n",
2433 				    mp->mnt_stat.f_mntonname,
2434 				    (intmax_t)cmd.value);
2435 			else
2436 				printf("%s: free blocks %jd-%jd\n",
2437 				    mp->mnt_stat.f_mntonname,
2438 				    (intmax_t)cmd.value,
2439 				    (intmax_t)cmd.value + cmd.size - 1);
2440 		}
2441 #endif /* DEBUG */
2442 		blkno = cmd.value;
2443 		blkcnt = cmd.size;
2444 		blksize = fs->fs_frag - (blkno % fs->fs_frag);
2445 		while (blkcnt > 0) {
2446 			if (blksize > blkcnt)
2447 				blksize = blkcnt;
2448 			ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2449 			    blksize * fs->fs_fsize, ROOTINO);
2450 			blkno += blksize;
2451 			blkcnt -= blksize;
2452 			blksize = fs->fs_frag;
2453 		}
2454 		break;
2455 
2456 	default:
2457 #ifdef DEBUG
2458 		if (fsckcmds) {
2459 			printf("Invalid request %d from fsck\n",
2460 			    oidp->oid_number);
2461 		}
2462 #endif /* DEBUG */
2463 		error = EINVAL;
2464 		break;
2465 
2466 	}
2467 	fdrop(fp, curthread);
2468 	vn_finished_write(mp);
2469 	return (error);
2470 }
2471