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