2 * Copyright (c) 2002 Networks Associates Technology, Inc.
5 * This software was developed for the FreeBSD Project by Marshall
6 * Kirk McKusick and Network Associates Laboratories, the Security
7 * Research Division of Network Associates, Inc. under DARPA/SPAWAR
8 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * Copyright (c) 1982, 1986, 1989, 1993
33 * The Regents of the University of California. All rights reserved.
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 * 4. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * @(#)ffs_alloc.c 8.18 (Berkeley) 5/26/95
62 #include <sys/cdefs.h>
63 __FBSDID("$FreeBSD$");
65 #include "opt_quota.h"
67 #include <sys/param.h>
68 #include <sys/capability.h>
69 #include <sys/systm.h>
73 #include <sys/fcntl.h>
75 #include <sys/filedesc.h>
78 #include <sys/vnode.h>
79 #include <sys/mount.h>
80 #include <sys/kernel.h>
81 #include <sys/syscallsubr.h>
82 #include <sys/sysctl.h>
83 #include <sys/syslog.h>
84 #include <sys/taskqueue.h>
86 #include <security/audit/audit.h>
88 #include <geom/geom.h>
90 #include <ufs/ufs/dir.h>
91 #include <ufs/ufs/extattr.h>
92 #include <ufs/ufs/quota.h>
93 #include <ufs/ufs/inode.h>
94 #include <ufs/ufs/ufs_extern.h>
95 #include <ufs/ufs/ufsmount.h>
97 #include <ufs/ffs/fs.h>
98 #include <ufs/ffs/ffs_extern.h>
99 #include <ufs/ffs/softdep.h>
101 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
102 int size, int rsize);
104 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int, int);
106 ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
107 static void ffs_blkfree_cg(struct ufsmount *, struct fs *,
108 struct vnode *, ufs2_daddr_t, long, ino_t,
110 static void ffs_blkfree_trim_completed(struct bio *);
111 static void ffs_blkfree_trim_task(void *ctx, int pending __unused);
113 static int ffs_checkblk(struct inode *, ufs2_daddr_t, long);
115 static ufs2_daddr_t ffs_clusteralloc(struct inode *, u_int, ufs2_daddr_t, int,
117 static ino_t ffs_dirpref(struct inode *);
118 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
120 static ufs2_daddr_t ffs_hashalloc
121 (struct inode *, u_int, ufs2_daddr_t, int, int, allocfcn_t *);
122 static ufs2_daddr_t ffs_nodealloccg(struct inode *, u_int, ufs2_daddr_t, int,
124 static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
125 static int ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
126 static int ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
129 * Allocate a block in the filesystem.
131 * The size of the requested block is given, which must be some
132 * multiple of fs_fsize and <= fs_bsize.
133 * A preference may be optionally specified. If a preference is given
134 * the following hierarchy is used to allocate a block:
135 * 1) allocate the requested block.
136 * 2) allocate a rotationally optimal block in the same cylinder.
137 * 3) allocate a block in the same cylinder group.
138 * 4) quadradically rehash into other cylinder groups, until an
139 * available block is located.
140 * If no block preference is given the following hierarchy is used
141 * to allocate a block:
142 * 1) allocate a block in the cylinder group that contains the
143 * inode for the file.
144 * 2) quadradically rehash into other cylinder groups, until an
145 * available block is located.
148 ffs_alloc(ip, lbn, bpref, size, flags, cred, bnp)
150 ufs2_daddr_t lbn, bpref;
156 struct ufsmount *ump;
159 static struct timeval lastfail;
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(ip->i_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, 0) &&
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 ip->i_flag |= IN_CHANGE;
207 ip->i_flag |= 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 if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
227 ffs_fserr(fs, ip->i_number, "filesystem full");
228 uprintf("\n%s: write failed, filesystem is full\n",
235 * Reallocate a fragment to a bigger size
237 * The number and size of the old block is given, and a preference
238 * and new size is also specified. The allocator attempts to extend
239 * the original block. Failing that, the regular block allocator is
240 * invoked to get an appropriate block.
243 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
248 int osize, nsize, flags;
255 struct ufsmount *ump;
256 u_int cg, request, reclaimed;
259 static struct timeval lastfail;
268 mtx_assert(UFS_MTX(ump), MA_OWNED);
270 if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
271 panic("ffs_realloccg: allocation on suspended filesystem");
272 if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
273 (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
275 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
276 devtoname(ip->i_dev), (long)fs->fs_bsize, osize,
277 nsize, fs->fs_fsmnt);
278 panic("ffs_realloccg: bad size");
281 panic("ffs_realloccg: missing credential");
282 #endif /* INVARIANTS */
285 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
286 freespace(fs, fs->fs_minfree) - numfrags(fs, nsize - osize) < 0) {
290 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
291 devtoname(ip->i_dev), (long)fs->fs_bsize, (intmax_t)bprev,
293 panic("ffs_realloccg: bad bprev");
297 * Allocate the extra space in the buffer.
299 error = bread(vp, lbprev, osize, NOCRED, &bp);
305 if (bp->b_blkno == bp->b_lblkno) {
306 if (lbprev >= NDADDR)
307 panic("ffs_realloccg: lbprev out of range");
308 bp->b_blkno = fsbtodb(fs, bprev);
312 error = chkdq(ip, btodb(nsize - osize), cred, 0);
319 * Check for extension in the existing location.
321 cg = dtog(fs, bprev);
323 bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
325 if (bp->b_blkno != fsbtodb(fs, bno))
326 panic("ffs_realloccg: bad blockno");
327 delta = btodb(nsize - osize);
328 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
330 ip->i_flag |= IN_CHANGE;
332 ip->i_flag |= IN_CHANGE | IN_UPDATE;
334 bp->b_flags |= B_DONE;
335 bzero(bp->b_data + osize, nsize - osize);
336 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
337 vfs_bio_set_valid(bp, osize, nsize - osize);
342 * Allocate a new disk location.
344 if (bpref >= fs->fs_size)
346 switch ((int)fs->fs_optim) {
349 * Allocate an exact sized fragment. Although this makes
350 * best use of space, we will waste time relocating it if
351 * the file continues to grow. If the fragmentation is
352 * less than half of the minimum free reserve, we choose
353 * to begin optimizing for time.
356 if (fs->fs_minfree <= 5 ||
357 fs->fs_cstotal.cs_nffree >
358 (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
360 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
362 fs->fs_optim = FS_OPTTIME;
366 * At this point we have discovered a file that is trying to
367 * grow a small fragment to a larger fragment. To save time,
368 * we allocate a full sized block, then free the unused portion.
369 * If the file continues to grow, the `ffs_fragextend' call
370 * above will be able to grow it in place without further
371 * copying. If aberrant programs cause disk fragmentation to
372 * grow within 2% of the free reserve, we choose to begin
373 * optimizing for space.
375 request = fs->fs_bsize;
376 if (fs->fs_cstotal.cs_nffree <
377 (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
379 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
381 fs->fs_optim = FS_OPTSPACE;
384 printf("dev = %s, optim = %ld, fs = %s\n",
385 devtoname(ip->i_dev), (long)fs->fs_optim, fs->fs_fsmnt);
386 panic("ffs_realloccg: bad optim");
389 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
391 bp->b_blkno = fsbtodb(fs, bno);
392 if (!DOINGSOFTDEP(vp))
393 ffs_blkfree(ump, fs, ip->i_devvp, bprev, (long)osize,
394 ip->i_number, vp->v_type, NULL);
395 delta = btodb(nsize - osize);
396 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
398 ip->i_flag |= IN_CHANGE;
400 ip->i_flag |= IN_CHANGE | IN_UPDATE;
402 bp->b_flags |= B_DONE;
403 bzero(bp->b_data + osize, nsize - osize);
404 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
405 vfs_bio_set_valid(bp, osize, nsize - osize);
412 * Restore user's disk quota because allocation failed.
414 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
421 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
429 softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
435 if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
436 ffs_fserr(fs, ip->i_number, "filesystem full");
437 uprintf("\n%s: write failed, filesystem is full\n",
444 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
446 * The vnode and an array of buffer pointers for a range of sequential
447 * logical blocks to be made contiguous is given. The allocator attempts
448 * to find a range of sequential blocks starting as close as possible
449 * from the end of the allocation for the logical block immediately
450 * preceding the current range. If successful, the physical block numbers
451 * in the buffer pointers and in the inode are changed to reflect the new
452 * allocation. If unsuccessful, the allocation is left unchanged. The
453 * success in doing the reallocation is returned. Note that the error
454 * return is not reflected back to the user. Rather the previous block
455 * allocation will be used.
458 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
460 static int doasyncfree = 1;
461 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0, "");
463 static int doreallocblks = 1;
464 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
467 static volatile int prtrealloc = 0;
472 struct vop_reallocblks_args /* {
474 struct cluster_save *a_buflist;
478 if (doreallocblks == 0)
481 * We can't wait in softdep prealloc as it may fsync and recurse
482 * here. Instead we simply fail to reallocate blocks if this
483 * rare condition arises.
485 if (DOINGSOFTDEP(ap->a_vp))
486 if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
488 if (VTOI(ap->a_vp)->i_ump->um_fstype == UFS1)
489 return (ffs_reallocblks_ufs1(ap));
490 return (ffs_reallocblks_ufs2(ap));
494 ffs_reallocblks_ufs1(ap)
495 struct vop_reallocblks_args /* {
497 struct cluster_save *a_buflist;
503 struct buf *sbp, *ebp;
504 ufs1_daddr_t *bap, *sbap, *ebap = 0;
505 struct cluster_save *buflist;
506 struct ufsmount *ump;
507 ufs_lbn_t start_lbn, end_lbn;
508 ufs1_daddr_t soff, newblk, blkno;
510 struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
511 int i, len, start_lvl, end_lvl, ssize;
517 if (fs->fs_contigsumsize <= 0)
519 buflist = ap->a_buflist;
520 len = buflist->bs_nchildren;
521 start_lbn = buflist->bs_children[0]->b_lblkno;
522 end_lbn = start_lbn + len - 1;
524 for (i = 0; i < len; i++)
525 if (!ffs_checkblk(ip,
526 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
527 panic("ffs_reallocblks: unallocated block 1");
528 for (i = 1; i < len; i++)
529 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
530 panic("ffs_reallocblks: non-logical cluster");
531 blkno = buflist->bs_children[0]->b_blkno;
532 ssize = fsbtodb(fs, fs->fs_frag);
533 for (i = 1; i < len - 1; i++)
534 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
535 panic("ffs_reallocblks: non-physical cluster %d", i);
538 * If the latest allocation is in a new cylinder group, assume that
539 * the filesystem has decided to move and do not force it back to
540 * the previous cylinder group.
542 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
543 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
545 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
546 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
549 * Get the starting offset and block map for the first block.
551 if (start_lvl == 0) {
552 sbap = &ip->i_din1->di_db[0];
555 idp = &start_ap[start_lvl - 1];
556 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
560 sbap = (ufs1_daddr_t *)sbp->b_data;
564 * If the block range spans two block maps, get the second map.
566 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
571 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
572 panic("ffs_reallocblk: start == end");
574 ssize = len - (idp->in_off + 1);
575 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
577 ebap = (ufs1_daddr_t *)ebp->b_data;
580 * Find the preferred location for the cluster.
583 pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
585 * Search the block map looking for an allocation of the desired size.
587 if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
588 len, len, ffs_clusteralloc)) == 0) {
593 * We have found a new contiguous block.
595 * First we have to replace the old block pointers with the new
596 * block pointers in the inode and indirect blocks associated
601 printf("realloc: ino %d, lbns %jd-%jd\n\told:", ip->i_number,
602 (intmax_t)start_lbn, (intmax_t)end_lbn);
605 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
611 if (!ffs_checkblk(ip,
612 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
613 panic("ffs_reallocblks: unallocated block 2");
614 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
615 panic("ffs_reallocblks: alloc mismatch");
619 printf(" %d,", *bap);
621 if (DOINGSOFTDEP(vp)) {
622 if (sbap == &ip->i_din1->di_db[0] && i < ssize)
623 softdep_setup_allocdirect(ip, start_lbn + i,
624 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
625 buflist->bs_children[i]);
627 softdep_setup_allocindir_page(ip, start_lbn + i,
628 i < ssize ? sbp : ebp, soff + i, blkno,
629 *bap, buflist->bs_children[i]);
634 * Next we must write out the modified inode and indirect blocks.
635 * For strict correctness, the writes should be synchronous since
636 * the old block values may have been written to disk. In practise
637 * they are almost never written, but if we are concerned about
638 * strict correctness, the `doasyncfree' flag should be set to zero.
640 * The test on `doasyncfree' should be changed to test a flag
641 * that shows whether the associated buffers and inodes have
642 * been written. The flag should be set when the cluster is
643 * started and cleared whenever the buffer or inode is flushed.
644 * We can then check below to see if it is set, and do the
645 * synchronous write only when it has been cleared.
647 if (sbap != &ip->i_din1->di_db[0]) {
653 ip->i_flag |= IN_CHANGE | IN_UPDATE;
664 * Last, free the old blocks and assign the new blocks to the buffers.
670 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
671 if (!DOINGSOFTDEP(vp))
672 ffs_blkfree(ump, fs, ip->i_devvp,
673 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
674 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
675 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
677 if (!ffs_checkblk(ip,
678 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
679 panic("ffs_reallocblks: unallocated block 3");
683 printf(" %d,", blkno);
697 if (sbap != &ip->i_din1->di_db[0])
703 ffs_reallocblks_ufs2(ap)
704 struct vop_reallocblks_args /* {
706 struct cluster_save *a_buflist;
712 struct buf *sbp, *ebp;
713 ufs2_daddr_t *bap, *sbap, *ebap = 0;
714 struct cluster_save *buflist;
715 struct ufsmount *ump;
716 ufs_lbn_t start_lbn, end_lbn;
717 ufs2_daddr_t soff, newblk, blkno, pref;
718 struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
719 int i, len, start_lvl, end_lvl, ssize;
725 if (fs->fs_contigsumsize <= 0)
727 buflist = ap->a_buflist;
728 len = buflist->bs_nchildren;
729 start_lbn = buflist->bs_children[0]->b_lblkno;
730 end_lbn = start_lbn + len - 1;
732 for (i = 0; i < len; i++)
733 if (!ffs_checkblk(ip,
734 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
735 panic("ffs_reallocblks: unallocated block 1");
736 for (i = 1; i < len; i++)
737 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
738 panic("ffs_reallocblks: non-logical cluster");
739 blkno = buflist->bs_children[0]->b_blkno;
740 ssize = fsbtodb(fs, fs->fs_frag);
741 for (i = 1; i < len - 1; i++)
742 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
743 panic("ffs_reallocblks: non-physical cluster %d", i);
746 * If the latest allocation is in a new cylinder group, assume that
747 * the filesystem has decided to move and do not force it back to
748 * the previous cylinder group.
750 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
751 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
753 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
754 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
757 * Get the starting offset and block map for the first block.
759 if (start_lvl == 0) {
760 sbap = &ip->i_din2->di_db[0];
763 idp = &start_ap[start_lvl - 1];
764 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
768 sbap = (ufs2_daddr_t *)sbp->b_data;
772 * If the block range spans two block maps, get the second map.
774 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
779 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
780 panic("ffs_reallocblk: start == end");
782 ssize = len - (idp->in_off + 1);
783 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
785 ebap = (ufs2_daddr_t *)ebp->b_data;
788 * Find the preferred location for the cluster.
791 pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
793 * Search the block map looking for an allocation of the desired size.
795 if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
796 len, len, ffs_clusteralloc)) == 0) {
801 * We have found a new contiguous block.
803 * First we have to replace the old block pointers with the new
804 * block pointers in the inode and indirect blocks associated
809 printf("realloc: ino %d, lbns %jd-%jd\n\told:", ip->i_number,
810 (intmax_t)start_lbn, (intmax_t)end_lbn);
813 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
819 if (!ffs_checkblk(ip,
820 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
821 panic("ffs_reallocblks: unallocated block 2");
822 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
823 panic("ffs_reallocblks: alloc mismatch");
827 printf(" %jd,", (intmax_t)*bap);
829 if (DOINGSOFTDEP(vp)) {
830 if (sbap == &ip->i_din2->di_db[0] && i < ssize)
831 softdep_setup_allocdirect(ip, start_lbn + i,
832 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
833 buflist->bs_children[i]);
835 softdep_setup_allocindir_page(ip, start_lbn + i,
836 i < ssize ? sbp : ebp, soff + i, blkno,
837 *bap, buflist->bs_children[i]);
842 * Next we must write out the modified inode and indirect blocks.
843 * For strict correctness, the writes should be synchronous since
844 * the old block values may have been written to disk. In practise
845 * they are almost never written, but if we are concerned about
846 * strict correctness, the `doasyncfree' flag should be set to zero.
848 * The test on `doasyncfree' should be changed to test a flag
849 * that shows whether the associated buffers and inodes have
850 * been written. The flag should be set when the cluster is
851 * started and cleared whenever the buffer or inode is flushed.
852 * We can then check below to see if it is set, and do the
853 * synchronous write only when it has been cleared.
855 if (sbap != &ip->i_din2->di_db[0]) {
861 ip->i_flag |= IN_CHANGE | IN_UPDATE;
872 * Last, free the old blocks and assign the new blocks to the buffers.
878 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
879 if (!DOINGSOFTDEP(vp))
880 ffs_blkfree(ump, fs, ip->i_devvp,
881 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
882 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
883 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
885 if (!ffs_checkblk(ip,
886 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
887 panic("ffs_reallocblks: unallocated block 3");
891 printf(" %jd,", (intmax_t)blkno);
905 if (sbap != &ip->i_din2->di_db[0])
911 * Allocate an inode in the filesystem.
913 * If allocating a directory, use ffs_dirpref to select the inode.
914 * If allocating in a directory, the following hierarchy is followed:
915 * 1) allocate the preferred inode.
916 * 2) allocate an inode in the same cylinder group.
917 * 3) quadradically rehash into other cylinder groups, until an
918 * available inode is located.
919 * If no inode preference is given the following hierarchy is used
920 * to allocate an inode:
921 * 1) allocate an inode in cylinder group 0.
922 * 2) quadradically rehash into other cylinder groups, until an
923 * available inode is located.
926 ffs_valloc(pvp, mode, cred, vpp)
936 struct ufsmount *ump;
939 int error, error1, reclaimed;
940 static struct timeval lastfail;
951 if (fs->fs_cstotal.cs_nifree == 0)
954 if ((mode & IFMT) == IFDIR)
955 ipref = ffs_dirpref(pip);
957 ipref = pip->i_number;
958 if (ipref >= fs->fs_ncg * fs->fs_ipg)
960 cg = ino_to_cg(fs, ipref);
962 * Track number of dirs created one after another
963 * in a same cg without intervening by files.
965 if ((mode & IFMT) == IFDIR) {
966 if (fs->fs_contigdirs[cg] < 255)
967 fs->fs_contigdirs[cg]++;
969 if (fs->fs_contigdirs[cg] > 0)
970 fs->fs_contigdirs[cg]--;
972 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
973 (allocfcn_t *)ffs_nodealloccg);
976 error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
978 error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
980 ffs_vfree(pvp, ino, mode);
985 ip->i_flag |= IN_MODIFIED;
993 printf("mode = 0%o, inum = %lu, fs = %s\n",
994 ip->i_mode, (u_long)ip->i_number, fs->fs_fsmnt);
995 panic("ffs_valloc: dup alloc");
997 if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) { /* XXX */
998 printf("free inode %s/%lu had %ld blocks\n",
999 fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1000 DIP_SET(ip, i_blocks, 0);
1003 DIP_SET(ip, i_flags, 0);
1005 * Set up a new generation number for this inode.
1007 if (ip->i_gen == 0 || ++ip->i_gen == 0)
1008 ip->i_gen = arc4random() / 2 + 1;
1009 DIP_SET(ip, i_gen, ip->i_gen);
1010 if (fs->fs_magic == FS_UFS2_MAGIC) {
1012 ip->i_din2->di_birthtime = ts.tv_sec;
1013 ip->i_din2->di_birthnsec = ts.tv_nsec;
1015 ufs_prepare_reclaim(*vpp);
1017 (*vpp)->v_vflag = 0;
1018 (*vpp)->v_type = VNON;
1019 if (fs->fs_magic == FS_UFS2_MAGIC)
1020 (*vpp)->v_op = &ffs_vnodeops2;
1022 (*vpp)->v_op = &ffs_vnodeops1;
1025 if (reclaimed == 0) {
1027 softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1031 if (ppsratecheck(&lastfail, &curfail, 1)) {
1032 ffs_fserr(fs, pip->i_number, "out of inodes");
1033 uprintf("\n%s: create/symlink failed, no inodes free\n",
1040 * Find a cylinder group to place a directory.
1042 * The policy implemented by this algorithm is to allocate a
1043 * directory inode in the same cylinder group as its parent
1044 * directory, but also to reserve space for its files inodes
1045 * and data. Restrict the number of directories which may be
1046 * allocated one after another in the same cylinder group
1047 * without intervening allocation of files.
1049 * If we allocate a first level directory then force allocation
1050 * in another cylinder group.
1057 u_int cg, prefcg, dirsize, cgsize;
1058 u_int avgifree, avgbfree, avgndir, curdirsize;
1059 u_int minifree, minbfree, maxndir;
1060 u_int mincg, minndir;
1061 u_int maxcontigdirs;
1063 mtx_assert(UFS_MTX(pip->i_ump), MA_OWNED);
1066 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1067 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1068 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1071 * Force allocation in another cg if creating a first level dir.
1073 ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1074 if (ITOV(pip)->v_vflag & VV_ROOT) {
1075 prefcg = arc4random() % fs->fs_ncg;
1077 minndir = fs->fs_ipg;
1078 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1079 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1080 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1081 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1083 minndir = fs->fs_cs(fs, cg).cs_ndir;
1085 for (cg = 0; cg < prefcg; cg++)
1086 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1087 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1088 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1090 minndir = fs->fs_cs(fs, cg).cs_ndir;
1092 return ((ino_t)(fs->fs_ipg * mincg));
1096 * Count various limits which used for
1097 * optimal allocation of a directory inode.
1099 maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1100 minifree = avgifree - avgifree / 4;
1103 minbfree = avgbfree - avgbfree / 4;
1106 cgsize = fs->fs_fsize * fs->fs_fpg;
1107 dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1108 curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1109 if (dirsize < curdirsize)
1110 dirsize = curdirsize;
1112 maxcontigdirs = 0; /* dirsize overflowed */
1114 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1115 if (fs->fs_avgfpdir > 0)
1116 maxcontigdirs = min(maxcontigdirs,
1117 fs->fs_ipg / fs->fs_avgfpdir);
1118 if (maxcontigdirs == 0)
1122 * Limit number of dirs in one cg and reserve space for
1123 * regular files, but only if we have no deficit in
1126 prefcg = ino_to_cg(fs, pip->i_number);
1127 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1128 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1129 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1130 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1131 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1132 return ((ino_t)(fs->fs_ipg * cg));
1134 for (cg = 0; cg < prefcg; cg++)
1135 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1136 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1137 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1138 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1139 return ((ino_t)(fs->fs_ipg * cg));
1142 * This is a backstop when we have deficit in space.
1144 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1145 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1146 return ((ino_t)(fs->fs_ipg * cg));
1147 for (cg = 0; cg < prefcg; cg++)
1148 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1150 return ((ino_t)(fs->fs_ipg * cg));
1154 * Select the desired position for the next block in a file. The file is
1155 * logically divided into sections. The first section is composed of the
1156 * direct blocks. Each additional section contains fs_maxbpg blocks.
1158 * If no blocks have been allocated in the first section, the policy is to
1159 * request a block in the same cylinder group as the inode that describes
1160 * the file. If no blocks have been allocated in any other section, the
1161 * policy is to place the section in a cylinder group with a greater than
1162 * average number of free blocks. An appropriate cylinder group is found
1163 * by using a rotor that sweeps the cylinder groups. When a new group of
1164 * blocks is needed, the sweep begins in the cylinder group following the
1165 * cylinder group from which the previous allocation was made. The sweep
1166 * continues until a cylinder group with greater than the average number
1167 * of free blocks is found. If the allocation is for the first block in an
1168 * indirect block, the information on the previous allocation is unavailable;
1169 * here a best guess is made based upon the logical block number being
1172 * If a section is already partially allocated, the policy is to
1173 * contiguously allocate fs_maxcontig blocks. The end of one of these
1174 * contiguous blocks and the beginning of the next is laid out
1175 * contiguously if possible.
1178 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1186 u_int avgbfree, startcg;
1188 mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1190 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1191 if (lbn < NDADDR + NINDIR(fs)) {
1192 cg = ino_to_cg(fs, ip->i_number);
1193 return (cgbase(fs, cg) + fs->fs_frag);
1196 * Find a cylinder with greater than average number of
1197 * unused data blocks.
1199 if (indx == 0 || bap[indx - 1] == 0)
1201 ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1203 startcg = dtog(fs, bap[indx - 1]) + 1;
1204 startcg %= fs->fs_ncg;
1205 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1206 for (cg = startcg; cg < fs->fs_ncg; cg++)
1207 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1208 fs->fs_cgrotor = cg;
1209 return (cgbase(fs, cg) + fs->fs_frag);
1211 for (cg = 0; cg <= startcg; cg++)
1212 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1213 fs->fs_cgrotor = cg;
1214 return (cgbase(fs, cg) + fs->fs_frag);
1219 * We just always try to lay things out contiguously.
1221 return (bap[indx - 1] + fs->fs_frag);
1225 * Same as above, but for UFS2
1228 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1236 u_int avgbfree, startcg;
1238 mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1240 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1241 if (lbn < NDADDR + NINDIR(fs)) {
1242 cg = ino_to_cg(fs, ip->i_number);
1243 return (cgbase(fs, cg) + fs->fs_frag);
1246 * Find a cylinder with greater than average number of
1247 * unused data blocks.
1249 if (indx == 0 || bap[indx - 1] == 0)
1251 ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1253 startcg = dtog(fs, bap[indx - 1]) + 1;
1254 startcg %= fs->fs_ncg;
1255 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1256 for (cg = startcg; cg < fs->fs_ncg; cg++)
1257 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1258 fs->fs_cgrotor = cg;
1259 return (cgbase(fs, cg) + fs->fs_frag);
1261 for (cg = 0; cg <= startcg; cg++)
1262 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1263 fs->fs_cgrotor = cg;
1264 return (cgbase(fs, cg) + fs->fs_frag);
1269 * We just always try to lay things out contiguously.
1271 return (bap[indx - 1] + fs->fs_frag);
1275 * Implement the cylinder overflow algorithm.
1277 * The policy implemented by this algorithm is:
1278 * 1) allocate the block in its requested cylinder group.
1279 * 2) quadradically rehash on the cylinder group number.
1280 * 3) brute force search for a free block.
1282 * Must be called with the UFS lock held. Will release the lock on success
1283 * and return with it held on failure.
1287 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1291 int size; /* Search size for data blocks, mode for inodes */
1292 int rsize; /* Real allocated size. */
1293 allocfcn_t *allocator;
1296 ufs2_daddr_t result;
1299 mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1301 if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1302 panic("ffs_hashalloc: allocation on suspended filesystem");
1306 * 1: preferred cylinder group
1308 result = (*allocator)(ip, cg, pref, size, rsize);
1312 * 2: quadratic rehash
1314 for (i = 1; i < fs->fs_ncg; i *= 2) {
1316 if (cg >= fs->fs_ncg)
1318 result = (*allocator)(ip, cg, 0, size, rsize);
1323 * 3: brute force search
1324 * Note that we start at i == 2, since 0 was checked initially,
1325 * and 1 is always checked in the quadratic rehash.
1327 cg = (icg + 2) % fs->fs_ncg;
1328 for (i = 2; i < fs->fs_ncg; i++) {
1329 result = (*allocator)(ip, cg, 0, size, rsize);
1333 if (cg == fs->fs_ncg)
1340 * Determine whether a fragment can be extended.
1342 * Check to see if the necessary fragments are available, and
1343 * if they are, allocate them.
1346 ffs_fragextend(ip, cg, bprev, osize, nsize)
1355 struct ufsmount *ump;
1364 if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1366 frags = numfrags(fs, nsize);
1367 bbase = fragnum(fs, bprev);
1368 if (bbase > fragnum(fs, (bprev + frags - 1))) {
1369 /* cannot extend across a block boundary */
1373 error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1374 (int)fs->fs_cgsize, NOCRED, &bp);
1377 cgp = (struct cg *)bp->b_data;
1378 if (!cg_chkmagic(cgp))
1380 bp->b_xflags |= BX_BKGRDWRITE;
1381 cgp->cg_old_time = cgp->cg_time = time_second;
1382 bno = dtogd(fs, bprev);
1383 blksfree = cg_blksfree(cgp);
1384 for (i = numfrags(fs, osize); i < frags; i++)
1385 if (isclr(blksfree, bno + i))
1388 * the current fragment can be extended
1389 * deduct the count on fragment being extended into
1390 * increase the count on the remaining fragment (if any)
1391 * allocate the extended piece
1393 for (i = frags; i < fs->fs_frag - bbase; i++)
1394 if (isclr(blksfree, bno + i))
1396 cgp->cg_frsum[i - numfrags(fs, osize)]--;
1398 cgp->cg_frsum[i - frags]++;
1399 for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1400 clrbit(blksfree, bno + i);
1401 cgp->cg_cs.cs_nffree--;
1405 fs->fs_cstotal.cs_nffree -= nffree;
1406 fs->fs_cs(fs, cg).cs_nffree -= nffree;
1408 ACTIVECLEAR(fs, cg);
1410 if (DOINGSOFTDEP(ITOV(ip)))
1411 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1412 frags, numfrags(fs, osize));
1424 * Determine whether a block can be allocated.
1426 * Check to see if a block of the appropriate size is available,
1427 * and if it is, allocate it.
1430 ffs_alloccg(ip, cg, bpref, size, rsize)
1440 struct ufsmount *ump;
1443 int i, allocsiz, error, frags;
1448 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1451 error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1452 (int)fs->fs_cgsize, NOCRED, &bp);
1455 cgp = (struct cg *)bp->b_data;
1456 if (!cg_chkmagic(cgp) ||
1457 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1459 bp->b_xflags |= BX_BKGRDWRITE;
1460 cgp->cg_old_time = cgp->cg_time = time_second;
1461 if (size == fs->fs_bsize) {
1463 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1464 ACTIVECLEAR(fs, cg);
1470 * check to see if any fragments are already available
1471 * allocsiz is the size which will be allocated, hacking
1472 * it down to a smaller size if necessary
1474 blksfree = cg_blksfree(cgp);
1475 frags = numfrags(fs, size);
1476 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1477 if (cgp->cg_frsum[allocsiz] != 0)
1479 if (allocsiz == fs->fs_frag) {
1481 * no fragments were available, so a block will be
1482 * allocated, and hacked up
1484 if (cgp->cg_cs.cs_nbfree == 0)
1487 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1488 ACTIVECLEAR(fs, cg);
1493 KASSERT(size == rsize,
1494 ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1495 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1498 for (i = 0; i < frags; i++)
1499 clrbit(blksfree, bno + i);
1500 cgp->cg_cs.cs_nffree -= frags;
1501 cgp->cg_frsum[allocsiz]--;
1502 if (frags != allocsiz)
1503 cgp->cg_frsum[allocsiz - frags]++;
1505 fs->fs_cstotal.cs_nffree -= frags;
1506 fs->fs_cs(fs, cg).cs_nffree -= frags;
1508 blkno = cgbase(fs, cg) + bno;
1509 ACTIVECLEAR(fs, cg);
1511 if (DOINGSOFTDEP(ITOV(ip)))
1512 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1523 * Allocate a block in a cylinder group.
1525 * This algorithm implements the following policy:
1526 * 1) allocate the requested block.
1527 * 2) allocate a rotationally optimal block in the same cylinder.
1528 * 3) allocate the next available block on the block rotor for the
1529 * specified cylinder group.
1530 * Note that this routine only allocates fs_bsize blocks; these
1531 * blocks may be fragmented by the routine that allocates them.
1534 ffs_alloccgblk(ip, bp, bpref, size)
1542 struct ufsmount *ump;
1550 mtx_assert(UFS_MTX(ump), MA_OWNED);
1551 cgp = (struct cg *)bp->b_data;
1552 blksfree = cg_blksfree(cgp);
1553 if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
1554 bpref = cgp->cg_rotor;
1556 bpref = blknum(fs, bpref);
1557 bno = dtogd(fs, bpref);
1559 * if the requested block is available, use it
1561 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1565 * Take the next available block in this cylinder group.
1567 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1570 cgp->cg_rotor = bno;
1572 blkno = fragstoblks(fs, bno);
1573 ffs_clrblock(fs, blksfree, (long)blkno);
1574 ffs_clusteracct(fs, cgp, blkno, -1);
1575 cgp->cg_cs.cs_nbfree--;
1576 fs->fs_cstotal.cs_nbfree--;
1577 fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1579 blkno = cgbase(fs, cgp->cg_cgx) + bno;
1581 * If the caller didn't want the whole block free the frags here.
1583 size = numfrags(fs, size);
1584 if (size != fs->fs_frag) {
1585 bno = dtogd(fs, blkno);
1586 for (i = size; i < fs->fs_frag; i++)
1587 setbit(blksfree, bno + i);
1588 i = fs->fs_frag - size;
1589 cgp->cg_cs.cs_nffree += i;
1590 fs->fs_cstotal.cs_nffree += i;
1591 fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1597 if (DOINGSOFTDEP(ITOV(ip)))
1598 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno,
1605 * Determine whether a cluster can be allocated.
1607 * We do not currently check for optimal rotational layout if there
1608 * are multiple choices in the same cylinder group. Instead we just
1609 * take the first one that we find following bpref.
1612 ffs_clusteralloc(ip, cg, bpref, len, unused)
1622 struct ufsmount *ump;
1623 int i, run, bit, map, got;
1631 if (fs->fs_maxcluster[cg] < len)
1634 if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1637 cgp = (struct cg *)bp->b_data;
1638 if (!cg_chkmagic(cgp))
1640 bp->b_xflags |= BX_BKGRDWRITE;
1642 * Check to see if a cluster of the needed size (or bigger) is
1643 * available in this cylinder group.
1645 lp = &cg_clustersum(cgp)[len];
1646 for (i = len; i <= fs->fs_contigsumsize; i++)
1649 if (i > fs->fs_contigsumsize) {
1651 * This is the first time looking for a cluster in this
1652 * cylinder group. Update the cluster summary information
1653 * to reflect the true maximum sized cluster so that
1654 * future cluster allocation requests can avoid reading
1655 * the cylinder group map only to find no clusters.
1657 lp = &cg_clustersum(cgp)[len - 1];
1658 for (i = len - 1; i > 0; i--)
1662 fs->fs_maxcluster[cg] = i;
1666 * Search the cluster map to find a big enough cluster.
1667 * We take the first one that we find, even if it is larger
1668 * than we need as we prefer to get one close to the previous
1669 * block allocation. We do not search before the current
1670 * preference point as we do not want to allocate a block
1671 * that is allocated before the previous one (as we will
1672 * then have to wait for another pass of the elevator
1673 * algorithm before it will be read). We prefer to fail and
1674 * be recalled to try an allocation in the next cylinder group.
1676 if (dtog(fs, bpref) != cg)
1679 bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1680 mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1682 bit = 1 << (bpref % NBBY);
1683 for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1684 if ((map & bit) == 0) {
1691 if ((got & (NBBY - 1)) != (NBBY - 1)) {
1698 if (got >= cgp->cg_nclusterblks)
1701 * Allocate the cluster that we have found.
1703 blksfree = cg_blksfree(cgp);
1704 for (i = 1; i <= len; i++)
1705 if (!ffs_isblock(fs, blksfree, got - run + i))
1706 panic("ffs_clusteralloc: map mismatch");
1707 bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1708 if (dtog(fs, bno) != cg)
1709 panic("ffs_clusteralloc: allocated out of group");
1710 len = blkstofrags(fs, len);
1712 for (i = 0; i < len; i += fs->fs_frag)
1713 if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
1714 panic("ffs_clusteralloc: lost block");
1715 ACTIVECLEAR(fs, cg);
1728 * Determine whether an inode can be allocated.
1730 * Check to see if an inode is available, and if it is,
1731 * allocate it using the following policy:
1732 * 1) allocate the requested inode.
1733 * 2) allocate the next available inode after the requested
1734 * inode in the specified cylinder group.
1737 ffs_nodealloccg(ip, cg, ipref, mode, unused)
1746 struct buf *bp, *ibp;
1747 struct ufsmount *ump;
1749 struct ufs2_dinode *dp2;
1750 int error, start, len, loc, map, i;
1754 if (fs->fs_cs(fs, cg).cs_nifree == 0)
1757 error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1758 (int)fs->fs_cgsize, NOCRED, &bp);
1764 cgp = (struct cg *)bp->b_data;
1765 if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1770 bp->b_xflags |= BX_BKGRDWRITE;
1771 cgp->cg_old_time = cgp->cg_time = time_second;
1772 inosused = cg_inosused(cgp);
1774 ipref %= fs->fs_ipg;
1775 if (isclr(inosused, ipref))
1778 start = cgp->cg_irotor / NBBY;
1779 len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1780 loc = skpc(0xff, len, &inosused[start]);
1784 loc = skpc(0xff, len, &inosused[0]);
1786 printf("cg = %d, irotor = %ld, fs = %s\n",
1787 cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
1788 panic("ffs_nodealloccg: map corrupted");
1792 i = start + len - loc;
1793 map = inosused[i] ^ 0xff;
1795 printf("fs = %s\n", fs->fs_fsmnt);
1796 panic("ffs_nodealloccg: block not in map");
1798 ipref = i * NBBY + ffs(map) - 1;
1799 cgp->cg_irotor = ipref;
1802 * Check to see if we need to initialize more inodes.
1805 if (fs->fs_magic == FS_UFS2_MAGIC &&
1806 ipref + INOPB(fs) > cgp->cg_initediblk &&
1807 cgp->cg_initediblk < cgp->cg_niblk) {
1808 ibp = getblk(ip->i_devvp, fsbtodb(fs,
1809 ino_to_fsba(fs, cg * fs->fs_ipg + cgp->cg_initediblk)),
1810 (int)fs->fs_bsize, 0, 0, 0);
1811 bzero(ibp->b_data, (int)fs->fs_bsize);
1812 dp2 = (struct ufs2_dinode *)(ibp->b_data);
1813 for (i = 0; i < INOPB(fs); i++) {
1814 dp2->di_gen = arc4random() / 2 + 1;
1817 cgp->cg_initediblk += INOPB(fs);
1820 ACTIVECLEAR(fs, cg);
1821 setbit(inosused, ipref);
1822 cgp->cg_cs.cs_nifree--;
1823 fs->fs_cstotal.cs_nifree--;
1824 fs->fs_cs(fs, cg).cs_nifree--;
1826 if ((mode & IFMT) == IFDIR) {
1827 cgp->cg_cs.cs_ndir++;
1828 fs->fs_cstotal.cs_ndir++;
1829 fs->fs_cs(fs, cg).cs_ndir++;
1832 if (DOINGSOFTDEP(ITOV(ip)))
1833 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
1837 return ((ino_t)(cg * fs->fs_ipg + ipref));
1841 * Free a block or fragment.
1843 * The specified block or fragment is placed back in the
1844 * free map. If a fragment is deallocated, a possible
1845 * block reassembly is checked.
1848 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
1849 struct ufsmount *ump;
1851 struct vnode *devvp;
1855 struct workhead *dephd;
1860 ufs1_daddr_t fragno, cgbno;
1861 ufs2_daddr_t cgblkno;
1862 int i, blk, frags, bbase;
1868 if (devvp->v_type == VREG) {
1869 /* devvp is a snapshot */
1870 dev = VTOI(devvp)->i_devvp->v_rdev;
1871 cgblkno = fragstoblks(fs, cgtod(fs, cg));
1873 /* devvp is a normal disk device */
1874 dev = devvp->v_rdev;
1875 cgblkno = fsbtodb(fs, cgtod(fs, cg));
1876 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
1879 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1880 fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1881 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
1882 devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
1883 size, fs->fs_fsmnt);
1884 panic("ffs_blkfree_cg: bad size");
1887 if ((u_int)bno >= fs->fs_size) {
1888 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
1890 ffs_fserr(fs, inum, "bad block");
1893 if (bread(devvp, cgblkno, (int)fs->fs_cgsize, NOCRED, &bp)) {
1897 cgp = (struct cg *)bp->b_data;
1898 if (!cg_chkmagic(cgp)) {
1902 bp->b_xflags |= BX_BKGRDWRITE;
1903 cgp->cg_old_time = cgp->cg_time = time_second;
1904 cgbno = dtogd(fs, bno);
1905 blksfree = cg_blksfree(cgp);
1907 if (size == fs->fs_bsize) {
1908 fragno = fragstoblks(fs, cgbno);
1909 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
1910 if (devvp->v_type == VREG) {
1912 /* devvp is a snapshot */
1916 printf("dev = %s, block = %jd, fs = %s\n",
1917 devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
1918 panic("ffs_blkfree_cg: freeing free block");
1920 ffs_setblock(fs, blksfree, fragno);
1921 ffs_clusteracct(fs, cgp, fragno, 1);
1922 cgp->cg_cs.cs_nbfree++;
1923 fs->fs_cstotal.cs_nbfree++;
1924 fs->fs_cs(fs, cg).cs_nbfree++;
1926 bbase = cgbno - fragnum(fs, cgbno);
1928 * decrement the counts associated with the old frags
1930 blk = blkmap(fs, blksfree, bbase);
1931 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1933 * deallocate the fragment
1935 frags = numfrags(fs, size);
1936 for (i = 0; i < frags; i++) {
1937 if (isset(blksfree, cgbno + i)) {
1938 printf("dev = %s, block = %jd, fs = %s\n",
1939 devtoname(dev), (intmax_t)(bno + i),
1941 panic("ffs_blkfree_cg: freeing free frag");
1943 setbit(blksfree, cgbno + i);
1945 cgp->cg_cs.cs_nffree += i;
1946 fs->fs_cstotal.cs_nffree += i;
1947 fs->fs_cs(fs, cg).cs_nffree += i;
1949 * add back in counts associated with the new frags
1951 blk = blkmap(fs, blksfree, bbase);
1952 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1954 * if a complete block has been reassembled, account for it
1956 fragno = fragstoblks(fs, bbase);
1957 if (ffs_isblock(fs, blksfree, fragno)) {
1958 cgp->cg_cs.cs_nffree -= fs->fs_frag;
1959 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1960 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1961 ffs_clusteracct(fs, cgp, fragno, 1);
1962 cgp->cg_cs.cs_nbfree++;
1963 fs->fs_cstotal.cs_nbfree++;
1964 fs->fs_cs(fs, cg).cs_nbfree++;
1968 ACTIVECLEAR(fs, cg);
1971 if (MOUNTEDSOFTDEP(mp) && devvp->v_type != VREG)
1972 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
1973 numfrags(fs, size), dephd);
1977 TASKQUEUE_DEFINE_THREAD(ffs_trim);
1979 struct ffs_blkfree_trim_params {
1981 struct ufsmount *ump;
1982 struct vnode *devvp;
1986 struct workhead *pdephd;
1987 struct workhead dephd;
1991 ffs_blkfree_trim_task(ctx, pending)
1995 struct ffs_blkfree_trim_params *tp;
1998 ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
1999 tp->inum, tp->pdephd);
2000 vn_finished_secondary_write(UFSTOVFS(tp->ump));
2005 ffs_blkfree_trim_completed(bip)
2008 struct ffs_blkfree_trim_params *tp;
2010 tp = bip->bio_caller2;
2012 TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2013 taskqueue_enqueue(taskqueue_ffs_trim, &tp->task);
2017 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd)
2018 struct ufsmount *ump;
2020 struct vnode *devvp;
2025 struct workhead *dephd;
2029 struct ffs_blkfree_trim_params *tp;
2032 * Check to see if a snapshot wants to claim the block.
2033 * Check that devvp is a normal disk device, not a snapshot,
2034 * it has a snapshot(s) associated with it, and one of the
2035 * snapshots wants to claim the block.
2037 if (devvp->v_type != VREG &&
2038 (devvp->v_vflag & VV_COPYONWRITE) &&
2039 ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2043 * Nothing to delay if TRIM is disabled, or the operation is
2044 * performed on the snapshot.
2046 if (!ump->um_candelete || devvp->v_type == VREG) {
2047 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2052 * Postpone the set of the free bit in the cg bitmap until the
2053 * BIO_DELETE is completed. Otherwise, due to disk queue
2054 * reordering, TRIM might be issued after we reuse the block
2055 * and write some new data into it.
2057 tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2063 if (dephd != NULL) {
2064 LIST_INIT(&tp->dephd);
2065 LIST_SWAP(dephd, &tp->dephd, worklist, wk_list);
2066 tp->pdephd = &tp->dephd;
2070 bip = g_alloc_bio();
2071 bip->bio_cmd = BIO_DELETE;
2072 bip->bio_offset = dbtob(fsbtodb(fs, bno));
2073 bip->bio_done = ffs_blkfree_trim_completed;
2074 bip->bio_length = size;
2075 bip->bio_caller2 = tp;
2078 vn_start_secondary_write(NULL, &mp, 0);
2079 g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2084 * Verify allocation of a block or fragment. Returns true if block or
2085 * fragment is allocated, false if it is free.
2088 ffs_checkblk(ip, bno, size)
2097 int i, error, frags, free;
2101 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2102 printf("bsize = %ld, size = %ld, fs = %s\n",
2103 (long)fs->fs_bsize, size, fs->fs_fsmnt);
2104 panic("ffs_checkblk: bad size");
2106 if ((u_int)bno >= fs->fs_size)
2107 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2108 error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
2109 (int)fs->fs_cgsize, NOCRED, &bp);
2111 panic("ffs_checkblk: cg bread failed");
2112 cgp = (struct cg *)bp->b_data;
2113 if (!cg_chkmagic(cgp))
2114 panic("ffs_checkblk: cg magic mismatch");
2115 bp->b_xflags |= BX_BKGRDWRITE;
2116 blksfree = cg_blksfree(cgp);
2117 cgbno = dtogd(fs, bno);
2118 if (size == fs->fs_bsize) {
2119 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2121 frags = numfrags(fs, size);
2122 for (free = 0, i = 0; i < frags; i++)
2123 if (isset(blksfree, cgbno + i))
2125 if (free != 0 && free != frags)
2126 panic("ffs_checkblk: partially free fragment");
2131 #endif /* INVARIANTS */
2137 ffs_vfree(pvp, ino, mode)
2144 if (DOINGSOFTDEP(pvp)) {
2145 softdep_freefile(pvp, ino, mode);
2149 return (ffs_freefile(ip->i_ump, ip->i_fs, ip->i_devvp, ino, mode,
2154 * Do the actual free operation.
2155 * The specified inode is placed back in the free map.
2158 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2159 struct ufsmount *ump;
2161 struct vnode *devvp;
2164 struct workhead *wkhd;
2174 cg = ino_to_cg(fs, ino);
2175 if (devvp->v_type == VREG) {
2176 /* devvp is a snapshot */
2177 dev = VTOI(devvp)->i_devvp->v_rdev;
2178 cgbno = fragstoblks(fs, cgtod(fs, cg));
2180 /* devvp is a normal disk device */
2181 dev = devvp->v_rdev;
2182 cgbno = fsbtodb(fs, cgtod(fs, cg));
2184 if (ino >= fs->fs_ipg * fs->fs_ncg)
2185 panic("ffs_freefile: range: dev = %s, ino = %lu, fs = %s",
2186 devtoname(dev), (u_long)ino, fs->fs_fsmnt);
2187 if ((error = bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp))) {
2191 cgp = (struct cg *)bp->b_data;
2192 if (!cg_chkmagic(cgp)) {
2196 bp->b_xflags |= BX_BKGRDWRITE;
2197 cgp->cg_old_time = cgp->cg_time = time_second;
2198 inosused = cg_inosused(cgp);
2200 if (isclr(inosused, ino)) {
2201 printf("dev = %s, ino = %u, fs = %s\n", devtoname(dev),
2202 ino + cg * fs->fs_ipg, fs->fs_fsmnt);
2203 if (fs->fs_ronly == 0)
2204 panic("ffs_freefile: freeing free inode");
2206 clrbit(inosused, ino);
2207 if (ino < cgp->cg_irotor)
2208 cgp->cg_irotor = ino;
2209 cgp->cg_cs.cs_nifree++;
2211 fs->fs_cstotal.cs_nifree++;
2212 fs->fs_cs(fs, cg).cs_nifree++;
2213 if ((mode & IFMT) == IFDIR) {
2214 cgp->cg_cs.cs_ndir--;
2215 fs->fs_cstotal.cs_ndir--;
2216 fs->fs_cs(fs, cg).cs_ndir--;
2219 ACTIVECLEAR(fs, cg);
2221 if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type != VREG)
2222 softdep_setup_inofree(UFSTOVFS(ump), bp,
2223 ino + cg * fs->fs_ipg, wkhd);
2229 * Check to see if a file is free.
2232 ffs_checkfreefile(fs, devvp, ino)
2234 struct vnode *devvp;
2244 cg = ino_to_cg(fs, ino);
2245 if (devvp->v_type == VREG) {
2246 /* devvp is a snapshot */
2247 cgbno = fragstoblks(fs, cgtod(fs, cg));
2249 /* devvp is a normal disk device */
2250 cgbno = fsbtodb(fs, cgtod(fs, cg));
2252 if (ino >= fs->fs_ipg * fs->fs_ncg)
2254 if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2258 cgp = (struct cg *)bp->b_data;
2259 if (!cg_chkmagic(cgp)) {
2263 inosused = cg_inosused(cgp);
2265 ret = isclr(inosused, ino);
2271 * Find a block of the specified size in the specified cylinder group.
2273 * It is a panic if a request is made to find a block if none are
2277 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2284 int start, len, loc, i;
2285 int blk, field, subfield, pos;
2289 * find the fragment by searching through the free block
2290 * map for an appropriate bit pattern
2293 start = dtogd(fs, bpref) / NBBY;
2295 start = cgp->cg_frotor / NBBY;
2296 blksfree = cg_blksfree(cgp);
2297 len = howmany(fs->fs_fpg, NBBY) - start;
2298 loc = scanc((u_int)len, (u_char *)&blksfree[start],
2299 fragtbl[fs->fs_frag],
2300 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2304 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2305 fragtbl[fs->fs_frag],
2306 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2308 printf("start = %d, len = %d, fs = %s\n",
2309 start, len, fs->fs_fsmnt);
2310 panic("ffs_alloccg: map corrupted");
2314 bno = (start + len - loc) * NBBY;
2315 cgp->cg_frotor = bno;
2317 * found the byte in the map
2318 * sift through the bits to find the selected frag
2320 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2321 blk = blkmap(fs, blksfree, bno);
2323 field = around[allocsiz];
2324 subfield = inside[allocsiz];
2325 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2326 if ((blk & field) == subfield)
2332 printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2333 panic("ffs_alloccg: block not in map");
2338 * Fserr prints the name of a filesystem with an error diagnostic.
2340 * The form of the error message is:
2344 ffs_fserr(fs, inum, cp)
2349 struct thread *td = curthread; /* XXX */
2350 struct proc *p = td->td_proc;
2352 log(LOG_ERR, "pid %d (%s), uid %d inumber %d on %s: %s\n",
2353 p->p_pid, p->p_comm, td->td_ucred->cr_uid, inum, fs->fs_fsmnt, cp);
2357 * This function provides the capability for the fsck program to
2358 * update an active filesystem. Fourteen operations are provided:
2360 * adjrefcnt(inode, amt) - adjusts the reference count on the
2361 * specified inode by the specified amount. Under normal
2362 * operation the count should always go down. Decrementing
2363 * the count to zero will cause the inode to be freed.
2364 * adjblkcnt(inode, amt) - adjust the number of blocks used by the
2365 * inode by the specified amount.
2366 * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2367 * adjust the superblock summary.
2368 * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2369 * are marked as free. Inodes should never have to be marked
2371 * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2372 * are marked as free. Inodes should never have to be marked
2374 * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2375 * are marked as free. Blocks should never have to be marked
2377 * setflags(flags, set/clear) - the fs_flags field has the specified
2378 * flags set (second parameter +1) or cleared (second parameter -1).
2379 * setcwd(dirinode) - set the current directory to dirinode in the
2380 * filesystem associated with the snapshot.
2381 * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
2382 * in the current directory is oldvalue then change it to newvalue.
2383 * unlink(nameptr, oldvalue) - Verify that the inode number associated
2384 * with nameptr in the current directory is oldvalue then unlink it.
2386 * The following functions may only be used on a quiescent filesystem
2387 * by the soft updates journal. They are not safe to be run on an active
2390 * setinode(inode, dip) - the specified disk inode is replaced with the
2391 * contents pointed to by dip.
2392 * setbufoutput(fd, flags) - output associated with the specified file
2393 * descriptor (which must reference the character device supporting
2394 * the filesystem) switches from using physio to running through the
2395 * buffer cache when flags is set to 1. The descriptor reverts to
2396 * physio for output when flags is set to zero.
2399 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2401 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2402 0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2404 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2405 sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2407 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2408 sysctl_ffs_fsck, "Adjust number of directories");
2410 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2411 sysctl_ffs_fsck, "Adjust number of free blocks");
2413 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2414 sysctl_ffs_fsck, "Adjust number of free inodes");
2416 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2417 sysctl_ffs_fsck, "Adjust number of free frags");
2419 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2420 sysctl_ffs_fsck, "Adjust number of free clusters");
2422 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2423 sysctl_ffs_fsck, "Free Range of Directory Inodes");
2425 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2426 sysctl_ffs_fsck, "Free Range of File Inodes");
2428 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2429 sysctl_ffs_fsck, "Free Range of Blocks");
2431 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2432 sysctl_ffs_fsck, "Change Filesystem Flags");
2434 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd, CTLFLAG_WR,
2435 sysctl_ffs_fsck, "Set Current Working Directory");
2437 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot, CTLFLAG_WR,
2438 sysctl_ffs_fsck, "Change Value of .. Entry");
2440 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink, CTLFLAG_WR,
2441 sysctl_ffs_fsck, "Unlink a Duplicate Name");
2443 static SYSCTL_NODE(_vfs_ffs, FFS_SET_INODE, setinode, CTLFLAG_WR,
2444 sysctl_ffs_fsck, "Update an On-Disk Inode");
2446 static SYSCTL_NODE(_vfs_ffs, FFS_SET_BUFOUTPUT, setbufoutput, CTLFLAG_WR,
2447 sysctl_ffs_fsck, "Set Buffered Writing for Descriptor");
2451 static int fsckcmds = 0;
2452 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2455 static int buffered_write(struct file *, struct uio *, struct ucred *,
2456 int, struct thread *);
2459 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2461 struct thread *td = curthread;
2462 struct fsck_cmd cmd;
2463 struct ufsmount *ump;
2464 struct vnode *vp, *vpold, *dvp, *fdvp;
2465 struct inode *ip, *dp;
2469 long blkcnt, blksize;
2470 struct filedesc *fdp;
2471 struct file *fp, *vfp;
2472 int vfslocked, filetype, error;
2473 static struct fileops *origops, bufferedops;
2475 if (req->newlen > sizeof cmd)
2477 if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2479 if (cmd.version != FFS_CMD_VERSION)
2480 return (ERPCMISMATCH);
2481 if ((error = getvnode(td->td_proc->p_fd, cmd.handle, CAP_FSCK,
2485 if (vp->v_type != VREG && vp->v_type != VDIR) {
2489 vn_start_write(vp, &mp, V_WAIT);
2490 if (mp == 0 || strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2491 vn_finished_write(mp);
2496 if ((mp->mnt_flag & MNT_RDONLY) &&
2497 ump->um_fsckpid != td->td_proc->p_pid) {
2498 vn_finished_write(mp);
2505 switch (oidp->oid_number) {
2510 printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2511 cmd.size > 0 ? "set" : "clear");
2514 fs->fs_flags |= (long)cmd.value;
2516 fs->fs_flags &= ~(long)cmd.value;
2519 case FFS_ADJ_REFCNT:
2522 printf("%s: adjust inode %jd link count by %jd\n",
2523 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2524 (intmax_t)cmd.size);
2527 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2530 ip->i_nlink += cmd.size;
2531 DIP_SET(ip, i_nlink, ip->i_nlink);
2532 ip->i_effnlink += cmd.size;
2533 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2534 error = ffs_update(vp, 1);
2535 if (DOINGSOFTDEP(vp))
2536 softdep_change_linkcnt(ip);
2540 case FFS_ADJ_BLKCNT:
2543 printf("%s: adjust inode %jd block count by %jd\n",
2544 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2545 (intmax_t)cmd.size);
2548 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2551 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2552 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2553 error = ffs_update(vp, 1);
2565 printf("%s: free %s inode %d\n",
2566 mp->mnt_stat.f_mntonname,
2567 filetype == IFDIR ? "directory" : "file",
2570 printf("%s: free %s inodes %d-%d\n",
2571 mp->mnt_stat.f_mntonname,
2572 filetype == IFDIR ? "directory" : "file",
2574 (ino_t)(cmd.value + cmd.size - 1));
2577 while (cmd.size > 0) {
2578 if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2579 cmd.value, filetype, NULL)))
2590 printf("%s: free block %jd\n",
2591 mp->mnt_stat.f_mntonname,
2592 (intmax_t)cmd.value);
2594 printf("%s: free blocks %jd-%jd\n",
2595 mp->mnt_stat.f_mntonname,
2596 (intmax_t)cmd.value,
2597 (intmax_t)cmd.value + cmd.size - 1);
2602 blksize = fs->fs_frag - (blkno % fs->fs_frag);
2603 while (blkcnt > 0) {
2604 if (blksize > blkcnt)
2606 ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2607 blksize * fs->fs_fsize, ROOTINO, VDIR, NULL);
2610 blksize = fs->fs_frag;
2615 * Adjust superblock summaries. fsck(8) is expected to
2616 * submit deltas when necessary.
2621 printf("%s: adjust number of directories by %jd\n",
2622 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2625 fs->fs_cstotal.cs_ndir += cmd.value;
2628 case FFS_ADJ_NBFREE:
2631 printf("%s: adjust number of free blocks by %+jd\n",
2632 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2635 fs->fs_cstotal.cs_nbfree += cmd.value;
2638 case FFS_ADJ_NIFREE:
2641 printf("%s: adjust number of free inodes by %+jd\n",
2642 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2645 fs->fs_cstotal.cs_nifree += cmd.value;
2648 case FFS_ADJ_NFFREE:
2651 printf("%s: adjust number of free frags by %+jd\n",
2652 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2655 fs->fs_cstotal.cs_nffree += cmd.value;
2658 case FFS_ADJ_NUMCLUSTERS:
2661 printf("%s: adjust number of free clusters by %+jd\n",
2662 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2665 fs->fs_cstotal.cs_numclusters += cmd.value;
2671 printf("%s: set current directory to inode %jd\n",
2672 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2675 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
2677 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2678 AUDIT_ARG_VNODE1(vp);
2679 if ((error = change_dir(vp, td)) != 0) {
2681 VFS_UNLOCK_GIANT(vfslocked);
2685 VFS_UNLOCK_GIANT(vfslocked);
2686 fdp = td->td_proc->p_fd;
2687 FILEDESC_XLOCK(fdp);
2688 vpold = fdp->fd_cdir;
2690 FILEDESC_XUNLOCK(fdp);
2691 vfslocked = VFS_LOCK_GIANT(vpold->v_mount);
2693 VFS_UNLOCK_GIANT(vfslocked);
2696 case FFS_SET_DOTDOT:
2699 printf("%s: change .. in cwd from %jd to %jd\n",
2700 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2701 (intmax_t)cmd.size);
2705 * First we have to get and lock the parent directory
2706 * to which ".." points.
2708 error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
2712 * Now we get and lock the child directory containing "..".
2714 FILEDESC_SLOCK(td->td_proc->p_fd);
2715 dvp = td->td_proc->p_fd->fd_cdir;
2716 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2717 if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
2722 dp->i_offset = 12; /* XXX mastertemplate.dot_reclen */
2723 error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
2736 if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
2737 strncpy(buf, "Name_too_long", 32);
2738 printf("%s: unlink %s (inode %jd)\n",
2739 mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
2743 * kern_unlinkat will do its own start/finish writes and
2744 * they do not nest, so drop ours here. Setting mp == NULL
2745 * indicates that vn_finished_write is not needed down below.
2747 vn_finished_write(mp);
2749 error = kern_unlinkat(td, AT_FDCWD, (char *)(intptr_t)cmd.value,
2750 UIO_USERSPACE, (ino_t)cmd.size);
2754 if (ump->um_fsckpid != td->td_proc->p_pid) {
2760 printf("%s: update inode %jd\n",
2761 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2764 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2766 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2767 AUDIT_ARG_VNODE1(vp);
2769 if (ip->i_ump->um_fstype == UFS1)
2770 error = copyin((void *)(intptr_t)cmd.size, ip->i_din1,
2771 sizeof(struct ufs1_dinode));
2773 error = copyin((void *)(intptr_t)cmd.size, ip->i_din2,
2774 sizeof(struct ufs2_dinode));
2777 VFS_UNLOCK_GIANT(vfslocked);
2780 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2781 error = ffs_update(vp, 1);
2783 VFS_UNLOCK_GIANT(vfslocked);
2786 case FFS_SET_BUFOUTPUT:
2787 if (ump->um_fsckpid != td->td_proc->p_pid) {
2791 if (VTOI(vp)->i_ump != ump) {
2797 printf("%s: %s buffered output for descriptor %jd\n",
2798 mp->mnt_stat.f_mntonname,
2799 cmd.size == 1 ? "enable" : "disable",
2800 (intmax_t)cmd.value);
2803 if ((error = getvnode(td->td_proc->p_fd, cmd.value,
2804 CAP_FSCK, &vfp)) != 0)
2806 if (vfp->f_vnode->v_type != VCHR) {
2811 if (origops == NULL) {
2812 origops = vfp->f_ops;
2813 bcopy((void *)origops, (void *)&bufferedops,
2814 sizeof(bufferedops));
2815 bufferedops.fo_write = buffered_write;
2818 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
2819 (uintptr_t)&bufferedops);
2821 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
2822 (uintptr_t)origops);
2829 printf("Invalid request %d from fsck\n",
2838 vn_finished_write(mp);
2843 * Function to switch a descriptor to use the buffer cache to stage
2844 * its I/O. This is needed so that writes to the filesystem device
2845 * will give snapshots a chance to copy modified blocks for which it
2846 * needs to retain copies.
2849 buffered_write(fp, uio, active_cred, flags, td)
2852 struct ucred *active_cred;
2856 struct vnode *devvp;
2860 int error, vfslocked;
2864 * The devvp is associated with the /dev filesystem. To discover
2865 * the filesystem with which the device is associated, we depend
2866 * on the application setting the current directory to a location
2867 * within the filesystem being written. Yes, this is an ugly hack.
2869 devvp = fp->f_vnode;
2870 ip = VTOI(td->td_proc->p_fd->fd_cdir);
2871 if (ip->i_devvp != devvp)
2874 vfslocked = VFS_LOCK_GIANT(ip->i_vnode->v_mount);
2875 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2876 if ((flags & FOF_OFFSET) == 0)
2877 uio->uio_offset = fp->f_offset;
2880 printf("%s: buffered write for block %jd\n",
2881 fs->fs_fsmnt, (intmax_t)btodb(uio->uio_offset));
2885 * All I/O must be contained within a filesystem block, start on
2886 * a fragment boundary, and be a multiple of fragments in length.
2888 if (uio->uio_resid > fs->fs_bsize - (uio->uio_offset % fs->fs_bsize) ||
2889 fragoff(fs, uio->uio_offset) != 0 ||
2890 fragoff(fs, uio->uio_resid) != 0) {
2894 lbn = numfrags(fs, uio->uio_offset);
2895 bp = getblk(devvp, lbn, uio->uio_resid, 0, 0, 0);
2896 bp->b_flags |= B_RELBUF;
2897 if ((error = uiomove((char *)bp->b_data, uio->uio_resid, uio)) != 0) {
2902 if ((flags & FOF_OFFSET) == 0)
2903 fp->f_offset = uio->uio_offset;
2904 fp->f_nextoff = uio->uio_offset;
2906 VOP_UNLOCK(devvp, 0);
2907 VFS_UNLOCK_GIANT(vfslocked);