2 * SPDX-License-Identifier: (BSD-2-Clause-FreeBSD AND BSD-3-Clause)
4 * Copyright (c) 2002 Networks Associates Technology, Inc.
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
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
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.
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
34 * Copyright (c) 1982, 1986, 1989, 1993
35 * The Regents of the University of California. All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
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.
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
61 * @(#)ffs_alloc.c 8.18 (Berkeley) 5/26/95
64 #include <sys/cdefs.h>
65 __FBSDID("$FreeBSD$");
67 #include "opt_quota.h"
69 #include <sys/param.h>
70 #include <sys/capsicum.h>
71 #include <sys/gsb_crc32.h>
72 #include <sys/systm.h>
76 #include <sys/fcntl.h>
78 #include <sys/filedesc.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>
89 #include <security/audit/audit.h>
91 #include <geom/geom.h>
92 #include <geom/geom_vfs.h>
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>
101 #include <ufs/ffs/fs.h>
102 #include <ufs/ffs/ffs_extern.h>
103 #include <ufs/ffs/softdep.h>
105 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
106 int size, int rsize);
108 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
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,
115 static int ffs_checkblk(struct inode *, ufs2_daddr_t, long);
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,
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,
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 *);
131 * Allocate a block in the filesystem.
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) quadradically 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) quadradically rehash into other cylinder groups, until an
147 * available block is located.
150 ffs_alloc(ip, lbn, bpref, size, flags, cred, bnp)
152 ufs2_daddr_t lbn, bpref;
158 struct ufsmount *ump;
169 mtx_assert(UFS_MTX(ump), MA_OWNED);
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,
175 panic("ffs_alloc: bad size");
178 panic("ffs_alloc: missing credential");
179 #endif /* INVARIANTS */
184 error = chkdq(ip, btodb(size), cred, 0);
189 if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
191 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
192 freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
194 if (bpref >= fs->fs_size)
197 cg = ino_to_cg(fs, ip->i_number);
199 cg = dtog(fs, bpref);
200 bno = ffs_hashalloc(ip, cg, bpref, size, size, ffs_alloccg);
203 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
205 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
207 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
215 * Restore user's disk quota because allocation failed.
217 (void) chkdq(ip, -btodb(size), cred, FORCE);
220 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
222 softdep_request_cleanup(fs, ITOV(ip), cred, FLUSH_BLOCKS_WAIT);
225 if (ffs_fsfail_cleanup_locked(ump, 0)) {
230 ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
232 ffs_fserr(fs, ip->i_number, "filesystem full");
233 uprintf("\n%s: write failed, filesystem is full\n",
242 * Reallocate a fragment to a bigger size
244 * The number and size of the old block is given, and a preference
245 * and new size is also specified. The allocator attempts to extend
246 * the original block. Failing that, the regular block allocator is
247 * invoked to get an appropriate block.
250 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
255 int osize, nsize, flags;
262 struct ufsmount *ump;
263 u_int cg, request, reclaimed;
272 gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
274 mtx_assert(UFS_MTX(ump), MA_OWNED);
276 if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
277 panic("ffs_realloccg: allocation on suspended filesystem");
278 if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
279 (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
281 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
282 devtoname(ump->um_dev), (long)fs->fs_bsize, osize,
283 nsize, fs->fs_fsmnt);
284 panic("ffs_realloccg: bad size");
287 panic("ffs_realloccg: missing credential");
288 #endif /* INVARIANTS */
291 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
292 freespace(fs, fs->fs_minfree) - numfrags(fs, nsize - osize) < 0) {
296 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
297 devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
299 panic("ffs_realloccg: bad bprev");
303 * Allocate the extra space in the buffer.
305 error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
310 if (bp->b_blkno == bp->b_lblkno) {
311 if (lbprev >= UFS_NDADDR)
312 panic("ffs_realloccg: lbprev out of range");
313 bp->b_blkno = fsbtodb(fs, bprev);
317 error = chkdq(ip, btodb(nsize - osize), cred, 0);
324 * Check for extension in the existing location.
327 cg = dtog(fs, bprev);
329 bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
331 if (bp->b_blkno != fsbtodb(fs, bno))
332 panic("ffs_realloccg: bad blockno");
333 delta = btodb(nsize - osize);
334 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
336 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
338 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
340 bp->b_flags |= B_DONE;
341 vfs_bio_bzero_buf(bp, osize, nsize - osize);
342 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
343 vfs_bio_set_valid(bp, osize, nsize - osize);
348 * Allocate a new disk location.
350 if (bpref >= fs->fs_size)
352 switch ((int)fs->fs_optim) {
355 * Allocate an exact sized fragment. Although this makes
356 * best use of space, we will waste time relocating it if
357 * the file continues to grow. If the fragmentation is
358 * less than half of the minimum free reserve, we choose
359 * to begin optimizing for time.
362 if (fs->fs_minfree <= 5 ||
363 fs->fs_cstotal.cs_nffree >
364 (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
366 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
368 fs->fs_optim = FS_OPTTIME;
372 * At this point we have discovered a file that is trying to
373 * grow a small fragment to a larger fragment. To save time,
374 * we allocate a full sized block, then free the unused portion.
375 * If the file continues to grow, the `ffs_fragextend' call
376 * above will be able to grow it in place without further
377 * copying. If aberrant programs cause disk fragmentation to
378 * grow within 2% of the free reserve, we choose to begin
379 * optimizing for space.
381 request = fs->fs_bsize;
382 if (fs->fs_cstotal.cs_nffree <
383 (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
385 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
387 fs->fs_optim = FS_OPTSPACE;
390 printf("dev = %s, optim = %ld, fs = %s\n",
391 devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
392 panic("ffs_realloccg: bad optim");
395 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
397 bp->b_blkno = fsbtodb(fs, bno);
398 if (!DOINGSOFTDEP(vp))
400 * The usual case is that a smaller fragment that
401 * was just allocated has been replaced with a bigger
402 * fragment or a full-size block. If it is marked as
403 * B_DELWRI, the current contents have not been written
404 * to disk. It is possible that the block was written
405 * earlier, but very uncommon. If the block has never
406 * been written, there is no need to send a BIO_DELETE
407 * for it when it is freed. The gain from avoiding the
408 * TRIMs for the common case of unwritten blocks far
409 * exceeds the cost of the write amplification for the
410 * uncommon case of failing to send a TRIM for a block
411 * that had been written.
413 ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
414 ip->i_number, vp->v_type, NULL,
415 (bp->b_flags & B_DELWRI) != 0 ?
416 NOTRIM_KEY : SINGLETON_KEY);
417 delta = btodb(nsize - osize);
418 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
420 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
422 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
424 bp->b_flags |= B_DONE;
425 vfs_bio_bzero_buf(bp, osize, nsize - osize);
426 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
427 vfs_bio_set_valid(bp, osize, nsize - osize);
434 * Restore user's disk quota because allocation failed.
436 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
443 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
451 softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
456 if (ffs_fsfail_cleanup_locked(ump, 0)) {
461 ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
463 ffs_fserr(fs, ip->i_number, "filesystem full");
464 uprintf("\n%s: write failed, filesystem is full\n",
473 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
475 * The vnode and an array of buffer pointers for a range of sequential
476 * logical blocks to be made contiguous is given. The allocator attempts
477 * to find a range of sequential blocks starting as close as possible
478 * from the end of the allocation for the logical block immediately
479 * preceding the current range. If successful, the physical block numbers
480 * in the buffer pointers and in the inode are changed to reflect the new
481 * allocation. If unsuccessful, the allocation is left unchanged. The
482 * success in doing the reallocation is returned. Note that the error
483 * return is not reflected back to the user. Rather the previous block
484 * allocation will be used.
487 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
490 static int doasyncfree = 1;
491 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
492 "do not force synchronous writes when blocks are reallocated");
494 static int doreallocblks = 1;
495 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
496 "enable block reallocation");
498 static int dotrimcons = 1;
499 SYSCTL_INT(_vfs_ffs, OID_AUTO, dotrimcons, CTLFLAG_RWTUN, &dotrimcons, 0,
500 "enable BIO_DELETE / TRIM consolidation");
502 static int maxclustersearch = 10;
503 SYSCTL_INT(_vfs_ffs, OID_AUTO, maxclustersearch, CTLFLAG_RW, &maxclustersearch,
504 0, "max number of cylinder group to search for contigous blocks");
507 static int prtrealloc = 0;
508 SYSCTL_INT(_debug, OID_AUTO, ffs_prtrealloc, CTLFLAG_RW, &prtrealloc, 0,
509 "print out FFS filesystem block reallocation operations");
514 struct vop_reallocblks_args /* {
516 struct cluster_save *a_buflist;
519 struct ufsmount *ump;
522 * We used to skip reallocating the blocks of a file into a
523 * contiguous sequence if the underlying flash device requested
524 * BIO_DELETE notifications, because devices that benefit from
525 * BIO_DELETE also benefit from not moving the data. However,
526 * the destination for the data is usually moved before the data
527 * is written to the initially allocated location, so we rarely
528 * suffer the penalty of extra writes. With the addition of the
529 * consolidation of contiguous blocks into single BIO_DELETE
530 * operations, having fewer but larger contiguous blocks reduces
531 * the number of (slow and expensive) BIO_DELETE operations. So
532 * when doing BIO_DELETE consolidation, we do block reallocation.
534 * Skip if reallocblks has been disabled globally.
536 ump = ap->a_vp->v_mount->mnt_data;
537 if ((((ump->um_flags) & UM_CANDELETE) != 0 && dotrimcons == 0) ||
542 * We can't wait in softdep prealloc as it may fsync and recurse
543 * here. Instead we simply fail to reallocate blocks if this
544 * rare condition arises.
546 if (DOINGSOFTDEP(ap->a_vp))
547 if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
549 if (ump->um_fstype == UFS1)
550 return (ffs_reallocblks_ufs1(ap));
551 return (ffs_reallocblks_ufs2(ap));
555 ffs_reallocblks_ufs1(ap)
556 struct vop_reallocblks_args /* {
558 struct cluster_save *a_buflist;
564 struct buf *sbp, *ebp, *bp;
565 ufs1_daddr_t *bap, *sbap, *ebap;
566 struct cluster_save *buflist;
567 struct ufsmount *ump;
568 ufs_lbn_t start_lbn, end_lbn;
569 ufs1_daddr_t soff, newblk, blkno;
571 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
572 int i, cg, len, start_lvl, end_lvl, ssize;
579 * If we are not tracking block clusters or if we have less than 4%
580 * free blocks left, then do not attempt to cluster. Running with
581 * less than 5% free block reserve is not recommended and those that
582 * choose to do so do not expect to have good file layout.
584 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
586 buflist = ap->a_buflist;
587 len = buflist->bs_nchildren;
588 start_lbn = buflist->bs_children[0]->b_lblkno;
589 end_lbn = start_lbn + len - 1;
591 for (i = 0; i < len; i++)
592 if (!ffs_checkblk(ip,
593 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
594 panic("ffs_reallocblks: unallocated block 1");
595 for (i = 1; i < len; i++)
596 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
597 panic("ffs_reallocblks: non-logical cluster");
598 blkno = buflist->bs_children[0]->b_blkno;
599 ssize = fsbtodb(fs, fs->fs_frag);
600 for (i = 1; i < len - 1; i++)
601 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
602 panic("ffs_reallocblks: non-physical cluster %d", i);
605 * If the cluster crosses the boundary for the first indirect
606 * block, leave space for the indirect block. Indirect blocks
607 * are initially laid out in a position after the last direct
608 * block. Block reallocation would usually destroy locality by
609 * moving the indirect block out of the way to make room for
610 * data blocks if we didn't compensate here. We should also do
611 * this for other indirect block boundaries, but it is only
612 * important for the first one.
614 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
617 * If the latest allocation is in a new cylinder group, assume that
618 * the filesystem has decided to move and do not force it back to
619 * the previous cylinder group.
621 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
622 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
624 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
625 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
628 * Get the starting offset and block map for the first block.
630 if (start_lvl == 0) {
631 sbap = &ip->i_din1->di_db[0];
634 idp = &start_ap[start_lvl - 1];
635 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
639 sbap = (ufs1_daddr_t *)sbp->b_data;
643 * If the block range spans two block maps, get the second map.
646 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
651 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
652 panic("ffs_reallocblk: start == end");
654 ssize = len - (idp->in_off + 1);
655 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
657 ebap = (ufs1_daddr_t *)ebp->b_data;
660 * Find the preferred location for the cluster. If we have not
661 * previously failed at this endeavor, then follow our standard
662 * preference calculation. If we have failed at it, then pick up
663 * where we last ended our search.
666 if (ip->i_nextclustercg == -1)
667 pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
669 pref = cgdata(fs, ip->i_nextclustercg);
671 * Search the block map looking for an allocation of the desired size.
672 * To avoid wasting too much time, we limit the number of cylinder
673 * groups that we will search.
676 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
677 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
680 if (cg >= fs->fs_ncg)
684 * If we have failed in our search, record where we gave up for
685 * next time. Otherwise, fall back to our usual search citerion.
688 ip->i_nextclustercg = cg;
692 ip->i_nextclustercg = -1;
694 * We have found a new contiguous block.
696 * First we have to replace the old block pointers with the new
697 * block pointers in the inode and indirect blocks associated
702 printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
703 (uintmax_t)ip->i_number,
704 (intmax_t)start_lbn, (intmax_t)end_lbn);
707 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
713 if (!ffs_checkblk(ip,
714 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
715 panic("ffs_reallocblks: unallocated block 2");
716 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
717 panic("ffs_reallocblks: alloc mismatch");
721 printf(" %d,", *bap);
723 if (DOINGSOFTDEP(vp)) {
724 if (sbap == &ip->i_din1->di_db[0] && i < ssize)
725 softdep_setup_allocdirect(ip, start_lbn + i,
726 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
727 buflist->bs_children[i]);
729 softdep_setup_allocindir_page(ip, start_lbn + i,
730 i < ssize ? sbp : ebp, soff + i, blkno,
731 *bap, buflist->bs_children[i]);
736 * Next we must write out the modified inode and indirect blocks.
737 * For strict correctness, the writes should be synchronous since
738 * the old block values may have been written to disk. In practise
739 * they are almost never written, but if we are concerned about
740 * strict correctness, the `doasyncfree' flag should be set to zero.
742 * The test on `doasyncfree' should be changed to test a flag
743 * that shows whether the associated buffers and inodes have
744 * been written. The flag should be set when the cluster is
745 * started and cleared whenever the buffer or inode is flushed.
746 * We can then check below to see if it is set, and do the
747 * synchronous write only when it has been cleared.
749 if (sbap != &ip->i_din1->di_db[0]) {
755 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
766 * Last, free the old blocks and assign the new blocks to the buffers.
772 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
773 bp = buflist->bs_children[i];
774 if (!DOINGSOFTDEP(vp))
776 * The usual case is that a set of N-contiguous blocks
777 * that was just allocated has been replaced with a
778 * set of N+1-contiguous blocks. If they are marked as
779 * B_DELWRI, the current contents have not been written
780 * to disk. It is possible that the blocks were written
781 * earlier, but very uncommon. If the blocks have never
782 * been written, there is no need to send a BIO_DELETE
783 * for them when they are freed. The gain from avoiding
784 * the TRIMs for the common case of unwritten blocks
785 * far exceeds the cost of the write amplification for
786 * the uncommon case of failing to send a TRIM for the
787 * blocks that had been written.
789 ffs_blkfree(ump, fs, ump->um_devvp,
790 dbtofsb(fs, bp->b_blkno),
791 fs->fs_bsize, ip->i_number, vp->v_type, NULL,
792 (bp->b_flags & B_DELWRI) != 0 ?
793 NOTRIM_KEY : SINGLETON_KEY);
794 bp->b_blkno = fsbtodb(fs, blkno);
796 if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
797 panic("ffs_reallocblks: unallocated block 3");
801 printf(" %d,", blkno);
815 if (sbap != &ip->i_din1->di_db[0])
821 ffs_reallocblks_ufs2(ap)
822 struct vop_reallocblks_args /* {
824 struct cluster_save *a_buflist;
830 struct buf *sbp, *ebp, *bp;
831 ufs2_daddr_t *bap, *sbap, *ebap;
832 struct cluster_save *buflist;
833 struct ufsmount *ump;
834 ufs_lbn_t start_lbn, end_lbn;
835 ufs2_daddr_t soff, newblk, blkno, pref;
836 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
837 int i, cg, len, start_lvl, end_lvl, ssize;
844 * If we are not tracking block clusters or if we have less than 4%
845 * free blocks left, then do not attempt to cluster. Running with
846 * less than 5% free block reserve is not recommended and those that
847 * choose to do so do not expect to have good file layout.
849 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
851 buflist = ap->a_buflist;
852 len = buflist->bs_nchildren;
853 start_lbn = buflist->bs_children[0]->b_lblkno;
854 end_lbn = start_lbn + len - 1;
856 for (i = 0; i < len; i++)
857 if (!ffs_checkblk(ip,
858 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
859 panic("ffs_reallocblks: unallocated block 1");
860 for (i = 1; i < len; i++)
861 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
862 panic("ffs_reallocblks: non-logical cluster");
863 blkno = buflist->bs_children[0]->b_blkno;
864 ssize = fsbtodb(fs, fs->fs_frag);
865 for (i = 1; i < len - 1; i++)
866 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
867 panic("ffs_reallocblks: non-physical cluster %d", i);
870 * If the cluster crosses the boundary for the first indirect
871 * block, do not move anything in it. Indirect blocks are
872 * usually initially laid out in a position between the data
873 * blocks. Block reallocation would usually destroy locality by
874 * moving the indirect block out of the way to make room for
875 * data blocks if we didn't compensate here. We should also do
876 * this for other indirect block boundaries, but it is only
877 * important for the first one.
879 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
882 * If the latest allocation is in a new cylinder group, assume that
883 * the filesystem has decided to move and do not force it back to
884 * the previous cylinder group.
886 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
887 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
889 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
890 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
893 * Get the starting offset and block map for the first block.
895 if (start_lvl == 0) {
896 sbap = &ip->i_din2->di_db[0];
899 idp = &start_ap[start_lvl - 1];
900 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
904 sbap = (ufs2_daddr_t *)sbp->b_data;
908 * If the block range spans two block maps, get the second map.
911 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
916 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
917 panic("ffs_reallocblk: start == end");
919 ssize = len - (idp->in_off + 1);
920 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
922 ebap = (ufs2_daddr_t *)ebp->b_data;
925 * Find the preferred location for the cluster. If we have not
926 * previously failed at this endeavor, then follow our standard
927 * preference calculation. If we have failed at it, then pick up
928 * where we last ended our search.
931 if (ip->i_nextclustercg == -1)
932 pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
934 pref = cgdata(fs, ip->i_nextclustercg);
936 * Search the block map looking for an allocation of the desired size.
937 * To avoid wasting too much time, we limit the number of cylinder
938 * groups that we will search.
941 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
942 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
945 if (cg >= fs->fs_ncg)
949 * If we have failed in our search, record where we gave up for
950 * next time. Otherwise, fall back to our usual search citerion.
953 ip->i_nextclustercg = cg;
957 ip->i_nextclustercg = -1;
959 * We have found a new contiguous block.
961 * First we have to replace the old block pointers with the new
962 * block pointers in the inode and indirect blocks associated
967 printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
968 (intmax_t)start_lbn, (intmax_t)end_lbn);
971 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
977 if (!ffs_checkblk(ip,
978 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
979 panic("ffs_reallocblks: unallocated block 2");
980 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
981 panic("ffs_reallocblks: alloc mismatch");
985 printf(" %jd,", (intmax_t)*bap);
987 if (DOINGSOFTDEP(vp)) {
988 if (sbap == &ip->i_din2->di_db[0] && i < ssize)
989 softdep_setup_allocdirect(ip, start_lbn + i,
990 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
991 buflist->bs_children[i]);
993 softdep_setup_allocindir_page(ip, start_lbn + i,
994 i < ssize ? sbp : ebp, soff + i, blkno,
995 *bap, buflist->bs_children[i]);
1000 * Next we must write out the modified inode and indirect blocks.
1001 * For strict correctness, the writes should be synchronous since
1002 * the old block values may have been written to disk. In practise
1003 * they are almost never written, but if we are concerned about
1004 * strict correctness, the `doasyncfree' flag should be set to zero.
1006 * The test on `doasyncfree' should be changed to test a flag
1007 * that shows whether the associated buffers and inodes have
1008 * been written. The flag should be set when the cluster is
1009 * started and cleared whenever the buffer or inode is flushed.
1010 * We can then check below to see if it is set, and do the
1011 * synchronous write only when it has been cleared.
1013 if (sbap != &ip->i_din2->di_db[0]) {
1019 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1030 * Last, free the old blocks and assign the new blocks to the buffers.
1036 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
1037 bp = buflist->bs_children[i];
1038 if (!DOINGSOFTDEP(vp))
1040 * The usual case is that a set of N-contiguous blocks
1041 * that was just allocated has been replaced with a
1042 * set of N+1-contiguous blocks. If they are marked as
1043 * B_DELWRI, the current contents have not been written
1044 * to disk. It is possible that the blocks were written
1045 * earlier, but very uncommon. If the blocks have never
1046 * been written, there is no need to send a BIO_DELETE
1047 * for them when they are freed. The gain from avoiding
1048 * the TRIMs for the common case of unwritten blocks
1049 * far exceeds the cost of the write amplification for
1050 * the uncommon case of failing to send a TRIM for the
1051 * blocks that had been written.
1053 ffs_blkfree(ump, fs, ump->um_devvp,
1054 dbtofsb(fs, bp->b_blkno),
1055 fs->fs_bsize, ip->i_number, vp->v_type, NULL,
1056 (bp->b_flags & B_DELWRI) != 0 ?
1057 NOTRIM_KEY : SINGLETON_KEY);
1058 bp->b_blkno = fsbtodb(fs, blkno);
1060 if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
1061 panic("ffs_reallocblks: unallocated block 3");
1065 printf(" %jd,", (intmax_t)blkno);
1079 if (sbap != &ip->i_din2->di_db[0])
1085 * Allocate an inode in the filesystem.
1087 * If allocating a directory, use ffs_dirpref to select the inode.
1088 * If allocating in a directory, the following hierarchy is followed:
1089 * 1) allocate the preferred inode.
1090 * 2) allocate an inode in the same cylinder group.
1091 * 3) quadradically rehash into other cylinder groups, until an
1092 * available inode is located.
1093 * If no inode preference is given the following hierarchy is used
1094 * to allocate an inode:
1095 * 1) allocate an inode in cylinder group 0.
1096 * 2) quadradically rehash into other cylinder groups, until an
1097 * available inode is located.
1100 ffs_valloc(pvp, mode, cred, vpp)
1110 struct ufsmount *ump;
1113 int error, reclaimed;
1123 if (fs->fs_cstotal.cs_nifree == 0)
1126 if ((mode & IFMT) == IFDIR)
1127 ipref = ffs_dirpref(pip);
1129 ipref = pip->i_number;
1130 if (ipref >= fs->fs_ncg * fs->fs_ipg)
1132 cg = ino_to_cg(fs, ipref);
1134 * Track number of dirs created one after another
1135 * in a same cg without intervening by files.
1137 if ((mode & IFMT) == IFDIR) {
1138 if (fs->fs_contigdirs[cg] < 255)
1139 fs->fs_contigdirs[cg]++;
1141 if (fs->fs_contigdirs[cg] > 0)
1142 fs->fs_contigdirs[cg]--;
1144 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1145 (allocfcn_t *)ffs_nodealloccg);
1149 * Get rid of the cached old vnode, force allocation of a new vnode
1150 * for this inode. If this fails, release the allocated ino and
1153 if ((error = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1154 FFSV_FORCEINSMQ | FFSV_REPLACE)) != 0) {
1155 ffs_vfree(pvp, ino, mode);
1159 * We got an inode, so check mode and panic if it is already allocated.
1163 printf("mode = 0%o, inum = %ju, fs = %s\n",
1164 ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1165 panic("ffs_valloc: dup alloc");
1167 if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) { /* XXX */
1168 printf("free inode %s/%lu had %ld blocks\n",
1169 fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1170 DIP_SET(ip, i_blocks, 0);
1173 DIP_SET(ip, i_flags, 0);
1175 * Set up a new generation number for this inode.
1177 while (ip->i_gen == 0 || ++ip->i_gen == 0)
1178 ip->i_gen = arc4random();
1179 DIP_SET(ip, i_gen, ip->i_gen);
1180 if (fs->fs_magic == FS_UFS2_MAGIC) {
1182 ip->i_din2->di_birthtime = ts.tv_sec;
1183 ip->i_din2->di_birthnsec = ts.tv_nsec;
1186 (*vpp)->v_vflag = 0;
1187 (*vpp)->v_type = VNON;
1188 if (fs->fs_magic == FS_UFS2_MAGIC) {
1189 (*vpp)->v_op = &ffs_vnodeops2;
1190 UFS_INODE_SET_FLAG(ip, IN_UFS2);
1192 (*vpp)->v_op = &ffs_vnodeops1;
1196 if (reclaimed == 0) {
1198 softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1201 if (ffs_fsfail_cleanup_locked(ump, 0)) {
1205 if (ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
1207 ffs_fserr(fs, pip->i_number, "out of inodes");
1208 uprintf("\n%s: create/symlink failed, no inodes free\n",
1217 * Find a cylinder group to place a directory.
1219 * The policy implemented by this algorithm is to allocate a
1220 * directory inode in the same cylinder group as its parent
1221 * directory, but also to reserve space for its files inodes
1222 * and data. Restrict the number of directories which may be
1223 * allocated one after another in the same cylinder group
1224 * without intervening allocation of files.
1226 * If we allocate a first level directory then force allocation
1227 * in another cylinder group.
1234 int cg, prefcg, dirsize, cgsize;
1235 u_int avgifree, avgbfree, avgndir, curdirsize;
1236 u_int minifree, minbfree, maxndir;
1237 u_int mincg, minndir;
1238 u_int maxcontigdirs;
1240 mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1243 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1244 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1245 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1248 * Force allocation in another cg if creating a first level dir.
1250 ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1251 if (ITOV(pip)->v_vflag & VV_ROOT) {
1252 prefcg = arc4random() % fs->fs_ncg;
1254 minndir = fs->fs_ipg;
1255 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1256 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1257 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1258 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1260 minndir = fs->fs_cs(fs, cg).cs_ndir;
1262 for (cg = 0; cg < prefcg; cg++)
1263 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1264 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1265 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1267 minndir = fs->fs_cs(fs, cg).cs_ndir;
1269 return ((ino_t)(fs->fs_ipg * mincg));
1273 * Count various limits which used for
1274 * optimal allocation of a directory inode.
1276 maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1277 minifree = avgifree - avgifree / 4;
1280 minbfree = avgbfree - avgbfree / 4;
1283 cgsize = fs->fs_fsize * fs->fs_fpg;
1284 dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1285 curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1286 if (dirsize < curdirsize)
1287 dirsize = curdirsize;
1289 maxcontigdirs = 0; /* dirsize overflowed */
1291 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1292 if (fs->fs_avgfpdir > 0)
1293 maxcontigdirs = min(maxcontigdirs,
1294 fs->fs_ipg / fs->fs_avgfpdir);
1295 if (maxcontigdirs == 0)
1299 * Limit number of dirs in one cg and reserve space for
1300 * regular files, but only if we have no deficit in
1303 * We are trying to find a suitable cylinder group nearby
1304 * our preferred cylinder group to place a new directory.
1305 * We scan from our preferred cylinder group forward looking
1306 * for a cylinder group that meets our criterion. If we get
1307 * to the final cylinder group and do not find anything,
1308 * we start scanning forwards from the beginning of the
1309 * filesystem. While it might seem sensible to start scanning
1310 * backwards or even to alternate looking forward and backward,
1311 * this approach fails badly when the filesystem is nearly full.
1312 * Specifically, we first search all the areas that have no space
1313 * and finally try the one preceding that. We repeat this on
1314 * every request and in the case of the final block end up
1315 * searching the entire filesystem. By jumping to the front
1316 * of the filesystem, our future forward searches always look
1317 * in new cylinder groups so finds every possible block after
1318 * one pass over the filesystem.
1320 prefcg = ino_to_cg(fs, pip->i_number);
1321 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1322 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1323 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1324 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1325 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1326 return ((ino_t)(fs->fs_ipg * cg));
1328 for (cg = 0; cg < prefcg; cg++)
1329 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1330 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1331 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1332 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1333 return ((ino_t)(fs->fs_ipg * cg));
1336 * This is a backstop when we have deficit in space.
1338 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1339 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1340 return ((ino_t)(fs->fs_ipg * cg));
1341 for (cg = 0; cg < prefcg; cg++)
1342 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1344 return ((ino_t)(fs->fs_ipg * cg));
1348 * Select the desired position for the next block in a file. The file is
1349 * logically divided into sections. The first section is composed of the
1350 * direct blocks and the next fs_maxbpg blocks. Each additional section
1351 * contains fs_maxbpg blocks.
1353 * If no blocks have been allocated in the first section, the policy is to
1354 * request a block in the same cylinder group as the inode that describes
1355 * the file. The first indirect is allocated immediately following the last
1356 * direct block and the data blocks for the first indirect immediately
1359 * If no blocks have been allocated in any other section, the indirect
1360 * block(s) are allocated in the same cylinder group as its inode in an
1361 * area reserved immediately following the inode blocks. The policy for
1362 * the data blocks is to place them in a cylinder group with a greater than
1363 * average number of free blocks. An appropriate cylinder group is found
1364 * by using a rotor that sweeps the cylinder groups. When a new group of
1365 * blocks is needed, the sweep begins in the cylinder group following the
1366 * cylinder group from which the previous allocation was made. The sweep
1367 * continues until a cylinder group with greater than the average number
1368 * of free blocks is found. If the allocation is for the first block in an
1369 * indirect block or the previous block is a hole, then the information on
1370 * the previous allocation is unavailable; here a best guess is made based
1371 * on the logical block number being allocated.
1373 * If a section is already partially allocated, the policy is to
1374 * allocate blocks contiguously within the section if possible.
1377 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1385 u_int avgbfree, startcg;
1386 ufs2_daddr_t pref, prevbn;
1388 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1389 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1392 * Allocation of indirect blocks is indicated by passing negative
1393 * values in indx: -1 for single indirect, -2 for double indirect,
1394 * -3 for triple indirect. As noted below, we attempt to allocate
1395 * the first indirect inline with the file data. For all later
1396 * indirect blocks, the data is often allocated in other cylinder
1397 * groups. However to speed random file access and to speed up
1398 * fsck, the filesystem reserves the first fs_metaspace blocks
1399 * (typically half of fs_minfree) of the data area of each cylinder
1400 * group to hold these later indirect blocks.
1402 inocg = ino_to_cg(fs, ip->i_number);
1405 * Our preference for indirect blocks is the zone at the
1406 * beginning of the inode's cylinder group data area that
1407 * we try to reserve for indirect blocks.
1409 pref = cgmeta(fs, inocg);
1411 * If we are allocating the first indirect block, try to
1412 * place it immediately following the last direct block.
1414 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1415 ip->i_din1->di_db[UFS_NDADDR - 1] != 0)
1416 pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1420 * If we are allocating the first data block in the first indirect
1421 * block and the indirect has been allocated in the data block area,
1422 * try to place it immediately following the indirect block.
1424 if (lbn == UFS_NDADDR) {
1425 pref = ip->i_din1->di_ib[0];
1426 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1427 pref < cgbase(fs, inocg + 1))
1428 return (pref + fs->fs_frag);
1431 * If we are at the beginning of a file, or we have already allocated
1432 * the maximum number of blocks per cylinder group, or we do not
1433 * have a block allocated immediately preceding us, then we need
1434 * to decide where to start allocating new blocks.
1439 prevbn = bap[indx - 1];
1440 if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1444 if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1446 * If we are allocating a directory data block, we want
1447 * to place it in the metadata area.
1449 if ((ip->i_mode & IFMT) == IFDIR)
1450 return (cgmeta(fs, inocg));
1452 * Until we fill all the direct and all the first indirect's
1453 * blocks, we try to allocate in the data area of the inode's
1456 if (lbn < UFS_NDADDR + NINDIR(fs))
1457 return (cgdata(fs, inocg));
1459 * Find a cylinder with greater than average number of
1460 * unused data blocks.
1462 if (indx == 0 || prevbn == 0)
1463 startcg = inocg + lbn / fs->fs_maxbpg;
1465 startcg = dtog(fs, prevbn) + 1;
1466 startcg %= fs->fs_ncg;
1467 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1468 for (cg = startcg; cg < fs->fs_ncg; cg++)
1469 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1470 fs->fs_cgrotor = cg;
1471 return (cgdata(fs, cg));
1473 for (cg = 0; cg <= startcg; cg++)
1474 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1475 fs->fs_cgrotor = cg;
1476 return (cgdata(fs, cg));
1481 * Otherwise, we just always try to lay things out contiguously.
1483 return (prevbn + fs->fs_frag);
1487 * Same as above, but for UFS2
1490 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1498 u_int avgbfree, startcg;
1499 ufs2_daddr_t pref, prevbn;
1501 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1502 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1505 * Allocation of indirect blocks is indicated by passing negative
1506 * values in indx: -1 for single indirect, -2 for double indirect,
1507 * -3 for triple indirect. As noted below, we attempt to allocate
1508 * the first indirect inline with the file data. For all later
1509 * indirect blocks, the data is often allocated in other cylinder
1510 * groups. However to speed random file access and to speed up
1511 * fsck, the filesystem reserves the first fs_metaspace blocks
1512 * (typically half of fs_minfree) of the data area of each cylinder
1513 * group to hold these later indirect blocks.
1515 inocg = ino_to_cg(fs, ip->i_number);
1518 * Our preference for indirect blocks is the zone at the
1519 * beginning of the inode's cylinder group data area that
1520 * we try to reserve for indirect blocks.
1522 pref = cgmeta(fs, inocg);
1524 * If we are allocating the first indirect block, try to
1525 * place it immediately following the last direct block.
1527 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1528 ip->i_din2->di_db[UFS_NDADDR - 1] != 0)
1529 pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1533 * If we are allocating the first data block in the first indirect
1534 * block and the indirect has been allocated in the data block area,
1535 * try to place it immediately following the indirect block.
1537 if (lbn == UFS_NDADDR) {
1538 pref = ip->i_din2->di_ib[0];
1539 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1540 pref < cgbase(fs, inocg + 1))
1541 return (pref + fs->fs_frag);
1544 * If we are at the beginning of a file, or we have already allocated
1545 * the maximum number of blocks per cylinder group, or we do not
1546 * have a block allocated immediately preceding us, then we need
1547 * to decide where to start allocating new blocks.
1552 prevbn = bap[indx - 1];
1553 if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1557 if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1559 * If we are allocating a directory data block, we want
1560 * to place it in the metadata area.
1562 if ((ip->i_mode & IFMT) == IFDIR)
1563 return (cgmeta(fs, inocg));
1565 * Until we fill all the direct and all the first indirect's
1566 * blocks, we try to allocate in the data area of the inode's
1569 if (lbn < UFS_NDADDR + NINDIR(fs))
1570 return (cgdata(fs, inocg));
1572 * Find a cylinder with greater than average number of
1573 * unused data blocks.
1575 if (indx == 0 || prevbn == 0)
1576 startcg = inocg + lbn / fs->fs_maxbpg;
1578 startcg = dtog(fs, prevbn) + 1;
1579 startcg %= fs->fs_ncg;
1580 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1581 for (cg = startcg; cg < fs->fs_ncg; cg++)
1582 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1583 fs->fs_cgrotor = cg;
1584 return (cgdata(fs, cg));
1586 for (cg = 0; cg <= startcg; cg++)
1587 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1588 fs->fs_cgrotor = cg;
1589 return (cgdata(fs, cg));
1594 * Otherwise, we just always try to lay things out contiguously.
1596 return (prevbn + fs->fs_frag);
1600 * Implement the cylinder overflow algorithm.
1602 * The policy implemented by this algorithm is:
1603 * 1) allocate the block in its requested cylinder group.
1604 * 2) quadradically rehash on the cylinder group number.
1605 * 3) brute force search for a free block.
1607 * Must be called with the UFS lock held. Will release the lock on success
1608 * and return with it held on failure.
1612 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1616 int size; /* Search size for data blocks, mode for inodes */
1617 int rsize; /* Real allocated size. */
1618 allocfcn_t *allocator;
1621 ufs2_daddr_t result;
1624 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1626 if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1627 panic("ffs_hashalloc: allocation on suspended filesystem");
1631 * 1: preferred cylinder group
1633 result = (*allocator)(ip, cg, pref, size, rsize);
1637 * 2: quadratic rehash
1639 for (i = 1; i < fs->fs_ncg; i *= 2) {
1641 if (cg >= fs->fs_ncg)
1643 result = (*allocator)(ip, cg, 0, size, rsize);
1648 * 3: brute force search
1649 * Note that we start at i == 2, since 0 was checked initially,
1650 * and 1 is always checked in the quadratic rehash.
1652 cg = (icg + 2) % fs->fs_ncg;
1653 for (i = 2; i < fs->fs_ncg; i++) {
1654 result = (*allocator)(ip, cg, 0, size, rsize);
1658 if (cg == fs->fs_ncg)
1665 * Determine whether a fragment can be extended.
1667 * Check to see if the necessary fragments are available, and
1668 * if they are, allocate them.
1671 ffs_fragextend(ip, cg, bprev, osize, nsize)
1680 struct ufsmount *ump;
1689 if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1691 frags = numfrags(fs, nsize);
1692 bbase = fragnum(fs, bprev);
1693 if (bbase > fragnum(fs, (bprev + frags - 1))) {
1694 /* cannot extend across a block boundary */
1698 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0)
1700 bno = dtogd(fs, bprev);
1701 blksfree = cg_blksfree(cgp);
1702 for (i = numfrags(fs, osize); i < frags; i++)
1703 if (isclr(blksfree, bno + i))
1706 * the current fragment can be extended
1707 * deduct the count on fragment being extended into
1708 * increase the count on the remaining fragment (if any)
1709 * allocate the extended piece
1711 for (i = frags; i < fs->fs_frag - bbase; i++)
1712 if (isclr(blksfree, bno + i))
1714 cgp->cg_frsum[i - numfrags(fs, osize)]--;
1716 cgp->cg_frsum[i - frags]++;
1717 for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1718 clrbit(blksfree, bno + i);
1719 cgp->cg_cs.cs_nffree--;
1723 fs->fs_cstotal.cs_nffree -= nffree;
1724 fs->fs_cs(fs, cg).cs_nffree -= nffree;
1726 ACTIVECLEAR(fs, cg);
1728 if (DOINGSOFTDEP(ITOV(ip)))
1729 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1730 frags, numfrags(fs, osize));
1742 * Determine whether a block can be allocated.
1744 * Check to see if a block of the appropriate size is available,
1745 * and if it is, allocate it.
1748 ffs_alloccg(ip, cg, bpref, size, rsize)
1758 struct ufsmount *ump;
1761 int i, allocsiz, error, frags;
1766 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1769 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0 ||
1770 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1772 if (size == fs->fs_bsize) {
1774 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1775 ACTIVECLEAR(fs, cg);
1781 * check to see if any fragments are already available
1782 * allocsiz is the size which will be allocated, hacking
1783 * it down to a smaller size if necessary
1785 blksfree = cg_blksfree(cgp);
1786 frags = numfrags(fs, size);
1787 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1788 if (cgp->cg_frsum[allocsiz] != 0)
1790 if (allocsiz == fs->fs_frag) {
1792 * no fragments were available, so a block will be
1793 * allocated, and hacked up
1795 if (cgp->cg_cs.cs_nbfree == 0)
1798 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1799 ACTIVECLEAR(fs, cg);
1804 KASSERT(size == rsize,
1805 ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1806 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1809 for (i = 0; i < frags; i++)
1810 clrbit(blksfree, bno + i);
1811 cgp->cg_cs.cs_nffree -= frags;
1812 cgp->cg_frsum[allocsiz]--;
1813 if (frags != allocsiz)
1814 cgp->cg_frsum[allocsiz - frags]++;
1816 fs->fs_cstotal.cs_nffree -= frags;
1817 fs->fs_cs(fs, cg).cs_nffree -= frags;
1819 blkno = cgbase(fs, cg) + bno;
1820 ACTIVECLEAR(fs, cg);
1822 if (DOINGSOFTDEP(ITOV(ip)))
1823 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1834 * Allocate a block in a cylinder group.
1836 * This algorithm implements the following policy:
1837 * 1) allocate the requested block.
1838 * 2) allocate a rotationally optimal block in the same cylinder.
1839 * 3) allocate the next available block on the block rotor for the
1840 * specified cylinder group.
1841 * Note that this routine only allocates fs_bsize blocks; these
1842 * blocks may be fragmented by the routine that allocates them.
1845 ffs_alloccgblk(ip, bp, bpref, size)
1853 struct ufsmount *ump;
1861 mtx_assert(UFS_MTX(ump), MA_OWNED);
1862 cgp = (struct cg *)bp->b_data;
1863 blksfree = cg_blksfree(cgp);
1865 bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1866 } else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1867 /* map bpref to correct zone in this cg */
1868 if (bpref < cgdata(fs, cgbpref))
1869 bpref = cgmeta(fs, cgp->cg_cgx);
1871 bpref = cgdata(fs, cgp->cg_cgx);
1874 * if the requested block is available, use it
1876 bno = dtogd(fs, blknum(fs, bpref));
1877 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1880 * Take the next available block in this cylinder group.
1882 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1885 /* Update cg_rotor only if allocated from the data zone */
1886 if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1887 cgp->cg_rotor = bno;
1889 blkno = fragstoblks(fs, bno);
1890 ffs_clrblock(fs, blksfree, (long)blkno);
1891 ffs_clusteracct(fs, cgp, blkno, -1);
1892 cgp->cg_cs.cs_nbfree--;
1893 fs->fs_cstotal.cs_nbfree--;
1894 fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1896 blkno = cgbase(fs, cgp->cg_cgx) + bno;
1898 * If the caller didn't want the whole block free the frags here.
1900 size = numfrags(fs, size);
1901 if (size != fs->fs_frag) {
1902 bno = dtogd(fs, blkno);
1903 for (i = size; i < fs->fs_frag; i++)
1904 setbit(blksfree, bno + i);
1905 i = fs->fs_frag - size;
1906 cgp->cg_cs.cs_nffree += i;
1907 fs->fs_cstotal.cs_nffree += i;
1908 fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1914 if (DOINGSOFTDEP(ITOV(ip)))
1915 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, size, 0);
1921 * Determine whether a cluster can be allocated.
1923 * We do not currently check for optimal rotational layout if there
1924 * are multiple choices in the same cylinder group. Instead we just
1925 * take the first one that we find following bpref.
1928 ffs_clusteralloc(ip, cg, bpref, len)
1937 struct ufsmount *ump;
1938 int i, run, bit, map, got, error;
1946 if (fs->fs_maxcluster[cg] < len)
1949 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
1954 * Check to see if a cluster of the needed size (or bigger) is
1955 * available in this cylinder group.
1957 lp = &cg_clustersum(cgp)[len];
1958 for (i = len; i <= fs->fs_contigsumsize; i++)
1961 if (i > fs->fs_contigsumsize) {
1963 * This is the first time looking for a cluster in this
1964 * cylinder group. Update the cluster summary information
1965 * to reflect the true maximum sized cluster so that
1966 * future cluster allocation requests can avoid reading
1967 * the cylinder group map only to find no clusters.
1969 lp = &cg_clustersum(cgp)[len - 1];
1970 for (i = len - 1; i > 0; i--)
1974 fs->fs_maxcluster[cg] = i;
1979 * Search the cluster map to find a big enough cluster.
1980 * We take the first one that we find, even if it is larger
1981 * than we need as we prefer to get one close to the previous
1982 * block allocation. We do not search before the current
1983 * preference point as we do not want to allocate a block
1984 * that is allocated before the previous one (as we will
1985 * then have to wait for another pass of the elevator
1986 * algorithm before it will be read). We prefer to fail and
1987 * be recalled to try an allocation in the next cylinder group.
1989 if (dtog(fs, bpref) != cg)
1990 bpref = cgdata(fs, cg);
1992 bpref = blknum(fs, bpref);
1993 bpref = fragstoblks(fs, dtogd(fs, bpref));
1994 mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1996 bit = 1 << (bpref % NBBY);
1997 for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1998 if ((map & bit) == 0) {
2005 if ((got & (NBBY - 1)) != (NBBY - 1)) {
2012 if (got >= cgp->cg_nclusterblks) {
2018 * Allocate the cluster that we have found.
2020 blksfree = cg_blksfree(cgp);
2021 for (i = 1; i <= len; i++)
2022 if (!ffs_isblock(fs, blksfree, got - run + i))
2023 panic("ffs_clusteralloc: map mismatch");
2024 bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
2025 if (dtog(fs, bno) != cg)
2026 panic("ffs_clusteralloc: allocated out of group");
2027 len = blkstofrags(fs, len);
2029 for (i = 0; i < len; i += fs->fs_frag)
2030 if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
2031 panic("ffs_clusteralloc: lost block");
2032 ACTIVECLEAR(fs, cg);
2038 static inline struct buf *
2039 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
2044 return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
2045 cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
2050 * Synchronous inode initialization is needed only when barrier writes do not
2051 * work as advertised, and will impose a heavy cost on file creation in a newly
2052 * created filesystem.
2054 static int doasyncinodeinit = 1;
2055 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncinodeinit, CTLFLAG_RWTUN,
2056 &doasyncinodeinit, 0,
2057 "Perform inode block initialization using asynchronous writes");
2060 * Determine whether an inode can be allocated.
2062 * Check to see if an inode is available, and if it is,
2063 * allocate it using the following policy:
2064 * 1) allocate the requested inode.
2065 * 2) allocate the next available inode after the requested
2066 * inode in the specified cylinder group.
2069 ffs_nodealloccg(ip, cg, ipref, mode, unused)
2078 struct buf *bp, *ibp;
2079 struct ufsmount *ump;
2080 u_int8_t *inosused, *loc;
2081 struct ufs2_dinode *dp2;
2082 int error, start, len, i;
2083 u_int32_t old_initediblk;
2088 if (fs->fs_cs(fs, cg).cs_nifree == 0)
2091 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
2096 if (cgp->cg_cs.cs_nifree == 0) {
2101 inosused = cg_inosused(cgp);
2103 ipref %= fs->fs_ipg;
2104 if (isclr(inosused, ipref))
2107 start = cgp->cg_irotor / NBBY;
2108 len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
2109 loc = memcchr(&inosused[start], 0xff, len);
2113 loc = memcchr(&inosused[start], 0xff, len);
2115 printf("cg = %d, irotor = %ld, fs = %s\n",
2116 cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2117 panic("ffs_nodealloccg: map corrupted");
2121 ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2124 * Check to see if we need to initialize more inodes.
2126 if (fs->fs_magic == FS_UFS2_MAGIC &&
2127 ipref + INOPB(fs) > cgp->cg_initediblk &&
2128 cgp->cg_initediblk < cgp->cg_niblk) {
2129 old_initediblk = cgp->cg_initediblk;
2132 * Free the cylinder group lock before writing the
2133 * initialized inode block. Entering the
2134 * babarrierwrite() with the cylinder group lock
2135 * causes lock order violation between the lock and
2138 * Another thread can decide to initialize the same
2139 * inode block, but whichever thread first gets the
2140 * cylinder group lock after writing the newly
2141 * allocated inode block will update it and the other
2142 * will realize that it has lost and leave the
2143 * cylinder group unchanged.
2145 ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2149 * The inode block buffer is already owned by
2150 * another thread, which must initialize it.
2151 * Wait on the buffer to allow another thread
2152 * to finish the updates, with dropped cg
2153 * buffer lock, then retry.
2155 ibp = getinobuf(ip, cg, old_initediblk, 0);
2160 bzero(ibp->b_data, (int)fs->fs_bsize);
2161 dp2 = (struct ufs2_dinode *)(ibp->b_data);
2162 for (i = 0; i < INOPB(fs); i++) {
2163 while (dp2->di_gen == 0)
2164 dp2->di_gen = arc4random();
2169 * Rather than adding a soft updates dependency to ensure
2170 * that the new inode block is written before it is claimed
2171 * by the cylinder group map, we just do a barrier write
2172 * here. The barrier write will ensure that the inode block
2173 * gets written before the updated cylinder group map can be
2174 * written. The barrier write should only slow down bulk
2175 * loading of newly created filesystems.
2177 if (doasyncinodeinit)
2178 babarrierwrite(ibp);
2183 * After the inode block is written, try to update the
2184 * cg initediblk pointer. If another thread beat us
2185 * to it, then leave it unchanged as the other thread
2186 * has already set it correctly.
2188 error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp);
2190 ACTIVECLEAR(fs, cg);
2194 if (cgp->cg_initediblk == old_initediblk)
2195 cgp->cg_initediblk += INOPB(fs);
2198 cgp->cg_irotor = ipref;
2200 ACTIVECLEAR(fs, cg);
2201 setbit(inosused, ipref);
2202 cgp->cg_cs.cs_nifree--;
2203 fs->fs_cstotal.cs_nifree--;
2204 fs->fs_cs(fs, cg).cs_nifree--;
2206 if ((mode & IFMT) == IFDIR) {
2207 cgp->cg_cs.cs_ndir++;
2208 fs->fs_cstotal.cs_ndir++;
2209 fs->fs_cs(fs, cg).cs_ndir++;
2212 if (DOINGSOFTDEP(ITOV(ip)))
2213 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2215 return ((ino_t)(cg * fs->fs_ipg + ipref));
2219 * Free a block or fragment.
2221 * The specified block or fragment is placed back in the
2222 * free map. If a fragment is deallocated, a possible
2223 * block reassembly is checked.
2226 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2227 struct ufsmount *ump;
2229 struct vnode *devvp;
2233 struct workhead *dephd;
2239 ufs1_daddr_t fragno, cgbno;
2240 int i, blk, frags, bbase, error;
2246 if (devvp->v_type == VREG) {
2247 /* devvp is a snapshot */
2248 MPASS(devvp->v_mount->mnt_data == ump);
2249 dev = ump->um_devvp->v_rdev;
2250 } else if (devvp->v_type == VCHR) {
2251 /* devvp is a normal disk device */
2252 dev = devvp->v_rdev;
2253 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
2257 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2258 fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2259 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2260 devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2261 size, fs->fs_fsmnt);
2262 panic("ffs_blkfree_cg: bad size");
2265 if ((u_int)bno >= fs->fs_size) {
2266 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2268 ffs_fserr(fs, inum, "bad block");
2271 if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2272 if (!ffs_fsfail_cleanup(ump, error) ||
2273 !MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2275 if (devvp->v_type == VREG)
2276 dbn = fragstoblks(fs, cgtod(fs, cg));
2278 dbn = fsbtodb(fs, cgtod(fs, cg));
2279 error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2280 KASSERT(error == 0, ("getblkx failed"));
2281 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2282 numfrags(fs, size), dephd);
2283 bp->b_flags |= B_RELBUF | B_NOCACHE;
2284 bp->b_flags &= ~B_CACHE;
2288 cgbno = dtogd(fs, bno);
2289 blksfree = cg_blksfree(cgp);
2291 if (size == fs->fs_bsize) {
2292 fragno = fragstoblks(fs, cgbno);
2293 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2294 if (devvp->v_type == VREG) {
2296 /* devvp is a snapshot */
2300 printf("dev = %s, block = %jd, fs = %s\n",
2301 devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2302 panic("ffs_blkfree_cg: freeing free block");
2304 ffs_setblock(fs, blksfree, fragno);
2305 ffs_clusteracct(fs, cgp, fragno, 1);
2306 cgp->cg_cs.cs_nbfree++;
2307 fs->fs_cstotal.cs_nbfree++;
2308 fs->fs_cs(fs, cg).cs_nbfree++;
2310 bbase = cgbno - fragnum(fs, cgbno);
2312 * decrement the counts associated with the old frags
2314 blk = blkmap(fs, blksfree, bbase);
2315 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2317 * deallocate the fragment
2319 frags = numfrags(fs, size);
2320 for (i = 0; i < frags; i++) {
2321 if (isset(blksfree, cgbno + i)) {
2322 printf("dev = %s, block = %jd, fs = %s\n",
2323 devtoname(dev), (intmax_t)(bno + i),
2325 panic("ffs_blkfree_cg: freeing free frag");
2327 setbit(blksfree, cgbno + i);
2329 cgp->cg_cs.cs_nffree += i;
2330 fs->fs_cstotal.cs_nffree += i;
2331 fs->fs_cs(fs, cg).cs_nffree += i;
2333 * add back in counts associated with the new frags
2335 blk = blkmap(fs, blksfree, bbase);
2336 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2338 * if a complete block has been reassembled, account for it
2340 fragno = fragstoblks(fs, bbase);
2341 if (ffs_isblock(fs, blksfree, fragno)) {
2342 cgp->cg_cs.cs_nffree -= fs->fs_frag;
2343 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2344 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2345 ffs_clusteracct(fs, cgp, fragno, 1);
2346 cgp->cg_cs.cs_nbfree++;
2347 fs->fs_cstotal.cs_nbfree++;
2348 fs->fs_cs(fs, cg).cs_nbfree++;
2352 ACTIVECLEAR(fs, cg);
2355 if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2356 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2357 numfrags(fs, size), dephd);
2362 * Structures and routines associated with trim management.
2364 * The following requests are passed to trim_lookup to indicate
2365 * the actions that should be taken.
2367 #define NEW 1 /* if found, error else allocate and hash it */
2368 #define OLD 2 /* if not found, error, else return it */
2369 #define REPLACE 3 /* if not found, error else unhash and reallocate it */
2370 #define DONE 4 /* if not found, error else unhash and return it */
2371 #define SINGLE 5 /* don't look up, just allocate it and don't hash it */
2373 MALLOC_DEFINE(M_TRIM, "ufs_trim", "UFS trim structures");
2375 #define TRIMLIST_HASH(ump, key) \
2376 (&(ump)->um_trimhash[(key) & (ump)->um_trimlisthashsize])
2379 * These structures describe each of the block free requests aggregated
2380 * together to make up a trim request.
2382 struct trim_blkreq {
2383 TAILQ_ENTRY(trim_blkreq) blkreqlist;
2386 struct workhead *pdephd;
2387 struct workhead dephd;
2391 * Description of a trim request.
2393 struct ffs_blkfree_trim_params {
2394 TAILQ_HEAD(, trim_blkreq) blklist;
2395 LIST_ENTRY(ffs_blkfree_trim_params) hashlist;
2397 struct ufsmount *ump;
2398 struct vnode *devvp;
2405 static void ffs_blkfree_trim_completed(struct buf *);
2406 static void ffs_blkfree_trim_task(void *ctx, int pending __unused);
2407 static struct ffs_blkfree_trim_params *trim_lookup(struct ufsmount *,
2408 struct vnode *, ufs2_daddr_t, long, ino_t, u_long, int);
2409 static void ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params *);
2412 * Called on trim completion to start a task to free the associated block(s).
2415 ffs_blkfree_trim_completed(bp)
2418 struct ffs_blkfree_trim_params *tp;
2420 tp = bp->b_fsprivate1;
2422 TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2423 taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
2427 * Trim completion task that free associated block(s).
2430 ffs_blkfree_trim_task(ctx, pending)
2434 struct ffs_blkfree_trim_params *tp;
2435 struct trim_blkreq *blkelm;
2436 struct ufsmount *ump;
2440 while ((blkelm = TAILQ_FIRST(&tp->blklist)) != NULL) {
2441 ffs_blkfree_cg(ump, ump->um_fs, tp->devvp, blkelm->bno,
2442 blkelm->size, tp->inum, blkelm->pdephd);
2443 TAILQ_REMOVE(&tp->blklist, blkelm, blkreqlist);
2444 free(blkelm, M_TRIM);
2446 vn_finished_secondary_write(UFSTOVFS(ump));
2448 ump->um_trim_inflight -= 1;
2449 ump->um_trim_inflight_blks -= numfrags(ump->um_fs, tp->size);
2455 * Lookup a trim request by inode number.
2456 * Allocate if requested (NEW, REPLACE, SINGLE).
2458 static struct ffs_blkfree_trim_params *
2459 trim_lookup(ump, devvp, bno, size, inum, key, alloctype)
2460 struct ufsmount *ump;
2461 struct vnode *devvp;
2468 struct trimlist_hashhead *tphashhead;
2469 struct ffs_blkfree_trim_params *tp, *ntp;
2471 ntp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TRIM, M_WAITOK);
2472 if (alloctype != SINGLE) {
2473 KASSERT(key >= FIRST_VALID_KEY, ("trim_lookup: invalid key"));
2475 tphashhead = TRIMLIST_HASH(ump, key);
2476 LIST_FOREACH(tp, tphashhead, hashlist)
2480 switch (alloctype) {
2482 KASSERT(tp == NULL, ("trim_lookup: found trim"));
2486 ("trim_lookup: missing call to ffs_blkrelease_start()"));
2491 KASSERT(tp != NULL, ("trim_lookup: missing REPLACE trim"));
2492 LIST_REMOVE(tp, hashlist);
2493 /* tp will be freed by caller */
2496 KASSERT(tp != NULL, ("trim_lookup: missing DONE trim"));
2497 LIST_REMOVE(tp, hashlist);
2502 TAILQ_INIT(&ntp->blklist);
2509 if (alloctype != SINGLE) {
2510 LIST_INSERT_HEAD(tphashhead, ntp, hashlist);
2517 * Dispatch a trim request.
2520 ffs_blkfree_sendtrim(tp)
2521 struct ffs_blkfree_trim_params *tp;
2523 struct ufsmount *ump;
2528 * Postpone the set of the free bit in the cg bitmap until the
2529 * BIO_DELETE is completed. Otherwise, due to disk queue
2530 * reordering, TRIM might be issued after we reuse the block
2531 * and write some new data into it.
2534 bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
2535 bp->b_iocmd = BIO_DELETE;
2536 bp->b_iooffset = dbtob(fsbtodb(ump->um_fs, tp->bno));
2537 bp->b_iodone = ffs_blkfree_trim_completed;
2538 bp->b_bcount = tp->size;
2539 bp->b_fsprivate1 = tp;
2541 ump->um_trim_total += 1;
2542 ump->um_trim_inflight += 1;
2543 ump->um_trim_inflight_blks += numfrags(ump->um_fs, tp->size);
2544 ump->um_trim_total_blks += numfrags(ump->um_fs, tp->size);
2548 vn_start_secondary_write(NULL, &mp, 0);
2549 g_vfs_strategy(ump->um_bo, bp);
2553 * Allocate a new key to use to identify a range of blocks.
2556 ffs_blkrelease_start(ump, devvp, inum)
2557 struct ufsmount *ump;
2558 struct vnode *devvp;
2561 static u_long masterkey;
2564 if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2565 return (SINGLETON_KEY);
2567 key = atomic_fetchadd_long(&masterkey, 1);
2568 } while (key < FIRST_VALID_KEY);
2569 (void) trim_lookup(ump, devvp, 0, 0, inum, key, NEW);
2574 * Deallocate a key that has been used to identify a range of blocks.
2577 ffs_blkrelease_finish(ump, key)
2578 struct ufsmount *ump;
2581 struct ffs_blkfree_trim_params *tp;
2583 if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2586 * If the vfs.ffs.dotrimcons sysctl option is enabled while
2587 * a file deletion is active, specifically after a call
2588 * to ffs_blkrelease_start() but before the call to
2589 * ffs_blkrelease_finish(), ffs_blkrelease_start() will
2590 * have handed out SINGLETON_KEY rather than starting a
2591 * collection sequence. Thus if we get a SINGLETON_KEY
2592 * passed to ffs_blkrelease_finish(), we just return rather
2593 * than trying to finish the nonexistent sequence.
2595 if (key == SINGLETON_KEY) {
2597 printf("%s: vfs.ffs.dotrimcons enabled on active filesystem\n",
2598 ump->um_mountp->mnt_stat.f_mntonname);
2603 * We are done with sending blocks using this key. Look up the key
2604 * using the DONE alloctype (in tp) to request that it be unhashed
2605 * as we will not be adding to it. If the key has never been used,
2606 * tp->size will be zero, so we can just free tp. Otherwise the call
2607 * to ffs_blkfree_sendtrim(tp) causes the block range described by
2608 * tp to be issued (and then tp to be freed).
2610 tp = trim_lookup(ump, NULL, 0, 0, 0, key, DONE);
2614 ffs_blkfree_sendtrim(tp);
2618 * Setup to free a block or fragment.
2620 * Check for snapshots that might want to claim the block.
2621 * If trims are requested, prepare a trim request. Attempt to
2622 * aggregate consecutive blocks into a single trim request.
2625 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd, key)
2626 struct ufsmount *ump;
2628 struct vnode *devvp;
2633 struct workhead *dephd;
2636 struct ffs_blkfree_trim_params *tp, *ntp;
2637 struct trim_blkreq *blkelm;
2640 * Check to see if a snapshot wants to claim the block.
2641 * Check that devvp is a normal disk device, not a snapshot,
2642 * it has a snapshot(s) associated with it, and one of the
2643 * snapshots wants to claim the block.
2645 if (devvp->v_type == VCHR &&
2646 (devvp->v_vflag & VV_COPYONWRITE) &&
2647 ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2651 * Nothing to delay if TRIM is not required for this block or TRIM
2652 * is disabled or the operation is performed on a snapshot.
2654 if (key == NOTRIM_KEY || ((ump->um_flags & UM_CANDELETE) == 0) ||
2655 devvp->v_type == VREG) {
2656 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2659 blkelm = malloc(sizeof(struct trim_blkreq), M_TRIM, M_WAITOK);
2661 blkelm->size = size;
2662 if (dephd == NULL) {
2663 blkelm->pdephd = NULL;
2665 LIST_INIT(&blkelm->dephd);
2666 LIST_SWAP(dephd, &blkelm->dephd, worklist, wk_list);
2667 blkelm->pdephd = &blkelm->dephd;
2669 if (key == SINGLETON_KEY) {
2671 * Just a single non-contiguous piece. Use the SINGLE
2672 * alloctype to return a trim request that will not be
2673 * hashed for future lookup.
2675 tp = trim_lookup(ump, devvp, bno, size, inum, key, SINGLE);
2676 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2677 ffs_blkfree_sendtrim(tp);
2681 * The callers of this function are not tracking whether or not
2682 * the blocks are contiguous. They are just saying that they
2683 * are freeing a set of blocks. It is this code that determines
2684 * the pieces of that range that are actually contiguous.
2686 * Calling ffs_blkrelease_start() will have created an entry
2689 tp = trim_lookup(ump, devvp, bno, size, inum, key, OLD);
2690 if (tp->size == 0) {
2692 * First block of a potential range, set block and size
2693 * for the trim block.
2697 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2701 * If this block is a continuation of the range (either
2702 * follows at the end or preceeds in the front) then we
2703 * add it to the front or back of the list and return.
2705 * If it is not a continuation of the trim that we were
2706 * building, using the REPLACE alloctype, we request that
2707 * the old trim request (still in tp) be unhashed and a
2708 * new range started (in ntp). The ffs_blkfree_sendtrim(tp)
2709 * call causes the block range described by tp to be issued
2710 * (and then tp to be freed).
2712 if (bno + numfrags(fs, size) == tp->bno) {
2713 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2717 } else if (bno == tp->bno + numfrags(fs, tp->size)) {
2718 TAILQ_INSERT_TAIL(&tp->blklist, blkelm, blkreqlist);
2722 ntp = trim_lookup(ump, devvp, bno, size, inum, key, REPLACE);
2723 TAILQ_INSERT_HEAD(&ntp->blklist, blkelm, blkreqlist);
2724 ffs_blkfree_sendtrim(tp);
2729 * Verify allocation of a block or fragment. Returns true if block or
2730 * fragment is allocated, false if it is free.
2733 ffs_checkblk(ip, bno, size)
2742 int i, error, frags, free;
2746 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2747 printf("bsize = %ld, size = %ld, fs = %s\n",
2748 (long)fs->fs_bsize, size, fs->fs_fsmnt);
2749 panic("ffs_checkblk: bad size");
2751 if ((u_int)bno >= fs->fs_size)
2752 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2753 error = ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), 0, &bp, &cgp);
2755 panic("ffs_checkblk: cylinder group read failed");
2756 blksfree = cg_blksfree(cgp);
2757 cgbno = dtogd(fs, bno);
2758 if (size == fs->fs_bsize) {
2759 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2761 frags = numfrags(fs, size);
2762 for (free = 0, i = 0; i < frags; i++)
2763 if (isset(blksfree, cgbno + i))
2765 if (free != 0 && free != frags)
2766 panic("ffs_checkblk: partially free fragment");
2771 #endif /* INVARIANTS */
2777 ffs_vfree(pvp, ino, mode)
2782 struct ufsmount *ump;
2784 if (DOINGSOFTDEP(pvp)) {
2785 softdep_freefile(pvp, ino, mode);
2788 ump = VFSTOUFS(pvp->v_mount);
2789 return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2793 * Do the actual free operation.
2794 * The specified inode is placed back in the free map.
2797 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2798 struct ufsmount *ump;
2800 struct vnode *devvp;
2803 struct workhead *wkhd;
2814 cg = ino_to_cg(fs, ino);
2815 if (devvp->v_type == VREG) {
2816 /* devvp is a snapshot */
2817 MPASS(devvp->v_mount->mnt_data == ump);
2818 dev = ump->um_devvp->v_rdev;
2819 } else if (devvp->v_type == VCHR) {
2820 /* devvp is a normal disk device */
2821 dev = devvp->v_rdev;
2826 if (ino >= fs->fs_ipg * fs->fs_ncg)
2827 panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2828 devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2829 if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2830 if (!ffs_fsfail_cleanup(ump, error) ||
2831 !MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2833 if (devvp->v_type == VREG)
2834 dbn = fragstoblks(fs, cgtod(fs, cg));
2836 dbn = fsbtodb(fs, cgtod(fs, cg));
2837 error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2838 KASSERT(error == 0, ("getblkx failed"));
2839 softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd);
2840 bp->b_flags |= B_RELBUF | B_NOCACHE;
2841 bp->b_flags &= ~B_CACHE;
2845 inosused = cg_inosused(cgp);
2846 cgino = ino % fs->fs_ipg;
2847 if (isclr(inosused, cgino)) {
2848 printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2849 (uintmax_t)ino, fs->fs_fsmnt);
2850 if (fs->fs_ronly == 0)
2851 panic("ffs_freefile: freeing free inode");
2853 clrbit(inosused, cgino);
2854 if (cgino < cgp->cg_irotor)
2855 cgp->cg_irotor = cgino;
2856 cgp->cg_cs.cs_nifree++;
2858 fs->fs_cstotal.cs_nifree++;
2859 fs->fs_cs(fs, cg).cs_nifree++;
2860 if ((mode & IFMT) == IFDIR) {
2861 cgp->cg_cs.cs_ndir--;
2862 fs->fs_cstotal.cs_ndir--;
2863 fs->fs_cs(fs, cg).cs_ndir--;
2866 ACTIVECLEAR(fs, cg);
2868 if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2869 softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd);
2875 * Check to see if a file is free.
2876 * Used to check for allocated files in snapshots.
2879 ffs_checkfreefile(fs, devvp, ino)
2881 struct vnode *devvp;
2890 cg = ino_to_cg(fs, ino);
2891 if ((devvp->v_type != VREG) && (devvp->v_type != VCHR))
2893 if (ino >= fs->fs_ipg * fs->fs_ncg)
2895 if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
2897 inosused = cg_inosused(cgp);
2899 ret = isclr(inosused, ino);
2905 * Find a block of the specified size in the specified cylinder group.
2907 * It is a panic if a request is made to find a block if none are
2911 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2918 int start, len, loc, i;
2919 int blk, field, subfield, pos;
2923 * find the fragment by searching through the free block
2924 * map for an appropriate bit pattern
2927 start = dtogd(fs, bpref) / NBBY;
2929 start = cgp->cg_frotor / NBBY;
2930 blksfree = cg_blksfree(cgp);
2931 len = howmany(fs->fs_fpg, NBBY) - start;
2932 loc = scanc((u_int)len, (u_char *)&blksfree[start],
2933 fragtbl[fs->fs_frag],
2934 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2938 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2939 fragtbl[fs->fs_frag],
2940 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2942 printf("start = %d, len = %d, fs = %s\n",
2943 start, len, fs->fs_fsmnt);
2944 panic("ffs_alloccg: map corrupted");
2948 bno = (start + len - loc) * NBBY;
2949 cgp->cg_frotor = bno;
2951 * found the byte in the map
2952 * sift through the bits to find the selected frag
2954 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2955 blk = blkmap(fs, blksfree, bno);
2957 field = around[allocsiz];
2958 subfield = inside[allocsiz];
2959 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2960 if ((blk & field) == subfield)
2966 printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2967 panic("ffs_alloccg: block not in map");
2971 static const struct statfs *
2972 ffs_getmntstat(struct vnode *devvp)
2975 if (devvp->v_type == VCHR)
2976 return (&devvp->v_rdev->si_mountpt->mnt_stat);
2977 return (ffs_getmntstat(VFSTOUFS(devvp->v_mount)->um_devvp));
2981 * Fetch and verify a cylinder group.
2984 ffs_getcg(fs, devvp, cg, flags, bpp, cgpp)
2986 struct vnode *devvp;
2994 const struct statfs *sfs;
3000 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
3002 if (devvp->v_type == VREG)
3003 blkno = fragstoblks(fs, cgtod(fs, cg));
3005 blkno = fsbtodb(fs, cgtod(fs, cg));
3006 error = breadn_flags(devvp, blkno, blkno, (int)fs->fs_cgsize, NULL,
3007 NULL, 0, NOCRED, flags, ffs_ckhash_cg, &bp);
3010 cgp = (struct cg *)bp->b_data;
3011 if ((fs->fs_metackhash & CK_CYLGRP) != 0 &&
3012 (bp->b_flags & B_CKHASH) != 0 &&
3013 cgp->cg_ckhash != bp->b_ckhash) {
3014 sfs = ffs_getmntstat(devvp);
3015 printf("UFS %s%s (%s) cylinder checksum failed: cg %u, cgp: "
3016 "0x%x != bp: 0x%jx\n",
3017 devvp->v_type == VCHR ? "" : "snapshot of ",
3018 sfs->f_mntfromname, sfs->f_mntonname,
3019 cg, cgp->cg_ckhash, (uintmax_t)bp->b_ckhash);
3020 bp->b_flags &= ~B_CKHASH;
3021 bp->b_flags |= B_INVAL | B_NOCACHE;
3025 if (!cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
3026 sfs = ffs_getmntstat(devvp);
3027 printf("UFS %s%s (%s)",
3028 devvp->v_type == VCHR ? "" : "snapshot of ",
3029 sfs->f_mntfromname, sfs->f_mntonname);
3030 if (!cg_chkmagic(cgp))
3031 printf(" cg %u: bad magic number 0x%x should be 0x%x\n",
3032 cg, cgp->cg_magic, CG_MAGIC);
3034 printf(": wrong cylinder group cg %u != cgx %u\n", cg,
3036 bp->b_flags &= ~B_CKHASH;
3037 bp->b_flags |= B_INVAL | B_NOCACHE;
3041 bp->b_flags &= ~B_CKHASH;
3042 bp->b_xflags |= BX_BKGRDWRITE;
3044 * If we are using check hashes on the cylinder group then we want
3045 * to limit changing the cylinder group time to when we are actually
3046 * going to write it to disk so that its check hash remains correct
3047 * in memory. If the CK_CYLGRP flag is set the time is updated in
3048 * ffs_bufwrite() as the buffer is queued for writing. Otherwise we
3049 * update the time here as we have done historically.
3051 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
3052 bp->b_xflags |= BX_CYLGRP;
3054 cgp->cg_old_time = cgp->cg_time = time_second;
3067 cgp = (struct cg *)bp->b_data;
3068 ckhash = cgp->cg_ckhash;
3070 bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
3071 cgp->cg_ckhash = ckhash;
3075 * Fserr prints the name of a filesystem with an error diagnostic.
3077 * The form of the error message is:
3081 ffs_fserr(fs, inum, cp)
3086 struct thread *td = curthread; /* XXX */
3087 struct proc *p = td->td_proc;
3089 log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
3090 p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
3095 * This function provides the capability for the fsck program to
3096 * update an active filesystem. Fourteen operations are provided:
3098 * adjrefcnt(inode, amt) - adjusts the reference count on the
3099 * specified inode by the specified amount. Under normal
3100 * operation the count should always go down. Decrementing
3101 * the count to zero will cause the inode to be freed.
3102 * adjblkcnt(inode, amt) - adjust the number of blocks used by the
3103 * inode by the specified amount.
3104 * setsize(inode, size) - set the size of the inode to the
3106 * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
3107 * adjust the superblock summary.
3108 * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
3109 * are marked as free. Inodes should never have to be marked
3111 * freefiles(inode, count) - file inodes [inode..inode + count - 1]
3112 * are marked as free. Inodes should never have to be marked
3114 * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
3115 * are marked as free. Blocks should never have to be marked
3117 * setflags(flags, set/clear) - the fs_flags field has the specified
3118 * flags set (second parameter +1) or cleared (second parameter -1).
3119 * setcwd(dirinode) - set the current directory to dirinode in the
3120 * filesystem associated with the snapshot.
3121 * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
3122 * in the current directory is oldvalue then change it to newvalue.
3123 * unlink(nameptr, oldvalue) - Verify that the inode number associated
3124 * with nameptr in the current directory is oldvalue then unlink it.
3127 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
3129 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt,
3130 CTLFLAG_WR | CTLTYPE_STRUCT | CTLFLAG_NEEDGIANT,
3131 0, 0, sysctl_ffs_fsck, "S,fsck",
3132 "Adjust Inode Reference Count");
3134 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt,
3135 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3136 "Adjust Inode Used Blocks Count");
3138 static SYSCTL_NODE(_vfs_ffs, FFS_SET_SIZE, setsize,
3139 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3140 "Set the inode size");
3142 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir,
3143 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3144 "Adjust number of directories");
3146 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree,
3147 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3148 "Adjust number of free blocks");
3150 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree,
3151 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3152 "Adjust number of free inodes");
3154 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree,
3155 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3156 "Adjust number of free frags");
3158 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters,
3159 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3160 "Adjust number of free clusters");
3162 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs,
3163 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3164 "Free Range of Directory Inodes");
3166 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles,
3167 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3168 "Free Range of File Inodes");
3170 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks,
3171 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3172 "Free Range of Blocks");
3174 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags,
3175 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3176 "Change Filesystem Flags");
3178 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd,
3179 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3180 "Set Current Working Directory");
3182 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot,
3183 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3184 "Change Value of .. Entry");
3186 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink,
3187 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3188 "Unlink a Duplicate Name");
3191 static int fsckcmds = 0;
3192 SYSCTL_INT(_debug, OID_AUTO, ffs_fsckcmds, CTLFLAG_RW, &fsckcmds, 0,
3193 "print out fsck_ffs-based filesystem update commands");
3194 #endif /* DIAGNOSTIC */
3197 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
3199 struct thread *td = curthread;
3200 struct fsck_cmd cmd;
3201 struct ufsmount *ump;
3202 struct vnode *vp, *dvp, *fdvp;
3203 struct inode *ip, *dp;
3208 long blkcnt, blksize;
3211 cap_rights_t rights;
3212 int filetype, error;
3214 if (req->newlen > sizeof cmd)
3216 if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
3218 if (cmd.version != FFS_CMD_VERSION)
3219 return (ERPCMISMATCH);
3220 if ((error = getvnode(td, cmd.handle,
3221 cap_rights_init(&rights, CAP_FSCK), &fp)) != 0)
3224 if (vp->v_type != VREG && vp->v_type != VDIR) {
3228 vn_start_write(vp, &mp, V_WAIT);
3230 strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
3231 vn_finished_write(mp);
3236 if ((mp->mnt_flag & MNT_RDONLY) &&
3237 ump->um_fsckpid != td->td_proc->p_pid) {
3238 vn_finished_write(mp);
3245 switch (oidp->oid_number) {
3250 printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
3251 cmd.size > 0 ? "set" : "clear");
3252 #endif /* DIAGNOSTIC */
3254 fs->fs_flags |= (long)cmd.value;
3256 fs->fs_flags &= ~(long)cmd.value;
3259 case FFS_ADJ_REFCNT:
3262 printf("%s: adjust inode %jd link count by %jd\n",
3263 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3264 (intmax_t)cmd.size);
3266 #endif /* DIAGNOSTIC */
3267 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3270 ip->i_nlink += cmd.size;
3271 DIP_SET(ip, i_nlink, ip->i_nlink);
3272 ip->i_effnlink += cmd.size;
3273 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3274 error = ffs_update(vp, 1);
3275 if (DOINGSOFTDEP(vp))
3276 softdep_change_linkcnt(ip);
3280 case FFS_ADJ_BLKCNT:
3283 printf("%s: adjust inode %jd block count by %jd\n",
3284 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3285 (intmax_t)cmd.size);
3287 #endif /* DIAGNOSTIC */
3288 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3291 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
3292 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3293 error = ffs_update(vp, 1);
3300 printf("%s: set inode %jd size to %jd\n",
3301 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3302 (intmax_t)cmd.size);
3304 #endif /* DIAGNOSTIC */
3305 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3308 DIP_SET(ip, i_size, cmd.size);
3309 UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_MODIFIED);
3310 error = ffs_update(vp, 1);
3322 printf("%s: free %s inode %ju\n",
3323 mp->mnt_stat.f_mntonname,
3324 filetype == IFDIR ? "directory" : "file",
3325 (uintmax_t)cmd.value);
3327 printf("%s: free %s inodes %ju-%ju\n",
3328 mp->mnt_stat.f_mntonname,
3329 filetype == IFDIR ? "directory" : "file",
3330 (uintmax_t)cmd.value,
3331 (uintmax_t)(cmd.value + cmd.size - 1));
3333 #endif /* DIAGNOSTIC */
3334 while (cmd.size > 0) {
3335 if ((error = ffs_freefile(ump, fs, ump->um_devvp,
3336 cmd.value, filetype, NULL)))
3347 printf("%s: free block %jd\n",
3348 mp->mnt_stat.f_mntonname,
3349 (intmax_t)cmd.value);
3351 printf("%s: free blocks %jd-%jd\n",
3352 mp->mnt_stat.f_mntonname,
3353 (intmax_t)cmd.value,
3354 (intmax_t)cmd.value + cmd.size - 1);
3356 #endif /* DIAGNOSTIC */
3359 blksize = fs->fs_frag - (blkno % fs->fs_frag);
3360 key = ffs_blkrelease_start(ump, ump->um_devvp, UFS_ROOTINO);
3361 while (blkcnt > 0) {
3362 if (blkcnt < blksize)
3364 ffs_blkfree(ump, fs, ump->um_devvp, blkno,
3365 blksize * fs->fs_fsize, UFS_ROOTINO,
3369 blksize = fs->fs_frag;
3371 ffs_blkrelease_finish(ump, key);
3375 * Adjust superblock summaries. fsck(8) is expected to
3376 * submit deltas when necessary.
3381 printf("%s: adjust number of directories by %jd\n",
3382 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3384 #endif /* DIAGNOSTIC */
3385 fs->fs_cstotal.cs_ndir += cmd.value;
3388 case FFS_ADJ_NBFREE:
3391 printf("%s: adjust number of free blocks by %+jd\n",
3392 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3394 #endif /* DIAGNOSTIC */
3395 fs->fs_cstotal.cs_nbfree += cmd.value;
3398 case FFS_ADJ_NIFREE:
3401 printf("%s: adjust number of free inodes by %+jd\n",
3402 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3404 #endif /* DIAGNOSTIC */
3405 fs->fs_cstotal.cs_nifree += cmd.value;
3408 case FFS_ADJ_NFFREE:
3411 printf("%s: adjust number of free frags by %+jd\n",
3412 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3414 #endif /* DIAGNOSTIC */
3415 fs->fs_cstotal.cs_nffree += cmd.value;
3418 case FFS_ADJ_NUMCLUSTERS:
3421 printf("%s: adjust number of free clusters by %+jd\n",
3422 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3424 #endif /* DIAGNOSTIC */
3425 fs->fs_cstotal.cs_numclusters += cmd.value;
3431 printf("%s: set current directory to inode %jd\n",
3432 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3434 #endif /* DIAGNOSTIC */
3435 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
3437 AUDIT_ARG_VNODE1(vp);
3438 if ((error = change_dir(vp, td)) != 0) {
3446 case FFS_SET_DOTDOT:
3449 printf("%s: change .. in cwd from %jd to %jd\n",
3450 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3451 (intmax_t)cmd.size);
3453 #endif /* DIAGNOSTIC */
3455 * First we have to get and lock the parent directory
3456 * to which ".." points.
3458 error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3462 * Now we get and lock the child directory containing "..".
3465 dvp = pwd->pwd_cdir;
3466 if ((error = vget(dvp, LK_EXCLUSIVE)) != 0) {
3472 dp->i_offset = 12; /* XXX mastertemplate.dot_reclen */
3473 error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3487 if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3488 strncpy(buf, "Name_too_long", 32);
3489 printf("%s: unlink %s (inode %jd)\n",
3490 mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3492 #endif /* DIAGNOSTIC */
3494 * kern_funlinkat will do its own start/finish writes and
3495 * they do not nest, so drop ours here. Setting mp == NULL
3496 * indicates that vn_finished_write is not needed down below.
3498 vn_finished_write(mp);
3500 error = kern_funlinkat(td, AT_FDCWD,
3501 (char *)(intptr_t)cmd.value, FD_NONE, UIO_USERSPACE,
3502 0, (ino_t)cmd.size);
3508 printf("Invalid request %d from fsck\n",
3511 #endif /* DIAGNOSTIC */
3517 vn_finished_write(mp);