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