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