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/systm.h>
75 #include <sys/fcntl.h>
77 #include <sys/filedesc.h>
80 #include <sys/vnode.h>
81 #include <sys/mount.h>
82 #include <sys/kernel.h>
83 #include <sys/syscallsubr.h>
84 #include <sys/sysctl.h>
85 #include <sys/syslog.h>
86 #include <sys/taskqueue.h>
88 #include <security/audit/audit.h>
90 #include <geom/geom.h>
92 #include <ufs/ufs/dir.h>
93 #include <ufs/ufs/extattr.h>
94 #include <ufs/ufs/quota.h>
95 #include <ufs/ufs/inode.h>
96 #include <ufs/ufs/ufs_extern.h>
97 #include <ufs/ufs/ufsmount.h>
99 #include <ufs/ffs/fs.h>
100 #include <ufs/ffs/ffs_extern.h>
101 #include <ufs/ffs/softdep.h>
103 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
104 int size, int rsize);
106 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
108 ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
109 static void ffs_blkfree_cg(struct ufsmount *, struct fs *,
110 struct vnode *, ufs2_daddr_t, long, ino_t,
112 static void ffs_blkfree_trim_completed(struct bio *);
113 static void ffs_blkfree_trim_task(void *ctx, int pending __unused);
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;
161 static struct timeval lastfail;
171 mtx_assert(UFS_MTX(ump), MA_OWNED);
173 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
174 printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
175 devtoname(ump->um_dev), (long)fs->fs_bsize, size,
177 panic("ffs_alloc: bad size");
180 panic("ffs_alloc: missing credential");
181 #endif /* INVARIANTS */
186 error = chkdq(ip, btodb(size), cred, 0);
191 if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
193 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
194 freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
196 if (bpref >= fs->fs_size)
199 cg = ino_to_cg(fs, ip->i_number);
201 cg = dtog(fs, bpref);
202 bno = ffs_hashalloc(ip, cg, bpref, size, size, ffs_alloccg);
205 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
207 ip->i_flag |= IN_CHANGE;
209 ip->i_flag |= IN_CHANGE | IN_UPDATE;
217 * Restore user's disk quota because allocation failed.
219 (void) chkdq(ip, -btodb(size), cred, FORCE);
222 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
224 softdep_request_cleanup(fs, ITOV(ip), cred, FLUSH_BLOCKS_WAIT);
228 if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
229 ffs_fserr(fs, ip->i_number, "filesystem full");
230 uprintf("\n%s: write failed, filesystem is full\n",
237 * Reallocate a fragment to a bigger size
239 * The number and size of the old block is given, and a preference
240 * and new size is also specified. The allocator attempts to extend
241 * the original block. Failing that, the regular block allocator is
242 * invoked to get an appropriate block.
245 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
250 int osize, nsize, flags;
257 struct ufsmount *ump;
258 u_int cg, request, reclaimed;
261 static struct timeval lastfail;
269 gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
271 mtx_assert(UFS_MTX(ump), MA_OWNED);
273 if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
274 panic("ffs_realloccg: allocation on suspended filesystem");
275 if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
276 (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
278 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
279 devtoname(ump->um_dev), (long)fs->fs_bsize, osize,
280 nsize, fs->fs_fsmnt);
281 panic("ffs_realloccg: bad size");
284 panic("ffs_realloccg: missing credential");
285 #endif /* INVARIANTS */
288 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
289 freespace(fs, fs->fs_minfree) - numfrags(fs, nsize - osize) < 0) {
293 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
294 devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
296 panic("ffs_realloccg: bad bprev");
300 * Allocate the extra space in the buffer.
302 error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
308 if (bp->b_blkno == bp->b_lblkno) {
309 if (lbprev >= UFS_NDADDR)
310 panic("ffs_realloccg: lbprev out of range");
311 bp->b_blkno = fsbtodb(fs, bprev);
315 error = chkdq(ip, btodb(nsize - osize), cred, 0);
322 * Check for extension in the existing location.
325 cg = dtog(fs, bprev);
327 bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
329 if (bp->b_blkno != fsbtodb(fs, bno))
330 panic("ffs_realloccg: bad blockno");
331 delta = btodb(nsize - osize);
332 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
334 ip->i_flag |= IN_CHANGE;
336 ip->i_flag |= IN_CHANGE | IN_UPDATE;
338 bp->b_flags |= B_DONE;
339 vfs_bio_bzero_buf(bp, osize, nsize - osize);
340 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
341 vfs_bio_set_valid(bp, osize, nsize - osize);
346 * Allocate a new disk location.
348 if (bpref >= fs->fs_size)
350 switch ((int)fs->fs_optim) {
353 * Allocate an exact sized fragment. Although this makes
354 * best use of space, we will waste time relocating it if
355 * the file continues to grow. If the fragmentation is
356 * less than half of the minimum free reserve, we choose
357 * to begin optimizing for time.
360 if (fs->fs_minfree <= 5 ||
361 fs->fs_cstotal.cs_nffree >
362 (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
364 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
366 fs->fs_optim = FS_OPTTIME;
370 * At this point we have discovered a file that is trying to
371 * grow a small fragment to a larger fragment. To save time,
372 * we allocate a full sized block, then free the unused portion.
373 * If the file continues to grow, the `ffs_fragextend' call
374 * above will be able to grow it in place without further
375 * copying. If aberrant programs cause disk fragmentation to
376 * grow within 2% of the free reserve, we choose to begin
377 * optimizing for space.
379 request = fs->fs_bsize;
380 if (fs->fs_cstotal.cs_nffree <
381 (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
383 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
385 fs->fs_optim = FS_OPTSPACE;
388 printf("dev = %s, optim = %ld, fs = %s\n",
389 devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
390 panic("ffs_realloccg: bad optim");
393 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
395 bp->b_blkno = fsbtodb(fs, bno);
396 if (!DOINGSOFTDEP(vp))
397 ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
398 ip->i_number, vp->v_type, NULL);
399 delta = btodb(nsize - osize);
400 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
402 ip->i_flag |= IN_CHANGE;
404 ip->i_flag |= IN_CHANGE | IN_UPDATE;
406 bp->b_flags |= B_DONE;
407 vfs_bio_bzero_buf(bp, osize, nsize - osize);
408 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
409 vfs_bio_set_valid(bp, osize, nsize - osize);
416 * Restore user's disk quota because allocation failed.
418 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
425 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
433 softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
439 if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
440 ffs_fserr(fs, ip->i_number, "filesystem full");
441 uprintf("\n%s: write failed, filesystem is full\n",
448 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
450 * The vnode and an array of buffer pointers for a range of sequential
451 * logical blocks to be made contiguous is given. The allocator attempts
452 * to find a range of sequential blocks starting as close as possible
453 * from the end of the allocation for the logical block immediately
454 * preceding the current range. If successful, the physical block numbers
455 * in the buffer pointers and in the inode are changed to reflect the new
456 * allocation. If unsuccessful, the allocation is left unchanged. The
457 * success in doing the reallocation is returned. Note that the error
458 * return is not reflected back to the user. Rather the previous block
459 * allocation will be used.
462 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
464 static int doasyncfree = 1;
465 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
466 "do not force synchronous writes when blocks are reallocated");
468 static int doreallocblks = 1;
469 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
470 "enable block reallocation");
472 static int maxclustersearch = 10;
473 SYSCTL_INT(_vfs_ffs, OID_AUTO, maxclustersearch, CTLFLAG_RW, &maxclustersearch,
474 0, "max number of cylinder group to search for contigous blocks");
477 static volatile int prtrealloc = 0;
482 struct vop_reallocblks_args /* {
484 struct cluster_save *a_buflist;
487 struct ufsmount *ump;
490 * If the underlying device can do deletes, then skip reallocating
491 * the blocks of this file into contiguous sequences. Devices that
492 * benefit from BIO_DELETE also benefit from not moving the data.
493 * These devices are flash and therefore work less well with this
494 * optimization. Also skip if reallocblks has been disabled globally.
496 ump = ap->a_vp->v_mount->mnt_data;
497 if (ump->um_candelete || doreallocblks == 0)
501 * We can't wait in softdep prealloc as it may fsync and recurse
502 * here. Instead we simply fail to reallocate blocks if this
503 * rare condition arises.
505 if (DOINGSOFTDEP(ap->a_vp))
506 if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
508 if (ump->um_fstype == UFS1)
509 return (ffs_reallocblks_ufs1(ap));
510 return (ffs_reallocblks_ufs2(ap));
514 ffs_reallocblks_ufs1(ap)
515 struct vop_reallocblks_args /* {
517 struct cluster_save *a_buflist;
523 struct buf *sbp, *ebp;
524 ufs1_daddr_t *bap, *sbap, *ebap;
525 struct cluster_save *buflist;
526 struct ufsmount *ump;
527 ufs_lbn_t start_lbn, end_lbn;
528 ufs1_daddr_t soff, newblk, blkno;
530 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
531 int i, cg, len, start_lvl, end_lvl, ssize;
538 * If we are not tracking block clusters or if we have less than 4%
539 * free blocks left, then do not attempt to cluster. Running with
540 * less than 5% free block reserve is not recommended and those that
541 * choose to do so do not expect to have good file layout.
543 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
545 buflist = ap->a_buflist;
546 len = buflist->bs_nchildren;
547 start_lbn = buflist->bs_children[0]->b_lblkno;
548 end_lbn = start_lbn + len - 1;
550 for (i = 0; i < len; i++)
551 if (!ffs_checkblk(ip,
552 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
553 panic("ffs_reallocblks: unallocated block 1");
554 for (i = 1; i < len; i++)
555 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
556 panic("ffs_reallocblks: non-logical cluster");
557 blkno = buflist->bs_children[0]->b_blkno;
558 ssize = fsbtodb(fs, fs->fs_frag);
559 for (i = 1; i < len - 1; i++)
560 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
561 panic("ffs_reallocblks: non-physical cluster %d", i);
564 * If the cluster crosses the boundary for the first indirect
565 * block, leave space for the indirect block. Indirect blocks
566 * are initially laid out in a position after the last direct
567 * block. Block reallocation would usually destroy locality by
568 * moving the indirect block out of the way to make room for
569 * data blocks if we didn't compensate here. We should also do
570 * this for other indirect block boundaries, but it is only
571 * important for the first one.
573 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
576 * If the latest allocation is in a new cylinder group, assume that
577 * the filesystem has decided to move and do not force it back to
578 * the previous cylinder group.
580 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
581 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
583 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
584 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
587 * Get the starting offset and block map for the first block.
589 if (start_lvl == 0) {
590 sbap = &ip->i_din1->di_db[0];
593 idp = &start_ap[start_lvl - 1];
594 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
598 sbap = (ufs1_daddr_t *)sbp->b_data;
602 * If the block range spans two block maps, get the second map.
605 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
610 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
611 panic("ffs_reallocblk: start == end");
613 ssize = len - (idp->in_off + 1);
614 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
616 ebap = (ufs1_daddr_t *)ebp->b_data;
619 * Find the preferred location for the cluster. If we have not
620 * previously failed at this endeavor, then follow our standard
621 * preference calculation. If we have failed at it, then pick up
622 * where we last ended our search.
625 if (ip->i_nextclustercg == -1)
626 pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
628 pref = cgdata(fs, ip->i_nextclustercg);
630 * Search the block map looking for an allocation of the desired size.
631 * To avoid wasting too much time, we limit the number of cylinder
632 * groups that we will search.
635 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
636 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
639 if (cg >= fs->fs_ncg)
643 * If we have failed in our search, record where we gave up for
644 * next time. Otherwise, fall back to our usual search citerion.
647 ip->i_nextclustercg = cg;
651 ip->i_nextclustercg = -1;
653 * We have found a new contiguous block.
655 * First we have to replace the old block pointers with the new
656 * block pointers in the inode and indirect blocks associated
661 printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
662 (uintmax_t)ip->i_number,
663 (intmax_t)start_lbn, (intmax_t)end_lbn);
666 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
672 if (!ffs_checkblk(ip,
673 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
674 panic("ffs_reallocblks: unallocated block 2");
675 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
676 panic("ffs_reallocblks: alloc mismatch");
680 printf(" %d,", *bap);
682 if (DOINGSOFTDEP(vp)) {
683 if (sbap == &ip->i_din1->di_db[0] && i < ssize)
684 softdep_setup_allocdirect(ip, start_lbn + i,
685 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
686 buflist->bs_children[i]);
688 softdep_setup_allocindir_page(ip, start_lbn + i,
689 i < ssize ? sbp : ebp, soff + i, blkno,
690 *bap, buflist->bs_children[i]);
695 * Next we must write out the modified inode and indirect blocks.
696 * For strict correctness, the writes should be synchronous since
697 * the old block values may have been written to disk. In practise
698 * they are almost never written, but if we are concerned about
699 * strict correctness, the `doasyncfree' flag should be set to zero.
701 * The test on `doasyncfree' should be changed to test a flag
702 * that shows whether the associated buffers and inodes have
703 * been written. The flag should be set when the cluster is
704 * started and cleared whenever the buffer or inode is flushed.
705 * We can then check below to see if it is set, and do the
706 * synchronous write only when it has been cleared.
708 if (sbap != &ip->i_din1->di_db[0]) {
714 ip->i_flag |= IN_CHANGE | IN_UPDATE;
725 * Last, free the old blocks and assign the new blocks to the buffers.
731 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
732 if (!DOINGSOFTDEP(vp))
733 ffs_blkfree(ump, fs, ump->um_devvp,
734 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
735 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
736 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
738 if (!ffs_checkblk(ip,
739 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
740 panic("ffs_reallocblks: unallocated block 3");
744 printf(" %d,", blkno);
758 if (sbap != &ip->i_din1->di_db[0])
764 ffs_reallocblks_ufs2(ap)
765 struct vop_reallocblks_args /* {
767 struct cluster_save *a_buflist;
773 struct buf *sbp, *ebp;
774 ufs2_daddr_t *bap, *sbap, *ebap;
775 struct cluster_save *buflist;
776 struct ufsmount *ump;
777 ufs_lbn_t start_lbn, end_lbn;
778 ufs2_daddr_t soff, newblk, blkno, pref;
779 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
780 int i, cg, len, start_lvl, end_lvl, ssize;
787 * If we are not tracking block clusters or if we have less than 4%
788 * free blocks left, then do not attempt to cluster. Running with
789 * less than 5% free block reserve is not recommended and those that
790 * choose to do so do not expect to have good file layout.
792 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
794 buflist = ap->a_buflist;
795 len = buflist->bs_nchildren;
796 start_lbn = buflist->bs_children[0]->b_lblkno;
797 end_lbn = start_lbn + len - 1;
799 for (i = 0; i < len; i++)
800 if (!ffs_checkblk(ip,
801 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
802 panic("ffs_reallocblks: unallocated block 1");
803 for (i = 1; i < len; i++)
804 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
805 panic("ffs_reallocblks: non-logical cluster");
806 blkno = buflist->bs_children[0]->b_blkno;
807 ssize = fsbtodb(fs, fs->fs_frag);
808 for (i = 1; i < len - 1; i++)
809 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
810 panic("ffs_reallocblks: non-physical cluster %d", i);
813 * If the cluster crosses the boundary for the first indirect
814 * block, do not move anything in it. Indirect blocks are
815 * usually initially laid out in a position between the data
816 * blocks. Block reallocation would usually destroy locality by
817 * moving the indirect block out of the way to make room for
818 * data blocks if we didn't compensate here. We should also do
819 * this for other indirect block boundaries, but it is only
820 * important for the first one.
822 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
825 * If the latest allocation is in a new cylinder group, assume that
826 * the filesystem has decided to move and do not force it back to
827 * the previous cylinder group.
829 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
830 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
832 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
833 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
836 * Get the starting offset and block map for the first block.
838 if (start_lvl == 0) {
839 sbap = &ip->i_din2->di_db[0];
842 idp = &start_ap[start_lvl - 1];
843 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
847 sbap = (ufs2_daddr_t *)sbp->b_data;
851 * If the block range spans two block maps, get the second map.
854 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
859 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
860 panic("ffs_reallocblk: start == end");
862 ssize = len - (idp->in_off + 1);
863 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
865 ebap = (ufs2_daddr_t *)ebp->b_data;
868 * Find the preferred location for the cluster. If we have not
869 * previously failed at this endeavor, then follow our standard
870 * preference calculation. If we have failed at it, then pick up
871 * where we last ended our search.
874 if (ip->i_nextclustercg == -1)
875 pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
877 pref = cgdata(fs, ip->i_nextclustercg);
879 * Search the block map looking for an allocation of the desired size.
880 * To avoid wasting too much time, we limit the number of cylinder
881 * groups that we will search.
884 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
885 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
888 if (cg >= fs->fs_ncg)
892 * If we have failed in our search, record where we gave up for
893 * next time. Otherwise, fall back to our usual search citerion.
896 ip->i_nextclustercg = cg;
900 ip->i_nextclustercg = -1;
902 * We have found a new contiguous block.
904 * First we have to replace the old block pointers with the new
905 * block pointers in the inode and indirect blocks associated
910 printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
911 (intmax_t)start_lbn, (intmax_t)end_lbn);
914 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
920 if (!ffs_checkblk(ip,
921 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
922 panic("ffs_reallocblks: unallocated block 2");
923 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
924 panic("ffs_reallocblks: alloc mismatch");
928 printf(" %jd,", (intmax_t)*bap);
930 if (DOINGSOFTDEP(vp)) {
931 if (sbap == &ip->i_din2->di_db[0] && i < ssize)
932 softdep_setup_allocdirect(ip, start_lbn + i,
933 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
934 buflist->bs_children[i]);
936 softdep_setup_allocindir_page(ip, start_lbn + i,
937 i < ssize ? sbp : ebp, soff + i, blkno,
938 *bap, buflist->bs_children[i]);
943 * Next we must write out the modified inode and indirect blocks.
944 * For strict correctness, the writes should be synchronous since
945 * the old block values may have been written to disk. In practise
946 * they are almost never written, but if we are concerned about
947 * strict correctness, the `doasyncfree' flag should be set to zero.
949 * The test on `doasyncfree' should be changed to test a flag
950 * that shows whether the associated buffers and inodes have
951 * been written. The flag should be set when the cluster is
952 * started and cleared whenever the buffer or inode is flushed.
953 * We can then check below to see if it is set, and do the
954 * synchronous write only when it has been cleared.
956 if (sbap != &ip->i_din2->di_db[0]) {
962 ip->i_flag |= IN_CHANGE | IN_UPDATE;
973 * Last, free the old blocks and assign the new blocks to the buffers.
979 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
980 if (!DOINGSOFTDEP(vp))
981 ffs_blkfree(ump, fs, ump->um_devvp,
982 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
983 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
984 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
986 if (!ffs_checkblk(ip,
987 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
988 panic("ffs_reallocblks: unallocated block 3");
992 printf(" %jd,", (intmax_t)blkno);
1006 if (sbap != &ip->i_din2->di_db[0])
1012 * Allocate an inode in the filesystem.
1014 * If allocating a directory, use ffs_dirpref to select the inode.
1015 * If allocating in a directory, the following hierarchy is followed:
1016 * 1) allocate the preferred inode.
1017 * 2) allocate an inode in the same cylinder group.
1018 * 3) quadradically rehash into other cylinder groups, until an
1019 * available inode is located.
1020 * If no inode preference is given the following hierarchy is used
1021 * to allocate an inode:
1022 * 1) allocate an inode in cylinder group 0.
1023 * 2) quadradically rehash into other cylinder groups, until an
1024 * available inode is located.
1027 ffs_valloc(pvp, mode, cred, vpp)
1037 struct ufsmount *ump;
1040 int error, error1, reclaimed;
1041 static struct timeval lastfail;
1052 if (fs->fs_cstotal.cs_nifree == 0)
1055 if ((mode & IFMT) == IFDIR)
1056 ipref = ffs_dirpref(pip);
1058 ipref = pip->i_number;
1059 if (ipref >= fs->fs_ncg * fs->fs_ipg)
1061 cg = ino_to_cg(fs, ipref);
1063 * Track number of dirs created one after another
1064 * in a same cg without intervening by files.
1066 if ((mode & IFMT) == IFDIR) {
1067 if (fs->fs_contigdirs[cg] < 255)
1068 fs->fs_contigdirs[cg]++;
1070 if (fs->fs_contigdirs[cg] > 0)
1071 fs->fs_contigdirs[cg]--;
1073 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1074 (allocfcn_t *)ffs_nodealloccg);
1077 error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
1079 error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1081 ffs_vfree(pvp, ino, mode);
1086 ip->i_flag |= IN_MODIFIED;
1094 printf("mode = 0%o, inum = %ju, fs = %s\n",
1095 ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1096 panic("ffs_valloc: dup alloc");
1098 if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) { /* XXX */
1099 printf("free inode %s/%lu had %ld blocks\n",
1100 fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1101 DIP_SET(ip, i_blocks, 0);
1104 DIP_SET(ip, i_flags, 0);
1106 * Set up a new generation number for this inode.
1108 while (ip->i_gen == 0 || ++ip->i_gen == 0)
1109 ip->i_gen = arc4random();
1110 DIP_SET(ip, i_gen, ip->i_gen);
1111 if (fs->fs_magic == FS_UFS2_MAGIC) {
1113 ip->i_din2->di_birthtime = ts.tv_sec;
1114 ip->i_din2->di_birthnsec = ts.tv_nsec;
1116 ufs_prepare_reclaim(*vpp);
1118 (*vpp)->v_vflag = 0;
1119 (*vpp)->v_type = VNON;
1120 if (fs->fs_magic == FS_UFS2_MAGIC) {
1121 (*vpp)->v_op = &ffs_vnodeops2;
1122 ip->i_flag |= IN_UFS2;
1124 (*vpp)->v_op = &ffs_vnodeops1;
1128 if (reclaimed == 0) {
1130 softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1134 if (ppsratecheck(&lastfail, &curfail, 1)) {
1135 ffs_fserr(fs, pip->i_number, "out of inodes");
1136 uprintf("\n%s: create/symlink failed, no inodes free\n",
1143 * Find a cylinder group to place a directory.
1145 * The policy implemented by this algorithm is to allocate a
1146 * directory inode in the same cylinder group as its parent
1147 * directory, but also to reserve space for its files inodes
1148 * and data. Restrict the number of directories which may be
1149 * allocated one after another in the same cylinder group
1150 * without intervening allocation of files.
1152 * If we allocate a first level directory then force allocation
1153 * in another cylinder group.
1160 int cg, prefcg, dirsize, cgsize;
1161 u_int avgifree, avgbfree, avgndir, curdirsize;
1162 u_int minifree, minbfree, maxndir;
1163 u_int mincg, minndir;
1164 u_int maxcontigdirs;
1166 mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1169 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1170 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1171 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1174 * Force allocation in another cg if creating a first level dir.
1176 ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1177 if (ITOV(pip)->v_vflag & VV_ROOT) {
1178 prefcg = arc4random() % fs->fs_ncg;
1180 minndir = fs->fs_ipg;
1181 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1182 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1183 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1184 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1186 minndir = fs->fs_cs(fs, cg).cs_ndir;
1188 for (cg = 0; cg < prefcg; cg++)
1189 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1190 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1191 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1193 minndir = fs->fs_cs(fs, cg).cs_ndir;
1195 return ((ino_t)(fs->fs_ipg * mincg));
1199 * Count various limits which used for
1200 * optimal allocation of a directory inode.
1202 maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1203 minifree = avgifree - avgifree / 4;
1206 minbfree = avgbfree - avgbfree / 4;
1209 cgsize = fs->fs_fsize * fs->fs_fpg;
1210 dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1211 curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1212 if (dirsize < curdirsize)
1213 dirsize = curdirsize;
1215 maxcontigdirs = 0; /* dirsize overflowed */
1217 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1218 if (fs->fs_avgfpdir > 0)
1219 maxcontigdirs = min(maxcontigdirs,
1220 fs->fs_ipg / fs->fs_avgfpdir);
1221 if (maxcontigdirs == 0)
1225 * Limit number of dirs in one cg and reserve space for
1226 * regular files, but only if we have no deficit in
1229 * We are trying to find a suitable cylinder group nearby
1230 * our preferred cylinder group to place a new directory.
1231 * We scan from our preferred cylinder group forward looking
1232 * for a cylinder group that meets our criterion. If we get
1233 * to the final cylinder group and do not find anything,
1234 * we start scanning forwards from the beginning of the
1235 * filesystem. While it might seem sensible to start scanning
1236 * backwards or even to alternate looking forward and backward,
1237 * this approach fails badly when the filesystem is nearly full.
1238 * Specifically, we first search all the areas that have no space
1239 * and finally try the one preceding that. We repeat this on
1240 * every request and in the case of the final block end up
1241 * searching the entire filesystem. By jumping to the front
1242 * of the filesystem, our future forward searches always look
1243 * in new cylinder groups so finds every possible block after
1244 * one pass over the filesystem.
1246 prefcg = ino_to_cg(fs, pip->i_number);
1247 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1248 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1249 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1250 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1251 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1252 return ((ino_t)(fs->fs_ipg * cg));
1254 for (cg = 0; cg < prefcg; cg++)
1255 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1256 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1257 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1258 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1259 return ((ino_t)(fs->fs_ipg * cg));
1262 * This is a backstop when we have deficit in space.
1264 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1265 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1266 return ((ino_t)(fs->fs_ipg * cg));
1267 for (cg = 0; cg < prefcg; cg++)
1268 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1270 return ((ino_t)(fs->fs_ipg * cg));
1274 * Select the desired position for the next block in a file. The file is
1275 * logically divided into sections. The first section is composed of the
1276 * direct blocks and the next fs_maxbpg blocks. Each additional section
1277 * contains fs_maxbpg blocks.
1279 * If no blocks have been allocated in the first section, the policy is to
1280 * request a block in the same cylinder group as the inode that describes
1281 * the file. The first indirect is allocated immediately following the last
1282 * direct block and the data blocks for the first indirect immediately
1285 * If no blocks have been allocated in any other section, the indirect
1286 * block(s) are allocated in the same cylinder group as its inode in an
1287 * area reserved immediately following the inode blocks. The policy for
1288 * the data blocks is to place them in a cylinder group with a greater than
1289 * average number of free blocks. An appropriate cylinder group is found
1290 * by using a rotor that sweeps the cylinder groups. When a new group of
1291 * blocks is needed, the sweep begins in the cylinder group following the
1292 * cylinder group from which the previous allocation was made. The sweep
1293 * continues until a cylinder group with greater than the average number
1294 * of free blocks is found. If the allocation is for the first block in an
1295 * indirect block or the previous block is a hole, then the information on
1296 * the previous allocation is unavailable; here a best guess is made based
1297 * on the logical block number being allocated.
1299 * If a section is already partially allocated, the policy is to
1300 * allocate blocks contiguously within the section if possible.
1303 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1311 u_int avgbfree, startcg;
1314 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1315 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1318 * Allocation of indirect blocks is indicated by passing negative
1319 * values in indx: -1 for single indirect, -2 for double indirect,
1320 * -3 for triple indirect. As noted below, we attempt to allocate
1321 * the first indirect inline with the file data. For all later
1322 * indirect blocks, the data is often allocated in other cylinder
1323 * groups. However to speed random file access and to speed up
1324 * fsck, the filesystem reserves the first fs_metaspace blocks
1325 * (typically half of fs_minfree) of the data area of each cylinder
1326 * group to hold these later indirect blocks.
1328 inocg = ino_to_cg(fs, ip->i_number);
1331 * Our preference for indirect blocks is the zone at the
1332 * beginning of the inode's cylinder group data area that
1333 * we try to reserve for indirect blocks.
1335 pref = cgmeta(fs, inocg);
1337 * If we are allocating the first indirect block, try to
1338 * place it immediately following the last direct block.
1340 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1341 ip->i_din1->di_db[UFS_NDADDR - 1] != 0)
1342 pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1346 * If we are allocating the first data block in the first indirect
1347 * block and the indirect has been allocated in the data block area,
1348 * try to place it immediately following the indirect block.
1350 if (lbn == UFS_NDADDR) {
1351 pref = ip->i_din1->di_ib[0];
1352 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1353 pref < cgbase(fs, inocg + 1))
1354 return (pref + fs->fs_frag);
1357 * If we are at the beginning of a file, or we have already allocated
1358 * the maximum number of blocks per cylinder group, or we do not
1359 * have a block allocated immediately preceding us, then we need
1360 * to decide where to start allocating new blocks.
1362 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1364 * If we are allocating a directory data block, we want
1365 * to place it in the metadata area.
1367 if ((ip->i_mode & IFMT) == IFDIR)
1368 return (cgmeta(fs, inocg));
1370 * Until we fill all the direct and all the first indirect's
1371 * blocks, we try to allocate in the data area of the inode's
1374 if (lbn < UFS_NDADDR + NINDIR(fs))
1375 return (cgdata(fs, inocg));
1377 * Find a cylinder with greater than average number of
1378 * unused data blocks.
1380 if (indx == 0 || bap[indx - 1] == 0)
1381 startcg = inocg + lbn / fs->fs_maxbpg;
1383 startcg = dtog(fs, bap[indx - 1]) + 1;
1384 startcg %= fs->fs_ncg;
1385 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1386 for (cg = startcg; cg < fs->fs_ncg; cg++)
1387 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1388 fs->fs_cgrotor = cg;
1389 return (cgdata(fs, cg));
1391 for (cg = 0; cg <= startcg; cg++)
1392 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1393 fs->fs_cgrotor = cg;
1394 return (cgdata(fs, cg));
1399 * Otherwise, we just always try to lay things out contiguously.
1401 return (bap[indx - 1] + fs->fs_frag);
1405 * Same as above, but for UFS2
1408 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1416 u_int avgbfree, startcg;
1419 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1420 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1423 * Allocation of indirect blocks is indicated by passing negative
1424 * values in indx: -1 for single indirect, -2 for double indirect,
1425 * -3 for triple indirect. As noted below, we attempt to allocate
1426 * the first indirect inline with the file data. For all later
1427 * indirect blocks, the data is often allocated in other cylinder
1428 * groups. However to speed random file access and to speed up
1429 * fsck, the filesystem reserves the first fs_metaspace blocks
1430 * (typically half of fs_minfree) of the data area of each cylinder
1431 * group to hold these later indirect blocks.
1433 inocg = ino_to_cg(fs, ip->i_number);
1436 * Our preference for indirect blocks is the zone at the
1437 * beginning of the inode's cylinder group data area that
1438 * we try to reserve for indirect blocks.
1440 pref = cgmeta(fs, inocg);
1442 * If we are allocating the first indirect block, try to
1443 * place it immediately following the last direct block.
1445 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1446 ip->i_din2->di_db[UFS_NDADDR - 1] != 0)
1447 pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1451 * If we are allocating the first data block in the first indirect
1452 * block and the indirect has been allocated in the data block area,
1453 * try to place it immediately following the indirect block.
1455 if (lbn == UFS_NDADDR) {
1456 pref = ip->i_din2->di_ib[0];
1457 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1458 pref < cgbase(fs, inocg + 1))
1459 return (pref + fs->fs_frag);
1462 * If we are at the beginning of a file, or we have already allocated
1463 * the maximum number of blocks per cylinder group, or we do not
1464 * have a block allocated immediately preceding us, then we need
1465 * to decide where to start allocating new blocks.
1467 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1469 * If we are allocating a directory data block, we want
1470 * to place it in the metadata area.
1472 if ((ip->i_mode & IFMT) == IFDIR)
1473 return (cgmeta(fs, inocg));
1475 * Until we fill all the direct and all the first indirect's
1476 * blocks, we try to allocate in the data area of the inode's
1479 if (lbn < UFS_NDADDR + NINDIR(fs))
1480 return (cgdata(fs, inocg));
1482 * Find a cylinder with greater than average number of
1483 * unused data blocks.
1485 if (indx == 0 || bap[indx - 1] == 0)
1486 startcg = inocg + lbn / fs->fs_maxbpg;
1488 startcg = dtog(fs, bap[indx - 1]) + 1;
1489 startcg %= fs->fs_ncg;
1490 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1491 for (cg = startcg; cg < fs->fs_ncg; cg++)
1492 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1493 fs->fs_cgrotor = cg;
1494 return (cgdata(fs, cg));
1496 for (cg = 0; cg <= startcg; cg++)
1497 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1498 fs->fs_cgrotor = cg;
1499 return (cgdata(fs, cg));
1504 * Otherwise, we just always try to lay things out contiguously.
1506 return (bap[indx - 1] + fs->fs_frag);
1510 * Implement the cylinder overflow algorithm.
1512 * The policy implemented by this algorithm is:
1513 * 1) allocate the block in its requested cylinder group.
1514 * 2) quadradically rehash on the cylinder group number.
1515 * 3) brute force search for a free block.
1517 * Must be called with the UFS lock held. Will release the lock on success
1518 * and return with it held on failure.
1522 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1526 int size; /* Search size for data blocks, mode for inodes */
1527 int rsize; /* Real allocated size. */
1528 allocfcn_t *allocator;
1531 ufs2_daddr_t result;
1534 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1536 if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1537 panic("ffs_hashalloc: allocation on suspended filesystem");
1541 * 1: preferred cylinder group
1543 result = (*allocator)(ip, cg, pref, size, rsize);
1547 * 2: quadratic rehash
1549 for (i = 1; i < fs->fs_ncg; i *= 2) {
1551 if (cg >= fs->fs_ncg)
1553 result = (*allocator)(ip, cg, 0, size, rsize);
1558 * 3: brute force search
1559 * Note that we start at i == 2, since 0 was checked initially,
1560 * and 1 is always checked in the quadratic rehash.
1562 cg = (icg + 2) % fs->fs_ncg;
1563 for (i = 2; i < fs->fs_ncg; i++) {
1564 result = (*allocator)(ip, cg, 0, size, rsize);
1568 if (cg == fs->fs_ncg)
1575 * Determine whether a fragment can be extended.
1577 * Check to see if the necessary fragments are available, and
1578 * if they are, allocate them.
1581 ffs_fragextend(ip, cg, bprev, osize, nsize)
1590 struct ufsmount *ump;
1599 if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1601 frags = numfrags(fs, nsize);
1602 bbase = fragnum(fs, bprev);
1603 if (bbase > fragnum(fs, (bprev + frags - 1))) {
1604 /* cannot extend across a block boundary */
1608 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0)
1610 bno = dtogd(fs, bprev);
1611 blksfree = cg_blksfree(cgp);
1612 for (i = numfrags(fs, osize); i < frags; i++)
1613 if (isclr(blksfree, bno + i))
1616 * the current fragment can be extended
1617 * deduct the count on fragment being extended into
1618 * increase the count on the remaining fragment (if any)
1619 * allocate the extended piece
1621 for (i = frags; i < fs->fs_frag - bbase; i++)
1622 if (isclr(blksfree, bno + i))
1624 cgp->cg_frsum[i - numfrags(fs, osize)]--;
1626 cgp->cg_frsum[i - frags]++;
1627 for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1628 clrbit(blksfree, bno + i);
1629 cgp->cg_cs.cs_nffree--;
1633 fs->fs_cstotal.cs_nffree -= nffree;
1634 fs->fs_cs(fs, cg).cs_nffree -= nffree;
1636 ACTIVECLEAR(fs, cg);
1638 if (DOINGSOFTDEP(ITOV(ip)))
1639 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1640 frags, numfrags(fs, osize));
1652 * Determine whether a block can be allocated.
1654 * Check to see if a block of the appropriate size is available,
1655 * and if it is, allocate it.
1658 ffs_alloccg(ip, cg, bpref, size, rsize)
1668 struct ufsmount *ump;
1671 int i, allocsiz, error, frags;
1676 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1679 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0 ||
1680 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1682 if (size == fs->fs_bsize) {
1684 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1685 ACTIVECLEAR(fs, cg);
1691 * check to see if any fragments are already available
1692 * allocsiz is the size which will be allocated, hacking
1693 * it down to a smaller size if necessary
1695 blksfree = cg_blksfree(cgp);
1696 frags = numfrags(fs, size);
1697 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1698 if (cgp->cg_frsum[allocsiz] != 0)
1700 if (allocsiz == fs->fs_frag) {
1702 * no fragments were available, so a block will be
1703 * allocated, and hacked up
1705 if (cgp->cg_cs.cs_nbfree == 0)
1708 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1709 ACTIVECLEAR(fs, cg);
1714 KASSERT(size == rsize,
1715 ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1716 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1719 for (i = 0; i < frags; i++)
1720 clrbit(blksfree, bno + i);
1721 cgp->cg_cs.cs_nffree -= frags;
1722 cgp->cg_frsum[allocsiz]--;
1723 if (frags != allocsiz)
1724 cgp->cg_frsum[allocsiz - frags]++;
1726 fs->fs_cstotal.cs_nffree -= frags;
1727 fs->fs_cs(fs, cg).cs_nffree -= frags;
1729 blkno = cgbase(fs, cg) + bno;
1730 ACTIVECLEAR(fs, cg);
1732 if (DOINGSOFTDEP(ITOV(ip)))
1733 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1744 * Allocate a block in a cylinder group.
1746 * This algorithm implements the following policy:
1747 * 1) allocate the requested block.
1748 * 2) allocate a rotationally optimal block in the same cylinder.
1749 * 3) allocate the next available block on the block rotor for the
1750 * specified cylinder group.
1751 * Note that this routine only allocates fs_bsize blocks; these
1752 * blocks may be fragmented by the routine that allocates them.
1755 ffs_alloccgblk(ip, bp, bpref, size)
1763 struct ufsmount *ump;
1771 mtx_assert(UFS_MTX(ump), MA_OWNED);
1772 cgp = (struct cg *)bp->b_data;
1773 blksfree = cg_blksfree(cgp);
1775 bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1776 } else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1777 /* map bpref to correct zone in this cg */
1778 if (bpref < cgdata(fs, cgbpref))
1779 bpref = cgmeta(fs, cgp->cg_cgx);
1781 bpref = cgdata(fs, cgp->cg_cgx);
1784 * if the requested block is available, use it
1786 bno = dtogd(fs, blknum(fs, bpref));
1787 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1790 * Take the next available block in this cylinder group.
1792 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1795 /* Update cg_rotor only if allocated from the data zone */
1796 if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1797 cgp->cg_rotor = bno;
1799 blkno = fragstoblks(fs, bno);
1800 ffs_clrblock(fs, blksfree, (long)blkno);
1801 ffs_clusteracct(fs, cgp, blkno, -1);
1802 cgp->cg_cs.cs_nbfree--;
1803 fs->fs_cstotal.cs_nbfree--;
1804 fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1806 blkno = cgbase(fs, cgp->cg_cgx) + bno;
1808 * If the caller didn't want the whole block free the frags here.
1810 size = numfrags(fs, size);
1811 if (size != fs->fs_frag) {
1812 bno = dtogd(fs, blkno);
1813 for (i = size; i < fs->fs_frag; i++)
1814 setbit(blksfree, bno + i);
1815 i = fs->fs_frag - size;
1816 cgp->cg_cs.cs_nffree += i;
1817 fs->fs_cstotal.cs_nffree += i;
1818 fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1824 if (DOINGSOFTDEP(ITOV(ip)))
1825 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno,
1832 * Determine whether a cluster can be allocated.
1834 * We do not currently check for optimal rotational layout if there
1835 * are multiple choices in the same cylinder group. Instead we just
1836 * take the first one that we find following bpref.
1839 ffs_clusteralloc(ip, cg, bpref, len)
1848 struct ufsmount *ump;
1849 int i, run, bit, map, got, error;
1857 if (fs->fs_maxcluster[cg] < len)
1860 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0) {
1865 * Check to see if a cluster of the needed size (or bigger) is
1866 * available in this cylinder group.
1868 lp = &cg_clustersum(cgp)[len];
1869 for (i = len; i <= fs->fs_contigsumsize; i++)
1872 if (i > fs->fs_contigsumsize) {
1874 * This is the first time looking for a cluster in this
1875 * cylinder group. Update the cluster summary information
1876 * to reflect the true maximum sized cluster so that
1877 * future cluster allocation requests can avoid reading
1878 * the cylinder group map only to find no clusters.
1880 lp = &cg_clustersum(cgp)[len - 1];
1881 for (i = len - 1; i > 0; i--)
1885 fs->fs_maxcluster[cg] = i;
1890 * Search the cluster map to find a big enough cluster.
1891 * We take the first one that we find, even if it is larger
1892 * than we need as we prefer to get one close to the previous
1893 * block allocation. We do not search before the current
1894 * preference point as we do not want to allocate a block
1895 * that is allocated before the previous one (as we will
1896 * then have to wait for another pass of the elevator
1897 * algorithm before it will be read). We prefer to fail and
1898 * be recalled to try an allocation in the next cylinder group.
1900 if (dtog(fs, bpref) != cg)
1901 bpref = cgdata(fs, cg);
1903 bpref = blknum(fs, bpref);
1904 bpref = fragstoblks(fs, dtogd(fs, bpref));
1905 mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1907 bit = 1 << (bpref % NBBY);
1908 for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1909 if ((map & bit) == 0) {
1916 if ((got & (NBBY - 1)) != (NBBY - 1)) {
1923 if (got >= cgp->cg_nclusterblks) {
1929 * Allocate the cluster that we have found.
1931 blksfree = cg_blksfree(cgp);
1932 for (i = 1; i <= len; i++)
1933 if (!ffs_isblock(fs, blksfree, got - run + i))
1934 panic("ffs_clusteralloc: map mismatch");
1935 bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1936 if (dtog(fs, bno) != cg)
1937 panic("ffs_clusteralloc: allocated out of group");
1938 len = blkstofrags(fs, len);
1940 for (i = 0; i < len; i += fs->fs_frag)
1941 if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
1942 panic("ffs_clusteralloc: lost block");
1943 ACTIVECLEAR(fs, cg);
1949 static inline struct buf *
1950 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
1955 return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
1956 cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
1961 * Synchronous inode initialization is needed only when barrier writes do not
1962 * work as advertised, and will impose a heavy cost on file creation in a newly
1963 * created filesystem.
1965 static int doasyncinodeinit = 1;
1966 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncinodeinit, CTLFLAG_RWTUN,
1967 &doasyncinodeinit, 0,
1968 "Perform inode block initialization using asynchronous writes");
1971 * Determine whether an inode can be allocated.
1973 * Check to see if an inode is available, and if it is,
1974 * allocate it using the following policy:
1975 * 1) allocate the requested inode.
1976 * 2) allocate the next available inode after the requested
1977 * inode in the specified cylinder group.
1980 ffs_nodealloccg(ip, cg, ipref, mode, unused)
1989 struct buf *bp, *ibp;
1990 struct ufsmount *ump;
1991 u_int8_t *inosused, *loc;
1992 struct ufs2_dinode *dp2;
1993 int error, start, len, i;
1994 u_int32_t old_initediblk;
1999 if (fs->fs_cs(fs, cg).cs_nifree == 0)
2002 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0) {
2007 if (cgp->cg_cs.cs_nifree == 0) {
2012 inosused = cg_inosused(cgp);
2014 ipref %= fs->fs_ipg;
2015 if (isclr(inosused, ipref))
2018 start = cgp->cg_irotor / NBBY;
2019 len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
2020 loc = memcchr(&inosused[start], 0xff, len);
2024 loc = memcchr(&inosused[start], 0xff, len);
2026 printf("cg = %d, irotor = %ld, fs = %s\n",
2027 cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2028 panic("ffs_nodealloccg: map corrupted");
2032 ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2035 * Check to see if we need to initialize more inodes.
2037 if (fs->fs_magic == FS_UFS2_MAGIC &&
2038 ipref + INOPB(fs) > cgp->cg_initediblk &&
2039 cgp->cg_initediblk < cgp->cg_niblk) {
2040 old_initediblk = cgp->cg_initediblk;
2043 * Free the cylinder group lock before writing the
2044 * initialized inode block. Entering the
2045 * babarrierwrite() with the cylinder group lock
2046 * causes lock order violation between the lock and
2049 * Another thread can decide to initialize the same
2050 * inode block, but whichever thread first gets the
2051 * cylinder group lock after writing the newly
2052 * allocated inode block will update it and the other
2053 * will realize that it has lost and leave the
2054 * cylinder group unchanged.
2056 ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2060 * The inode block buffer is already owned by
2061 * another thread, which must initialize it.
2062 * Wait on the buffer to allow another thread
2063 * to finish the updates, with dropped cg
2064 * buffer lock, then retry.
2066 ibp = getinobuf(ip, cg, old_initediblk, 0);
2071 bzero(ibp->b_data, (int)fs->fs_bsize);
2072 dp2 = (struct ufs2_dinode *)(ibp->b_data);
2073 for (i = 0; i < INOPB(fs); i++) {
2074 while (dp2->di_gen == 0)
2075 dp2->di_gen = arc4random();
2080 * Rather than adding a soft updates dependency to ensure
2081 * that the new inode block is written before it is claimed
2082 * by the cylinder group map, we just do a barrier write
2083 * here. The barrier write will ensure that the inode block
2084 * gets written before the updated cylinder group map can be
2085 * written. The barrier write should only slow down bulk
2086 * loading of newly created filesystems.
2088 if (doasyncinodeinit)
2089 babarrierwrite(ibp);
2094 * After the inode block is written, try to update the
2095 * cg initediblk pointer. If another thread beat us
2096 * to it, then leave it unchanged as the other thread
2097 * has already set it correctly.
2099 error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp);
2101 ACTIVECLEAR(fs, cg);
2105 if (cgp->cg_initediblk == old_initediblk)
2106 cgp->cg_initediblk += INOPB(fs);
2109 cgp->cg_irotor = ipref;
2111 ACTIVECLEAR(fs, cg);
2112 setbit(inosused, ipref);
2113 cgp->cg_cs.cs_nifree--;
2114 fs->fs_cstotal.cs_nifree--;
2115 fs->fs_cs(fs, cg).cs_nifree--;
2117 if ((mode & IFMT) == IFDIR) {
2118 cgp->cg_cs.cs_ndir++;
2119 fs->fs_cstotal.cs_ndir++;
2120 fs->fs_cs(fs, cg).cs_ndir++;
2123 if (DOINGSOFTDEP(ITOV(ip)))
2124 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2126 return ((ino_t)(cg * fs->fs_ipg + ipref));
2130 * Free a block or fragment.
2132 * The specified block or fragment is placed back in the
2133 * free map. If a fragment is deallocated, a possible
2134 * block reassembly is checked.
2137 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2138 struct ufsmount *ump;
2140 struct vnode *devvp;
2144 struct workhead *dephd;
2149 ufs1_daddr_t fragno, cgbno;
2150 int i, blk, frags, bbase, error;
2156 if (devvp->v_type == VREG) {
2157 /* devvp is a snapshot */
2158 MPASS(devvp->v_mount->mnt_data == ump);
2159 dev = ump->um_devvp->v_rdev;
2160 } else if (devvp->v_type == VCHR) {
2161 /* devvp is a normal disk device */
2162 dev = devvp->v_rdev;
2163 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
2167 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2168 fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2169 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2170 devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2171 size, fs->fs_fsmnt);
2172 panic("ffs_blkfree_cg: bad size");
2175 if ((u_int)bno >= fs->fs_size) {
2176 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2178 ffs_fserr(fs, inum, "bad block");
2181 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2183 cgbno = dtogd(fs, bno);
2184 blksfree = cg_blksfree(cgp);
2186 if (size == fs->fs_bsize) {
2187 fragno = fragstoblks(fs, cgbno);
2188 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2189 if (devvp->v_type == VREG) {
2191 /* devvp is a snapshot */
2195 printf("dev = %s, block = %jd, fs = %s\n",
2196 devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2197 panic("ffs_blkfree_cg: freeing free block");
2199 ffs_setblock(fs, blksfree, fragno);
2200 ffs_clusteracct(fs, cgp, fragno, 1);
2201 cgp->cg_cs.cs_nbfree++;
2202 fs->fs_cstotal.cs_nbfree++;
2203 fs->fs_cs(fs, cg).cs_nbfree++;
2205 bbase = cgbno - fragnum(fs, cgbno);
2207 * decrement the counts associated with the old frags
2209 blk = blkmap(fs, blksfree, bbase);
2210 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2212 * deallocate the fragment
2214 frags = numfrags(fs, size);
2215 for (i = 0; i < frags; i++) {
2216 if (isset(blksfree, cgbno + i)) {
2217 printf("dev = %s, block = %jd, fs = %s\n",
2218 devtoname(dev), (intmax_t)(bno + i),
2220 panic("ffs_blkfree_cg: freeing free frag");
2222 setbit(blksfree, cgbno + i);
2224 cgp->cg_cs.cs_nffree += i;
2225 fs->fs_cstotal.cs_nffree += i;
2226 fs->fs_cs(fs, cg).cs_nffree += i;
2228 * add back in counts associated with the new frags
2230 blk = blkmap(fs, blksfree, bbase);
2231 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2233 * if a complete block has been reassembled, account for it
2235 fragno = fragstoblks(fs, bbase);
2236 if (ffs_isblock(fs, blksfree, fragno)) {
2237 cgp->cg_cs.cs_nffree -= fs->fs_frag;
2238 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2239 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2240 ffs_clusteracct(fs, cgp, fragno, 1);
2241 cgp->cg_cs.cs_nbfree++;
2242 fs->fs_cstotal.cs_nbfree++;
2243 fs->fs_cs(fs, cg).cs_nbfree++;
2247 ACTIVECLEAR(fs, cg);
2250 if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2251 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2252 numfrags(fs, size), dephd);
2256 struct ffs_blkfree_trim_params {
2258 struct ufsmount *ump;
2259 struct vnode *devvp;
2263 struct workhead *pdephd;
2264 struct workhead dephd;
2268 ffs_blkfree_trim_task(ctx, pending)
2272 struct ffs_blkfree_trim_params *tp;
2275 ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
2276 tp->inum, tp->pdephd);
2277 vn_finished_secondary_write(UFSTOVFS(tp->ump));
2278 atomic_add_int(&tp->ump->um_trim_inflight, -1);
2283 ffs_blkfree_trim_completed(bip)
2286 struct ffs_blkfree_trim_params *tp;
2288 tp = bip->bio_caller2;
2290 TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2291 taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
2295 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd)
2296 struct ufsmount *ump;
2298 struct vnode *devvp;
2303 struct workhead *dephd;
2307 struct ffs_blkfree_trim_params *tp;
2310 * Check to see if a snapshot wants to claim the block.
2311 * Check that devvp is a normal disk device, not a snapshot,
2312 * it has a snapshot(s) associated with it, and one of the
2313 * snapshots wants to claim the block.
2315 if (devvp->v_type == VCHR &&
2316 (devvp->v_vflag & VV_COPYONWRITE) &&
2317 ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2321 * Nothing to delay if TRIM is disabled, or the operation is
2322 * performed on the snapshot.
2324 if (!ump->um_candelete || devvp->v_type == VREG) {
2325 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2330 * Postpone the set of the free bit in the cg bitmap until the
2331 * BIO_DELETE is completed. Otherwise, due to disk queue
2332 * reordering, TRIM might be issued after we reuse the block
2333 * and write some new data into it.
2335 atomic_add_int(&ump->um_trim_inflight, 1);
2336 tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2342 if (dephd != NULL) {
2343 LIST_INIT(&tp->dephd);
2344 LIST_SWAP(dephd, &tp->dephd, worklist, wk_list);
2345 tp->pdephd = &tp->dephd;
2349 bip = g_alloc_bio();
2350 bip->bio_cmd = BIO_DELETE;
2351 bip->bio_offset = dbtob(fsbtodb(fs, bno));
2352 bip->bio_done = ffs_blkfree_trim_completed;
2353 bip->bio_length = size;
2354 bip->bio_caller2 = tp;
2357 vn_start_secondary_write(NULL, &mp, 0);
2358 g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2363 * Verify allocation of a block or fragment. Returns true if block or
2364 * fragment is allocated, false if it is free.
2367 ffs_checkblk(ip, bno, size)
2376 int i, error, frags, free;
2380 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2381 printf("bsize = %ld, size = %ld, fs = %s\n",
2382 (long)fs->fs_bsize, size, fs->fs_fsmnt);
2383 panic("ffs_checkblk: bad size");
2385 if ((u_int)bno >= fs->fs_size)
2386 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2387 error = ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), &bp, &cgp);
2389 panic("ffs_checkblk: cylinder group read failed");
2390 blksfree = cg_blksfree(cgp);
2391 cgbno = dtogd(fs, bno);
2392 if (size == fs->fs_bsize) {
2393 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2395 frags = numfrags(fs, size);
2396 for (free = 0, i = 0; i < frags; i++)
2397 if (isset(blksfree, cgbno + i))
2399 if (free != 0 && free != frags)
2400 panic("ffs_checkblk: partially free fragment");
2405 #endif /* INVARIANTS */
2411 ffs_vfree(pvp, ino, mode)
2416 struct ufsmount *ump;
2418 if (DOINGSOFTDEP(pvp)) {
2419 softdep_freefile(pvp, ino, mode);
2422 ump = VFSTOUFS(pvp->v_mount);
2423 return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2427 * Do the actual free operation.
2428 * The specified inode is placed back in the free map.
2431 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2432 struct ufsmount *ump;
2434 struct vnode *devvp;
2437 struct workhead *wkhd;
2447 cg = ino_to_cg(fs, ino);
2448 if (devvp->v_type == VREG) {
2449 /* devvp is a snapshot */
2450 MPASS(devvp->v_mount->mnt_data == ump);
2451 dev = ump->um_devvp->v_rdev;
2452 cgbno = fragstoblks(fs, cgtod(fs, cg));
2453 } else if (devvp->v_type == VCHR) {
2454 /* devvp is a normal disk device */
2455 dev = devvp->v_rdev;
2456 cgbno = fsbtodb(fs, cgtod(fs, cg));
2461 if (ino >= fs->fs_ipg * fs->fs_ncg)
2462 panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2463 devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2464 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2466 inosused = cg_inosused(cgp);
2468 if (isclr(inosused, ino)) {
2469 printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2470 (uintmax_t)(ino + cg * fs->fs_ipg), fs->fs_fsmnt);
2471 if (fs->fs_ronly == 0)
2472 panic("ffs_freefile: freeing free inode");
2474 clrbit(inosused, ino);
2475 if (ino < cgp->cg_irotor)
2476 cgp->cg_irotor = ino;
2477 cgp->cg_cs.cs_nifree++;
2479 fs->fs_cstotal.cs_nifree++;
2480 fs->fs_cs(fs, cg).cs_nifree++;
2481 if ((mode & IFMT) == IFDIR) {
2482 cgp->cg_cs.cs_ndir--;
2483 fs->fs_cstotal.cs_ndir--;
2484 fs->fs_cs(fs, cg).cs_ndir--;
2487 ACTIVECLEAR(fs, cg);
2489 if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2490 softdep_setup_inofree(UFSTOVFS(ump), bp,
2491 ino + cg * fs->fs_ipg, wkhd);
2497 * Check to see if a file is free.
2498 * Used to check for allocated files in snapshots.
2501 ffs_checkfreefile(fs, devvp, ino)
2503 struct vnode *devvp;
2513 cg = ino_to_cg(fs, ino);
2514 if (devvp->v_type == VREG) {
2515 /* devvp is a snapshot */
2516 cgbno = fragstoblks(fs, cgtod(fs, cg));
2517 } else if (devvp->v_type == VCHR) {
2518 /* devvp is a normal disk device */
2519 cgbno = fsbtodb(fs, cgtod(fs, cg));
2523 if (ino >= fs->fs_ipg * fs->fs_ncg)
2525 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2527 inosused = cg_inosused(cgp);
2529 ret = isclr(inosused, ino);
2535 * Find a block of the specified size in the specified cylinder group.
2537 * It is a panic if a request is made to find a block if none are
2541 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2548 int start, len, loc, i;
2549 int blk, field, subfield, pos;
2553 * find the fragment by searching through the free block
2554 * map for an appropriate bit pattern
2557 start = dtogd(fs, bpref) / NBBY;
2559 start = cgp->cg_frotor / NBBY;
2560 blksfree = cg_blksfree(cgp);
2561 len = howmany(fs->fs_fpg, NBBY) - start;
2562 loc = scanc((u_int)len, (u_char *)&blksfree[start],
2563 fragtbl[fs->fs_frag],
2564 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2568 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2569 fragtbl[fs->fs_frag],
2570 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2572 printf("start = %d, len = %d, fs = %s\n",
2573 start, len, fs->fs_fsmnt);
2574 panic("ffs_alloccg: map corrupted");
2578 bno = (start + len - loc) * NBBY;
2579 cgp->cg_frotor = bno;
2581 * found the byte in the map
2582 * sift through the bits to find the selected frag
2584 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2585 blk = blkmap(fs, blksfree, bno);
2587 field = around[allocsiz];
2588 subfield = inside[allocsiz];
2589 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2590 if ((blk & field) == subfield)
2596 printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2597 panic("ffs_alloccg: block not in map");
2601 static const struct statfs *
2602 ffs_getmntstat(struct vnode *devvp)
2605 if (devvp->v_type == VCHR)
2606 return (&devvp->v_rdev->si_mountpt->mnt_stat);
2607 return (ffs_getmntstat(VFSTOUFS(devvp->v_mount)->um_devvp));
2611 * Fetch and verify a cylinder group.
2614 ffs_getcg(fs, devvp, cg, bpp, cgpp)
2616 struct vnode *devvp;
2623 const struct statfs *sfs;
2629 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
2631 error = breadn_flags(devvp, devvp->v_type == VREG ?
2632 fragstoblks(fs, cgtod(fs, cg)) : fsbtodb(fs, cgtod(fs, cg)),
2633 (int)fs->fs_cgsize, NULL, NULL, 0, NOCRED, flags,
2634 ffs_ckhash_cg, &bp);
2637 cgp = (struct cg *)bp->b_data;
2638 if ((fs->fs_metackhash & CK_CYLGRP) != 0 &&
2639 (bp->b_flags & B_CKHASH) != 0 &&
2640 cgp->cg_ckhash != bp->b_ckhash) {
2641 sfs = ffs_getmntstat(devvp);
2642 printf("UFS %s%s (%s) cylinder checksum failed: cg %u, cgp: "
2643 "0x%x != bp: 0x%jx\n",
2644 devvp->v_type == VCHR ? "" : "snapshot of ",
2645 sfs->f_mntfromname, sfs->f_mntonname,
2646 cg, cgp->cg_ckhash, (uintmax_t)bp->b_ckhash);
2647 bp->b_flags &= ~B_CKHASH;
2648 bp->b_flags |= B_INVAL | B_NOCACHE;
2652 if (!cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
2653 sfs = ffs_getmntstat(devvp);
2654 printf("UFS %s%s (%s)",
2655 devvp->v_type == VCHR ? "" : "snapshot of ",
2656 sfs->f_mntfromname, sfs->f_mntonname);
2657 if (!cg_chkmagic(cgp))
2658 printf(" cg %u: bad magic number 0x%x should be 0x%x\n",
2659 cg, cgp->cg_magic, CG_MAGIC);
2661 printf(": wrong cylinder group cg %u != cgx %u\n", cg,
2663 bp->b_flags &= ~B_CKHASH;
2664 bp->b_flags |= B_INVAL | B_NOCACHE;
2668 bp->b_flags &= ~B_CKHASH;
2669 bp->b_xflags |= BX_BKGRDWRITE;
2671 * If we are using check hashes on the cylinder group then we want
2672 * to limit changing the cylinder group time to when we are actually
2673 * going to write it to disk so that its check hash remains correct
2674 * in memory. If the CK_CYLGRP flag is set the time is updated in
2675 * ffs_bufwrite() as the buffer is queued for writing. Otherwise we
2676 * update the time here as we have done historically.
2678 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
2679 bp->b_xflags |= BX_CYLGRP;
2681 cgp->cg_old_time = cgp->cg_time = time_second;
2694 cgp = (struct cg *)bp->b_data;
2695 ckhash = cgp->cg_ckhash;
2697 bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
2698 cgp->cg_ckhash = ckhash;
2702 * Fserr prints the name of a filesystem with an error diagnostic.
2704 * The form of the error message is:
2708 ffs_fserr(fs, inum, cp)
2713 struct thread *td = curthread; /* XXX */
2714 struct proc *p = td->td_proc;
2716 log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
2717 p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
2722 * This function provides the capability for the fsck program to
2723 * update an active filesystem. Fourteen operations are provided:
2725 * adjrefcnt(inode, amt) - adjusts the reference count on the
2726 * specified inode by the specified amount. Under normal
2727 * operation the count should always go down. Decrementing
2728 * the count to zero will cause the inode to be freed.
2729 * adjblkcnt(inode, amt) - adjust the number of blocks used by the
2730 * inode by the specified amount.
2731 * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2732 * adjust the superblock summary.
2733 * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2734 * are marked as free. Inodes should never have to be marked
2736 * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2737 * are marked as free. Inodes should never have to be marked
2739 * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2740 * are marked as free. Blocks should never have to be marked
2742 * setflags(flags, set/clear) - the fs_flags field has the specified
2743 * flags set (second parameter +1) or cleared (second parameter -1).
2744 * setcwd(dirinode) - set the current directory to dirinode in the
2745 * filesystem associated with the snapshot.
2746 * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
2747 * in the current directory is oldvalue then change it to newvalue.
2748 * unlink(nameptr, oldvalue) - Verify that the inode number associated
2749 * with nameptr in the current directory is oldvalue then unlink it.
2751 * The following functions may only be used on a quiescent filesystem
2752 * by the soft updates journal. They are not safe to be run on an active
2755 * setinode(inode, dip) - the specified disk inode is replaced with the
2756 * contents pointed to by dip.
2757 * setbufoutput(fd, flags) - output associated with the specified file
2758 * descriptor (which must reference the character device supporting
2759 * the filesystem) switches from using physio to running through the
2760 * buffer cache when flags is set to 1. The descriptor reverts to
2761 * physio for output when flags is set to zero.
2764 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2766 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2767 0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2769 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2770 sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2772 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2773 sysctl_ffs_fsck, "Adjust number of directories");
2775 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2776 sysctl_ffs_fsck, "Adjust number of free blocks");
2778 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2779 sysctl_ffs_fsck, "Adjust number of free inodes");
2781 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2782 sysctl_ffs_fsck, "Adjust number of free frags");
2784 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2785 sysctl_ffs_fsck, "Adjust number of free clusters");
2787 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2788 sysctl_ffs_fsck, "Free Range of Directory Inodes");
2790 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2791 sysctl_ffs_fsck, "Free Range of File Inodes");
2793 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2794 sysctl_ffs_fsck, "Free Range of Blocks");
2796 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2797 sysctl_ffs_fsck, "Change Filesystem Flags");
2799 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd, CTLFLAG_WR,
2800 sysctl_ffs_fsck, "Set Current Working Directory");
2802 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot, CTLFLAG_WR,
2803 sysctl_ffs_fsck, "Change Value of .. Entry");
2805 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink, CTLFLAG_WR,
2806 sysctl_ffs_fsck, "Unlink a Duplicate Name");
2808 static SYSCTL_NODE(_vfs_ffs, FFS_SET_INODE, setinode, CTLFLAG_WR,
2809 sysctl_ffs_fsck, "Update an On-Disk Inode");
2811 static SYSCTL_NODE(_vfs_ffs, FFS_SET_BUFOUTPUT, setbufoutput, CTLFLAG_WR,
2812 sysctl_ffs_fsck, "Set Buffered Writing for Descriptor");
2816 static int fsckcmds = 0;
2817 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2820 static int buffered_write(struct file *, struct uio *, struct ucred *,
2821 int, struct thread *);
2824 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2826 struct thread *td = curthread;
2827 struct fsck_cmd cmd;
2828 struct ufsmount *ump;
2829 struct vnode *vp, *dvp, *fdvp;
2830 struct inode *ip, *dp;
2834 long blkcnt, blksize;
2835 struct file *fp, *vfp;
2836 cap_rights_t rights;
2837 int filetype, error;
2838 static struct fileops *origops, bufferedops;
2840 if (req->newlen > sizeof cmd)
2842 if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2844 if (cmd.version != FFS_CMD_VERSION)
2845 return (ERPCMISMATCH);
2846 if ((error = getvnode(td, cmd.handle,
2847 cap_rights_init(&rights, CAP_FSCK), &fp)) != 0)
2850 if (vp->v_type != VREG && vp->v_type != VDIR) {
2854 vn_start_write(vp, &mp, V_WAIT);
2856 strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2857 vn_finished_write(mp);
2862 if ((mp->mnt_flag & MNT_RDONLY) &&
2863 ump->um_fsckpid != td->td_proc->p_pid) {
2864 vn_finished_write(mp);
2871 switch (oidp->oid_number) {
2876 printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2877 cmd.size > 0 ? "set" : "clear");
2880 fs->fs_flags |= (long)cmd.value;
2882 fs->fs_flags &= ~(long)cmd.value;
2885 case FFS_ADJ_REFCNT:
2888 printf("%s: adjust inode %jd link count by %jd\n",
2889 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2890 (intmax_t)cmd.size);
2893 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2896 ip->i_nlink += cmd.size;
2897 DIP_SET(ip, i_nlink, ip->i_nlink);
2898 ip->i_effnlink += cmd.size;
2899 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2900 error = ffs_update(vp, 1);
2901 if (DOINGSOFTDEP(vp))
2902 softdep_change_linkcnt(ip);
2906 case FFS_ADJ_BLKCNT:
2909 printf("%s: adjust inode %jd block count by %jd\n",
2910 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2911 (intmax_t)cmd.size);
2914 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2917 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2918 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2919 error = ffs_update(vp, 1);
2931 printf("%s: free %s inode %ju\n",
2932 mp->mnt_stat.f_mntonname,
2933 filetype == IFDIR ? "directory" : "file",
2934 (uintmax_t)cmd.value);
2936 printf("%s: free %s inodes %ju-%ju\n",
2937 mp->mnt_stat.f_mntonname,
2938 filetype == IFDIR ? "directory" : "file",
2939 (uintmax_t)cmd.value,
2940 (uintmax_t)(cmd.value + cmd.size - 1));
2943 while (cmd.size > 0) {
2944 if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2945 cmd.value, filetype, NULL)))
2956 printf("%s: free block %jd\n",
2957 mp->mnt_stat.f_mntonname,
2958 (intmax_t)cmd.value);
2960 printf("%s: free blocks %jd-%jd\n",
2961 mp->mnt_stat.f_mntonname,
2962 (intmax_t)cmd.value,
2963 (intmax_t)cmd.value + cmd.size - 1);
2968 blksize = fs->fs_frag - (blkno % fs->fs_frag);
2969 while (blkcnt > 0) {
2970 if (blksize > blkcnt)
2972 ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2973 blksize * fs->fs_fsize, UFS_ROOTINO, VDIR, NULL);
2976 blksize = fs->fs_frag;
2981 * Adjust superblock summaries. fsck(8) is expected to
2982 * submit deltas when necessary.
2987 printf("%s: adjust number of directories by %jd\n",
2988 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2991 fs->fs_cstotal.cs_ndir += cmd.value;
2994 case FFS_ADJ_NBFREE:
2997 printf("%s: adjust number of free blocks by %+jd\n",
2998 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3001 fs->fs_cstotal.cs_nbfree += cmd.value;
3004 case FFS_ADJ_NIFREE:
3007 printf("%s: adjust number of free inodes by %+jd\n",
3008 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3011 fs->fs_cstotal.cs_nifree += cmd.value;
3014 case FFS_ADJ_NFFREE:
3017 printf("%s: adjust number of free frags by %+jd\n",
3018 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3021 fs->fs_cstotal.cs_nffree += cmd.value;
3024 case FFS_ADJ_NUMCLUSTERS:
3027 printf("%s: adjust number of free clusters by %+jd\n",
3028 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3031 fs->fs_cstotal.cs_numclusters += cmd.value;
3037 printf("%s: set current directory to inode %jd\n",
3038 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3041 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
3043 AUDIT_ARG_VNODE1(vp);
3044 if ((error = change_dir(vp, td)) != 0) {
3052 case FFS_SET_DOTDOT:
3055 printf("%s: change .. in cwd from %jd to %jd\n",
3056 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3057 (intmax_t)cmd.size);
3061 * First we have to get and lock the parent directory
3062 * to which ".." points.
3064 error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3068 * Now we get and lock the child directory containing "..".
3070 FILEDESC_SLOCK(td->td_proc->p_fd);
3071 dvp = td->td_proc->p_fd->fd_cdir;
3072 FILEDESC_SUNLOCK(td->td_proc->p_fd);
3073 if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
3078 dp->i_offset = 12; /* XXX mastertemplate.dot_reclen */
3079 error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3092 if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3093 strncpy(buf, "Name_too_long", 32);
3094 printf("%s: unlink %s (inode %jd)\n",
3095 mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3099 * kern_unlinkat will do its own start/finish writes and
3100 * they do not nest, so drop ours here. Setting mp == NULL
3101 * indicates that vn_finished_write is not needed down below.
3103 vn_finished_write(mp);
3105 error = kern_unlinkat(td, AT_FDCWD, (char *)(intptr_t)cmd.value,
3106 UIO_USERSPACE, (ino_t)cmd.size);
3110 if (ump->um_fsckpid != td->td_proc->p_pid) {
3116 printf("%s: update inode %jd\n",
3117 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3120 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3122 AUDIT_ARG_VNODE1(vp);
3125 error = copyin((void *)(intptr_t)cmd.size, ip->i_din1,
3126 sizeof(struct ufs1_dinode));
3128 error = copyin((void *)(intptr_t)cmd.size, ip->i_din2,
3129 sizeof(struct ufs2_dinode));
3134 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
3135 error = ffs_update(vp, 1);
3139 case FFS_SET_BUFOUTPUT:
3140 if (ump->um_fsckpid != td->td_proc->p_pid) {
3144 if (ITOUMP(VTOI(vp)) != ump) {
3150 printf("%s: %s buffered output for descriptor %jd\n",
3151 mp->mnt_stat.f_mntonname,
3152 cmd.size == 1 ? "enable" : "disable",
3153 (intmax_t)cmd.value);
3156 if ((error = getvnode(td, cmd.value,
3157 cap_rights_init(&rights, CAP_FSCK), &vfp)) != 0)
3159 if (vfp->f_vnode->v_type != VCHR) {
3164 if (origops == NULL) {
3165 origops = vfp->f_ops;
3166 bcopy((void *)origops, (void *)&bufferedops,
3167 sizeof(bufferedops));
3168 bufferedops.fo_write = buffered_write;
3171 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3172 (uintptr_t)&bufferedops);
3174 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3175 (uintptr_t)origops);
3182 printf("Invalid request %d from fsck\n",
3191 vn_finished_write(mp);
3196 * Function to switch a descriptor to use the buffer cache to stage
3197 * its I/O. This is needed so that writes to the filesystem device
3198 * will give snapshots a chance to copy modified blocks for which it
3199 * needs to retain copies.
3202 buffered_write(fp, uio, active_cred, flags, td)
3205 struct ucred *active_cred;
3209 struct vnode *devvp, *vp;
3213 struct filedesc *fdp;
3218 * The devvp is associated with the /dev filesystem. To discover
3219 * the filesystem with which the device is associated, we depend
3220 * on the application setting the current directory to a location
3221 * within the filesystem being written. Yes, this is an ugly hack.
3223 devvp = fp->f_vnode;
3224 if (!vn_isdisk(devvp, NULL))
3226 fdp = td->td_proc->p_fd;
3227 FILEDESC_SLOCK(fdp);
3230 FILEDESC_SUNLOCK(fdp);
3231 vn_lock(vp, LK_SHARED | LK_RETRY);
3233 * Check that the current directory vnode indeed belongs to
3234 * UFS before trying to dereference UFS-specific v_data fields.
3236 if (vp->v_op != &ffs_vnodeops1 && vp->v_op != &ffs_vnodeops2) {
3241 if (ITODEVVP(ip) != devvp) {
3247 foffset_lock_uio(fp, uio, flags);
3248 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
3251 printf("%s: buffered write for block %jd\n",
3252 fs->fs_fsmnt, (intmax_t)btodb(uio->uio_offset));
3256 * All I/O must be contained within a filesystem block, start on
3257 * a fragment boundary, and be a multiple of fragments in length.
3259 if (uio->uio_resid > fs->fs_bsize - (uio->uio_offset % fs->fs_bsize) ||
3260 fragoff(fs, uio->uio_offset) != 0 ||
3261 fragoff(fs, uio->uio_resid) != 0) {
3265 lbn = numfrags(fs, uio->uio_offset);
3266 bp = getblk(devvp, lbn, uio->uio_resid, 0, 0, 0);
3267 bp->b_flags |= B_RELBUF;
3268 if ((error = uiomove((char *)bp->b_data, uio->uio_resid, uio)) != 0) {
3274 VOP_UNLOCK(devvp, 0);
3275 foffset_unlock_uio(fp, uio, flags | FOF_NEXTOFF);