xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
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/capsicum.h>
69 #include <sys/systm.h>
70 #include <sys/bio.h>
71 #include <sys/buf.h>
72 #include <sys/conf.h>
73 #include <sys/fcntl.h>
74 #include <sys/file.h>
75 #include <sys/filedesc.h>
76 #include <sys/priv.h>
77 #include <sys/proc.h>
78 #include <sys/vnode.h>
79 #include <sys/mount.h>
80 #include <sys/kernel.h>
81 #include <sys/syscallsubr.h>
82 #include <sys/sysctl.h>
83 #include <sys/syslog.h>
84 #include <sys/taskqueue.h>
85 
86 #include <security/audit/audit.h>
87 
88 #include <geom/geom.h>
89 
90 #include <ufs/ufs/dir.h>
91 #include <ufs/ufs/extattr.h>
92 #include <ufs/ufs/quota.h>
93 #include <ufs/ufs/inode.h>
94 #include <ufs/ufs/ufs_extern.h>
95 #include <ufs/ufs/ufsmount.h>
96 
97 #include <ufs/ffs/fs.h>
98 #include <ufs/ffs/ffs_extern.h>
99 #include <ufs/ffs/softdep.h>
100 
101 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
102 				  int size, int rsize);
103 
104 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
105 static ufs2_daddr_t
106 	      ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
107 static void	ffs_blkfree_cg(struct ufsmount *, struct fs *,
108 		    struct vnode *, ufs2_daddr_t, long, ino_t,
109 		    struct workhead *);
110 static void	ffs_blkfree_trim_completed(struct bio *);
111 static void	ffs_blkfree_trim_task(void *ctx, int pending __unused);
112 #ifdef INVARIANTS
113 static int	ffs_checkblk(struct inode *, ufs2_daddr_t, long);
114 #endif
115 static ufs2_daddr_t ffs_clusteralloc(struct inode *, u_int, ufs2_daddr_t, int,
116 		    int);
117 static ino_t	ffs_dirpref(struct inode *);
118 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
119 		    int, int);
120 static ufs2_daddr_t	ffs_hashalloc
121 		(struct inode *, u_int, ufs2_daddr_t, int, int, allocfcn_t *);
122 static ufs2_daddr_t ffs_nodealloccg(struct inode *, u_int, ufs2_daddr_t, int,
123 		    int);
124 static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
125 static int	ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
126 static int	ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
127 
128 /*
129  * Allocate a block in the filesystem.
130  *
131  * The size of the requested block is given, which must be some
132  * multiple of fs_fsize and <= fs_bsize.
133  * A preference may be optionally specified. If a preference is given
134  * the following hierarchy is used to allocate a block:
135  *   1) allocate the requested block.
136  *   2) allocate a rotationally optimal block in the same cylinder.
137  *   3) allocate a block in the same cylinder group.
138  *   4) quadradically rehash into other cylinder groups, until an
139  *      available block is located.
140  * If no block preference is given the following hierarchy is used
141  * to allocate a block:
142  *   1) allocate a block in the cylinder group that contains the
143  *      inode for the file.
144  *   2) quadradically rehash into other cylinder groups, until an
145  *      available block is located.
146  */
147 int
148 ffs_alloc(ip, lbn, bpref, size, flags, cred, bnp)
149 	struct inode *ip;
150 	ufs2_daddr_t lbn, bpref;
151 	int size, flags;
152 	struct ucred *cred;
153 	ufs2_daddr_t *bnp;
154 {
155 	struct fs *fs;
156 	struct ufsmount *ump;
157 	ufs2_daddr_t bno;
158 	u_int cg, reclaimed;
159 	static struct timeval lastfail;
160 	static int curfail;
161 	int64_t delta;
162 #ifdef QUOTA
163 	int error;
164 #endif
165 
166 	*bnp = 0;
167 	fs = ip->i_fs;
168 	ump = ip->i_ump;
169 	mtx_assert(UFS_MTX(ump), MA_OWNED);
170 #ifdef INVARIANTS
171 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
172 		printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
173 		    devtoname(ip->i_dev), (long)fs->fs_bsize, size,
174 		    fs->fs_fsmnt);
175 		panic("ffs_alloc: bad size");
176 	}
177 	if (cred == NOCRED)
178 		panic("ffs_alloc: missing credential");
179 #endif /* INVARIANTS */
180 	reclaimed = 0;
181 retry:
182 #ifdef QUOTA
183 	UFS_UNLOCK(ump);
184 	error = chkdq(ip, btodb(size), cred, 0);
185 	if (error)
186 		return (error);
187 	UFS_LOCK(ump);
188 #endif
189 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
190 		goto nospace;
191 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
192 	    freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
193 		goto nospace;
194 	if (bpref >= fs->fs_size)
195 		bpref = 0;
196 	if (bpref == 0)
197 		cg = ino_to_cg(fs, ip->i_number);
198 	else
199 		cg = dtog(fs, bpref);
200 	bno = ffs_hashalloc(ip, cg, bpref, size, size, ffs_alloccg);
201 	if (bno > 0) {
202 		delta = btodb(size);
203 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
204 		if (flags & IO_EXT)
205 			ip->i_flag |= IN_CHANGE;
206 		else
207 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
208 		*bnp = bno;
209 		return (0);
210 	}
211 nospace:
212 #ifdef QUOTA
213 	UFS_UNLOCK(ump);
214 	/*
215 	 * Restore user's disk quota because allocation failed.
216 	 */
217 	(void) chkdq(ip, -btodb(size), cred, FORCE);
218 	UFS_LOCK(ump);
219 #endif
220 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
221 		reclaimed = 1;
222 		softdep_request_cleanup(fs, ITOV(ip), cred, FLUSH_BLOCKS_WAIT);
223 		goto retry;
224 	}
225 	UFS_UNLOCK(ump);
226 	if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
227 		ffs_fserr(fs, ip->i_number, "filesystem full");
228 		uprintf("\n%s: write failed, filesystem is full\n",
229 		    fs->fs_fsmnt);
230 	}
231 	return (ENOSPC);
232 }
233 
234 /*
235  * Reallocate a fragment to a bigger size
236  *
237  * The number and size of the old block is given, and a preference
238  * and new size is also specified. The allocator attempts to extend
239  * the original block. Failing that, the regular block allocator is
240  * invoked to get an appropriate block.
241  */
242 int
243 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
244 	struct inode *ip;
245 	ufs2_daddr_t lbprev;
246 	ufs2_daddr_t bprev;
247 	ufs2_daddr_t bpref;
248 	int osize, nsize, flags;
249 	struct ucred *cred;
250 	struct buf **bpp;
251 {
252 	struct vnode *vp;
253 	struct fs *fs;
254 	struct buf *bp;
255 	struct ufsmount *ump;
256 	u_int cg, request, reclaimed;
257 	int error, gbflags;
258 	ufs2_daddr_t bno;
259 	static struct timeval lastfail;
260 	static int curfail;
261 	int64_t delta;
262 
263 	*bpp = 0;
264 	vp = ITOV(ip);
265 	fs = ip->i_fs;
266 	bp = NULL;
267 	ump = ip->i_ump;
268 	gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
269 
270 	mtx_assert(UFS_MTX(ump), MA_OWNED);
271 #ifdef INVARIANTS
272 	if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
273 		panic("ffs_realloccg: allocation on suspended filesystem");
274 	if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
275 	    (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
276 		printf(
277 		"dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
278 		    devtoname(ip->i_dev), (long)fs->fs_bsize, osize,
279 		    nsize, fs->fs_fsmnt);
280 		panic("ffs_realloccg: bad size");
281 	}
282 	if (cred == NOCRED)
283 		panic("ffs_realloccg: missing credential");
284 #endif /* INVARIANTS */
285 	reclaimed = 0;
286 retry:
287 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
288 	    freespace(fs, fs->fs_minfree) -  numfrags(fs, nsize - osize) < 0) {
289 		goto nospace;
290 	}
291 	if (bprev == 0) {
292 		printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
293 		    devtoname(ip->i_dev), (long)fs->fs_bsize, (intmax_t)bprev,
294 		    fs->fs_fsmnt);
295 		panic("ffs_realloccg: bad bprev");
296 	}
297 	UFS_UNLOCK(ump);
298 	/*
299 	 * Allocate the extra space in the buffer.
300 	 */
301 	error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
302 	if (error) {
303 		brelse(bp);
304 		return (error);
305 	}
306 
307 	if (bp->b_blkno == bp->b_lblkno) {
308 		if (lbprev >= NDADDR)
309 			panic("ffs_realloccg: lbprev out of range");
310 		bp->b_blkno = fsbtodb(fs, bprev);
311 	}
312 
313 #ifdef QUOTA
314 	error = chkdq(ip, btodb(nsize - osize), cred, 0);
315 	if (error) {
316 		brelse(bp);
317 		return (error);
318 	}
319 #endif
320 	/*
321 	 * Check for extension in the existing location.
322 	 */
323 	cg = dtog(fs, bprev);
324 	UFS_LOCK(ump);
325 	bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
326 	if (bno) {
327 		if (bp->b_blkno != fsbtodb(fs, bno))
328 			panic("ffs_realloccg: bad blockno");
329 		delta = btodb(nsize - osize);
330 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
331 		if (flags & IO_EXT)
332 			ip->i_flag |= IN_CHANGE;
333 		else
334 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
335 		allocbuf(bp, nsize);
336 		bp->b_flags |= B_DONE;
337 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
338 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
339 			vfs_bio_set_valid(bp, osize, nsize - osize);
340 		*bpp = bp;
341 		return (0);
342 	}
343 	/*
344 	 * Allocate a new disk location.
345 	 */
346 	if (bpref >= fs->fs_size)
347 		bpref = 0;
348 	switch ((int)fs->fs_optim) {
349 	case FS_OPTSPACE:
350 		/*
351 		 * Allocate an exact sized fragment. Although this makes
352 		 * best use of space, we will waste time relocating it if
353 		 * the file continues to grow. If the fragmentation is
354 		 * less than half of the minimum free reserve, we choose
355 		 * to begin optimizing for time.
356 		 */
357 		request = nsize;
358 		if (fs->fs_minfree <= 5 ||
359 		    fs->fs_cstotal.cs_nffree >
360 		    (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
361 			break;
362 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
363 			fs->fs_fsmnt);
364 		fs->fs_optim = FS_OPTTIME;
365 		break;
366 	case FS_OPTTIME:
367 		/*
368 		 * At this point we have discovered a file that is trying to
369 		 * grow a small fragment to a larger fragment. To save time,
370 		 * we allocate a full sized block, then free the unused portion.
371 		 * If the file continues to grow, the `ffs_fragextend' call
372 		 * above will be able to grow it in place without further
373 		 * copying. If aberrant programs cause disk fragmentation to
374 		 * grow within 2% of the free reserve, we choose to begin
375 		 * optimizing for space.
376 		 */
377 		request = fs->fs_bsize;
378 		if (fs->fs_cstotal.cs_nffree <
379 		    (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
380 			break;
381 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
382 			fs->fs_fsmnt);
383 		fs->fs_optim = FS_OPTSPACE;
384 		break;
385 	default:
386 		printf("dev = %s, optim = %ld, fs = %s\n",
387 		    devtoname(ip->i_dev), (long)fs->fs_optim, fs->fs_fsmnt);
388 		panic("ffs_realloccg: bad optim");
389 		/* NOTREACHED */
390 	}
391 	bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
392 	if (bno > 0) {
393 		bp->b_blkno = fsbtodb(fs, bno);
394 		if (!DOINGSOFTDEP(vp))
395 			ffs_blkfree(ump, fs, ip->i_devvp, bprev, (long)osize,
396 			    ip->i_number, vp->v_type, NULL);
397 		delta = btodb(nsize - osize);
398 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
399 		if (flags & IO_EXT)
400 			ip->i_flag |= IN_CHANGE;
401 		else
402 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
403 		allocbuf(bp, nsize);
404 		bp->b_flags |= B_DONE;
405 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
406 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
407 			vfs_bio_set_valid(bp, osize, nsize - osize);
408 		*bpp = bp;
409 		return (0);
410 	}
411 #ifdef QUOTA
412 	UFS_UNLOCK(ump);
413 	/*
414 	 * Restore user's disk quota because allocation failed.
415 	 */
416 	(void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
417 	UFS_LOCK(ump);
418 #endif
419 nospace:
420 	/*
421 	 * no space available
422 	 */
423 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
424 		reclaimed = 1;
425 		UFS_UNLOCK(ump);
426 		if (bp) {
427 			brelse(bp);
428 			bp = NULL;
429 		}
430 		UFS_LOCK(ump);
431 		softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
432 		goto retry;
433 	}
434 	UFS_UNLOCK(ump);
435 	if (bp)
436 		brelse(bp);
437 	if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
438 		ffs_fserr(fs, ip->i_number, "filesystem full");
439 		uprintf("\n%s: write failed, filesystem is full\n",
440 		    fs->fs_fsmnt);
441 	}
442 	return (ENOSPC);
443 }
444 
445 /*
446  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
447  *
448  * The vnode and an array of buffer pointers for a range of sequential
449  * logical blocks to be made contiguous is given. The allocator attempts
450  * to find a range of sequential blocks starting as close as possible
451  * from the end of the allocation for the logical block immediately
452  * preceding the current range. If successful, the physical block numbers
453  * in the buffer pointers and in the inode are changed to reflect the new
454  * allocation. If unsuccessful, the allocation is left unchanged. The
455  * success in doing the reallocation is returned. Note that the error
456  * return is not reflected back to the user. Rather the previous block
457  * allocation will be used.
458  */
459 
460 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
461 
462 static int doasyncfree = 1;
463 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0, "");
464 
465 static int doreallocblks = 1;
466 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
467 
468 #ifdef DEBUG
469 static volatile int prtrealloc = 0;
470 #endif
471 
472 int
473 ffs_reallocblks(ap)
474 	struct vop_reallocblks_args /* {
475 		struct vnode *a_vp;
476 		struct cluster_save *a_buflist;
477 	} */ *ap;
478 {
479 
480 	if (doreallocblks == 0)
481 		return (ENOSPC);
482 	/*
483 	 * We can't wait in softdep prealloc as it may fsync and recurse
484 	 * here.  Instead we simply fail to reallocate blocks if this
485 	 * rare condition arises.
486 	 */
487 	if (DOINGSOFTDEP(ap->a_vp))
488 		if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
489 			return (ENOSPC);
490 	if (VTOI(ap->a_vp)->i_ump->um_fstype == UFS1)
491 		return (ffs_reallocblks_ufs1(ap));
492 	return (ffs_reallocblks_ufs2(ap));
493 }
494 
495 static int
496 ffs_reallocblks_ufs1(ap)
497 	struct vop_reallocblks_args /* {
498 		struct vnode *a_vp;
499 		struct cluster_save *a_buflist;
500 	} */ *ap;
501 {
502 	struct fs *fs;
503 	struct inode *ip;
504 	struct vnode *vp;
505 	struct buf *sbp, *ebp;
506 	ufs1_daddr_t *bap, *sbap, *ebap = 0;
507 	struct cluster_save *buflist;
508 	struct ufsmount *ump;
509 	ufs_lbn_t start_lbn, end_lbn;
510 	ufs1_daddr_t soff, newblk, blkno;
511 	ufs2_daddr_t pref;
512 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
513 	int i, len, start_lvl, end_lvl, ssize;
514 
515 	vp = ap->a_vp;
516 	ip = VTOI(vp);
517 	fs = ip->i_fs;
518 	ump = ip->i_ump;
519 	/*
520 	 * If we are not tracking block clusters or if we have less than 4%
521 	 * free blocks left, then do not attempt to cluster. Running with
522 	 * less than 5% free block reserve is not recommended and those that
523 	 * choose to do so do not expect to have good file layout.
524 	 */
525 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
526 		return (ENOSPC);
527 	buflist = ap->a_buflist;
528 	len = buflist->bs_nchildren;
529 	start_lbn = buflist->bs_children[0]->b_lblkno;
530 	end_lbn = start_lbn + len - 1;
531 #ifdef INVARIANTS
532 	for (i = 0; i < len; i++)
533 		if (!ffs_checkblk(ip,
534 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
535 			panic("ffs_reallocblks: unallocated block 1");
536 	for (i = 1; i < len; i++)
537 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
538 			panic("ffs_reallocblks: non-logical cluster");
539 	blkno = buflist->bs_children[0]->b_blkno;
540 	ssize = fsbtodb(fs, fs->fs_frag);
541 	for (i = 1; i < len - 1; i++)
542 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
543 			panic("ffs_reallocblks: non-physical cluster %d", i);
544 #endif
545 	/*
546 	 * If the cluster crosses the boundary for the first indirect
547 	 * block, leave space for the indirect block. Indirect blocks
548 	 * are initially laid out in a position after the last direct
549 	 * block. Block reallocation would usually destroy locality by
550 	 * moving the indirect block out of the way to make room for
551 	 * data blocks if we didn't compensate here. We should also do
552 	 * this for other indirect block boundaries, but it is only
553 	 * important for the first one.
554 	 */
555 	if (start_lbn < NDADDR && end_lbn >= NDADDR)
556 		return (ENOSPC);
557 	/*
558 	 * If the latest allocation is in a new cylinder group, assume that
559 	 * the filesystem has decided to move and do not force it back to
560 	 * the previous cylinder group.
561 	 */
562 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
563 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
564 		return (ENOSPC);
565 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
566 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
567 		return (ENOSPC);
568 	/*
569 	 * Get the starting offset and block map for the first block.
570 	 */
571 	if (start_lvl == 0) {
572 		sbap = &ip->i_din1->di_db[0];
573 		soff = start_lbn;
574 	} else {
575 		idp = &start_ap[start_lvl - 1];
576 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
577 			brelse(sbp);
578 			return (ENOSPC);
579 		}
580 		sbap = (ufs1_daddr_t *)sbp->b_data;
581 		soff = idp->in_off;
582 	}
583 	/*
584 	 * If the block range spans two block maps, get the second map.
585 	 */
586 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
587 		ssize = len;
588 	} else {
589 #ifdef INVARIANTS
590 		if (start_lvl > 0 &&
591 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
592 			panic("ffs_reallocblk: start == end");
593 #endif
594 		ssize = len - (idp->in_off + 1);
595 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
596 			goto fail;
597 		ebap = (ufs1_daddr_t *)ebp->b_data;
598 	}
599 	/*
600 	 * Find the preferred location for the cluster.
601 	 */
602 	UFS_LOCK(ump);
603 	pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
604 	/*
605 	 * Search the block map looking for an allocation of the desired size.
606 	 */
607 	if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
608 	    len, len, ffs_clusteralloc)) == 0) {
609 		UFS_UNLOCK(ump);
610 		goto fail;
611 	}
612 	/*
613 	 * We have found a new contiguous block.
614 	 *
615 	 * First we have to replace the old block pointers with the new
616 	 * block pointers in the inode and indirect blocks associated
617 	 * with the file.
618 	 */
619 #ifdef DEBUG
620 	if (prtrealloc)
621 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
622 		    (uintmax_t)ip->i_number,
623 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
624 #endif
625 	blkno = newblk;
626 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
627 		if (i == ssize) {
628 			bap = ebap;
629 			soff = -i;
630 		}
631 #ifdef INVARIANTS
632 		if (!ffs_checkblk(ip,
633 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
634 			panic("ffs_reallocblks: unallocated block 2");
635 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
636 			panic("ffs_reallocblks: alloc mismatch");
637 #endif
638 #ifdef DEBUG
639 		if (prtrealloc)
640 			printf(" %d,", *bap);
641 #endif
642 		if (DOINGSOFTDEP(vp)) {
643 			if (sbap == &ip->i_din1->di_db[0] && i < ssize)
644 				softdep_setup_allocdirect(ip, start_lbn + i,
645 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
646 				    buflist->bs_children[i]);
647 			else
648 				softdep_setup_allocindir_page(ip, start_lbn + i,
649 				    i < ssize ? sbp : ebp, soff + i, blkno,
650 				    *bap, buflist->bs_children[i]);
651 		}
652 		*bap++ = blkno;
653 	}
654 	/*
655 	 * Next we must write out the modified inode and indirect blocks.
656 	 * For strict correctness, the writes should be synchronous since
657 	 * the old block values may have been written to disk. In practise
658 	 * they are almost never written, but if we are concerned about
659 	 * strict correctness, the `doasyncfree' flag should be set to zero.
660 	 *
661 	 * The test on `doasyncfree' should be changed to test a flag
662 	 * that shows whether the associated buffers and inodes have
663 	 * been written. The flag should be set when the cluster is
664 	 * started and cleared whenever the buffer or inode is flushed.
665 	 * We can then check below to see if it is set, and do the
666 	 * synchronous write only when it has been cleared.
667 	 */
668 	if (sbap != &ip->i_din1->di_db[0]) {
669 		if (doasyncfree)
670 			bdwrite(sbp);
671 		else
672 			bwrite(sbp);
673 	} else {
674 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
675 		if (!doasyncfree)
676 			ffs_update(vp, 1);
677 	}
678 	if (ssize < len) {
679 		if (doasyncfree)
680 			bdwrite(ebp);
681 		else
682 			bwrite(ebp);
683 	}
684 	/*
685 	 * Last, free the old blocks and assign the new blocks to the buffers.
686 	 */
687 #ifdef DEBUG
688 	if (prtrealloc)
689 		printf("\n\tnew:");
690 #endif
691 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
692 		if (!DOINGSOFTDEP(vp))
693 			ffs_blkfree(ump, fs, ip->i_devvp,
694 			    dbtofsb(fs, buflist->bs_children[i]->b_blkno),
695 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL);
696 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
697 #ifdef INVARIANTS
698 		if (!ffs_checkblk(ip,
699 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
700 			panic("ffs_reallocblks: unallocated block 3");
701 #endif
702 #ifdef DEBUG
703 		if (prtrealloc)
704 			printf(" %d,", blkno);
705 #endif
706 	}
707 #ifdef DEBUG
708 	if (prtrealloc) {
709 		prtrealloc--;
710 		printf("\n");
711 	}
712 #endif
713 	return (0);
714 
715 fail:
716 	if (ssize < len)
717 		brelse(ebp);
718 	if (sbap != &ip->i_din1->di_db[0])
719 		brelse(sbp);
720 	return (ENOSPC);
721 }
722 
723 static int
724 ffs_reallocblks_ufs2(ap)
725 	struct vop_reallocblks_args /* {
726 		struct vnode *a_vp;
727 		struct cluster_save *a_buflist;
728 	} */ *ap;
729 {
730 	struct fs *fs;
731 	struct inode *ip;
732 	struct vnode *vp;
733 	struct buf *sbp, *ebp;
734 	ufs2_daddr_t *bap, *sbap, *ebap = 0;
735 	struct cluster_save *buflist;
736 	struct ufsmount *ump;
737 	ufs_lbn_t start_lbn, end_lbn;
738 	ufs2_daddr_t soff, newblk, blkno, pref;
739 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
740 	int i, len, start_lvl, end_lvl, ssize;
741 
742 	vp = ap->a_vp;
743 	ip = VTOI(vp);
744 	fs = ip->i_fs;
745 	ump = ip->i_ump;
746 	/*
747 	 * If we are not tracking block clusters or if we have less than 4%
748 	 * free blocks left, then do not attempt to cluster. Running with
749 	 * less than 5% free block reserve is not recommended and those that
750 	 * choose to do so do not expect to have good file layout.
751 	 */
752 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
753 		return (ENOSPC);
754 	buflist = ap->a_buflist;
755 	len = buflist->bs_nchildren;
756 	start_lbn = buflist->bs_children[0]->b_lblkno;
757 	end_lbn = start_lbn + len - 1;
758 #ifdef INVARIANTS
759 	for (i = 0; i < len; i++)
760 		if (!ffs_checkblk(ip,
761 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
762 			panic("ffs_reallocblks: unallocated block 1");
763 	for (i = 1; i < len; i++)
764 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
765 			panic("ffs_reallocblks: non-logical cluster");
766 	blkno = buflist->bs_children[0]->b_blkno;
767 	ssize = fsbtodb(fs, fs->fs_frag);
768 	for (i = 1; i < len - 1; i++)
769 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
770 			panic("ffs_reallocblks: non-physical cluster %d", i);
771 #endif
772 	/*
773 	 * If the cluster crosses the boundary for the first indirect
774 	 * block, do not move anything in it. Indirect blocks are
775 	 * usually initially laid out in a position between the data
776 	 * blocks. Block reallocation would usually destroy locality by
777 	 * moving the indirect block out of the way to make room for
778 	 * data blocks if we didn't compensate here. We should also do
779 	 * this for other indirect block boundaries, but it is only
780 	 * important for the first one.
781 	 */
782 	if (start_lbn < NDADDR && end_lbn >= NDADDR)
783 		return (ENOSPC);
784 	/*
785 	 * If the latest allocation is in a new cylinder group, assume that
786 	 * the filesystem has decided to move and do not force it back to
787 	 * the previous cylinder group.
788 	 */
789 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
790 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
791 		return (ENOSPC);
792 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
793 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
794 		return (ENOSPC);
795 	/*
796 	 * Get the starting offset and block map for the first block.
797 	 */
798 	if (start_lvl == 0) {
799 		sbap = &ip->i_din2->di_db[0];
800 		soff = start_lbn;
801 	} else {
802 		idp = &start_ap[start_lvl - 1];
803 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
804 			brelse(sbp);
805 			return (ENOSPC);
806 		}
807 		sbap = (ufs2_daddr_t *)sbp->b_data;
808 		soff = idp->in_off;
809 	}
810 	/*
811 	 * If the block range spans two block maps, get the second map.
812 	 */
813 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
814 		ssize = len;
815 	} else {
816 #ifdef INVARIANTS
817 		if (start_lvl > 0 &&
818 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
819 			panic("ffs_reallocblk: start == end");
820 #endif
821 		ssize = len - (idp->in_off + 1);
822 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
823 			goto fail;
824 		ebap = (ufs2_daddr_t *)ebp->b_data;
825 	}
826 	/*
827 	 * Find the preferred location for the cluster.
828 	 */
829 	UFS_LOCK(ump);
830 	pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
831 	/*
832 	 * Search the block map looking for an allocation of the desired size.
833 	 */
834 	if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
835 	    len, len, ffs_clusteralloc)) == 0) {
836 		UFS_UNLOCK(ump);
837 		goto fail;
838 	}
839 	/*
840 	 * We have found a new contiguous block.
841 	 *
842 	 * First we have to replace the old block pointers with the new
843 	 * block pointers in the inode and indirect blocks associated
844 	 * with the file.
845 	 */
846 #ifdef DEBUG
847 	if (prtrealloc)
848 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
849 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
850 #endif
851 	blkno = newblk;
852 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
853 		if (i == ssize) {
854 			bap = ebap;
855 			soff = -i;
856 		}
857 #ifdef INVARIANTS
858 		if (!ffs_checkblk(ip,
859 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
860 			panic("ffs_reallocblks: unallocated block 2");
861 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
862 			panic("ffs_reallocblks: alloc mismatch");
863 #endif
864 #ifdef DEBUG
865 		if (prtrealloc)
866 			printf(" %jd,", (intmax_t)*bap);
867 #endif
868 		if (DOINGSOFTDEP(vp)) {
869 			if (sbap == &ip->i_din2->di_db[0] && i < ssize)
870 				softdep_setup_allocdirect(ip, start_lbn + i,
871 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
872 				    buflist->bs_children[i]);
873 			else
874 				softdep_setup_allocindir_page(ip, start_lbn + i,
875 				    i < ssize ? sbp : ebp, soff + i, blkno,
876 				    *bap, buflist->bs_children[i]);
877 		}
878 		*bap++ = blkno;
879 	}
880 	/*
881 	 * Next we must write out the modified inode and indirect blocks.
882 	 * For strict correctness, the writes should be synchronous since
883 	 * the old block values may have been written to disk. In practise
884 	 * they are almost never written, but if we are concerned about
885 	 * strict correctness, the `doasyncfree' flag should be set to zero.
886 	 *
887 	 * The test on `doasyncfree' should be changed to test a flag
888 	 * that shows whether the associated buffers and inodes have
889 	 * been written. The flag should be set when the cluster is
890 	 * started and cleared whenever the buffer or inode is flushed.
891 	 * We can then check below to see if it is set, and do the
892 	 * synchronous write only when it has been cleared.
893 	 */
894 	if (sbap != &ip->i_din2->di_db[0]) {
895 		if (doasyncfree)
896 			bdwrite(sbp);
897 		else
898 			bwrite(sbp);
899 	} else {
900 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
901 		if (!doasyncfree)
902 			ffs_update(vp, 1);
903 	}
904 	if (ssize < len) {
905 		if (doasyncfree)
906 			bdwrite(ebp);
907 		else
908 			bwrite(ebp);
909 	}
910 	/*
911 	 * Last, free the old blocks and assign the new blocks to the buffers.
912 	 */
913 #ifdef DEBUG
914 	if (prtrealloc)
915 		printf("\n\tnew:");
916 #endif
917 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
918 		if (!DOINGSOFTDEP(vp))
919 			ffs_blkfree(ump, fs, ip->i_devvp,
920 			    dbtofsb(fs, buflist->bs_children[i]->b_blkno),
921 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL);
922 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
923 #ifdef INVARIANTS
924 		if (!ffs_checkblk(ip,
925 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
926 			panic("ffs_reallocblks: unallocated block 3");
927 #endif
928 #ifdef DEBUG
929 		if (prtrealloc)
930 			printf(" %jd,", (intmax_t)blkno);
931 #endif
932 	}
933 #ifdef DEBUG
934 	if (prtrealloc) {
935 		prtrealloc--;
936 		printf("\n");
937 	}
938 #endif
939 	return (0);
940 
941 fail:
942 	if (ssize < len)
943 		brelse(ebp);
944 	if (sbap != &ip->i_din2->di_db[0])
945 		brelse(sbp);
946 	return (ENOSPC);
947 }
948 
949 /*
950  * Allocate an inode in the filesystem.
951  *
952  * If allocating a directory, use ffs_dirpref to select the inode.
953  * If allocating in a directory, the following hierarchy is followed:
954  *   1) allocate the preferred inode.
955  *   2) allocate an inode in the same cylinder group.
956  *   3) quadradically rehash into other cylinder groups, until an
957  *      available inode is located.
958  * If no inode preference is given the following hierarchy is used
959  * to allocate an inode:
960  *   1) allocate an inode in cylinder group 0.
961  *   2) quadradically rehash into other cylinder groups, until an
962  *      available inode is located.
963  */
964 int
965 ffs_valloc(pvp, mode, cred, vpp)
966 	struct vnode *pvp;
967 	int mode;
968 	struct ucred *cred;
969 	struct vnode **vpp;
970 {
971 	struct inode *pip;
972 	struct fs *fs;
973 	struct inode *ip;
974 	struct timespec ts;
975 	struct ufsmount *ump;
976 	ino_t ino, ipref;
977 	u_int cg;
978 	int error, error1, reclaimed;
979 	static struct timeval lastfail;
980 	static int curfail;
981 
982 	*vpp = NULL;
983 	pip = VTOI(pvp);
984 	fs = pip->i_fs;
985 	ump = pip->i_ump;
986 
987 	UFS_LOCK(ump);
988 	reclaimed = 0;
989 retry:
990 	if (fs->fs_cstotal.cs_nifree == 0)
991 		goto noinodes;
992 
993 	if ((mode & IFMT) == IFDIR)
994 		ipref = ffs_dirpref(pip);
995 	else
996 		ipref = pip->i_number;
997 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
998 		ipref = 0;
999 	cg = ino_to_cg(fs, ipref);
1000 	/*
1001 	 * Track number of dirs created one after another
1002 	 * in a same cg without intervening by files.
1003 	 */
1004 	if ((mode & IFMT) == IFDIR) {
1005 		if (fs->fs_contigdirs[cg] < 255)
1006 			fs->fs_contigdirs[cg]++;
1007 	} else {
1008 		if (fs->fs_contigdirs[cg] > 0)
1009 			fs->fs_contigdirs[cg]--;
1010 	}
1011 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1012 					(allocfcn_t *)ffs_nodealloccg);
1013 	if (ino == 0)
1014 		goto noinodes;
1015 	error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
1016 	if (error) {
1017 		error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1018 		    FFSV_FORCEINSMQ);
1019 		ffs_vfree(pvp, ino, mode);
1020 		if (error1 == 0) {
1021 			ip = VTOI(*vpp);
1022 			if (ip->i_mode)
1023 				goto dup_alloc;
1024 			ip->i_flag |= IN_MODIFIED;
1025 			vput(*vpp);
1026 		}
1027 		return (error);
1028 	}
1029 	ip = VTOI(*vpp);
1030 	if (ip->i_mode) {
1031 dup_alloc:
1032 		printf("mode = 0%o, inum = %ju, fs = %s\n",
1033 		    ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1034 		panic("ffs_valloc: dup alloc");
1035 	}
1036 	if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) {  /* XXX */
1037 		printf("free inode %s/%lu had %ld blocks\n",
1038 		    fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1039 		DIP_SET(ip, i_blocks, 0);
1040 	}
1041 	ip->i_flags = 0;
1042 	DIP_SET(ip, i_flags, 0);
1043 	/*
1044 	 * Set up a new generation number for this inode.
1045 	 */
1046 	if (ip->i_gen == 0 || ++ip->i_gen == 0)
1047 		ip->i_gen = arc4random() / 2 + 1;
1048 	DIP_SET(ip, i_gen, ip->i_gen);
1049 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1050 		vfs_timestamp(&ts);
1051 		ip->i_din2->di_birthtime = ts.tv_sec;
1052 		ip->i_din2->di_birthnsec = ts.tv_nsec;
1053 	}
1054 	ufs_prepare_reclaim(*vpp);
1055 	ip->i_flag = 0;
1056 	(*vpp)->v_vflag = 0;
1057 	(*vpp)->v_type = VNON;
1058 	if (fs->fs_magic == FS_UFS2_MAGIC)
1059 		(*vpp)->v_op = &ffs_vnodeops2;
1060 	else
1061 		(*vpp)->v_op = &ffs_vnodeops1;
1062 	return (0);
1063 noinodes:
1064 	if (reclaimed == 0) {
1065 		reclaimed = 1;
1066 		softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1067 		goto retry;
1068 	}
1069 	UFS_UNLOCK(ump);
1070 	if (ppsratecheck(&lastfail, &curfail, 1)) {
1071 		ffs_fserr(fs, pip->i_number, "out of inodes");
1072 		uprintf("\n%s: create/symlink failed, no inodes free\n",
1073 		    fs->fs_fsmnt);
1074 	}
1075 	return (ENOSPC);
1076 }
1077 
1078 /*
1079  * Find a cylinder group to place a directory.
1080  *
1081  * The policy implemented by this algorithm is to allocate a
1082  * directory inode in the same cylinder group as its parent
1083  * directory, but also to reserve space for its files inodes
1084  * and data. Restrict the number of directories which may be
1085  * allocated one after another in the same cylinder group
1086  * without intervening allocation of files.
1087  *
1088  * If we allocate a first level directory then force allocation
1089  * in another cylinder group.
1090  */
1091 static ino_t
1092 ffs_dirpref(pip)
1093 	struct inode *pip;
1094 {
1095 	struct fs *fs;
1096 	int cg, prefcg, dirsize, cgsize;
1097 	u_int avgifree, avgbfree, avgndir, curdirsize;
1098 	u_int minifree, minbfree, maxndir;
1099 	u_int mincg, minndir;
1100 	u_int maxcontigdirs;
1101 
1102 	mtx_assert(UFS_MTX(pip->i_ump), MA_OWNED);
1103 	fs = pip->i_fs;
1104 
1105 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1106 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1107 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1108 
1109 	/*
1110 	 * Force allocation in another cg if creating a first level dir.
1111 	 */
1112 	ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1113 	if (ITOV(pip)->v_vflag & VV_ROOT) {
1114 		prefcg = arc4random() % fs->fs_ncg;
1115 		mincg = prefcg;
1116 		minndir = fs->fs_ipg;
1117 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
1118 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1119 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1120 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1121 				mincg = cg;
1122 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1123 			}
1124 		for (cg = 0; cg < prefcg; cg++)
1125 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1126 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1127 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1128 				mincg = cg;
1129 				minndir = fs->fs_cs(fs, cg).cs_ndir;
1130 			}
1131 		return ((ino_t)(fs->fs_ipg * mincg));
1132 	}
1133 
1134 	/*
1135 	 * Count various limits which used for
1136 	 * optimal allocation of a directory inode.
1137 	 */
1138 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1139 	minifree = avgifree - avgifree / 4;
1140 	if (minifree < 1)
1141 		minifree = 1;
1142 	minbfree = avgbfree - avgbfree / 4;
1143 	if (minbfree < 1)
1144 		minbfree = 1;
1145 	cgsize = fs->fs_fsize * fs->fs_fpg;
1146 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1147 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1148 	if (dirsize < curdirsize)
1149 		dirsize = curdirsize;
1150 	if (dirsize <= 0)
1151 		maxcontigdirs = 0;		/* dirsize overflowed */
1152 	else
1153 		maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1154 	if (fs->fs_avgfpdir > 0)
1155 		maxcontigdirs = min(maxcontigdirs,
1156 				    fs->fs_ipg / fs->fs_avgfpdir);
1157 	if (maxcontigdirs == 0)
1158 		maxcontigdirs = 1;
1159 
1160 	/*
1161 	 * Limit number of dirs in one cg and reserve space for
1162 	 * regular files, but only if we have no deficit in
1163 	 * inodes or space.
1164 	 *
1165 	 * We are trying to find a suitable cylinder group nearby
1166 	 * our preferred cylinder group to place a new directory.
1167 	 * We scan from our preferred cylinder group forward looking
1168 	 * for a cylinder group that meets our criterion. If we get
1169 	 * to the final cylinder group and do not find anything,
1170 	 * we start scanning forwards from the beginning of the
1171 	 * filesystem. While it might seem sensible to start scanning
1172 	 * backwards or even to alternate looking forward and backward,
1173 	 * this approach fails badly when the filesystem is nearly full.
1174 	 * Specifically, we first search all the areas that have no space
1175 	 * and finally try the one preceeding that. We repeat this on
1176 	 * every request and in the case of the final block end up
1177 	 * searching the entire filesystem. By jumping to the front
1178 	 * of the filesystem, our future forward searches always look
1179 	 * in new cylinder groups so finds every possible block after
1180 	 * one pass over the filesystem.
1181 	 */
1182 	prefcg = ino_to_cg(fs, pip->i_number);
1183 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1184 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1185 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1186 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1187 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1188 				return ((ino_t)(fs->fs_ipg * cg));
1189 		}
1190 	for (cg = 0; cg < prefcg; cg++)
1191 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1192 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1193 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1194 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1195 				return ((ino_t)(fs->fs_ipg * cg));
1196 		}
1197 	/*
1198 	 * This is a backstop when we have deficit in space.
1199 	 */
1200 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1201 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1202 			return ((ino_t)(fs->fs_ipg * cg));
1203 	for (cg = 0; cg < prefcg; cg++)
1204 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1205 			break;
1206 	return ((ino_t)(fs->fs_ipg * cg));
1207 }
1208 
1209 /*
1210  * Select the desired position for the next block in a file.  The file is
1211  * logically divided into sections. The first section is composed of the
1212  * direct blocks and the next fs_maxbpg blocks. Each additional section
1213  * contains fs_maxbpg blocks.
1214  *
1215  * If no blocks have been allocated in the first section, the policy is to
1216  * request a block in the same cylinder group as the inode that describes
1217  * the file. The first indirect is allocated immediately following the last
1218  * direct block and the data blocks for the first indirect immediately
1219  * follow it.
1220  *
1221  * If no blocks have been allocated in any other section, the indirect
1222  * block(s) are allocated in the same cylinder group as its inode in an
1223  * area reserved immediately following the inode blocks. The policy for
1224  * the data blocks is to place them in a cylinder group with a greater than
1225  * average number of free blocks. An appropriate cylinder group is found
1226  * by using a rotor that sweeps the cylinder groups. When a new group of
1227  * blocks is needed, the sweep begins in the cylinder group following the
1228  * cylinder group from which the previous allocation was made. The sweep
1229  * continues until a cylinder group with greater than the average number
1230  * of free blocks is found. If the allocation is for the first block in an
1231  * indirect block or the previous block is a hole, then the information on
1232  * the previous allocation is unavailable; here a best guess is made based
1233  * on the logical block number being allocated.
1234  *
1235  * If a section is already partially allocated, the policy is to
1236  * allocate blocks contiguously within the section if possible.
1237  */
1238 ufs2_daddr_t
1239 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1240 	struct inode *ip;
1241 	ufs_lbn_t lbn;
1242 	int indx;
1243 	ufs1_daddr_t *bap;
1244 {
1245 	struct fs *fs;
1246 	u_int cg, inocg;
1247 	u_int avgbfree, startcg;
1248 	ufs2_daddr_t pref;
1249 
1250 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1251 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1252 	fs = ip->i_fs;
1253 	/*
1254 	 * Allocation of indirect blocks is indicated by passing negative
1255 	 * values in indx: -1 for single indirect, -2 for double indirect,
1256 	 * -3 for triple indirect. As noted below, we attempt to allocate
1257 	 * the first indirect inline with the file data. For all later
1258 	 * indirect blocks, the data is often allocated in other cylinder
1259 	 * groups. However to speed random file access and to speed up
1260 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1261 	 * (typically half of fs_minfree) of the data area of each cylinder
1262 	 * group to hold these later indirect blocks.
1263 	 */
1264 	inocg = ino_to_cg(fs, ip->i_number);
1265 	if (indx < 0) {
1266 		/*
1267 		 * Our preference for indirect blocks is the zone at the
1268 		 * beginning of the inode's cylinder group data area that
1269 		 * we try to reserve for indirect blocks.
1270 		 */
1271 		pref = cgmeta(fs, inocg);
1272 		/*
1273 		 * If we are allocating the first indirect block, try to
1274 		 * place it immediately following the last direct block.
1275 		 */
1276 		if (indx == -1 && lbn < NDADDR + NINDIR(fs) &&
1277 		    ip->i_din1->di_db[NDADDR - 1] != 0)
1278 			pref = ip->i_din1->di_db[NDADDR - 1] + fs->fs_frag;
1279 		return (pref);
1280 	}
1281 	/*
1282 	 * If we are allocating the first data block in the first indirect
1283 	 * block and the indirect has been allocated in the data block area,
1284 	 * try to place it immediately following the indirect block.
1285 	 */
1286 	if (lbn == NDADDR) {
1287 		pref = ip->i_din1->di_ib[0];
1288 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1289 		    pref < cgbase(fs, inocg + 1))
1290 			return (pref + fs->fs_frag);
1291 	}
1292 	/*
1293 	 * If we are at the beginning of a file, or we have already allocated
1294 	 * the maximum number of blocks per cylinder group, or we do not
1295 	 * have a block allocated immediately preceeding us, then we need
1296 	 * to decide where to start allocating new blocks.
1297 	 */
1298 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1299 		/*
1300 		 * If we are allocating a directory data block, we want
1301 		 * to place it in the metadata area.
1302 		 */
1303 		if ((ip->i_mode & IFMT) == IFDIR)
1304 			return (cgmeta(fs, inocg));
1305 		/*
1306 		 * Until we fill all the direct and all the first indirect's
1307 		 * blocks, we try to allocate in the data area of the inode's
1308 		 * cylinder group.
1309 		 */
1310 		if (lbn < NDADDR + NINDIR(fs))
1311 			return (cgdata(fs, inocg));
1312 		/*
1313 		 * Find a cylinder with greater than average number of
1314 		 * unused data blocks.
1315 		 */
1316 		if (indx == 0 || bap[indx - 1] == 0)
1317 			startcg = inocg + lbn / fs->fs_maxbpg;
1318 		else
1319 			startcg = dtog(fs, bap[indx - 1]) + 1;
1320 		startcg %= fs->fs_ncg;
1321 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1322 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1323 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1324 				fs->fs_cgrotor = cg;
1325 				return (cgdata(fs, cg));
1326 			}
1327 		for (cg = 0; cg <= startcg; cg++)
1328 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1329 				fs->fs_cgrotor = cg;
1330 				return (cgdata(fs, cg));
1331 			}
1332 		return (0);
1333 	}
1334 	/*
1335 	 * Otherwise, we just always try to lay things out contiguously.
1336 	 */
1337 	return (bap[indx - 1] + fs->fs_frag);
1338 }
1339 
1340 /*
1341  * Same as above, but for UFS2
1342  */
1343 ufs2_daddr_t
1344 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1345 	struct inode *ip;
1346 	ufs_lbn_t lbn;
1347 	int indx;
1348 	ufs2_daddr_t *bap;
1349 {
1350 	struct fs *fs;
1351 	u_int cg, inocg;
1352 	u_int avgbfree, startcg;
1353 	ufs2_daddr_t pref;
1354 
1355 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1356 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1357 	fs = ip->i_fs;
1358 	/*
1359 	 * Allocation of indirect blocks is indicated by passing negative
1360 	 * values in indx: -1 for single indirect, -2 for double indirect,
1361 	 * -3 for triple indirect. As noted below, we attempt to allocate
1362 	 * the first indirect inline with the file data. For all later
1363 	 * indirect blocks, the data is often allocated in other cylinder
1364 	 * groups. However to speed random file access and to speed up
1365 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1366 	 * (typically half of fs_minfree) of the data area of each cylinder
1367 	 * group to hold these later indirect blocks.
1368 	 */
1369 	inocg = ino_to_cg(fs, ip->i_number);
1370 	if (indx < 0) {
1371 		/*
1372 		 * Our preference for indirect blocks is the zone at the
1373 		 * beginning of the inode's cylinder group data area that
1374 		 * we try to reserve for indirect blocks.
1375 		 */
1376 		pref = cgmeta(fs, inocg);
1377 		/*
1378 		 * If we are allocating the first indirect block, try to
1379 		 * place it immediately following the last direct block.
1380 		 */
1381 		if (indx == -1 && lbn < NDADDR + NINDIR(fs) &&
1382 		    ip->i_din2->di_db[NDADDR - 1] != 0)
1383 			pref = ip->i_din2->di_db[NDADDR - 1] + fs->fs_frag;
1384 		return (pref);
1385 	}
1386 	/*
1387 	 * If we are allocating the first data block in the first indirect
1388 	 * block and the indirect has been allocated in the data block area,
1389 	 * try to place it immediately following the indirect block.
1390 	 */
1391 	if (lbn == NDADDR) {
1392 		pref = ip->i_din2->di_ib[0];
1393 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1394 		    pref < cgbase(fs, inocg + 1))
1395 			return (pref + fs->fs_frag);
1396 	}
1397 	/*
1398 	 * If we are at the beginning of a file, or we have already allocated
1399 	 * the maximum number of blocks per cylinder group, or we do not
1400 	 * have a block allocated immediately preceeding us, then we need
1401 	 * to decide where to start allocating new blocks.
1402 	 */
1403 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1404 		/*
1405 		 * If we are allocating a directory data block, we want
1406 		 * to place it in the metadata area.
1407 		 */
1408 		if ((ip->i_mode & IFMT) == IFDIR)
1409 			return (cgmeta(fs, inocg));
1410 		/*
1411 		 * Until we fill all the direct and all the first indirect's
1412 		 * blocks, we try to allocate in the data area of the inode's
1413 		 * cylinder group.
1414 		 */
1415 		if (lbn < NDADDR + NINDIR(fs))
1416 			return (cgdata(fs, inocg));
1417 		/*
1418 		 * Find a cylinder with greater than average number of
1419 		 * unused data blocks.
1420 		 */
1421 		if (indx == 0 || bap[indx - 1] == 0)
1422 			startcg = inocg + lbn / fs->fs_maxbpg;
1423 		else
1424 			startcg = dtog(fs, bap[indx - 1]) + 1;
1425 		startcg %= fs->fs_ncg;
1426 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1427 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1428 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1429 				fs->fs_cgrotor = cg;
1430 				return (cgdata(fs, cg));
1431 			}
1432 		for (cg = 0; cg <= startcg; cg++)
1433 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1434 				fs->fs_cgrotor = cg;
1435 				return (cgdata(fs, cg));
1436 			}
1437 		return (0);
1438 	}
1439 	/*
1440 	 * Otherwise, we just always try to lay things out contiguously.
1441 	 */
1442 	return (bap[indx - 1] + fs->fs_frag);
1443 }
1444 
1445 /*
1446  * Implement the cylinder overflow algorithm.
1447  *
1448  * The policy implemented by this algorithm is:
1449  *   1) allocate the block in its requested cylinder group.
1450  *   2) quadradically rehash on the cylinder group number.
1451  *   3) brute force search for a free block.
1452  *
1453  * Must be called with the UFS lock held.  Will release the lock on success
1454  * and return with it held on failure.
1455  */
1456 /*VARARGS5*/
1457 static ufs2_daddr_t
1458 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1459 	struct inode *ip;
1460 	u_int cg;
1461 	ufs2_daddr_t pref;
1462 	int size;	/* Search size for data blocks, mode for inodes */
1463 	int rsize;	/* Real allocated size. */
1464 	allocfcn_t *allocator;
1465 {
1466 	struct fs *fs;
1467 	ufs2_daddr_t result;
1468 	u_int i, icg = cg;
1469 
1470 	mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1471 #ifdef INVARIANTS
1472 	if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1473 		panic("ffs_hashalloc: allocation on suspended filesystem");
1474 #endif
1475 	fs = ip->i_fs;
1476 	/*
1477 	 * 1: preferred cylinder group
1478 	 */
1479 	result = (*allocator)(ip, cg, pref, size, rsize);
1480 	if (result)
1481 		return (result);
1482 	/*
1483 	 * 2: quadratic rehash
1484 	 */
1485 	for (i = 1; i < fs->fs_ncg; i *= 2) {
1486 		cg += i;
1487 		if (cg >= fs->fs_ncg)
1488 			cg -= fs->fs_ncg;
1489 		result = (*allocator)(ip, cg, 0, size, rsize);
1490 		if (result)
1491 			return (result);
1492 	}
1493 	/*
1494 	 * 3: brute force search
1495 	 * Note that we start at i == 2, since 0 was checked initially,
1496 	 * and 1 is always checked in the quadratic rehash.
1497 	 */
1498 	cg = (icg + 2) % fs->fs_ncg;
1499 	for (i = 2; i < fs->fs_ncg; i++) {
1500 		result = (*allocator)(ip, cg, 0, size, rsize);
1501 		if (result)
1502 			return (result);
1503 		cg++;
1504 		if (cg == fs->fs_ncg)
1505 			cg = 0;
1506 	}
1507 	return (0);
1508 }
1509 
1510 /*
1511  * Determine whether a fragment can be extended.
1512  *
1513  * Check to see if the necessary fragments are available, and
1514  * if they are, allocate them.
1515  */
1516 static ufs2_daddr_t
1517 ffs_fragextend(ip, cg, bprev, osize, nsize)
1518 	struct inode *ip;
1519 	u_int cg;
1520 	ufs2_daddr_t bprev;
1521 	int osize, nsize;
1522 {
1523 	struct fs *fs;
1524 	struct cg *cgp;
1525 	struct buf *bp;
1526 	struct ufsmount *ump;
1527 	int nffree;
1528 	long bno;
1529 	int frags, bbase;
1530 	int i, error;
1531 	u_int8_t *blksfree;
1532 
1533 	ump = ip->i_ump;
1534 	fs = ip->i_fs;
1535 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1536 		return (0);
1537 	frags = numfrags(fs, nsize);
1538 	bbase = fragnum(fs, bprev);
1539 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
1540 		/* cannot extend across a block boundary */
1541 		return (0);
1542 	}
1543 	UFS_UNLOCK(ump);
1544 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1545 		(int)fs->fs_cgsize, NOCRED, &bp);
1546 	if (error)
1547 		goto fail;
1548 	cgp = (struct cg *)bp->b_data;
1549 	if (!cg_chkmagic(cgp))
1550 		goto fail;
1551 	bp->b_xflags |= BX_BKGRDWRITE;
1552 	cgp->cg_old_time = cgp->cg_time = time_second;
1553 	bno = dtogd(fs, bprev);
1554 	blksfree = cg_blksfree(cgp);
1555 	for (i = numfrags(fs, osize); i < frags; i++)
1556 		if (isclr(blksfree, bno + i))
1557 			goto fail;
1558 	/*
1559 	 * the current fragment can be extended
1560 	 * deduct the count on fragment being extended into
1561 	 * increase the count on the remaining fragment (if any)
1562 	 * allocate the extended piece
1563 	 */
1564 	for (i = frags; i < fs->fs_frag - bbase; i++)
1565 		if (isclr(blksfree, bno + i))
1566 			break;
1567 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
1568 	if (i != frags)
1569 		cgp->cg_frsum[i - frags]++;
1570 	for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1571 		clrbit(blksfree, bno + i);
1572 		cgp->cg_cs.cs_nffree--;
1573 		nffree++;
1574 	}
1575 	UFS_LOCK(ump);
1576 	fs->fs_cstotal.cs_nffree -= nffree;
1577 	fs->fs_cs(fs, cg).cs_nffree -= nffree;
1578 	fs->fs_fmod = 1;
1579 	ACTIVECLEAR(fs, cg);
1580 	UFS_UNLOCK(ump);
1581 	if (DOINGSOFTDEP(ITOV(ip)))
1582 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1583 		    frags, numfrags(fs, osize));
1584 	bdwrite(bp);
1585 	return (bprev);
1586 
1587 fail:
1588 	brelse(bp);
1589 	UFS_LOCK(ump);
1590 	return (0);
1591 
1592 }
1593 
1594 /*
1595  * Determine whether a block can be allocated.
1596  *
1597  * Check to see if a block of the appropriate size is available,
1598  * and if it is, allocate it.
1599  */
1600 static ufs2_daddr_t
1601 ffs_alloccg(ip, cg, bpref, size, rsize)
1602 	struct inode *ip;
1603 	u_int cg;
1604 	ufs2_daddr_t bpref;
1605 	int size;
1606 	int rsize;
1607 {
1608 	struct fs *fs;
1609 	struct cg *cgp;
1610 	struct buf *bp;
1611 	struct ufsmount *ump;
1612 	ufs1_daddr_t bno;
1613 	ufs2_daddr_t blkno;
1614 	int i, allocsiz, error, frags;
1615 	u_int8_t *blksfree;
1616 
1617 	ump = ip->i_ump;
1618 	fs = ip->i_fs;
1619 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1620 		return (0);
1621 	UFS_UNLOCK(ump);
1622 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1623 		(int)fs->fs_cgsize, NOCRED, &bp);
1624 	if (error)
1625 		goto fail;
1626 	cgp = (struct cg *)bp->b_data;
1627 	if (!cg_chkmagic(cgp) ||
1628 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1629 		goto fail;
1630 	bp->b_xflags |= BX_BKGRDWRITE;
1631 	cgp->cg_old_time = cgp->cg_time = time_second;
1632 	if (size == fs->fs_bsize) {
1633 		UFS_LOCK(ump);
1634 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1635 		ACTIVECLEAR(fs, cg);
1636 		UFS_UNLOCK(ump);
1637 		bdwrite(bp);
1638 		return (blkno);
1639 	}
1640 	/*
1641 	 * check to see if any fragments are already available
1642 	 * allocsiz is the size which will be allocated, hacking
1643 	 * it down to a smaller size if necessary
1644 	 */
1645 	blksfree = cg_blksfree(cgp);
1646 	frags = numfrags(fs, size);
1647 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1648 		if (cgp->cg_frsum[allocsiz] != 0)
1649 			break;
1650 	if (allocsiz == fs->fs_frag) {
1651 		/*
1652 		 * no fragments were available, so a block will be
1653 		 * allocated, and hacked up
1654 		 */
1655 		if (cgp->cg_cs.cs_nbfree == 0)
1656 			goto fail;
1657 		UFS_LOCK(ump);
1658 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1659 		ACTIVECLEAR(fs, cg);
1660 		UFS_UNLOCK(ump);
1661 		bdwrite(bp);
1662 		return (blkno);
1663 	}
1664 	KASSERT(size == rsize,
1665 	    ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1666 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1667 	if (bno < 0)
1668 		goto fail;
1669 	for (i = 0; i < frags; i++)
1670 		clrbit(blksfree, bno + i);
1671 	cgp->cg_cs.cs_nffree -= frags;
1672 	cgp->cg_frsum[allocsiz]--;
1673 	if (frags != allocsiz)
1674 		cgp->cg_frsum[allocsiz - frags]++;
1675 	UFS_LOCK(ump);
1676 	fs->fs_cstotal.cs_nffree -= frags;
1677 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1678 	fs->fs_fmod = 1;
1679 	blkno = cgbase(fs, cg) + bno;
1680 	ACTIVECLEAR(fs, cg);
1681 	UFS_UNLOCK(ump);
1682 	if (DOINGSOFTDEP(ITOV(ip)))
1683 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1684 	bdwrite(bp);
1685 	return (blkno);
1686 
1687 fail:
1688 	brelse(bp);
1689 	UFS_LOCK(ump);
1690 	return (0);
1691 }
1692 
1693 /*
1694  * Allocate a block in a cylinder group.
1695  *
1696  * This algorithm implements the following policy:
1697  *   1) allocate the requested block.
1698  *   2) allocate a rotationally optimal block in the same cylinder.
1699  *   3) allocate the next available block on the block rotor for the
1700  *      specified cylinder group.
1701  * Note that this routine only allocates fs_bsize blocks; these
1702  * blocks may be fragmented by the routine that allocates them.
1703  */
1704 static ufs2_daddr_t
1705 ffs_alloccgblk(ip, bp, bpref, size)
1706 	struct inode *ip;
1707 	struct buf *bp;
1708 	ufs2_daddr_t bpref;
1709 	int size;
1710 {
1711 	struct fs *fs;
1712 	struct cg *cgp;
1713 	struct ufsmount *ump;
1714 	ufs1_daddr_t bno;
1715 	ufs2_daddr_t blkno;
1716 	u_int8_t *blksfree;
1717 	int i, cgbpref;
1718 
1719 	fs = ip->i_fs;
1720 	ump = ip->i_ump;
1721 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1722 	cgp = (struct cg *)bp->b_data;
1723 	blksfree = cg_blksfree(cgp);
1724 	if (bpref == 0) {
1725 		bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1726 	} else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1727 		/* map bpref to correct zone in this cg */
1728 		if (bpref < cgdata(fs, cgbpref))
1729 			bpref = cgmeta(fs, cgp->cg_cgx);
1730 		else
1731 			bpref = cgdata(fs, cgp->cg_cgx);
1732 	}
1733 	/*
1734 	 * if the requested block is available, use it
1735 	 */
1736 	bno = dtogd(fs, blknum(fs, bpref));
1737 	if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1738 		goto gotit;
1739 	/*
1740 	 * Take the next available block in this cylinder group.
1741 	 */
1742 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1743 	if (bno < 0)
1744 		return (0);
1745 	/* Update cg_rotor only if allocated from the data zone */
1746 	if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1747 		cgp->cg_rotor = bno;
1748 gotit:
1749 	blkno = fragstoblks(fs, bno);
1750 	ffs_clrblock(fs, blksfree, (long)blkno);
1751 	ffs_clusteracct(fs, cgp, blkno, -1);
1752 	cgp->cg_cs.cs_nbfree--;
1753 	fs->fs_cstotal.cs_nbfree--;
1754 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1755 	fs->fs_fmod = 1;
1756 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1757 	/*
1758 	 * If the caller didn't want the whole block free the frags here.
1759 	 */
1760 	size = numfrags(fs, size);
1761 	if (size != fs->fs_frag) {
1762 		bno = dtogd(fs, blkno);
1763 		for (i = size; i < fs->fs_frag; i++)
1764 			setbit(blksfree, bno + i);
1765 		i = fs->fs_frag - size;
1766 		cgp->cg_cs.cs_nffree += i;
1767 		fs->fs_cstotal.cs_nffree += i;
1768 		fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1769 		fs->fs_fmod = 1;
1770 		cgp->cg_frsum[i]++;
1771 	}
1772 	/* XXX Fixme. */
1773 	UFS_UNLOCK(ump);
1774 	if (DOINGSOFTDEP(ITOV(ip)))
1775 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno,
1776 		    size, 0);
1777 	UFS_LOCK(ump);
1778 	return (blkno);
1779 }
1780 
1781 /*
1782  * Determine whether a cluster can be allocated.
1783  *
1784  * We do not currently check for optimal rotational layout if there
1785  * are multiple choices in the same cylinder group. Instead we just
1786  * take the first one that we find following bpref.
1787  */
1788 static ufs2_daddr_t
1789 ffs_clusteralloc(ip, cg, bpref, len, unused)
1790 	struct inode *ip;
1791 	u_int cg;
1792 	ufs2_daddr_t bpref;
1793 	int len;
1794 	int unused;
1795 {
1796 	struct fs *fs;
1797 	struct cg *cgp;
1798 	struct buf *bp;
1799 	struct ufsmount *ump;
1800 	int i, run, bit, map, got;
1801 	ufs2_daddr_t bno;
1802 	u_char *mapp;
1803 	int32_t *lp;
1804 	u_int8_t *blksfree;
1805 
1806 	fs = ip->i_fs;
1807 	ump = ip->i_ump;
1808 	if (fs->fs_maxcluster[cg] < len)
1809 		return (0);
1810 	UFS_UNLOCK(ump);
1811 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1812 	    NOCRED, &bp))
1813 		goto fail_lock;
1814 	cgp = (struct cg *)bp->b_data;
1815 	if (!cg_chkmagic(cgp))
1816 		goto fail_lock;
1817 	bp->b_xflags |= BX_BKGRDWRITE;
1818 	/*
1819 	 * Check to see if a cluster of the needed size (or bigger) is
1820 	 * available in this cylinder group.
1821 	 */
1822 	lp = &cg_clustersum(cgp)[len];
1823 	for (i = len; i <= fs->fs_contigsumsize; i++)
1824 		if (*lp++ > 0)
1825 			break;
1826 	if (i > fs->fs_contigsumsize) {
1827 		/*
1828 		 * This is the first time looking for a cluster in this
1829 		 * cylinder group. Update the cluster summary information
1830 		 * to reflect the true maximum sized cluster so that
1831 		 * future cluster allocation requests can avoid reading
1832 		 * the cylinder group map only to find no clusters.
1833 		 */
1834 		lp = &cg_clustersum(cgp)[len - 1];
1835 		for (i = len - 1; i > 0; i--)
1836 			if (*lp-- > 0)
1837 				break;
1838 		UFS_LOCK(ump);
1839 		fs->fs_maxcluster[cg] = i;
1840 		goto fail;
1841 	}
1842 	/*
1843 	 * Search the cluster map to find a big enough cluster.
1844 	 * We take the first one that we find, even if it is larger
1845 	 * than we need as we prefer to get one close to the previous
1846 	 * block allocation. We do not search before the current
1847 	 * preference point as we do not want to allocate a block
1848 	 * that is allocated before the previous one (as we will
1849 	 * then have to wait for another pass of the elevator
1850 	 * algorithm before it will be read). We prefer to fail and
1851 	 * be recalled to try an allocation in the next cylinder group.
1852 	 */
1853 	if (dtog(fs, bpref) != cg)
1854 		bpref = cgdata(fs, cg);
1855 	else
1856 		bpref = blknum(fs, bpref);
1857 	bpref = fragstoblks(fs, dtogd(fs, bpref));
1858 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1859 	map = *mapp++;
1860 	bit = 1 << (bpref % NBBY);
1861 	for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1862 		if ((map & bit) == 0) {
1863 			run = 0;
1864 		} else {
1865 			run++;
1866 			if (run == len)
1867 				break;
1868 		}
1869 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
1870 			bit <<= 1;
1871 		} else {
1872 			map = *mapp++;
1873 			bit = 1;
1874 		}
1875 	}
1876 	if (got >= cgp->cg_nclusterblks)
1877 		goto fail_lock;
1878 	/*
1879 	 * Allocate the cluster that we have found.
1880 	 */
1881 	blksfree = cg_blksfree(cgp);
1882 	for (i = 1; i <= len; i++)
1883 		if (!ffs_isblock(fs, blksfree, got - run + i))
1884 			panic("ffs_clusteralloc: map mismatch");
1885 	bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1886 	if (dtog(fs, bno) != cg)
1887 		panic("ffs_clusteralloc: allocated out of group");
1888 	len = blkstofrags(fs, len);
1889 	UFS_LOCK(ump);
1890 	for (i = 0; i < len; i += fs->fs_frag)
1891 		if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
1892 			panic("ffs_clusteralloc: lost block");
1893 	ACTIVECLEAR(fs, cg);
1894 	UFS_UNLOCK(ump);
1895 	bdwrite(bp);
1896 	return (bno);
1897 
1898 fail_lock:
1899 	UFS_LOCK(ump);
1900 fail:
1901 	brelse(bp);
1902 	return (0);
1903 }
1904 
1905 static inline struct buf *
1906 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
1907 {
1908 	struct fs *fs;
1909 
1910 	fs = ip->i_fs;
1911 	return (getblk(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs,
1912 	    cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
1913 	    gbflags));
1914 }
1915 
1916 /*
1917  * Determine whether an inode can be allocated.
1918  *
1919  * Check to see if an inode is available, and if it is,
1920  * allocate it using the following policy:
1921  *   1) allocate the requested inode.
1922  *   2) allocate the next available inode after the requested
1923  *      inode in the specified cylinder group.
1924  */
1925 static ufs2_daddr_t
1926 ffs_nodealloccg(ip, cg, ipref, mode, unused)
1927 	struct inode *ip;
1928 	u_int cg;
1929 	ufs2_daddr_t ipref;
1930 	int mode;
1931 	int unused;
1932 {
1933 	struct fs *fs;
1934 	struct cg *cgp;
1935 	struct buf *bp, *ibp;
1936 	struct ufsmount *ump;
1937 	u_int8_t *inosused, *loc;
1938 	struct ufs2_dinode *dp2;
1939 	int error, start, len, i;
1940 	u_int32_t old_initediblk;
1941 
1942 	fs = ip->i_fs;
1943 	ump = ip->i_ump;
1944 check_nifree:
1945 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1946 		return (0);
1947 	UFS_UNLOCK(ump);
1948 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1949 		(int)fs->fs_cgsize, NOCRED, &bp);
1950 	if (error) {
1951 		brelse(bp);
1952 		UFS_LOCK(ump);
1953 		return (0);
1954 	}
1955 	cgp = (struct cg *)bp->b_data;
1956 restart:
1957 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1958 		brelse(bp);
1959 		UFS_LOCK(ump);
1960 		return (0);
1961 	}
1962 	bp->b_xflags |= BX_BKGRDWRITE;
1963 	inosused = cg_inosused(cgp);
1964 	if (ipref) {
1965 		ipref %= fs->fs_ipg;
1966 		if (isclr(inosused, ipref))
1967 			goto gotit;
1968 	}
1969 	start = cgp->cg_irotor / NBBY;
1970 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1971 	loc = memcchr(&inosused[start], 0xff, len);
1972 	if (loc == NULL) {
1973 		len = start + 1;
1974 		start = 0;
1975 		loc = memcchr(&inosused[start], 0xff, len);
1976 		if (loc == NULL) {
1977 			printf("cg = %d, irotor = %ld, fs = %s\n",
1978 			    cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
1979 			panic("ffs_nodealloccg: map corrupted");
1980 			/* NOTREACHED */
1981 		}
1982 	}
1983 	ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
1984 gotit:
1985 	/*
1986 	 * Check to see if we need to initialize more inodes.
1987 	 */
1988 	if (fs->fs_magic == FS_UFS2_MAGIC &&
1989 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
1990 	    cgp->cg_initediblk < cgp->cg_niblk) {
1991 		old_initediblk = cgp->cg_initediblk;
1992 
1993 		/*
1994 		 * Free the cylinder group lock before writing the
1995 		 * initialized inode block.  Entering the
1996 		 * babarrierwrite() with the cylinder group lock
1997 		 * causes lock order violation between the lock and
1998 		 * snaplk.
1999 		 *
2000 		 * Another thread can decide to initialize the same
2001 		 * inode block, but whichever thread first gets the
2002 		 * cylinder group lock after writing the newly
2003 		 * allocated inode block will update it and the other
2004 		 * will realize that it has lost and leave the
2005 		 * cylinder group unchanged.
2006 		 */
2007 		ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2008 		brelse(bp);
2009 		if (ibp == NULL) {
2010 			/*
2011 			 * The inode block buffer is already owned by
2012 			 * another thread, which must initialize it.
2013 			 * Wait on the buffer to allow another thread
2014 			 * to finish the updates, with dropped cg
2015 			 * buffer lock, then retry.
2016 			 */
2017 			ibp = getinobuf(ip, cg, old_initediblk, 0);
2018 			brelse(ibp);
2019 			UFS_LOCK(ump);
2020 			goto check_nifree;
2021 		}
2022 		bzero(ibp->b_data, (int)fs->fs_bsize);
2023 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
2024 		for (i = 0; i < INOPB(fs); i++) {
2025 			dp2->di_gen = arc4random() / 2 + 1;
2026 			dp2++;
2027 		}
2028 		/*
2029 		 * Rather than adding a soft updates dependency to ensure
2030 		 * that the new inode block is written before it is claimed
2031 		 * by the cylinder group map, we just do a barrier write
2032 		 * here. The barrier write will ensure that the inode block
2033 		 * gets written before the updated cylinder group map can be
2034 		 * written. The barrier write should only slow down bulk
2035 		 * loading of newly created filesystems.
2036 		 */
2037 		babarrierwrite(ibp);
2038 
2039 		/*
2040 		 * After the inode block is written, try to update the
2041 		 * cg initediblk pointer.  If another thread beat us
2042 		 * to it, then leave it unchanged as the other thread
2043 		 * has already set it correctly.
2044 		 */
2045 		error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
2046 		    (int)fs->fs_cgsize, NOCRED, &bp);
2047 		UFS_LOCK(ump);
2048 		ACTIVECLEAR(fs, cg);
2049 		UFS_UNLOCK(ump);
2050 		if (error != 0) {
2051 			brelse(bp);
2052 			return (error);
2053 		}
2054 		cgp = (struct cg *)bp->b_data;
2055 		if (cgp->cg_initediblk == old_initediblk)
2056 			cgp->cg_initediblk += INOPB(fs);
2057 		goto restart;
2058 	}
2059 	cgp->cg_old_time = cgp->cg_time = time_second;
2060 	cgp->cg_irotor = ipref;
2061 	UFS_LOCK(ump);
2062 	ACTIVECLEAR(fs, cg);
2063 	setbit(inosused, ipref);
2064 	cgp->cg_cs.cs_nifree--;
2065 	fs->fs_cstotal.cs_nifree--;
2066 	fs->fs_cs(fs, cg).cs_nifree--;
2067 	fs->fs_fmod = 1;
2068 	if ((mode & IFMT) == IFDIR) {
2069 		cgp->cg_cs.cs_ndir++;
2070 		fs->fs_cstotal.cs_ndir++;
2071 		fs->fs_cs(fs, cg).cs_ndir++;
2072 	}
2073 	UFS_UNLOCK(ump);
2074 	if (DOINGSOFTDEP(ITOV(ip)))
2075 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2076 	bdwrite(bp);
2077 	return ((ino_t)(cg * fs->fs_ipg + ipref));
2078 }
2079 
2080 /*
2081  * Free a block or fragment.
2082  *
2083  * The specified block or fragment is placed back in the
2084  * free map. If a fragment is deallocated, a possible
2085  * block reassembly is checked.
2086  */
2087 static void
2088 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2089 	struct ufsmount *ump;
2090 	struct fs *fs;
2091 	struct vnode *devvp;
2092 	ufs2_daddr_t bno;
2093 	long size;
2094 	ino_t inum;
2095 	struct workhead *dephd;
2096 {
2097 	struct mount *mp;
2098 	struct cg *cgp;
2099 	struct buf *bp;
2100 	ufs1_daddr_t fragno, cgbno;
2101 	ufs2_daddr_t cgblkno;
2102 	int i, blk, frags, bbase;
2103 	u_int cg;
2104 	u_int8_t *blksfree;
2105 	struct cdev *dev;
2106 
2107 	cg = dtog(fs, bno);
2108 	if (devvp->v_type == VREG) {
2109 		/* devvp is a snapshot */
2110 		dev = VTOI(devvp)->i_devvp->v_rdev;
2111 		cgblkno = fragstoblks(fs, cgtod(fs, cg));
2112 	} else {
2113 		/* devvp is a normal disk device */
2114 		dev = devvp->v_rdev;
2115 		cgblkno = fsbtodb(fs, cgtod(fs, cg));
2116 		ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
2117 	}
2118 #ifdef INVARIANTS
2119 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2120 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2121 		printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2122 		    devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2123 		    size, fs->fs_fsmnt);
2124 		panic("ffs_blkfree_cg: bad size");
2125 	}
2126 #endif
2127 	if ((u_int)bno >= fs->fs_size) {
2128 		printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2129 		    (u_long)inum);
2130 		ffs_fserr(fs, inum, "bad block");
2131 		return;
2132 	}
2133 	if (bread(devvp, cgblkno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2134 		brelse(bp);
2135 		return;
2136 	}
2137 	cgp = (struct cg *)bp->b_data;
2138 	if (!cg_chkmagic(cgp)) {
2139 		brelse(bp);
2140 		return;
2141 	}
2142 	bp->b_xflags |= BX_BKGRDWRITE;
2143 	cgp->cg_old_time = cgp->cg_time = time_second;
2144 	cgbno = dtogd(fs, bno);
2145 	blksfree = cg_blksfree(cgp);
2146 	UFS_LOCK(ump);
2147 	if (size == fs->fs_bsize) {
2148 		fragno = fragstoblks(fs, cgbno);
2149 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2150 			if (devvp->v_type == VREG) {
2151 				UFS_UNLOCK(ump);
2152 				/* devvp is a snapshot */
2153 				brelse(bp);
2154 				return;
2155 			}
2156 			printf("dev = %s, block = %jd, fs = %s\n",
2157 			    devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2158 			panic("ffs_blkfree_cg: freeing free block");
2159 		}
2160 		ffs_setblock(fs, blksfree, fragno);
2161 		ffs_clusteracct(fs, cgp, fragno, 1);
2162 		cgp->cg_cs.cs_nbfree++;
2163 		fs->fs_cstotal.cs_nbfree++;
2164 		fs->fs_cs(fs, cg).cs_nbfree++;
2165 	} else {
2166 		bbase = cgbno - fragnum(fs, cgbno);
2167 		/*
2168 		 * decrement the counts associated with the old frags
2169 		 */
2170 		blk = blkmap(fs, blksfree, bbase);
2171 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2172 		/*
2173 		 * deallocate the fragment
2174 		 */
2175 		frags = numfrags(fs, size);
2176 		for (i = 0; i < frags; i++) {
2177 			if (isset(blksfree, cgbno + i)) {
2178 				printf("dev = %s, block = %jd, fs = %s\n",
2179 				    devtoname(dev), (intmax_t)(bno + i),
2180 				    fs->fs_fsmnt);
2181 				panic("ffs_blkfree_cg: freeing free frag");
2182 			}
2183 			setbit(blksfree, cgbno + i);
2184 		}
2185 		cgp->cg_cs.cs_nffree += i;
2186 		fs->fs_cstotal.cs_nffree += i;
2187 		fs->fs_cs(fs, cg).cs_nffree += i;
2188 		/*
2189 		 * add back in counts associated with the new frags
2190 		 */
2191 		blk = blkmap(fs, blksfree, bbase);
2192 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2193 		/*
2194 		 * if a complete block has been reassembled, account for it
2195 		 */
2196 		fragno = fragstoblks(fs, bbase);
2197 		if (ffs_isblock(fs, blksfree, fragno)) {
2198 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
2199 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2200 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2201 			ffs_clusteracct(fs, cgp, fragno, 1);
2202 			cgp->cg_cs.cs_nbfree++;
2203 			fs->fs_cstotal.cs_nbfree++;
2204 			fs->fs_cs(fs, cg).cs_nbfree++;
2205 		}
2206 	}
2207 	fs->fs_fmod = 1;
2208 	ACTIVECLEAR(fs, cg);
2209 	UFS_UNLOCK(ump);
2210 	mp = UFSTOVFS(ump);
2211 	if (MOUNTEDSOFTDEP(mp) && devvp->v_type != VREG)
2212 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2213 		    numfrags(fs, size), dephd);
2214 	bdwrite(bp);
2215 }
2216 
2217 TASKQUEUE_DEFINE_THREAD(ffs_trim);
2218 
2219 struct ffs_blkfree_trim_params {
2220 	struct task task;
2221 	struct ufsmount *ump;
2222 	struct vnode *devvp;
2223 	ufs2_daddr_t bno;
2224 	long size;
2225 	ino_t inum;
2226 	struct workhead *pdephd;
2227 	struct workhead dephd;
2228 };
2229 
2230 static void
2231 ffs_blkfree_trim_task(ctx, pending)
2232 	void *ctx;
2233 	int pending;
2234 {
2235 	struct ffs_blkfree_trim_params *tp;
2236 
2237 	tp = ctx;
2238 	ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
2239 	    tp->inum, tp->pdephd);
2240 	vn_finished_secondary_write(UFSTOVFS(tp->ump));
2241 	free(tp, M_TEMP);
2242 }
2243 
2244 static void
2245 ffs_blkfree_trim_completed(bip)
2246 	struct bio *bip;
2247 {
2248 	struct ffs_blkfree_trim_params *tp;
2249 
2250 	tp = bip->bio_caller2;
2251 	g_destroy_bio(bip);
2252 	TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2253 	taskqueue_enqueue(taskqueue_ffs_trim, &tp->task);
2254 }
2255 
2256 void
2257 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd)
2258 	struct ufsmount *ump;
2259 	struct fs *fs;
2260 	struct vnode *devvp;
2261 	ufs2_daddr_t bno;
2262 	long size;
2263 	ino_t inum;
2264 	enum vtype vtype;
2265 	struct workhead *dephd;
2266 {
2267 	struct mount *mp;
2268 	struct bio *bip;
2269 	struct ffs_blkfree_trim_params *tp;
2270 
2271 	/*
2272 	 * Check to see if a snapshot wants to claim the block.
2273 	 * Check that devvp is a normal disk device, not a snapshot,
2274 	 * it has a snapshot(s) associated with it, and one of the
2275 	 * snapshots wants to claim the block.
2276 	 */
2277 	if (devvp->v_type != VREG &&
2278 	    (devvp->v_vflag & VV_COPYONWRITE) &&
2279 	    ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2280 		return;
2281 	}
2282 	/*
2283 	 * Nothing to delay if TRIM is disabled, or the operation is
2284 	 * performed on the snapshot.
2285 	 */
2286 	if (!ump->um_candelete || devvp->v_type == VREG) {
2287 		ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2288 		return;
2289 	}
2290 
2291 	/*
2292 	 * Postpone the set of the free bit in the cg bitmap until the
2293 	 * BIO_DELETE is completed.  Otherwise, due to disk queue
2294 	 * reordering, TRIM might be issued after we reuse the block
2295 	 * and write some new data into it.
2296 	 */
2297 	tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2298 	tp->ump = ump;
2299 	tp->devvp = devvp;
2300 	tp->bno = bno;
2301 	tp->size = size;
2302 	tp->inum = inum;
2303 	if (dephd != NULL) {
2304 		LIST_INIT(&tp->dephd);
2305 		LIST_SWAP(dephd, &tp->dephd, worklist, wk_list);
2306 		tp->pdephd = &tp->dephd;
2307 	} else
2308 		tp->pdephd = NULL;
2309 
2310 	bip = g_alloc_bio();
2311 	bip->bio_cmd = BIO_DELETE;
2312 	bip->bio_offset = dbtob(fsbtodb(fs, bno));
2313 	bip->bio_done = ffs_blkfree_trim_completed;
2314 	bip->bio_length = size;
2315 	bip->bio_caller2 = tp;
2316 
2317 	mp = UFSTOVFS(ump);
2318 	vn_start_secondary_write(NULL, &mp, 0);
2319 	g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2320 }
2321 
2322 #ifdef INVARIANTS
2323 /*
2324  * Verify allocation of a block or fragment. Returns true if block or
2325  * fragment is allocated, false if it is free.
2326  */
2327 static int
2328 ffs_checkblk(ip, bno, size)
2329 	struct inode *ip;
2330 	ufs2_daddr_t bno;
2331 	long size;
2332 {
2333 	struct fs *fs;
2334 	struct cg *cgp;
2335 	struct buf *bp;
2336 	ufs1_daddr_t cgbno;
2337 	int i, error, frags, free;
2338 	u_int8_t *blksfree;
2339 
2340 	fs = ip->i_fs;
2341 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2342 		printf("bsize = %ld, size = %ld, fs = %s\n",
2343 		    (long)fs->fs_bsize, size, fs->fs_fsmnt);
2344 		panic("ffs_checkblk: bad size");
2345 	}
2346 	if ((u_int)bno >= fs->fs_size)
2347 		panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2348 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
2349 		(int)fs->fs_cgsize, NOCRED, &bp);
2350 	if (error)
2351 		panic("ffs_checkblk: cg bread failed");
2352 	cgp = (struct cg *)bp->b_data;
2353 	if (!cg_chkmagic(cgp))
2354 		panic("ffs_checkblk: cg magic mismatch");
2355 	bp->b_xflags |= BX_BKGRDWRITE;
2356 	blksfree = cg_blksfree(cgp);
2357 	cgbno = dtogd(fs, bno);
2358 	if (size == fs->fs_bsize) {
2359 		free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2360 	} else {
2361 		frags = numfrags(fs, size);
2362 		for (free = 0, i = 0; i < frags; i++)
2363 			if (isset(blksfree, cgbno + i))
2364 				free++;
2365 		if (free != 0 && free != frags)
2366 			panic("ffs_checkblk: partially free fragment");
2367 	}
2368 	brelse(bp);
2369 	return (!free);
2370 }
2371 #endif /* INVARIANTS */
2372 
2373 /*
2374  * Free an inode.
2375  */
2376 int
2377 ffs_vfree(pvp, ino, mode)
2378 	struct vnode *pvp;
2379 	ino_t ino;
2380 	int mode;
2381 {
2382 	struct inode *ip;
2383 
2384 	if (DOINGSOFTDEP(pvp)) {
2385 		softdep_freefile(pvp, ino, mode);
2386 		return (0);
2387 	}
2388 	ip = VTOI(pvp);
2389 	return (ffs_freefile(ip->i_ump, ip->i_fs, ip->i_devvp, ino, mode,
2390 	    NULL));
2391 }
2392 
2393 /*
2394  * Do the actual free operation.
2395  * The specified inode is placed back in the free map.
2396  */
2397 int
2398 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2399 	struct ufsmount *ump;
2400 	struct fs *fs;
2401 	struct vnode *devvp;
2402 	ino_t ino;
2403 	int mode;
2404 	struct workhead *wkhd;
2405 {
2406 	struct cg *cgp;
2407 	struct buf *bp;
2408 	ufs2_daddr_t cgbno;
2409 	int error;
2410 	u_int cg;
2411 	u_int8_t *inosused;
2412 	struct cdev *dev;
2413 
2414 	cg = ino_to_cg(fs, ino);
2415 	if (devvp->v_type == VREG) {
2416 		/* devvp is a snapshot */
2417 		dev = VTOI(devvp)->i_devvp->v_rdev;
2418 		cgbno = fragstoblks(fs, cgtod(fs, cg));
2419 	} else {
2420 		/* devvp is a normal disk device */
2421 		dev = devvp->v_rdev;
2422 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2423 	}
2424 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2425 		panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2426 		    devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2427 	if ((error = bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp))) {
2428 		brelse(bp);
2429 		return (error);
2430 	}
2431 	cgp = (struct cg *)bp->b_data;
2432 	if (!cg_chkmagic(cgp)) {
2433 		brelse(bp);
2434 		return (0);
2435 	}
2436 	bp->b_xflags |= BX_BKGRDWRITE;
2437 	cgp->cg_old_time = cgp->cg_time = time_second;
2438 	inosused = cg_inosused(cgp);
2439 	ino %= fs->fs_ipg;
2440 	if (isclr(inosused, ino)) {
2441 		printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2442 		    (uintmax_t)(ino + cg * fs->fs_ipg), fs->fs_fsmnt);
2443 		if (fs->fs_ronly == 0)
2444 			panic("ffs_freefile: freeing free inode");
2445 	}
2446 	clrbit(inosused, ino);
2447 	if (ino < cgp->cg_irotor)
2448 		cgp->cg_irotor = ino;
2449 	cgp->cg_cs.cs_nifree++;
2450 	UFS_LOCK(ump);
2451 	fs->fs_cstotal.cs_nifree++;
2452 	fs->fs_cs(fs, cg).cs_nifree++;
2453 	if ((mode & IFMT) == IFDIR) {
2454 		cgp->cg_cs.cs_ndir--;
2455 		fs->fs_cstotal.cs_ndir--;
2456 		fs->fs_cs(fs, cg).cs_ndir--;
2457 	}
2458 	fs->fs_fmod = 1;
2459 	ACTIVECLEAR(fs, cg);
2460 	UFS_UNLOCK(ump);
2461 	if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type != VREG)
2462 		softdep_setup_inofree(UFSTOVFS(ump), bp,
2463 		    ino + cg * fs->fs_ipg, wkhd);
2464 	bdwrite(bp);
2465 	return (0);
2466 }
2467 
2468 /*
2469  * Check to see if a file is free.
2470  */
2471 int
2472 ffs_checkfreefile(fs, devvp, ino)
2473 	struct fs *fs;
2474 	struct vnode *devvp;
2475 	ino_t ino;
2476 {
2477 	struct cg *cgp;
2478 	struct buf *bp;
2479 	ufs2_daddr_t cgbno;
2480 	int ret;
2481 	u_int cg;
2482 	u_int8_t *inosused;
2483 
2484 	cg = ino_to_cg(fs, ino);
2485 	if (devvp->v_type == VREG) {
2486 		/* devvp is a snapshot */
2487 		cgbno = fragstoblks(fs, cgtod(fs, cg));
2488 	} else {
2489 		/* devvp is a normal disk device */
2490 		cgbno = fsbtodb(fs, cgtod(fs, cg));
2491 	}
2492 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2493 		return (1);
2494 	if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2495 		brelse(bp);
2496 		return (1);
2497 	}
2498 	cgp = (struct cg *)bp->b_data;
2499 	if (!cg_chkmagic(cgp)) {
2500 		brelse(bp);
2501 		return (1);
2502 	}
2503 	inosused = cg_inosused(cgp);
2504 	ino %= fs->fs_ipg;
2505 	ret = isclr(inosused, ino);
2506 	brelse(bp);
2507 	return (ret);
2508 }
2509 
2510 /*
2511  * Find a block of the specified size in the specified cylinder group.
2512  *
2513  * It is a panic if a request is made to find a block if none are
2514  * available.
2515  */
2516 static ufs1_daddr_t
2517 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2518 	struct fs *fs;
2519 	struct cg *cgp;
2520 	ufs2_daddr_t bpref;
2521 	int allocsiz;
2522 {
2523 	ufs1_daddr_t bno;
2524 	int start, len, loc, i;
2525 	int blk, field, subfield, pos;
2526 	u_int8_t *blksfree;
2527 
2528 	/*
2529 	 * find the fragment by searching through the free block
2530 	 * map for an appropriate bit pattern
2531 	 */
2532 	if (bpref)
2533 		start = dtogd(fs, bpref) / NBBY;
2534 	else
2535 		start = cgp->cg_frotor / NBBY;
2536 	blksfree = cg_blksfree(cgp);
2537 	len = howmany(fs->fs_fpg, NBBY) - start;
2538 	loc = scanc((u_int)len, (u_char *)&blksfree[start],
2539 		fragtbl[fs->fs_frag],
2540 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2541 	if (loc == 0) {
2542 		len = start + 1;
2543 		start = 0;
2544 		loc = scanc((u_int)len, (u_char *)&blksfree[0],
2545 			fragtbl[fs->fs_frag],
2546 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2547 		if (loc == 0) {
2548 			printf("start = %d, len = %d, fs = %s\n",
2549 			    start, len, fs->fs_fsmnt);
2550 			panic("ffs_alloccg: map corrupted");
2551 			/* NOTREACHED */
2552 		}
2553 	}
2554 	bno = (start + len - loc) * NBBY;
2555 	cgp->cg_frotor = bno;
2556 	/*
2557 	 * found the byte in the map
2558 	 * sift through the bits to find the selected frag
2559 	 */
2560 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2561 		blk = blkmap(fs, blksfree, bno);
2562 		blk <<= 1;
2563 		field = around[allocsiz];
2564 		subfield = inside[allocsiz];
2565 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2566 			if ((blk & field) == subfield)
2567 				return (bno + pos);
2568 			field <<= 1;
2569 			subfield <<= 1;
2570 		}
2571 	}
2572 	printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2573 	panic("ffs_alloccg: block not in map");
2574 	return (-1);
2575 }
2576 
2577 /*
2578  * Fserr prints the name of a filesystem with an error diagnostic.
2579  *
2580  * The form of the error message is:
2581  *	fs: error message
2582  */
2583 void
2584 ffs_fserr(fs, inum, cp)
2585 	struct fs *fs;
2586 	ino_t inum;
2587 	char *cp;
2588 {
2589 	struct thread *td = curthread;	/* XXX */
2590 	struct proc *p = td->td_proc;
2591 
2592 	log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
2593 	    p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
2594 	    fs->fs_fsmnt, cp);
2595 }
2596 
2597 /*
2598  * This function provides the capability for the fsck program to
2599  * update an active filesystem. Fourteen operations are provided:
2600  *
2601  * adjrefcnt(inode, amt) - adjusts the reference count on the
2602  *	specified inode by the specified amount. Under normal
2603  *	operation the count should always go down. Decrementing
2604  *	the count to zero will cause the inode to be freed.
2605  * adjblkcnt(inode, amt) - adjust the number of blocks used by the
2606  *	inode by the specified amount.
2607  * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2608  *	adjust the superblock summary.
2609  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2610  *	are marked as free. Inodes should never have to be marked
2611  *	as in use.
2612  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2613  *	are marked as free. Inodes should never have to be marked
2614  *	as in use.
2615  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2616  *	are marked as free. Blocks should never have to be marked
2617  *	as in use.
2618  * setflags(flags, set/clear) - the fs_flags field has the specified
2619  *	flags set (second parameter +1) or cleared (second parameter -1).
2620  * setcwd(dirinode) - set the current directory to dirinode in the
2621  *	filesystem associated with the snapshot.
2622  * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
2623  *	in the current directory is oldvalue then change it to newvalue.
2624  * unlink(nameptr, oldvalue) - Verify that the inode number associated
2625  *	with nameptr in the current directory is oldvalue then unlink it.
2626  *
2627  * The following functions may only be used on a quiescent filesystem
2628  * by the soft updates journal. They are not safe to be run on an active
2629  * filesystem.
2630  *
2631  * setinode(inode, dip) - the specified disk inode is replaced with the
2632  *	contents pointed to by dip.
2633  * setbufoutput(fd, flags) - output associated with the specified file
2634  *	descriptor (which must reference the character device supporting
2635  *	the filesystem) switches from using physio to running through the
2636  *	buffer cache when flags is set to 1. The descriptor reverts to
2637  *	physio for output when flags is set to zero.
2638  */
2639 
2640 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2641 
2642 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2643 	0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2644 
2645 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2646 	sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2647 
2648 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2649 	sysctl_ffs_fsck, "Adjust number of directories");
2650 
2651 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2652 	sysctl_ffs_fsck, "Adjust number of free blocks");
2653 
2654 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2655 	sysctl_ffs_fsck, "Adjust number of free inodes");
2656 
2657 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2658 	sysctl_ffs_fsck, "Adjust number of free frags");
2659 
2660 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2661 	sysctl_ffs_fsck, "Adjust number of free clusters");
2662 
2663 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2664 	sysctl_ffs_fsck, "Free Range of Directory Inodes");
2665 
2666 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2667 	sysctl_ffs_fsck, "Free Range of File Inodes");
2668 
2669 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2670 	sysctl_ffs_fsck, "Free Range of Blocks");
2671 
2672 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2673 	sysctl_ffs_fsck, "Change Filesystem Flags");
2674 
2675 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd, CTLFLAG_WR,
2676 	sysctl_ffs_fsck, "Set Current Working Directory");
2677 
2678 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot, CTLFLAG_WR,
2679 	sysctl_ffs_fsck, "Change Value of .. Entry");
2680 
2681 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink, CTLFLAG_WR,
2682 	sysctl_ffs_fsck, "Unlink a Duplicate Name");
2683 
2684 static SYSCTL_NODE(_vfs_ffs, FFS_SET_INODE, setinode, CTLFLAG_WR,
2685 	sysctl_ffs_fsck, "Update an On-Disk Inode");
2686 
2687 static SYSCTL_NODE(_vfs_ffs, FFS_SET_BUFOUTPUT, setbufoutput, CTLFLAG_WR,
2688 	sysctl_ffs_fsck, "Set Buffered Writing for Descriptor");
2689 
2690 #define DEBUG 1
2691 #ifdef DEBUG
2692 static int fsckcmds = 0;
2693 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2694 #endif /* DEBUG */
2695 
2696 static int buffered_write(struct file *, struct uio *, struct ucred *,
2697 	int, struct thread *);
2698 
2699 static int
2700 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2701 {
2702 	struct thread *td = curthread;
2703 	struct fsck_cmd cmd;
2704 	struct ufsmount *ump;
2705 	struct vnode *vp, *vpold, *dvp, *fdvp;
2706 	struct inode *ip, *dp;
2707 	struct mount *mp;
2708 	struct fs *fs;
2709 	ufs2_daddr_t blkno;
2710 	long blkcnt, blksize;
2711 	struct filedesc *fdp;
2712 	struct file *fp, *vfp;
2713 	cap_rights_t rights;
2714 	int filetype, error;
2715 	static struct fileops *origops, bufferedops;
2716 
2717 	if (req->newlen > sizeof cmd)
2718 		return (EBADRPC);
2719 	if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2720 		return (error);
2721 	if (cmd.version != FFS_CMD_VERSION)
2722 		return (ERPCMISMATCH);
2723 	if ((error = getvnode(td->td_proc->p_fd, cmd.handle,
2724 	    cap_rights_init(&rights, CAP_FSCK), &fp)) != 0)
2725 		return (error);
2726 	vp = fp->f_data;
2727 	if (vp->v_type != VREG && vp->v_type != VDIR) {
2728 		fdrop(fp, td);
2729 		return (EINVAL);
2730 	}
2731 	vn_start_write(vp, &mp, V_WAIT);
2732 	if (mp == 0 || strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2733 		vn_finished_write(mp);
2734 		fdrop(fp, td);
2735 		return (EINVAL);
2736 	}
2737 	ump = VFSTOUFS(mp);
2738 	if ((mp->mnt_flag & MNT_RDONLY) &&
2739 	    ump->um_fsckpid != td->td_proc->p_pid) {
2740 		vn_finished_write(mp);
2741 		fdrop(fp, td);
2742 		return (EROFS);
2743 	}
2744 	fs = ump->um_fs;
2745 	filetype = IFREG;
2746 
2747 	switch (oidp->oid_number) {
2748 
2749 	case FFS_SET_FLAGS:
2750 #ifdef DEBUG
2751 		if (fsckcmds)
2752 			printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2753 			    cmd.size > 0 ? "set" : "clear");
2754 #endif /* DEBUG */
2755 		if (cmd.size > 0)
2756 			fs->fs_flags |= (long)cmd.value;
2757 		else
2758 			fs->fs_flags &= ~(long)cmd.value;
2759 		break;
2760 
2761 	case FFS_ADJ_REFCNT:
2762 #ifdef DEBUG
2763 		if (fsckcmds) {
2764 			printf("%s: adjust inode %jd link count by %jd\n",
2765 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2766 			    (intmax_t)cmd.size);
2767 		}
2768 #endif /* DEBUG */
2769 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2770 			break;
2771 		ip = VTOI(vp);
2772 		ip->i_nlink += cmd.size;
2773 		DIP_SET(ip, i_nlink, ip->i_nlink);
2774 		ip->i_effnlink += cmd.size;
2775 		ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2776 		error = ffs_update(vp, 1);
2777 		if (DOINGSOFTDEP(vp))
2778 			softdep_change_linkcnt(ip);
2779 		vput(vp);
2780 		break;
2781 
2782 	case FFS_ADJ_BLKCNT:
2783 #ifdef DEBUG
2784 		if (fsckcmds) {
2785 			printf("%s: adjust inode %jd block count by %jd\n",
2786 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2787 			    (intmax_t)cmd.size);
2788 		}
2789 #endif /* DEBUG */
2790 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2791 			break;
2792 		ip = VTOI(vp);
2793 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2794 		ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2795 		error = ffs_update(vp, 1);
2796 		vput(vp);
2797 		break;
2798 
2799 	case FFS_DIR_FREE:
2800 		filetype = IFDIR;
2801 		/* fall through */
2802 
2803 	case FFS_FILE_FREE:
2804 #ifdef DEBUG
2805 		if (fsckcmds) {
2806 			if (cmd.size == 1)
2807 				printf("%s: free %s inode %ju\n",
2808 				    mp->mnt_stat.f_mntonname,
2809 				    filetype == IFDIR ? "directory" : "file",
2810 				    (uintmax_t)cmd.value);
2811 			else
2812 				printf("%s: free %s inodes %ju-%ju\n",
2813 				    mp->mnt_stat.f_mntonname,
2814 				    filetype == IFDIR ? "directory" : "file",
2815 				    (uintmax_t)cmd.value,
2816 				    (uintmax_t)(cmd.value + cmd.size - 1));
2817 		}
2818 #endif /* DEBUG */
2819 		while (cmd.size > 0) {
2820 			if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2821 			    cmd.value, filetype, NULL)))
2822 				break;
2823 			cmd.size -= 1;
2824 			cmd.value += 1;
2825 		}
2826 		break;
2827 
2828 	case FFS_BLK_FREE:
2829 #ifdef DEBUG
2830 		if (fsckcmds) {
2831 			if (cmd.size == 1)
2832 				printf("%s: free block %jd\n",
2833 				    mp->mnt_stat.f_mntonname,
2834 				    (intmax_t)cmd.value);
2835 			else
2836 				printf("%s: free blocks %jd-%jd\n",
2837 				    mp->mnt_stat.f_mntonname,
2838 				    (intmax_t)cmd.value,
2839 				    (intmax_t)cmd.value + cmd.size - 1);
2840 		}
2841 #endif /* DEBUG */
2842 		blkno = cmd.value;
2843 		blkcnt = cmd.size;
2844 		blksize = fs->fs_frag - (blkno % fs->fs_frag);
2845 		while (blkcnt > 0) {
2846 			if (blksize > blkcnt)
2847 				blksize = blkcnt;
2848 			ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2849 			    blksize * fs->fs_fsize, ROOTINO, VDIR, NULL);
2850 			blkno += blksize;
2851 			blkcnt -= blksize;
2852 			blksize = fs->fs_frag;
2853 		}
2854 		break;
2855 
2856 	/*
2857 	 * Adjust superblock summaries.  fsck(8) is expected to
2858 	 * submit deltas when necessary.
2859 	 */
2860 	case FFS_ADJ_NDIR:
2861 #ifdef DEBUG
2862 		if (fsckcmds) {
2863 			printf("%s: adjust number of directories by %jd\n",
2864 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2865 		}
2866 #endif /* DEBUG */
2867 		fs->fs_cstotal.cs_ndir += cmd.value;
2868 		break;
2869 
2870 	case FFS_ADJ_NBFREE:
2871 #ifdef DEBUG
2872 		if (fsckcmds) {
2873 			printf("%s: adjust number of free blocks by %+jd\n",
2874 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2875 		}
2876 #endif /* DEBUG */
2877 		fs->fs_cstotal.cs_nbfree += cmd.value;
2878 		break;
2879 
2880 	case FFS_ADJ_NIFREE:
2881 #ifdef DEBUG
2882 		if (fsckcmds) {
2883 			printf("%s: adjust number of free inodes by %+jd\n",
2884 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2885 		}
2886 #endif /* DEBUG */
2887 		fs->fs_cstotal.cs_nifree += cmd.value;
2888 		break;
2889 
2890 	case FFS_ADJ_NFFREE:
2891 #ifdef DEBUG
2892 		if (fsckcmds) {
2893 			printf("%s: adjust number of free frags by %+jd\n",
2894 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2895 		}
2896 #endif /* DEBUG */
2897 		fs->fs_cstotal.cs_nffree += cmd.value;
2898 		break;
2899 
2900 	case FFS_ADJ_NUMCLUSTERS:
2901 #ifdef DEBUG
2902 		if (fsckcmds) {
2903 			printf("%s: adjust number of free clusters by %+jd\n",
2904 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2905 		}
2906 #endif /* DEBUG */
2907 		fs->fs_cstotal.cs_numclusters += cmd.value;
2908 		break;
2909 
2910 	case FFS_SET_CWD:
2911 #ifdef DEBUG
2912 		if (fsckcmds) {
2913 			printf("%s: set current directory to inode %jd\n",
2914 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2915 		}
2916 #endif /* DEBUG */
2917 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
2918 			break;
2919 		AUDIT_ARG_VNODE1(vp);
2920 		if ((error = change_dir(vp, td)) != 0) {
2921 			vput(vp);
2922 			break;
2923 		}
2924 		VOP_UNLOCK(vp, 0);
2925 		fdp = td->td_proc->p_fd;
2926 		FILEDESC_XLOCK(fdp);
2927 		vpold = fdp->fd_cdir;
2928 		fdp->fd_cdir = vp;
2929 		FILEDESC_XUNLOCK(fdp);
2930 		vrele(vpold);
2931 		break;
2932 
2933 	case FFS_SET_DOTDOT:
2934 #ifdef DEBUG
2935 		if (fsckcmds) {
2936 			printf("%s: change .. in cwd from %jd to %jd\n",
2937 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2938 			    (intmax_t)cmd.size);
2939 		}
2940 #endif /* DEBUG */
2941 		/*
2942 		 * First we have to get and lock the parent directory
2943 		 * to which ".." points.
2944 		 */
2945 		error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
2946 		if (error)
2947 			break;
2948 		/*
2949 		 * Now we get and lock the child directory containing "..".
2950 		 */
2951 		FILEDESC_SLOCK(td->td_proc->p_fd);
2952 		dvp = td->td_proc->p_fd->fd_cdir;
2953 		FILEDESC_SUNLOCK(td->td_proc->p_fd);
2954 		if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
2955 			vput(fdvp);
2956 			break;
2957 		}
2958 		dp = VTOI(dvp);
2959 		dp->i_offset = 12;	/* XXX mastertemplate.dot_reclen */
2960 		error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
2961 		    DT_DIR, 0);
2962 		cache_purge(fdvp);
2963 		cache_purge(dvp);
2964 		vput(dvp);
2965 		vput(fdvp);
2966 		break;
2967 
2968 	case FFS_UNLINK:
2969 #ifdef DEBUG
2970 		if (fsckcmds) {
2971 			char buf[32];
2972 
2973 			if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
2974 				strncpy(buf, "Name_too_long", 32);
2975 			printf("%s: unlink %s (inode %jd)\n",
2976 			    mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
2977 		}
2978 #endif /* DEBUG */
2979 		/*
2980 		 * kern_unlinkat will do its own start/finish writes and
2981 		 * they do not nest, so drop ours here. Setting mp == NULL
2982 		 * indicates that vn_finished_write is not needed down below.
2983 		 */
2984 		vn_finished_write(mp);
2985 		mp = NULL;
2986 		error = kern_unlinkat(td, AT_FDCWD, (char *)(intptr_t)cmd.value,
2987 		    UIO_USERSPACE, (ino_t)cmd.size);
2988 		break;
2989 
2990 	case FFS_SET_INODE:
2991 		if (ump->um_fsckpid != td->td_proc->p_pid) {
2992 			error = EPERM;
2993 			break;
2994 		}
2995 #ifdef DEBUG
2996 		if (fsckcmds) {
2997 			printf("%s: update inode %jd\n",
2998 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2999 		}
3000 #endif /* DEBUG */
3001 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3002 			break;
3003 		AUDIT_ARG_VNODE1(vp);
3004 		ip = VTOI(vp);
3005 		if (ip->i_ump->um_fstype == UFS1)
3006 			error = copyin((void *)(intptr_t)cmd.size, ip->i_din1,
3007 			    sizeof(struct ufs1_dinode));
3008 		else
3009 			error = copyin((void *)(intptr_t)cmd.size, ip->i_din2,
3010 			    sizeof(struct ufs2_dinode));
3011 		if (error) {
3012 			vput(vp);
3013 			break;
3014 		}
3015 		ip->i_flag |= IN_CHANGE | IN_MODIFIED;
3016 		error = ffs_update(vp, 1);
3017 		vput(vp);
3018 		break;
3019 
3020 	case FFS_SET_BUFOUTPUT:
3021 		if (ump->um_fsckpid != td->td_proc->p_pid) {
3022 			error = EPERM;
3023 			break;
3024 		}
3025 		if (VTOI(vp)->i_ump != ump) {
3026 			error = EINVAL;
3027 			break;
3028 		}
3029 #ifdef DEBUG
3030 		if (fsckcmds) {
3031 			printf("%s: %s buffered output for descriptor %jd\n",
3032 			    mp->mnt_stat.f_mntonname,
3033 			    cmd.size == 1 ? "enable" : "disable",
3034 			    (intmax_t)cmd.value);
3035 		}
3036 #endif /* DEBUG */
3037 		if ((error = getvnode(td->td_proc->p_fd, cmd.value,
3038 		    cap_rights_init(&rights, CAP_FSCK), &vfp)) != 0)
3039 			break;
3040 		if (vfp->f_vnode->v_type != VCHR) {
3041 			fdrop(vfp, td);
3042 			error = EINVAL;
3043 			break;
3044 		}
3045 		if (origops == NULL) {
3046 			origops = vfp->f_ops;
3047 			bcopy((void *)origops, (void *)&bufferedops,
3048 			    sizeof(bufferedops));
3049 			bufferedops.fo_write = buffered_write;
3050 		}
3051 		if (cmd.size == 1)
3052 			atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3053 			    (uintptr_t)&bufferedops);
3054 		else
3055 			atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3056 			    (uintptr_t)origops);
3057 		fdrop(vfp, td);
3058 		break;
3059 
3060 	default:
3061 #ifdef DEBUG
3062 		if (fsckcmds) {
3063 			printf("Invalid request %d from fsck\n",
3064 			    oidp->oid_number);
3065 		}
3066 #endif /* DEBUG */
3067 		error = EINVAL;
3068 		break;
3069 
3070 	}
3071 	fdrop(fp, td);
3072 	vn_finished_write(mp);
3073 	return (error);
3074 }
3075 
3076 /*
3077  * Function to switch a descriptor to use the buffer cache to stage
3078  * its I/O. This is needed so that writes to the filesystem device
3079  * will give snapshots a chance to copy modified blocks for which it
3080  * needs to retain copies.
3081  */
3082 static int
3083 buffered_write(fp, uio, active_cred, flags, td)
3084 	struct file *fp;
3085 	struct uio *uio;
3086 	struct ucred *active_cred;
3087 	int flags;
3088 	struct thread *td;
3089 {
3090 	struct vnode *devvp, *vp;
3091 	struct inode *ip;
3092 	struct buf *bp;
3093 	struct fs *fs;
3094 	struct filedesc *fdp;
3095 	int error;
3096 	daddr_t lbn;
3097 
3098 	/*
3099 	 * The devvp is associated with the /dev filesystem. To discover
3100 	 * the filesystem with which the device is associated, we depend
3101 	 * on the application setting the current directory to a location
3102 	 * within the filesystem being written. Yes, this is an ugly hack.
3103 	 */
3104 	devvp = fp->f_vnode;
3105 	if (!vn_isdisk(devvp, NULL))
3106 		return (EINVAL);
3107 	fdp = td->td_proc->p_fd;
3108 	FILEDESC_SLOCK(fdp);
3109 	vp = fdp->fd_cdir;
3110 	vref(vp);
3111 	FILEDESC_SUNLOCK(fdp);
3112 	vn_lock(vp, LK_SHARED | LK_RETRY);
3113 	/*
3114 	 * Check that the current directory vnode indeed belongs to
3115 	 * UFS before trying to dereference UFS-specific v_data fields.
3116 	 */
3117 	if (vp->v_op != &ffs_vnodeops1 && vp->v_op != &ffs_vnodeops2) {
3118 		vput(vp);
3119 		return (EINVAL);
3120 	}
3121 	ip = VTOI(vp);
3122 	if (ip->i_devvp != devvp) {
3123 		vput(vp);
3124 		return (EINVAL);
3125 	}
3126 	fs = ip->i_fs;
3127 	vput(vp);
3128 	foffset_lock_uio(fp, uio, flags);
3129 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
3130 #ifdef DEBUG
3131 	if (fsckcmds) {
3132 		printf("%s: buffered write for block %jd\n",
3133 		    fs->fs_fsmnt, (intmax_t)btodb(uio->uio_offset));
3134 	}
3135 #endif /* DEBUG */
3136 	/*
3137 	 * All I/O must be contained within a filesystem block, start on
3138 	 * a fragment boundary, and be a multiple of fragments in length.
3139 	 */
3140 	if (uio->uio_resid > fs->fs_bsize - (uio->uio_offset % fs->fs_bsize) ||
3141 	    fragoff(fs, uio->uio_offset) != 0 ||
3142 	    fragoff(fs, uio->uio_resid) != 0) {
3143 		error = EINVAL;
3144 		goto out;
3145 	}
3146 	lbn = numfrags(fs, uio->uio_offset);
3147 	bp = getblk(devvp, lbn, uio->uio_resid, 0, 0, 0);
3148 	bp->b_flags |= B_RELBUF;
3149 	if ((error = uiomove((char *)bp->b_data, uio->uio_resid, uio)) != 0) {
3150 		brelse(bp);
3151 		goto out;
3152 	}
3153 	error = bwrite(bp);
3154 out:
3155 	VOP_UNLOCK(devvp, 0);
3156 	foffset_unlock_uio(fp, uio, flags | FOF_NEXTOFF);
3157 	return (error);
3158 }
3159