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