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