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);
226 ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
228 ffs_fserr(fs, ip->i_number, "filesystem full");
229 uprintf("\n%s: write failed, filesystem is full\n",
238 * Reallocate a fragment to a bigger size
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.
246 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
251 int osize, nsize, flags;
258 struct ufsmount *ump;
259 u_int cg, request, reclaimed;
268 gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
270 mtx_assert(UFS_MTX(ump), MA_OWNED);
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) {
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");
283 panic("ffs_realloccg: missing credential");
284 #endif /* INVARIANTS */
287 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
288 freespace(fs, fs->fs_minfree) - numfrags(fs, nsize - osize) < 0) {
292 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
293 devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
295 panic("ffs_realloccg: bad bprev");
299 * Allocate the extra space in the buffer.
301 error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
306 if (bp->b_blkno == bp->b_lblkno) {
307 if (lbprev >= UFS_NDADDR)
308 panic("ffs_realloccg: lbprev out of range");
309 bp->b_blkno = fsbtodb(fs, bprev);
313 error = chkdq(ip, btodb(nsize - osize), cred, 0);
320 * Check for extension in the existing location.
323 cg = dtog(fs, bprev);
325 bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
327 if (bp->b_blkno != fsbtodb(fs, bno))
328 panic("ffs_realloccg: bad blockno");
329 delta = btodb(nsize - osize);
330 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
332 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
334 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
336 bp->b_flags |= B_DONE;
337 vfs_bio_bzero_buf(bp, osize, nsize - osize);
338 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
339 vfs_bio_set_valid(bp, osize, nsize - osize);
344 * Allocate a new disk location.
346 if (bpref >= fs->fs_size)
348 switch ((int)fs->fs_optim) {
351 * Allocate an exact sized fragment. Although this makes
352 * best use of space, we will waste time relocating it if
353 * the file continues to grow. If the fragmentation is
354 * less than half of the minimum free reserve, we choose
355 * to begin optimizing for time.
358 if (fs->fs_minfree <= 5 ||
359 fs->fs_cstotal.cs_nffree >
360 (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
362 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
364 fs->fs_optim = FS_OPTTIME;
368 * At this point we have discovered a file that is trying to
369 * grow a small fragment to a larger fragment. To save time,
370 * we allocate a full sized block, then free the unused portion.
371 * If the file continues to grow, the `ffs_fragextend' call
372 * above will be able to grow it in place without further
373 * copying. If aberrant programs cause disk fragmentation to
374 * grow within 2% of the free reserve, we choose to begin
375 * optimizing for space.
377 request = fs->fs_bsize;
378 if (fs->fs_cstotal.cs_nffree <
379 (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
381 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
383 fs->fs_optim = FS_OPTSPACE;
386 printf("dev = %s, optim = %ld, fs = %s\n",
387 devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
388 panic("ffs_realloccg: bad optim");
391 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
393 bp->b_blkno = fsbtodb(fs, bno);
394 if (!DOINGSOFTDEP(vp))
396 * The usual case is that a smaller fragment that
397 * was just allocated has been replaced with a bigger
398 * fragment or a full-size block. If it is marked as
399 * B_DELWRI, the current contents have not been written
400 * to disk. It is possible that the block was written
401 * earlier, but very uncommon. If the block has never
402 * been written, there is no need to send a BIO_DELETE
403 * for it when it is freed. The gain from avoiding the
404 * TRIMs for the common case of unwritten blocks far
405 * exceeds the cost of the write amplification for the
406 * uncommon case of failing to send a TRIM for a block
407 * that had been written.
409 ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
410 ip->i_number, vp->v_type, NULL,
411 (bp->b_flags & B_DELWRI) != 0 ?
412 NOTRIM_KEY : SINGLETON_KEY);
413 delta = btodb(nsize - osize);
414 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
416 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
418 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
420 bp->b_flags |= B_DONE;
421 vfs_bio_bzero_buf(bp, osize, nsize - osize);
422 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
423 vfs_bio_set_valid(bp, osize, nsize - osize);
430 * Restore user's disk quota because allocation failed.
432 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
439 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
447 softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
451 ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
453 ffs_fserr(fs, ip->i_number, "filesystem full");
454 uprintf("\n%s: write failed, filesystem is full\n",
465 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
467 * The vnode and an array of buffer pointers for a range of sequential
468 * logical blocks to be made contiguous is given. The allocator attempts
469 * to find a range of sequential blocks starting as close as possible
470 * from the end of the allocation for the logical block immediately
471 * preceding the current range. If successful, the physical block numbers
472 * in the buffer pointers and in the inode are changed to reflect the new
473 * allocation. If unsuccessful, the allocation is left unchanged. The
474 * success in doing the reallocation is returned. Note that the error
475 * return is not reflected back to the user. Rather the previous block
476 * allocation will be used.
479 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
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");
486 static int doreallocblks = 1;
487 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
488 "enable block reallocation");
490 static int dotrimcons = 1;
491 SYSCTL_INT(_vfs_ffs, OID_AUTO, dotrimcons, CTLFLAG_RWTUN, &dotrimcons, 0,
492 "enable BIO_DELETE / TRIM consolidation");
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");
499 static int prtrealloc = 0;
500 SYSCTL_INT(_debug, OID_AUTO, ffs_prtrealloc, CTLFLAG_RW, &prtrealloc, 0,
501 "print out FFS filesystem block reallocation operations");
506 struct vop_reallocblks_args /* {
508 struct cluster_save *a_buflist;
511 struct ufsmount *ump;
514 * We used to skip reallocating the blocks of a file into a
515 * contiguous sequence if the underlying flash device requested
516 * BIO_DELETE notifications, because devices that benefit from
517 * BIO_DELETE also benefit from not moving the data. However,
518 * the destination for the data is usually moved before the data
519 * is written to the initially allocated location, so we rarely
520 * suffer the penalty of extra writes. With the addition of the
521 * consolidation of contiguous blocks into single BIO_DELETE
522 * operations, having fewer but larger contiguous blocks reduces
523 * the number of (slow and expensive) BIO_DELETE operations. So
524 * when doing BIO_DELETE consolidation, we do block reallocation.
526 * Skip if reallocblks has been disabled globally.
528 ump = ap->a_vp->v_mount->mnt_data;
529 if ((((ump->um_flags) & UM_CANDELETE) != 0 && dotrimcons == 0) ||
534 * We can't wait in softdep prealloc as it may fsync and recurse
535 * here. Instead we simply fail to reallocate blocks if this
536 * rare condition arises.
538 if (DOINGSOFTDEP(ap->a_vp))
539 if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
541 if (ump->um_fstype == UFS1)
542 return (ffs_reallocblks_ufs1(ap));
543 return (ffs_reallocblks_ufs2(ap));
547 ffs_reallocblks_ufs1(ap)
548 struct vop_reallocblks_args /* {
550 struct cluster_save *a_buflist;
556 struct buf *sbp, *ebp, *bp;
557 ufs1_daddr_t *bap, *sbap, *ebap;
558 struct cluster_save *buflist;
559 struct ufsmount *ump;
560 ufs_lbn_t start_lbn, end_lbn;
561 ufs1_daddr_t soff, newblk, blkno;
563 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
564 int i, cg, len, start_lvl, end_lvl, ssize;
571 * If we are not tracking block clusters or if we have less than 4%
572 * free blocks left, then do not attempt to cluster. Running with
573 * less than 5% free block reserve is not recommended and those that
574 * choose to do so do not expect to have good file layout.
576 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
578 buflist = ap->a_buflist;
579 len = buflist->bs_nchildren;
580 start_lbn = buflist->bs_children[0]->b_lblkno;
581 end_lbn = start_lbn + len - 1;
583 for (i = 0; i < len; i++)
584 if (!ffs_checkblk(ip,
585 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
586 panic("ffs_reallocblks: unallocated block 1");
587 for (i = 1; i < len; i++)
588 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
589 panic("ffs_reallocblks: non-logical cluster");
590 blkno = buflist->bs_children[0]->b_blkno;
591 ssize = fsbtodb(fs, fs->fs_frag);
592 for (i = 1; i < len - 1; i++)
593 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
594 panic("ffs_reallocblks: non-physical cluster %d", i);
597 * If the cluster crosses the boundary for the first indirect
598 * block, leave space for the indirect block. Indirect blocks
599 * are initially laid out in a position after the last direct
600 * block. Block reallocation would usually destroy locality by
601 * moving the indirect block out of the way to make room for
602 * data blocks if we didn't compensate here. We should also do
603 * this for other indirect block boundaries, but it is only
604 * important for the first one.
606 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
609 * If the latest allocation is in a new cylinder group, assume that
610 * the filesystem has decided to move and do not force it back to
611 * the previous cylinder group.
613 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
614 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
616 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
617 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
620 * Get the starting offset and block map for the first block.
622 if (start_lvl == 0) {
623 sbap = &ip->i_din1->di_db[0];
626 idp = &start_ap[start_lvl - 1];
627 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
631 sbap = (ufs1_daddr_t *)sbp->b_data;
635 * If the block range spans two block maps, get the second map.
638 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
643 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
644 panic("ffs_reallocblk: start == end");
646 ssize = len - (idp->in_off + 1);
647 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
649 ebap = (ufs1_daddr_t *)ebp->b_data;
652 * Find the preferred location for the cluster. If we have not
653 * previously failed at this endeavor, then follow our standard
654 * preference calculation. If we have failed at it, then pick up
655 * where we last ended our search.
658 if (ip->i_nextclustercg == -1)
659 pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
661 pref = cgdata(fs, ip->i_nextclustercg);
663 * Search the block map looking for an allocation of the desired size.
664 * To avoid wasting too much time, we limit the number of cylinder
665 * groups that we will search.
668 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
669 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
672 if (cg >= fs->fs_ncg)
676 * If we have failed in our search, record where we gave up for
677 * next time. Otherwise, fall back to our usual search citerion.
680 ip->i_nextclustercg = cg;
684 ip->i_nextclustercg = -1;
686 * We have found a new contiguous block.
688 * First we have to replace the old block pointers with the new
689 * block pointers in the inode and indirect blocks associated
694 printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
695 (uintmax_t)ip->i_number,
696 (intmax_t)start_lbn, (intmax_t)end_lbn);
699 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
705 if (!ffs_checkblk(ip,
706 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
707 panic("ffs_reallocblks: unallocated block 2");
708 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
709 panic("ffs_reallocblks: alloc mismatch");
713 printf(" %d,", *bap);
715 if (DOINGSOFTDEP(vp)) {
716 if (sbap == &ip->i_din1->di_db[0] && i < ssize)
717 softdep_setup_allocdirect(ip, start_lbn + i,
718 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
719 buflist->bs_children[i]);
721 softdep_setup_allocindir_page(ip, start_lbn + i,
722 i < ssize ? sbp : ebp, soff + i, blkno,
723 *bap, buflist->bs_children[i]);
728 * Next we must write out the modified inode and indirect blocks.
729 * For strict correctness, the writes should be synchronous since
730 * the old block values may have been written to disk. In practise
731 * they are almost never written, but if we are concerned about
732 * strict correctness, the `doasyncfree' flag should be set to zero.
734 * The test on `doasyncfree' should be changed to test a flag
735 * that shows whether the associated buffers and inodes have
736 * been written. The flag should be set when the cluster is
737 * started and cleared whenever the buffer or inode is flushed.
738 * We can then check below to see if it is set, and do the
739 * synchronous write only when it has been cleared.
741 if (sbap != &ip->i_din1->di_db[0]) {
747 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
758 * Last, free the old blocks and assign the new blocks to the buffers.
764 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
765 bp = buflist->bs_children[i];
766 if (!DOINGSOFTDEP(vp))
768 * The usual case is that a set of N-contiguous blocks
769 * that was just allocated has been replaced with a
770 * set of N+1-contiguous blocks. If they are marked as
771 * B_DELWRI, the current contents have not been written
772 * to disk. It is possible that the blocks were written
773 * earlier, but very uncommon. If the blocks have never
774 * been written, there is no need to send a BIO_DELETE
775 * for them when they are freed. The gain from avoiding
776 * the TRIMs for the common case of unwritten blocks
777 * far exceeds the cost of the write amplification for
778 * the uncommon case of failing to send a TRIM for the
779 * blocks that had been written.
781 ffs_blkfree(ump, fs, ump->um_devvp,
782 dbtofsb(fs, bp->b_blkno),
783 fs->fs_bsize, ip->i_number, vp->v_type, NULL,
784 (bp->b_flags & B_DELWRI) != 0 ?
785 NOTRIM_KEY : SINGLETON_KEY);
786 bp->b_blkno = fsbtodb(fs, blkno);
788 if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
789 panic("ffs_reallocblks: unallocated block 3");
793 printf(" %d,", blkno);
807 if (sbap != &ip->i_din1->di_db[0])
813 ffs_reallocblks_ufs2(ap)
814 struct vop_reallocblks_args /* {
816 struct cluster_save *a_buflist;
822 struct buf *sbp, *ebp, *bp;
823 ufs2_daddr_t *bap, *sbap, *ebap;
824 struct cluster_save *buflist;
825 struct ufsmount *ump;
826 ufs_lbn_t start_lbn, end_lbn;
827 ufs2_daddr_t soff, newblk, blkno, pref;
828 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
829 int i, cg, len, start_lvl, end_lvl, ssize;
836 * If we are not tracking block clusters or if we have less than 4%
837 * free blocks left, then do not attempt to cluster. Running with
838 * less than 5% free block reserve is not recommended and those that
839 * choose to do so do not expect to have good file layout.
841 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
843 buflist = ap->a_buflist;
844 len = buflist->bs_nchildren;
845 start_lbn = buflist->bs_children[0]->b_lblkno;
846 end_lbn = start_lbn + len - 1;
848 for (i = 0; i < len; i++)
849 if (!ffs_checkblk(ip,
850 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
851 panic("ffs_reallocblks: unallocated block 1");
852 for (i = 1; i < len; i++)
853 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
854 panic("ffs_reallocblks: non-logical cluster");
855 blkno = buflist->bs_children[0]->b_blkno;
856 ssize = fsbtodb(fs, fs->fs_frag);
857 for (i = 1; i < len - 1; i++)
858 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
859 panic("ffs_reallocblks: non-physical cluster %d", i);
862 * If the cluster crosses the boundary for the first indirect
863 * block, do not move anything in it. Indirect blocks are
864 * usually initially laid out in a position between the data
865 * blocks. Block reallocation would usually destroy locality by
866 * moving the indirect block out of the way to make room for
867 * data blocks if we didn't compensate here. We should also do
868 * this for other indirect block boundaries, but it is only
869 * important for the first one.
871 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
874 * If the latest allocation is in a new cylinder group, assume that
875 * the filesystem has decided to move and do not force it back to
876 * the previous cylinder group.
878 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
879 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
881 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
882 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
885 * Get the starting offset and block map for the first block.
887 if (start_lvl == 0) {
888 sbap = &ip->i_din2->di_db[0];
891 idp = &start_ap[start_lvl - 1];
892 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
896 sbap = (ufs2_daddr_t *)sbp->b_data;
900 * If the block range spans two block maps, get the second map.
903 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
908 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
909 panic("ffs_reallocblk: start == end");
911 ssize = len - (idp->in_off + 1);
912 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
914 ebap = (ufs2_daddr_t *)ebp->b_data;
917 * Find the preferred location for the cluster. If we have not
918 * previously failed at this endeavor, then follow our standard
919 * preference calculation. If we have failed at it, then pick up
920 * where we last ended our search.
923 if (ip->i_nextclustercg == -1)
924 pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
926 pref = cgdata(fs, ip->i_nextclustercg);
928 * Search the block map looking for an allocation of the desired size.
929 * To avoid wasting too much time, we limit the number of cylinder
930 * groups that we will search.
933 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
934 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
937 if (cg >= fs->fs_ncg)
941 * If we have failed in our search, record where we gave up for
942 * next time. Otherwise, fall back to our usual search citerion.
945 ip->i_nextclustercg = cg;
949 ip->i_nextclustercg = -1;
951 * We have found a new contiguous block.
953 * First we have to replace the old block pointers with the new
954 * block pointers in the inode and indirect blocks associated
959 printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
960 (intmax_t)start_lbn, (intmax_t)end_lbn);
963 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
969 if (!ffs_checkblk(ip,
970 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
971 panic("ffs_reallocblks: unallocated block 2");
972 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
973 panic("ffs_reallocblks: alloc mismatch");
977 printf(" %jd,", (intmax_t)*bap);
979 if (DOINGSOFTDEP(vp)) {
980 if (sbap == &ip->i_din2->di_db[0] && i < ssize)
981 softdep_setup_allocdirect(ip, start_lbn + i,
982 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
983 buflist->bs_children[i]);
985 softdep_setup_allocindir_page(ip, start_lbn + i,
986 i < ssize ? sbp : ebp, soff + i, blkno,
987 *bap, buflist->bs_children[i]);
992 * Next we must write out the modified inode and indirect blocks.
993 * For strict correctness, the writes should be synchronous since
994 * the old block values may have been written to disk. In practise
995 * they are almost never written, but if we are concerned about
996 * strict correctness, the `doasyncfree' flag should be set to zero.
998 * The test on `doasyncfree' should be changed to test a flag
999 * that shows whether the associated buffers and inodes have
1000 * been written. The flag should be set when the cluster is
1001 * started and cleared whenever the buffer or inode is flushed.
1002 * We can then check below to see if it is set, and do the
1003 * synchronous write only when it has been cleared.
1005 if (sbap != &ip->i_din2->di_db[0]) {
1011 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1022 * Last, free the old blocks and assign the new blocks to the buffers.
1028 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
1029 bp = buflist->bs_children[i];
1030 if (!DOINGSOFTDEP(vp))
1032 * The usual case is that a set of N-contiguous blocks
1033 * that was just allocated has been replaced with a
1034 * set of N+1-contiguous blocks. If they are marked as
1035 * B_DELWRI, the current contents have not been written
1036 * to disk. It is possible that the blocks were written
1037 * earlier, but very uncommon. If the blocks have never
1038 * been written, there is no need to send a BIO_DELETE
1039 * for them when they are freed. The gain from avoiding
1040 * the TRIMs for the common case of unwritten blocks
1041 * far exceeds the cost of the write amplification for
1042 * the uncommon case of failing to send a TRIM for the
1043 * blocks that had been written.
1045 ffs_blkfree(ump, fs, ump->um_devvp,
1046 dbtofsb(fs, bp->b_blkno),
1047 fs->fs_bsize, ip->i_number, vp->v_type, NULL,
1048 (bp->b_flags & B_DELWRI) != 0 ?
1049 NOTRIM_KEY : SINGLETON_KEY);
1050 bp->b_blkno = fsbtodb(fs, blkno);
1052 if (!ffs_checkblk(ip, dbtofsb(fs, bp->b_blkno), fs->fs_bsize))
1053 panic("ffs_reallocblks: unallocated block 3");
1057 printf(" %jd,", (intmax_t)blkno);
1071 if (sbap != &ip->i_din2->di_db[0])
1077 * Allocate an inode in the filesystem.
1079 * If allocating a directory, use ffs_dirpref to select the inode.
1080 * If allocating in a directory, the following hierarchy is followed:
1081 * 1) allocate the preferred inode.
1082 * 2) allocate an inode in the same cylinder group.
1083 * 3) quadradically rehash into other cylinder groups, until an
1084 * available inode is located.
1085 * If no inode preference is given the following hierarchy is used
1086 * to allocate an inode:
1087 * 1) allocate an inode in cylinder group 0.
1088 * 2) quadradically rehash into other cylinder groups, until an
1089 * available inode is located.
1092 ffs_valloc(pvp, mode, cred, vpp)
1102 struct ufsmount *ump;
1105 int error, error1, reclaimed;
1115 if (fs->fs_cstotal.cs_nifree == 0)
1118 if ((mode & IFMT) == IFDIR)
1119 ipref = ffs_dirpref(pip);
1121 ipref = pip->i_number;
1122 if (ipref >= fs->fs_ncg * fs->fs_ipg)
1124 cg = ino_to_cg(fs, ipref);
1126 * Track number of dirs created one after another
1127 * in a same cg without intervening by files.
1129 if ((mode & IFMT) == IFDIR) {
1130 if (fs->fs_contigdirs[cg] < 255)
1131 fs->fs_contigdirs[cg]++;
1133 if (fs->fs_contigdirs[cg] > 0)
1134 fs->fs_contigdirs[cg]--;
1136 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1137 (allocfcn_t *)ffs_nodealloccg);
1142 * Get rid of the cached old vnode, force allocation of a new vnode
1145 error = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp, FFSV_REPLACE);
1147 error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1148 FFSV_FORCEINSMQ | FFSV_REPLACE);
1149 ffs_vfree(pvp, ino, mode);
1154 UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
1162 printf("mode = 0%o, inum = %ju, fs = %s\n",
1163 ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1164 panic("ffs_valloc: dup alloc");
1166 if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) { /* XXX */
1167 printf("free inode %s/%lu had %ld blocks\n",
1168 fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1169 DIP_SET(ip, i_blocks, 0);
1172 DIP_SET(ip, i_flags, 0);
1174 * Set up a new generation number for this inode.
1176 while (ip->i_gen == 0 || ++ip->i_gen == 0)
1177 ip->i_gen = arc4random();
1178 DIP_SET(ip, i_gen, ip->i_gen);
1179 if (fs->fs_magic == FS_UFS2_MAGIC) {
1181 ip->i_din2->di_birthtime = ts.tv_sec;
1182 ip->i_din2->di_birthnsec = ts.tv_nsec;
1185 (*vpp)->v_vflag = 0;
1186 (*vpp)->v_type = VNON;
1187 if (fs->fs_magic == FS_UFS2_MAGIC) {
1188 (*vpp)->v_op = &ffs_vnodeops2;
1189 UFS_INODE_SET_FLAG(ip, IN_UFS2);
1191 (*vpp)->v_op = &ffs_vnodeops1;
1195 if (reclaimed == 0) {
1197 softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1200 if (ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
1202 ffs_fserr(fs, pip->i_number, "out of inodes");
1203 uprintf("\n%s: create/symlink failed, no inodes free\n",
1212 * Find a cylinder group to place a directory.
1214 * The policy implemented by this algorithm is to allocate a
1215 * directory inode in the same cylinder group as its parent
1216 * directory, but also to reserve space for its files inodes
1217 * and data. Restrict the number of directories which may be
1218 * allocated one after another in the same cylinder group
1219 * without intervening allocation of files.
1221 * If we allocate a first level directory then force allocation
1222 * in another cylinder group.
1229 int cg, prefcg, dirsize, cgsize;
1230 u_int avgifree, avgbfree, avgndir, curdirsize;
1231 u_int minifree, minbfree, maxndir;
1232 u_int mincg, minndir;
1233 u_int maxcontigdirs;
1235 mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1238 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1239 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1240 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1243 * Force allocation in another cg if creating a first level dir.
1245 ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1246 if (ITOV(pip)->v_vflag & VV_ROOT) {
1247 prefcg = arc4random() % fs->fs_ncg;
1249 minndir = fs->fs_ipg;
1250 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1251 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1252 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1253 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1255 minndir = fs->fs_cs(fs, cg).cs_ndir;
1257 for (cg = 0; cg < prefcg; cg++)
1258 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1259 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1260 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1262 minndir = fs->fs_cs(fs, cg).cs_ndir;
1264 return ((ino_t)(fs->fs_ipg * mincg));
1268 * Count various limits which used for
1269 * optimal allocation of a directory inode.
1271 maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1272 minifree = avgifree - avgifree / 4;
1275 minbfree = avgbfree - avgbfree / 4;
1278 cgsize = fs->fs_fsize * fs->fs_fpg;
1279 dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1280 curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1281 if (dirsize < curdirsize)
1282 dirsize = curdirsize;
1284 maxcontigdirs = 0; /* dirsize overflowed */
1286 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1287 if (fs->fs_avgfpdir > 0)
1288 maxcontigdirs = min(maxcontigdirs,
1289 fs->fs_ipg / fs->fs_avgfpdir);
1290 if (maxcontigdirs == 0)
1294 * Limit number of dirs in one cg and reserve space for
1295 * regular files, but only if we have no deficit in
1298 * We are trying to find a suitable cylinder group nearby
1299 * our preferred cylinder group to place a new directory.
1300 * We scan from our preferred cylinder group forward looking
1301 * for a cylinder group that meets our criterion. If we get
1302 * to the final cylinder group and do not find anything,
1303 * we start scanning forwards from the beginning of the
1304 * filesystem. While it might seem sensible to start scanning
1305 * backwards or even to alternate looking forward and backward,
1306 * this approach fails badly when the filesystem is nearly full.
1307 * Specifically, we first search all the areas that have no space
1308 * and finally try the one preceding that. We repeat this on
1309 * every request and in the case of the final block end up
1310 * searching the entire filesystem. By jumping to the front
1311 * of the filesystem, our future forward searches always look
1312 * in new cylinder groups so finds every possible block after
1313 * one pass over the filesystem.
1315 prefcg = ino_to_cg(fs, pip->i_number);
1316 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1317 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1318 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1319 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1320 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1321 return ((ino_t)(fs->fs_ipg * cg));
1323 for (cg = 0; cg < prefcg; cg++)
1324 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1325 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1326 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1327 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1328 return ((ino_t)(fs->fs_ipg * cg));
1331 * This is a backstop when we have deficit in space.
1333 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1334 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1335 return ((ino_t)(fs->fs_ipg * cg));
1336 for (cg = 0; cg < prefcg; cg++)
1337 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1339 return ((ino_t)(fs->fs_ipg * cg));
1343 * Select the desired position for the next block in a file. The file is
1344 * logically divided into sections. The first section is composed of the
1345 * direct blocks and the next fs_maxbpg blocks. Each additional section
1346 * contains fs_maxbpg blocks.
1348 * If no blocks have been allocated in the first section, the policy is to
1349 * request a block in the same cylinder group as the inode that describes
1350 * the file. The first indirect is allocated immediately following the last
1351 * direct block and the data blocks for the first indirect immediately
1354 * If no blocks have been allocated in any other section, the indirect
1355 * block(s) are allocated in the same cylinder group as its inode in an
1356 * area reserved immediately following the inode blocks. The policy for
1357 * the data blocks is to place them in a cylinder group with a greater than
1358 * average number of free blocks. An appropriate cylinder group is found
1359 * by using a rotor that sweeps the cylinder groups. When a new group of
1360 * blocks is needed, the sweep begins in the cylinder group following the
1361 * cylinder group from which the previous allocation was made. The sweep
1362 * continues until a cylinder group with greater than the average number
1363 * of free blocks is found. If the allocation is for the first block in an
1364 * indirect block or the previous block is a hole, then the information on
1365 * the previous allocation is unavailable; here a best guess is made based
1366 * on the logical block number being allocated.
1368 * If a section is already partially allocated, the policy is to
1369 * allocate blocks contiguously within the section if possible.
1372 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1380 u_int avgbfree, startcg;
1381 ufs2_daddr_t pref, prevbn;
1383 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1384 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1387 * Allocation of indirect blocks is indicated by passing negative
1388 * values in indx: -1 for single indirect, -2 for double indirect,
1389 * -3 for triple indirect. As noted below, we attempt to allocate
1390 * the first indirect inline with the file data. For all later
1391 * indirect blocks, the data is often allocated in other cylinder
1392 * groups. However to speed random file access and to speed up
1393 * fsck, the filesystem reserves the first fs_metaspace blocks
1394 * (typically half of fs_minfree) of the data area of each cylinder
1395 * group to hold these later indirect blocks.
1397 inocg = ino_to_cg(fs, ip->i_number);
1400 * Our preference for indirect blocks is the zone at the
1401 * beginning of the inode's cylinder group data area that
1402 * we try to reserve for indirect blocks.
1404 pref = cgmeta(fs, inocg);
1406 * If we are allocating the first indirect block, try to
1407 * place it immediately following the last direct block.
1409 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1410 ip->i_din1->di_db[UFS_NDADDR - 1] != 0)
1411 pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1415 * If we are allocating the first data block in the first indirect
1416 * block and the indirect has been allocated in the data block area,
1417 * try to place it immediately following the indirect block.
1419 if (lbn == UFS_NDADDR) {
1420 pref = ip->i_din1->di_ib[0];
1421 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1422 pref < cgbase(fs, inocg + 1))
1423 return (pref + fs->fs_frag);
1426 * If we are at the beginning of a file, or we have already allocated
1427 * the maximum number of blocks per cylinder group, or we do not
1428 * have a block allocated immediately preceding us, then we need
1429 * to decide where to start allocating new blocks.
1434 prevbn = bap[indx - 1];
1435 if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1439 if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1441 * If we are allocating a directory data block, we want
1442 * to place it in the metadata area.
1444 if ((ip->i_mode & IFMT) == IFDIR)
1445 return (cgmeta(fs, inocg));
1447 * Until we fill all the direct and all the first indirect's
1448 * blocks, we try to allocate in the data area of the inode's
1451 if (lbn < UFS_NDADDR + NINDIR(fs))
1452 return (cgdata(fs, inocg));
1454 * Find a cylinder with greater than average number of
1455 * unused data blocks.
1457 if (indx == 0 || prevbn == 0)
1458 startcg = inocg + lbn / fs->fs_maxbpg;
1460 startcg = dtog(fs, prevbn) + 1;
1461 startcg %= fs->fs_ncg;
1462 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1463 for (cg = startcg; cg < fs->fs_ncg; cg++)
1464 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1465 fs->fs_cgrotor = cg;
1466 return (cgdata(fs, cg));
1468 for (cg = 0; cg <= startcg; cg++)
1469 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1470 fs->fs_cgrotor = cg;
1471 return (cgdata(fs, cg));
1476 * Otherwise, we just always try to lay things out contiguously.
1478 return (prevbn + fs->fs_frag);
1482 * Same as above, but for UFS2
1485 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1493 u_int avgbfree, startcg;
1494 ufs2_daddr_t pref, prevbn;
1496 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1497 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1500 * Allocation of indirect blocks is indicated by passing negative
1501 * values in indx: -1 for single indirect, -2 for double indirect,
1502 * -3 for triple indirect. As noted below, we attempt to allocate
1503 * the first indirect inline with the file data. For all later
1504 * indirect blocks, the data is often allocated in other cylinder
1505 * groups. However to speed random file access and to speed up
1506 * fsck, the filesystem reserves the first fs_metaspace blocks
1507 * (typically half of fs_minfree) of the data area of each cylinder
1508 * group to hold these later indirect blocks.
1510 inocg = ino_to_cg(fs, ip->i_number);
1513 * Our preference for indirect blocks is the zone at the
1514 * beginning of the inode's cylinder group data area that
1515 * we try to reserve for indirect blocks.
1517 pref = cgmeta(fs, inocg);
1519 * If we are allocating the first indirect block, try to
1520 * place it immediately following the last direct block.
1522 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1523 ip->i_din2->di_db[UFS_NDADDR - 1] != 0)
1524 pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1528 * If we are allocating the first data block in the first indirect
1529 * block and the indirect has been allocated in the data block area,
1530 * try to place it immediately following the indirect block.
1532 if (lbn == UFS_NDADDR) {
1533 pref = ip->i_din2->di_ib[0];
1534 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1535 pref < cgbase(fs, inocg + 1))
1536 return (pref + fs->fs_frag);
1539 * If we are at the beginning of a file, or we have already allocated
1540 * the maximum number of blocks per cylinder group, or we do not
1541 * have a block allocated immediately preceding us, then we need
1542 * to decide where to start allocating new blocks.
1547 prevbn = bap[indx - 1];
1548 if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1552 if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1554 * If we are allocating a directory data block, we want
1555 * to place it in the metadata area.
1557 if ((ip->i_mode & IFMT) == IFDIR)
1558 return (cgmeta(fs, inocg));
1560 * Until we fill all the direct and all the first indirect's
1561 * blocks, we try to allocate in the data area of the inode's
1564 if (lbn < UFS_NDADDR + NINDIR(fs))
1565 return (cgdata(fs, inocg));
1567 * Find a cylinder with greater than average number of
1568 * unused data blocks.
1570 if (indx == 0 || prevbn == 0)
1571 startcg = inocg + lbn / fs->fs_maxbpg;
1573 startcg = dtog(fs, prevbn) + 1;
1574 startcg %= fs->fs_ncg;
1575 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1576 for (cg = startcg; cg < fs->fs_ncg; cg++)
1577 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1578 fs->fs_cgrotor = cg;
1579 return (cgdata(fs, cg));
1581 for (cg = 0; cg <= startcg; cg++)
1582 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1583 fs->fs_cgrotor = cg;
1584 return (cgdata(fs, cg));
1589 * Otherwise, we just always try to lay things out contiguously.
1591 return (prevbn + fs->fs_frag);
1595 * Implement the cylinder overflow algorithm.
1597 * The policy implemented by this algorithm is:
1598 * 1) allocate the block in its requested cylinder group.
1599 * 2) quadradically rehash on the cylinder group number.
1600 * 3) brute force search for a free block.
1602 * Must be called with the UFS lock held. Will release the lock on success
1603 * and return with it held on failure.
1607 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1611 int size; /* Search size for data blocks, mode for inodes */
1612 int rsize; /* Real allocated size. */
1613 allocfcn_t *allocator;
1616 ufs2_daddr_t result;
1619 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1621 if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1622 panic("ffs_hashalloc: allocation on suspended filesystem");
1626 * 1: preferred cylinder group
1628 result = (*allocator)(ip, cg, pref, size, rsize);
1632 * 2: quadratic rehash
1634 for (i = 1; i < fs->fs_ncg; i *= 2) {
1636 if (cg >= fs->fs_ncg)
1638 result = (*allocator)(ip, cg, 0, size, rsize);
1643 * 3: brute force search
1644 * Note that we start at i == 2, since 0 was checked initially,
1645 * and 1 is always checked in the quadratic rehash.
1647 cg = (icg + 2) % fs->fs_ncg;
1648 for (i = 2; i < fs->fs_ncg; i++) {
1649 result = (*allocator)(ip, cg, 0, size, rsize);
1653 if (cg == fs->fs_ncg)
1660 * Determine whether a fragment can be extended.
1662 * Check to see if the necessary fragments are available, and
1663 * if they are, allocate them.
1666 ffs_fragextend(ip, cg, bprev, osize, nsize)
1675 struct ufsmount *ump;
1684 if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1686 frags = numfrags(fs, nsize);
1687 bbase = fragnum(fs, bprev);
1688 if (bbase > fragnum(fs, (bprev + frags - 1))) {
1689 /* cannot extend across a block boundary */
1693 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0)
1695 bno = dtogd(fs, bprev);
1696 blksfree = cg_blksfree(cgp);
1697 for (i = numfrags(fs, osize); i < frags; i++)
1698 if (isclr(blksfree, bno + i))
1701 * the current fragment can be extended
1702 * deduct the count on fragment being extended into
1703 * increase the count on the remaining fragment (if any)
1704 * allocate the extended piece
1706 for (i = frags; i < fs->fs_frag - bbase; i++)
1707 if (isclr(blksfree, bno + i))
1709 cgp->cg_frsum[i - numfrags(fs, osize)]--;
1711 cgp->cg_frsum[i - frags]++;
1712 for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1713 clrbit(blksfree, bno + i);
1714 cgp->cg_cs.cs_nffree--;
1718 fs->fs_cstotal.cs_nffree -= nffree;
1719 fs->fs_cs(fs, cg).cs_nffree -= nffree;
1721 ACTIVECLEAR(fs, cg);
1723 if (DOINGSOFTDEP(ITOV(ip)))
1724 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1725 frags, numfrags(fs, osize));
1737 * Determine whether a block can be allocated.
1739 * Check to see if a block of the appropriate size is available,
1740 * and if it is, allocate it.
1743 ffs_alloccg(ip, cg, bpref, size, rsize)
1753 struct ufsmount *ump;
1756 int i, allocsiz, error, frags;
1761 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1764 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0 ||
1765 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1767 if (size == fs->fs_bsize) {
1769 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1770 ACTIVECLEAR(fs, cg);
1776 * check to see if any fragments are already available
1777 * allocsiz is the size which will be allocated, hacking
1778 * it down to a smaller size if necessary
1780 blksfree = cg_blksfree(cgp);
1781 frags = numfrags(fs, size);
1782 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1783 if (cgp->cg_frsum[allocsiz] != 0)
1785 if (allocsiz == fs->fs_frag) {
1787 * no fragments were available, so a block will be
1788 * allocated, and hacked up
1790 if (cgp->cg_cs.cs_nbfree == 0)
1793 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1794 ACTIVECLEAR(fs, cg);
1799 KASSERT(size == rsize,
1800 ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1801 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1804 for (i = 0; i < frags; i++)
1805 clrbit(blksfree, bno + i);
1806 cgp->cg_cs.cs_nffree -= frags;
1807 cgp->cg_frsum[allocsiz]--;
1808 if (frags != allocsiz)
1809 cgp->cg_frsum[allocsiz - frags]++;
1811 fs->fs_cstotal.cs_nffree -= frags;
1812 fs->fs_cs(fs, cg).cs_nffree -= frags;
1814 blkno = cgbase(fs, cg) + bno;
1815 ACTIVECLEAR(fs, cg);
1817 if (DOINGSOFTDEP(ITOV(ip)))
1818 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1829 * Allocate a block in a cylinder group.
1831 * This algorithm implements the following policy:
1832 * 1) allocate the requested block.
1833 * 2) allocate a rotationally optimal block in the same cylinder.
1834 * 3) allocate the next available block on the block rotor for the
1835 * specified cylinder group.
1836 * Note that this routine only allocates fs_bsize blocks; these
1837 * blocks may be fragmented by the routine that allocates them.
1840 ffs_alloccgblk(ip, bp, bpref, size)
1848 struct ufsmount *ump;
1856 mtx_assert(UFS_MTX(ump), MA_OWNED);
1857 cgp = (struct cg *)bp->b_data;
1858 blksfree = cg_blksfree(cgp);
1860 bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1861 } else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1862 /* map bpref to correct zone in this cg */
1863 if (bpref < cgdata(fs, cgbpref))
1864 bpref = cgmeta(fs, cgp->cg_cgx);
1866 bpref = cgdata(fs, cgp->cg_cgx);
1869 * if the requested block is available, use it
1871 bno = dtogd(fs, blknum(fs, bpref));
1872 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1875 * Take the next available block in this cylinder group.
1877 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1880 /* Update cg_rotor only if allocated from the data zone */
1881 if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1882 cgp->cg_rotor = bno;
1884 blkno = fragstoblks(fs, bno);
1885 ffs_clrblock(fs, blksfree, (long)blkno);
1886 ffs_clusteracct(fs, cgp, blkno, -1);
1887 cgp->cg_cs.cs_nbfree--;
1888 fs->fs_cstotal.cs_nbfree--;
1889 fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1891 blkno = cgbase(fs, cgp->cg_cgx) + bno;
1893 * If the caller didn't want the whole block free the frags here.
1895 size = numfrags(fs, size);
1896 if (size != fs->fs_frag) {
1897 bno = dtogd(fs, blkno);
1898 for (i = size; i < fs->fs_frag; i++)
1899 setbit(blksfree, bno + i);
1900 i = fs->fs_frag - size;
1901 cgp->cg_cs.cs_nffree += i;
1902 fs->fs_cstotal.cs_nffree += i;
1903 fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1909 if (DOINGSOFTDEP(ITOV(ip)))
1910 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, size, 0);
1916 * Determine whether a cluster can be allocated.
1918 * We do not currently check for optimal rotational layout if there
1919 * are multiple choices in the same cylinder group. Instead we just
1920 * take the first one that we find following bpref.
1923 ffs_clusteralloc(ip, cg, bpref, len)
1932 struct ufsmount *ump;
1933 int i, run, bit, map, got, error;
1941 if (fs->fs_maxcluster[cg] < len)
1944 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
1949 * Check to see if a cluster of the needed size (or bigger) is
1950 * available in this cylinder group.
1952 lp = &cg_clustersum(cgp)[len];
1953 for (i = len; i <= fs->fs_contigsumsize; i++)
1956 if (i > fs->fs_contigsumsize) {
1958 * This is the first time looking for a cluster in this
1959 * cylinder group. Update the cluster summary information
1960 * to reflect the true maximum sized cluster so that
1961 * future cluster allocation requests can avoid reading
1962 * the cylinder group map only to find no clusters.
1964 lp = &cg_clustersum(cgp)[len - 1];
1965 for (i = len - 1; i > 0; i--)
1969 fs->fs_maxcluster[cg] = i;
1974 * Search the cluster map to find a big enough cluster.
1975 * We take the first one that we find, even if it is larger
1976 * than we need as we prefer to get one close to the previous
1977 * block allocation. We do not search before the current
1978 * preference point as we do not want to allocate a block
1979 * that is allocated before the previous one (as we will
1980 * then have to wait for another pass of the elevator
1981 * algorithm before it will be read). We prefer to fail and
1982 * be recalled to try an allocation in the next cylinder group.
1984 if (dtog(fs, bpref) != cg)
1985 bpref = cgdata(fs, cg);
1987 bpref = blknum(fs, bpref);
1988 bpref = fragstoblks(fs, dtogd(fs, bpref));
1989 mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1991 bit = 1 << (bpref % NBBY);
1992 for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1993 if ((map & bit) == 0) {
2000 if ((got & (NBBY - 1)) != (NBBY - 1)) {
2007 if (got >= cgp->cg_nclusterblks) {
2013 * Allocate the cluster that we have found.
2015 blksfree = cg_blksfree(cgp);
2016 for (i = 1; i <= len; i++)
2017 if (!ffs_isblock(fs, blksfree, got - run + i))
2018 panic("ffs_clusteralloc: map mismatch");
2019 bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
2020 if (dtog(fs, bno) != cg)
2021 panic("ffs_clusteralloc: allocated out of group");
2022 len = blkstofrags(fs, len);
2024 for (i = 0; i < len; i += fs->fs_frag)
2025 if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
2026 panic("ffs_clusteralloc: lost block");
2027 ACTIVECLEAR(fs, cg);
2033 static inline struct buf *
2034 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
2039 return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
2040 cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
2045 * Synchronous inode initialization is needed only when barrier writes do not
2046 * work as advertised, and will impose a heavy cost on file creation in a newly
2047 * created filesystem.
2049 static int doasyncinodeinit = 1;
2050 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncinodeinit, CTLFLAG_RWTUN,
2051 &doasyncinodeinit, 0,
2052 "Perform inode block initialization using asynchronous writes");
2055 * Determine whether an inode can be allocated.
2057 * Check to see if an inode is available, and if it is,
2058 * allocate it using the following policy:
2059 * 1) allocate the requested inode.
2060 * 2) allocate the next available inode after the requested
2061 * inode in the specified cylinder group.
2064 ffs_nodealloccg(ip, cg, ipref, mode, unused)
2073 struct buf *bp, *ibp;
2074 struct ufsmount *ump;
2075 u_int8_t *inosused, *loc;
2076 struct ufs2_dinode *dp2;
2077 int error, start, len, i;
2078 u_int32_t old_initediblk;
2083 if (fs->fs_cs(fs, cg).cs_nifree == 0)
2086 if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
2091 if (cgp->cg_cs.cs_nifree == 0) {
2096 inosused = cg_inosused(cgp);
2098 ipref %= fs->fs_ipg;
2099 if (isclr(inosused, ipref))
2102 start = cgp->cg_irotor / NBBY;
2103 len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
2104 loc = memcchr(&inosused[start], 0xff, len);
2108 loc = memcchr(&inosused[start], 0xff, len);
2110 printf("cg = %d, irotor = %ld, fs = %s\n",
2111 cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2112 panic("ffs_nodealloccg: map corrupted");
2116 ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2119 * Check to see if we need to initialize more inodes.
2121 if (fs->fs_magic == FS_UFS2_MAGIC &&
2122 ipref + INOPB(fs) > cgp->cg_initediblk &&
2123 cgp->cg_initediblk < cgp->cg_niblk) {
2124 old_initediblk = cgp->cg_initediblk;
2127 * Free the cylinder group lock before writing the
2128 * initialized inode block. Entering the
2129 * babarrierwrite() with the cylinder group lock
2130 * causes lock order violation between the lock and
2133 * Another thread can decide to initialize the same
2134 * inode block, but whichever thread first gets the
2135 * cylinder group lock after writing the newly
2136 * allocated inode block will update it and the other
2137 * will realize that it has lost and leave the
2138 * cylinder group unchanged.
2140 ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2144 * The inode block buffer is already owned by
2145 * another thread, which must initialize it.
2146 * Wait on the buffer to allow another thread
2147 * to finish the updates, with dropped cg
2148 * buffer lock, then retry.
2150 ibp = getinobuf(ip, cg, old_initediblk, 0);
2155 bzero(ibp->b_data, (int)fs->fs_bsize);
2156 dp2 = (struct ufs2_dinode *)(ibp->b_data);
2157 for (i = 0; i < INOPB(fs); i++) {
2158 while (dp2->di_gen == 0)
2159 dp2->di_gen = arc4random();
2164 * Rather than adding a soft updates dependency to ensure
2165 * that the new inode block is written before it is claimed
2166 * by the cylinder group map, we just do a barrier write
2167 * here. The barrier write will ensure that the inode block
2168 * gets written before the updated cylinder group map can be
2169 * written. The barrier write should only slow down bulk
2170 * loading of newly created filesystems.
2172 if (doasyncinodeinit)
2173 babarrierwrite(ibp);
2178 * After the inode block is written, try to update the
2179 * cg initediblk pointer. If another thread beat us
2180 * to it, then leave it unchanged as the other thread
2181 * has already set it correctly.
2183 error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp);
2185 ACTIVECLEAR(fs, cg);
2189 if (cgp->cg_initediblk == old_initediblk)
2190 cgp->cg_initediblk += INOPB(fs);
2193 cgp->cg_irotor = ipref;
2195 ACTIVECLEAR(fs, cg);
2196 setbit(inosused, ipref);
2197 cgp->cg_cs.cs_nifree--;
2198 fs->fs_cstotal.cs_nifree--;
2199 fs->fs_cs(fs, cg).cs_nifree--;
2201 if ((mode & IFMT) == IFDIR) {
2202 cgp->cg_cs.cs_ndir++;
2203 fs->fs_cstotal.cs_ndir++;
2204 fs->fs_cs(fs, cg).cs_ndir++;
2207 if (DOINGSOFTDEP(ITOV(ip)))
2208 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2210 return ((ino_t)(cg * fs->fs_ipg + ipref));
2214 * Free a block or fragment.
2216 * The specified block or fragment is placed back in the
2217 * free map. If a fragment is deallocated, a possible
2218 * block reassembly is checked.
2221 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2222 struct ufsmount *ump;
2224 struct vnode *devvp;
2228 struct workhead *dephd;
2233 ufs1_daddr_t fragno, cgbno;
2234 int i, blk, frags, bbase, error;
2240 if (devvp->v_type == VREG) {
2241 /* devvp is a snapshot */
2242 MPASS(devvp->v_mount->mnt_data == ump);
2243 dev = ump->um_devvp->v_rdev;
2244 } else if (devvp->v_type == VCHR) {
2245 /* devvp is a normal disk device */
2246 dev = devvp->v_rdev;
2247 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
2251 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2252 fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2253 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2254 devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2255 size, fs->fs_fsmnt);
2256 panic("ffs_blkfree_cg: bad size");
2259 if ((u_int)bno >= fs->fs_size) {
2260 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2262 ffs_fserr(fs, inum, "bad block");
2265 if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
2267 cgbno = dtogd(fs, bno);
2268 blksfree = cg_blksfree(cgp);
2270 if (size == fs->fs_bsize) {
2271 fragno = fragstoblks(fs, cgbno);
2272 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2273 if (devvp->v_type == VREG) {
2275 /* devvp is a snapshot */
2279 printf("dev = %s, block = %jd, fs = %s\n",
2280 devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2281 panic("ffs_blkfree_cg: freeing free block");
2283 ffs_setblock(fs, blksfree, fragno);
2284 ffs_clusteracct(fs, cgp, fragno, 1);
2285 cgp->cg_cs.cs_nbfree++;
2286 fs->fs_cstotal.cs_nbfree++;
2287 fs->fs_cs(fs, cg).cs_nbfree++;
2289 bbase = cgbno - fragnum(fs, cgbno);
2291 * decrement the counts associated with the old frags
2293 blk = blkmap(fs, blksfree, bbase);
2294 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2296 * deallocate the fragment
2298 frags = numfrags(fs, size);
2299 for (i = 0; i < frags; i++) {
2300 if (isset(blksfree, cgbno + i)) {
2301 printf("dev = %s, block = %jd, fs = %s\n",
2302 devtoname(dev), (intmax_t)(bno + i),
2304 panic("ffs_blkfree_cg: freeing free frag");
2306 setbit(blksfree, cgbno + i);
2308 cgp->cg_cs.cs_nffree += i;
2309 fs->fs_cstotal.cs_nffree += i;
2310 fs->fs_cs(fs, cg).cs_nffree += i;
2312 * add back in counts associated with the new frags
2314 blk = blkmap(fs, blksfree, bbase);
2315 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2317 * if a complete block has been reassembled, account for it
2319 fragno = fragstoblks(fs, bbase);
2320 if (ffs_isblock(fs, blksfree, fragno)) {
2321 cgp->cg_cs.cs_nffree -= fs->fs_frag;
2322 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2323 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2324 ffs_clusteracct(fs, cgp, fragno, 1);
2325 cgp->cg_cs.cs_nbfree++;
2326 fs->fs_cstotal.cs_nbfree++;
2327 fs->fs_cs(fs, cg).cs_nbfree++;
2331 ACTIVECLEAR(fs, cg);
2334 if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2335 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2336 numfrags(fs, size), dephd);
2341 * Structures and routines associated with trim management.
2343 * The following requests are passed to trim_lookup to indicate
2344 * the actions that should be taken.
2346 #define NEW 1 /* if found, error else allocate and hash it */
2347 #define OLD 2 /* if not found, error, else return it */
2348 #define REPLACE 3 /* if not found, error else unhash and reallocate it */
2349 #define DONE 4 /* if not found, error else unhash and return it */
2350 #define SINGLE 5 /* don't look up, just allocate it and don't hash it */
2352 MALLOC_DEFINE(M_TRIM, "ufs_trim", "UFS trim structures");
2354 #define TRIMLIST_HASH(ump, key) \
2355 (&(ump)->um_trimhash[(key) & (ump)->um_trimlisthashsize])
2358 * These structures describe each of the block free requests aggregated
2359 * together to make up a trim request.
2361 struct trim_blkreq {
2362 TAILQ_ENTRY(trim_blkreq) blkreqlist;
2365 struct workhead *pdephd;
2366 struct workhead dephd;
2370 * Description of a trim request.
2372 struct ffs_blkfree_trim_params {
2373 TAILQ_HEAD(, trim_blkreq) blklist;
2374 LIST_ENTRY(ffs_blkfree_trim_params) hashlist;
2376 struct ufsmount *ump;
2377 struct vnode *devvp;
2384 static void ffs_blkfree_trim_completed(struct buf *);
2385 static void ffs_blkfree_trim_task(void *ctx, int pending __unused);
2386 static struct ffs_blkfree_trim_params *trim_lookup(struct ufsmount *,
2387 struct vnode *, ufs2_daddr_t, long, ino_t, u_long, int);
2388 static void ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params *);
2391 * Called on trim completion to start a task to free the associated block(s).
2394 ffs_blkfree_trim_completed(bp)
2397 struct ffs_blkfree_trim_params *tp;
2399 tp = bp->b_fsprivate1;
2401 TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2402 taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
2406 * Trim completion task that free associated block(s).
2409 ffs_blkfree_trim_task(ctx, pending)
2413 struct ffs_blkfree_trim_params *tp;
2414 struct trim_blkreq *blkelm;
2415 struct ufsmount *ump;
2419 while ((blkelm = TAILQ_FIRST(&tp->blklist)) != NULL) {
2420 ffs_blkfree_cg(ump, ump->um_fs, tp->devvp, blkelm->bno,
2421 blkelm->size, tp->inum, blkelm->pdephd);
2422 TAILQ_REMOVE(&tp->blklist, blkelm, blkreqlist);
2423 free(blkelm, M_TRIM);
2425 vn_finished_secondary_write(UFSTOVFS(ump));
2427 ump->um_trim_inflight -= 1;
2428 ump->um_trim_inflight_blks -= numfrags(ump->um_fs, tp->size);
2434 * Lookup a trim request by inode number.
2435 * Allocate if requested (NEW, REPLACE, SINGLE).
2437 static struct ffs_blkfree_trim_params *
2438 trim_lookup(ump, devvp, bno, size, inum, key, alloctype)
2439 struct ufsmount *ump;
2440 struct vnode *devvp;
2447 struct trimlist_hashhead *tphashhead;
2448 struct ffs_blkfree_trim_params *tp, *ntp;
2450 ntp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TRIM, M_WAITOK);
2451 if (alloctype != SINGLE) {
2452 KASSERT(key >= FIRST_VALID_KEY, ("trim_lookup: invalid key"));
2454 tphashhead = TRIMLIST_HASH(ump, key);
2455 LIST_FOREACH(tp, tphashhead, hashlist)
2459 switch (alloctype) {
2461 KASSERT(tp == NULL, ("trim_lookup: found trim"));
2465 ("trim_lookup: missing call to ffs_blkrelease_start()"));
2470 KASSERT(tp != NULL, ("trim_lookup: missing REPLACE trim"));
2471 LIST_REMOVE(tp, hashlist);
2472 /* tp will be freed by caller */
2475 KASSERT(tp != NULL, ("trim_lookup: missing DONE trim"));
2476 LIST_REMOVE(tp, hashlist);
2481 TAILQ_INIT(&ntp->blklist);
2488 if (alloctype != SINGLE) {
2489 LIST_INSERT_HEAD(tphashhead, ntp, hashlist);
2496 * Dispatch a trim request.
2499 ffs_blkfree_sendtrim(tp)
2500 struct ffs_blkfree_trim_params *tp;
2502 struct ufsmount *ump;
2507 * Postpone the set of the free bit in the cg bitmap until the
2508 * BIO_DELETE is completed. Otherwise, due to disk queue
2509 * reordering, TRIM might be issued after we reuse the block
2510 * and write some new data into it.
2513 bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
2514 bp->b_iocmd = BIO_DELETE;
2515 bp->b_iooffset = dbtob(fsbtodb(ump->um_fs, tp->bno));
2516 bp->b_iodone = ffs_blkfree_trim_completed;
2517 bp->b_bcount = tp->size;
2518 bp->b_fsprivate1 = tp;
2520 ump->um_trim_total += 1;
2521 ump->um_trim_inflight += 1;
2522 ump->um_trim_inflight_blks += numfrags(ump->um_fs, tp->size);
2523 ump->um_trim_total_blks += numfrags(ump->um_fs, tp->size);
2527 vn_start_secondary_write(NULL, &mp, 0);
2528 g_vfs_strategy(ump->um_bo, bp);
2532 * Allocate a new key to use to identify a range of blocks.
2535 ffs_blkrelease_start(ump, devvp, inum)
2536 struct ufsmount *ump;
2537 struct vnode *devvp;
2540 static u_long masterkey;
2543 if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2544 return (SINGLETON_KEY);
2546 key = atomic_fetchadd_long(&masterkey, 1);
2547 } while (key < FIRST_VALID_KEY);
2548 (void) trim_lookup(ump, devvp, 0, 0, inum, key, NEW);
2553 * Deallocate a key that has been used to identify a range of blocks.
2556 ffs_blkrelease_finish(ump, key)
2557 struct ufsmount *ump;
2560 struct ffs_blkfree_trim_params *tp;
2562 if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
2565 * If the vfs.ffs.dotrimcons sysctl option is enabled while
2566 * a file deletion is active, specifically after a call
2567 * to ffs_blkrelease_start() but before the call to
2568 * ffs_blkrelease_finish(), ffs_blkrelease_start() will
2569 * have handed out SINGLETON_KEY rather than starting a
2570 * collection sequence. Thus if we get a SINGLETON_KEY
2571 * passed to ffs_blkrelease_finish(), we just return rather
2572 * than trying to finish the nonexistent sequence.
2574 if (key == SINGLETON_KEY) {
2576 printf("%s: vfs.ffs.dotrimcons enabled on active filesystem\n",
2577 ump->um_mountp->mnt_stat.f_mntonname);
2582 * We are done with sending blocks using this key. Look up the key
2583 * using the DONE alloctype (in tp) to request that it be unhashed
2584 * as we will not be adding to it. If the key has never been used,
2585 * tp->size will be zero, so we can just free tp. Otherwise the call
2586 * to ffs_blkfree_sendtrim(tp) causes the block range described by
2587 * tp to be issued (and then tp to be freed).
2589 tp = trim_lookup(ump, NULL, 0, 0, 0, key, DONE);
2593 ffs_blkfree_sendtrim(tp);
2597 * Setup to free a block or fragment.
2599 * Check for snapshots that might want to claim the block.
2600 * If trims are requested, prepare a trim request. Attempt to
2601 * aggregate consecutive blocks into a single trim request.
2604 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd, key)
2605 struct ufsmount *ump;
2607 struct vnode *devvp;
2612 struct workhead *dephd;
2615 struct ffs_blkfree_trim_params *tp, *ntp;
2616 struct trim_blkreq *blkelm;
2619 * Check to see if a snapshot wants to claim the block.
2620 * Check that devvp is a normal disk device, not a snapshot,
2621 * it has a snapshot(s) associated with it, and one of the
2622 * snapshots wants to claim the block.
2624 if (devvp->v_type == VCHR &&
2625 (devvp->v_vflag & VV_COPYONWRITE) &&
2626 ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2630 * Nothing to delay if TRIM is not required for this block or TRIM
2631 * is disabled or the operation is performed on a snapshot.
2633 if (key == NOTRIM_KEY || ((ump->um_flags & UM_CANDELETE) == 0) ||
2634 devvp->v_type == VREG) {
2635 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2638 blkelm = malloc(sizeof(struct trim_blkreq), M_TRIM, M_WAITOK);
2640 blkelm->size = size;
2641 if (dephd == NULL) {
2642 blkelm->pdephd = NULL;
2644 LIST_INIT(&blkelm->dephd);
2645 LIST_SWAP(dephd, &blkelm->dephd, worklist, wk_list);
2646 blkelm->pdephd = &blkelm->dephd;
2648 if (key == SINGLETON_KEY) {
2650 * Just a single non-contiguous piece. Use the SINGLE
2651 * alloctype to return a trim request that will not be
2652 * hashed for future lookup.
2654 tp = trim_lookup(ump, devvp, bno, size, inum, key, SINGLE);
2655 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2656 ffs_blkfree_sendtrim(tp);
2660 * The callers of this function are not tracking whether or not
2661 * the blocks are contiguous. They are just saying that they
2662 * are freeing a set of blocks. It is this code that determines
2663 * the pieces of that range that are actually contiguous.
2665 * Calling ffs_blkrelease_start() will have created an entry
2668 tp = trim_lookup(ump, devvp, bno, size, inum, key, OLD);
2669 if (tp->size == 0) {
2671 * First block of a potential range, set block and size
2672 * for the trim block.
2676 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2680 * If this block is a continuation of the range (either
2681 * follows at the end or preceeds in the front) then we
2682 * add it to the front or back of the list and return.
2684 * If it is not a continuation of the trim that we were
2685 * building, using the REPLACE alloctype, we request that
2686 * the old trim request (still in tp) be unhashed and a
2687 * new range started (in ntp). The ffs_blkfree_sendtrim(tp)
2688 * call causes the block range described by tp to be issued
2689 * (and then tp to be freed).
2691 if (bno + numfrags(fs, size) == tp->bno) {
2692 TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2696 } else if (bno == tp->bno + numfrags(fs, tp->size)) {
2697 TAILQ_INSERT_TAIL(&tp->blklist, blkelm, blkreqlist);
2701 ntp = trim_lookup(ump, devvp, bno, size, inum, key, REPLACE);
2702 TAILQ_INSERT_HEAD(&ntp->blklist, blkelm, blkreqlist);
2703 ffs_blkfree_sendtrim(tp);
2708 * Verify allocation of a block or fragment. Returns true if block or
2709 * fragment is allocated, false if it is free.
2712 ffs_checkblk(ip, bno, size)
2721 int i, error, frags, free;
2725 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2726 printf("bsize = %ld, size = %ld, fs = %s\n",
2727 (long)fs->fs_bsize, size, fs->fs_fsmnt);
2728 panic("ffs_checkblk: bad size");
2730 if ((u_int)bno >= fs->fs_size)
2731 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2732 error = ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), 0, &bp, &cgp);
2734 panic("ffs_checkblk: cylinder group read failed");
2735 blksfree = cg_blksfree(cgp);
2736 cgbno = dtogd(fs, bno);
2737 if (size == fs->fs_bsize) {
2738 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2740 frags = numfrags(fs, size);
2741 for (free = 0, i = 0; i < frags; i++)
2742 if (isset(blksfree, cgbno + i))
2744 if (free != 0 && free != frags)
2745 panic("ffs_checkblk: partially free fragment");
2750 #endif /* INVARIANTS */
2756 ffs_vfree(pvp, ino, mode)
2761 struct ufsmount *ump;
2763 if (DOINGSOFTDEP(pvp)) {
2764 softdep_freefile(pvp, ino, mode);
2767 ump = VFSTOUFS(pvp->v_mount);
2768 return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2772 * Do the actual free operation.
2773 * The specified inode is placed back in the free map.
2776 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2777 struct ufsmount *ump;
2779 struct vnode *devvp;
2782 struct workhead *wkhd;
2792 cg = ino_to_cg(fs, ino);
2793 if (devvp->v_type == VREG) {
2794 /* devvp is a snapshot */
2795 MPASS(devvp->v_mount->mnt_data == ump);
2796 dev = ump->um_devvp->v_rdev;
2797 } else if (devvp->v_type == VCHR) {
2798 /* devvp is a normal disk device */
2799 dev = devvp->v_rdev;
2804 if (ino >= fs->fs_ipg * fs->fs_ncg)
2805 panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2806 devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2807 if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
2809 inosused = cg_inosused(cgp);
2810 cgino = ino % fs->fs_ipg;
2811 if (isclr(inosused, cgino)) {
2812 printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2813 (uintmax_t)ino, fs->fs_fsmnt);
2814 if (fs->fs_ronly == 0)
2815 panic("ffs_freefile: freeing free inode");
2817 clrbit(inosused, cgino);
2818 if (cgino < cgp->cg_irotor)
2819 cgp->cg_irotor = cgino;
2820 cgp->cg_cs.cs_nifree++;
2822 fs->fs_cstotal.cs_nifree++;
2823 fs->fs_cs(fs, cg).cs_nifree++;
2824 if ((mode & IFMT) == IFDIR) {
2825 cgp->cg_cs.cs_ndir--;
2826 fs->fs_cstotal.cs_ndir--;
2827 fs->fs_cs(fs, cg).cs_ndir--;
2830 ACTIVECLEAR(fs, cg);
2832 if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2833 softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd);
2839 * Check to see if a file is free.
2840 * Used to check for allocated files in snapshots.
2843 ffs_checkfreefile(fs, devvp, ino)
2845 struct vnode *devvp;
2854 cg = ino_to_cg(fs, ino);
2855 if ((devvp->v_type != VREG) && (devvp->v_type != VCHR))
2857 if (ino >= fs->fs_ipg * fs->fs_ncg)
2859 if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
2861 inosused = cg_inosused(cgp);
2863 ret = isclr(inosused, ino);
2869 * Find a block of the specified size in the specified cylinder group.
2871 * It is a panic if a request is made to find a block if none are
2875 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2882 int start, len, loc, i;
2883 int blk, field, subfield, pos;
2887 * find the fragment by searching through the free block
2888 * map for an appropriate bit pattern
2891 start = dtogd(fs, bpref) / NBBY;
2893 start = cgp->cg_frotor / NBBY;
2894 blksfree = cg_blksfree(cgp);
2895 len = howmany(fs->fs_fpg, NBBY) - start;
2896 loc = scanc((u_int)len, (u_char *)&blksfree[start],
2897 fragtbl[fs->fs_frag],
2898 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2902 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2903 fragtbl[fs->fs_frag],
2904 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2906 printf("start = %d, len = %d, fs = %s\n",
2907 start, len, fs->fs_fsmnt);
2908 panic("ffs_alloccg: map corrupted");
2912 bno = (start + len - loc) * NBBY;
2913 cgp->cg_frotor = bno;
2915 * found the byte in the map
2916 * sift through the bits to find the selected frag
2918 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2919 blk = blkmap(fs, blksfree, bno);
2921 field = around[allocsiz];
2922 subfield = inside[allocsiz];
2923 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2924 if ((blk & field) == subfield)
2930 printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2931 panic("ffs_alloccg: block not in map");
2935 static const struct statfs *
2936 ffs_getmntstat(struct vnode *devvp)
2939 if (devvp->v_type == VCHR)
2940 return (&devvp->v_rdev->si_mountpt->mnt_stat);
2941 return (ffs_getmntstat(VFSTOUFS(devvp->v_mount)->um_devvp));
2945 * Fetch and verify a cylinder group.
2948 ffs_getcg(fs, devvp, cg, flags, bpp, cgpp)
2950 struct vnode *devvp;
2958 const struct statfs *sfs;
2964 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
2966 if (devvp->v_type == VREG)
2967 blkno = fragstoblks(fs, cgtod(fs, cg));
2969 blkno = fsbtodb(fs, cgtod(fs, cg));
2970 error = breadn_flags(devvp, blkno, blkno, (int)fs->fs_cgsize, NULL,
2971 NULL, 0, NOCRED, flags, ffs_ckhash_cg, &bp);
2974 cgp = (struct cg *)bp->b_data;
2975 if ((fs->fs_metackhash & CK_CYLGRP) != 0 &&
2976 (bp->b_flags & B_CKHASH) != 0 &&
2977 cgp->cg_ckhash != bp->b_ckhash) {
2978 sfs = ffs_getmntstat(devvp);
2979 printf("UFS %s%s (%s) cylinder checksum failed: cg %u, cgp: "
2980 "0x%x != bp: 0x%jx\n",
2981 devvp->v_type == VCHR ? "" : "snapshot of ",
2982 sfs->f_mntfromname, sfs->f_mntonname,
2983 cg, cgp->cg_ckhash, (uintmax_t)bp->b_ckhash);
2984 bp->b_flags &= ~B_CKHASH;
2985 bp->b_flags |= B_INVAL | B_NOCACHE;
2989 if (!cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
2990 sfs = ffs_getmntstat(devvp);
2991 printf("UFS %s%s (%s)",
2992 devvp->v_type == VCHR ? "" : "snapshot of ",
2993 sfs->f_mntfromname, sfs->f_mntonname);
2994 if (!cg_chkmagic(cgp))
2995 printf(" cg %u: bad magic number 0x%x should be 0x%x\n",
2996 cg, cgp->cg_magic, CG_MAGIC);
2998 printf(": wrong cylinder group cg %u != cgx %u\n", cg,
3000 bp->b_flags &= ~B_CKHASH;
3001 bp->b_flags |= B_INVAL | B_NOCACHE;
3005 bp->b_flags &= ~B_CKHASH;
3006 bp->b_xflags |= BX_BKGRDWRITE;
3008 * If we are using check hashes on the cylinder group then we want
3009 * to limit changing the cylinder group time to when we are actually
3010 * going to write it to disk so that its check hash remains correct
3011 * in memory. If the CK_CYLGRP flag is set the time is updated in
3012 * ffs_bufwrite() as the buffer is queued for writing. Otherwise we
3013 * update the time here as we have done historically.
3015 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
3016 bp->b_xflags |= BX_CYLGRP;
3018 cgp->cg_old_time = cgp->cg_time = time_second;
3031 cgp = (struct cg *)bp->b_data;
3032 ckhash = cgp->cg_ckhash;
3034 bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
3035 cgp->cg_ckhash = ckhash;
3039 * Fserr prints the name of a filesystem with an error diagnostic.
3041 * The form of the error message is:
3045 ffs_fserr(fs, inum, cp)
3050 struct thread *td = curthread; /* XXX */
3051 struct proc *p = td->td_proc;
3053 log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
3054 p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
3059 * This function provides the capability for the fsck program to
3060 * update an active filesystem. Fourteen operations are provided:
3062 * adjrefcnt(inode, amt) - adjusts the reference count on the
3063 * specified inode by the specified amount. Under normal
3064 * operation the count should always go down. Decrementing
3065 * the count to zero will cause the inode to be freed.
3066 * adjblkcnt(inode, amt) - adjust the number of blocks used by the
3067 * inode by the specified amount.
3068 * adjsize(inode, size) - set the size of the inode to the
3070 * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
3071 * adjust the superblock summary.
3072 * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
3073 * are marked as free. Inodes should never have to be marked
3075 * freefiles(inode, count) - file inodes [inode..inode + count - 1]
3076 * are marked as free. Inodes should never have to be marked
3078 * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
3079 * are marked as free. Blocks should never have to be marked
3081 * setflags(flags, set/clear) - the fs_flags field has the specified
3082 * flags set (second parameter +1) or cleared (second parameter -1).
3083 * setcwd(dirinode) - set the current directory to dirinode in the
3084 * filesystem associated with the snapshot.
3085 * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
3086 * in the current directory is oldvalue then change it to newvalue.
3087 * unlink(nameptr, oldvalue) - Verify that the inode number associated
3088 * with nameptr in the current directory is oldvalue then unlink it.
3091 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
3093 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt,
3094 CTLFLAG_WR | CTLTYPE_STRUCT | CTLFLAG_NEEDGIANT,
3095 0, 0, sysctl_ffs_fsck, "S,fsck",
3096 "Adjust Inode Reference Count");
3098 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt,
3099 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3100 "Adjust Inode Used Blocks Count");
3102 static SYSCTL_NODE(_vfs_ffs, FFS_SET_SIZE, setsize,
3103 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3104 "Set the inode size");
3106 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir,
3107 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3108 "Adjust number of directories");
3110 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree,
3111 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3112 "Adjust number of free blocks");
3114 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree,
3115 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3116 "Adjust number of free inodes");
3118 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree,
3119 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3120 "Adjust number of free frags");
3122 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters,
3123 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3124 "Adjust number of free clusters");
3126 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs,
3127 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3128 "Free Range of Directory Inodes");
3130 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles,
3131 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3132 "Free Range of File Inodes");
3134 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks,
3135 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3136 "Free Range of Blocks");
3138 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags,
3139 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3140 "Change Filesystem Flags");
3142 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd,
3143 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3144 "Set Current Working Directory");
3146 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot,
3147 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3148 "Change Value of .. Entry");
3150 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink,
3151 CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3152 "Unlink a Duplicate Name");
3155 static int fsckcmds = 0;
3156 SYSCTL_INT(_debug, OID_AUTO, ffs_fsckcmds, CTLFLAG_RW, &fsckcmds, 0,
3157 "print out fsck_ffs-based filesystem update commands");
3158 #endif /* DIAGNOSTIC */
3161 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
3163 struct thread *td = curthread;
3164 struct fsck_cmd cmd;
3165 struct ufsmount *ump;
3166 struct vnode *vp, *dvp, *fdvp;
3167 struct inode *ip, *dp;
3172 long blkcnt, blksize;
3175 cap_rights_t rights;
3176 int filetype, error;
3178 if (req->newlen > sizeof cmd)
3180 if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
3182 if (cmd.version != FFS_CMD_VERSION)
3183 return (ERPCMISMATCH);
3184 if ((error = getvnode(td, cmd.handle,
3185 cap_rights_init(&rights, CAP_FSCK), &fp)) != 0)
3188 if (vp->v_type != VREG && vp->v_type != VDIR) {
3192 vn_start_write(vp, &mp, V_WAIT);
3194 strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
3195 vn_finished_write(mp);
3200 if ((mp->mnt_flag & MNT_RDONLY) &&
3201 ump->um_fsckpid != td->td_proc->p_pid) {
3202 vn_finished_write(mp);
3209 switch (oidp->oid_number) {
3214 printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
3215 cmd.size > 0 ? "set" : "clear");
3216 #endif /* DIAGNOSTIC */
3218 fs->fs_flags |= (long)cmd.value;
3220 fs->fs_flags &= ~(long)cmd.value;
3223 case FFS_ADJ_REFCNT:
3226 printf("%s: adjust inode %jd link count by %jd\n",
3227 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3228 (intmax_t)cmd.size);
3230 #endif /* DIAGNOSTIC */
3231 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3234 ip->i_nlink += cmd.size;
3235 DIP_SET(ip, i_nlink, ip->i_nlink);
3236 ip->i_effnlink += cmd.size;
3237 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3238 error = ffs_update(vp, 1);
3239 if (DOINGSOFTDEP(vp))
3240 softdep_change_linkcnt(ip);
3244 case FFS_ADJ_BLKCNT:
3247 printf("%s: adjust inode %jd block count by %jd\n",
3248 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3249 (intmax_t)cmd.size);
3251 #endif /* DIAGNOSTIC */
3252 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3255 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
3256 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3257 error = ffs_update(vp, 1);
3264 printf("%s: set inode %jd size to %jd\n",
3265 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3266 (intmax_t)cmd.size);
3268 #endif /* DIAGNOSTIC */
3269 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3272 DIP_SET(ip, i_size, cmd.size);
3273 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3274 error = ffs_update(vp, 1);
3286 printf("%s: free %s inode %ju\n",
3287 mp->mnt_stat.f_mntonname,
3288 filetype == IFDIR ? "directory" : "file",
3289 (uintmax_t)cmd.value);
3291 printf("%s: free %s inodes %ju-%ju\n",
3292 mp->mnt_stat.f_mntonname,
3293 filetype == IFDIR ? "directory" : "file",
3294 (uintmax_t)cmd.value,
3295 (uintmax_t)(cmd.value + cmd.size - 1));
3297 #endif /* DIAGNOSTIC */
3298 while (cmd.size > 0) {
3299 if ((error = ffs_freefile(ump, fs, ump->um_devvp,
3300 cmd.value, filetype, NULL)))
3311 printf("%s: free block %jd\n",
3312 mp->mnt_stat.f_mntonname,
3313 (intmax_t)cmd.value);
3315 printf("%s: free blocks %jd-%jd\n",
3316 mp->mnt_stat.f_mntonname,
3317 (intmax_t)cmd.value,
3318 (intmax_t)cmd.value + cmd.size - 1);
3320 #endif /* DIAGNOSTIC */
3323 blksize = fs->fs_frag - (blkno % fs->fs_frag);
3324 key = ffs_blkrelease_start(ump, ump->um_devvp, UFS_ROOTINO);
3325 while (blkcnt > 0) {
3326 if (blkcnt < blksize)
3328 ffs_blkfree(ump, fs, ump->um_devvp, blkno,
3329 blksize * fs->fs_fsize, UFS_ROOTINO,
3333 blksize = fs->fs_frag;
3335 ffs_blkrelease_finish(ump, key);
3339 * Adjust superblock summaries. fsck(8) is expected to
3340 * submit deltas when necessary.
3345 printf("%s: adjust number of directories by %jd\n",
3346 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3348 #endif /* DIAGNOSTIC */
3349 fs->fs_cstotal.cs_ndir += cmd.value;
3352 case FFS_ADJ_NBFREE:
3355 printf("%s: adjust number of free blocks by %+jd\n",
3356 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3358 #endif /* DIAGNOSTIC */
3359 fs->fs_cstotal.cs_nbfree += cmd.value;
3362 case FFS_ADJ_NIFREE:
3365 printf("%s: adjust number of free inodes by %+jd\n",
3366 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3368 #endif /* DIAGNOSTIC */
3369 fs->fs_cstotal.cs_nifree += cmd.value;
3372 case FFS_ADJ_NFFREE:
3375 printf("%s: adjust number of free frags by %+jd\n",
3376 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3378 #endif /* DIAGNOSTIC */
3379 fs->fs_cstotal.cs_nffree += cmd.value;
3382 case FFS_ADJ_NUMCLUSTERS:
3385 printf("%s: adjust number of free clusters by %+jd\n",
3386 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3388 #endif /* DIAGNOSTIC */
3389 fs->fs_cstotal.cs_numclusters += cmd.value;
3395 printf("%s: set current directory to inode %jd\n",
3396 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3398 #endif /* DIAGNOSTIC */
3399 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
3401 AUDIT_ARG_VNODE1(vp);
3402 if ((error = change_dir(vp, td)) != 0) {
3410 case FFS_SET_DOTDOT:
3413 printf("%s: change .. in cwd from %jd to %jd\n",
3414 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3415 (intmax_t)cmd.size);
3417 #endif /* DIAGNOSTIC */
3419 * First we have to get and lock the parent directory
3420 * to which ".." points.
3422 error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3426 * Now we get and lock the child directory containing "..".
3429 dvp = pwd->pwd_cdir;
3430 if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
3436 dp->i_offset = 12; /* XXX mastertemplate.dot_reclen */
3437 error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3451 if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3452 strncpy(buf, "Name_too_long", 32);
3453 printf("%s: unlink %s (inode %jd)\n",
3454 mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3456 #endif /* DIAGNOSTIC */
3458 * kern_funlinkat will do its own start/finish writes and
3459 * they do not nest, so drop ours here. Setting mp == NULL
3460 * indicates that vn_finished_write is not needed down below.
3462 vn_finished_write(mp);
3464 error = kern_funlinkat(td, AT_FDCWD,
3465 (char *)(intptr_t)cmd.value, FD_NONE, UIO_USERSPACE,
3466 0, (ino_t)cmd.size);
3472 printf("Invalid request %d from fsck\n",
3475 #endif /* DIAGNOSTIC */
3481 vn_finished_write(mp);