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 * 3. 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/capsicum.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);
116 static ino_t ffs_dirpref(struct inode *);
117 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
119 static ufs2_daddr_t ffs_hashalloc
120 (struct inode *, u_int, ufs2_daddr_t, int, int, allocfcn_t *);
121 static ufs2_daddr_t ffs_nodealloccg(struct inode *, u_int, ufs2_daddr_t, int,
123 static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
124 static int ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
125 static int ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
126 static void ffs_ckhash_cg(struct buf *);
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(ump->um_dev), (long)fs->fs_bsize, size,
175 panic("ffs_alloc: bad size");
178 panic("ffs_alloc: missing credential");
179 #endif /* INVARIANTS */
184 error = chkdq(ip, btodb(size), cred, 0);
189 if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
191 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 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;
267 gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
269 mtx_assert(UFS_MTX(ump), MA_OWNED);
271 if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
272 panic("ffs_realloccg: allocation on suspended filesystem");
273 if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
274 (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
276 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
277 devtoname(ump->um_dev), (long)fs->fs_bsize, osize,
278 nsize, fs->fs_fsmnt);
279 panic("ffs_realloccg: bad size");
282 panic("ffs_realloccg: missing credential");
283 #endif /* INVARIANTS */
286 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
287 freespace(fs, fs->fs_minfree) - numfrags(fs, nsize - osize) < 0) {
291 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
292 devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
294 panic("ffs_realloccg: bad bprev");
298 * Allocate the extra space in the buffer.
300 error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
306 if (bp->b_blkno == bp->b_lblkno) {
307 if (lbprev >= UFS_NDADDR)
308 panic("ffs_realloccg: lbprev out of range");
309 bp->b_blkno = fsbtodb(fs, bprev);
313 error = chkdq(ip, btodb(nsize - osize), cred, 0);
320 * Check for extension in the existing location.
323 cg = dtog(fs, bprev);
325 bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
327 if (bp->b_blkno != fsbtodb(fs, bno))
328 panic("ffs_realloccg: bad blockno");
329 delta = btodb(nsize - osize);
330 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
332 ip->i_flag |= IN_CHANGE;
334 ip->i_flag |= IN_CHANGE | IN_UPDATE;
336 bp->b_flags |= B_DONE;
337 vfs_bio_bzero_buf(bp, osize, nsize - osize);
338 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
339 vfs_bio_set_valid(bp, osize, nsize - osize);
344 * Allocate a new disk location.
346 if (bpref >= fs->fs_size)
348 switch ((int)fs->fs_optim) {
351 * Allocate an exact sized fragment. Although this makes
352 * best use of space, we will waste time relocating it if
353 * the file continues to grow. If the fragmentation is
354 * less than half of the minimum free reserve, we choose
355 * to begin optimizing for time.
358 if (fs->fs_minfree <= 5 ||
359 fs->fs_cstotal.cs_nffree >
360 (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
362 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
364 fs->fs_optim = FS_OPTTIME;
368 * At this point we have discovered a file that is trying to
369 * grow a small fragment to a larger fragment. To save time,
370 * we allocate a full sized block, then free the unused portion.
371 * If the file continues to grow, the `ffs_fragextend' call
372 * above will be able to grow it in place without further
373 * copying. If aberrant programs cause disk fragmentation to
374 * grow within 2% of the free reserve, we choose to begin
375 * optimizing for space.
377 request = fs->fs_bsize;
378 if (fs->fs_cstotal.cs_nffree <
379 (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
381 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
383 fs->fs_optim = FS_OPTSPACE;
386 printf("dev = %s, optim = %ld, fs = %s\n",
387 devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
388 panic("ffs_realloccg: bad optim");
391 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
393 bp->b_blkno = fsbtodb(fs, bno);
394 if (!DOINGSOFTDEP(vp))
395 ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
396 ip->i_number, vp->v_type, NULL);
397 delta = btodb(nsize - osize);
398 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
400 ip->i_flag |= IN_CHANGE;
402 ip->i_flag |= IN_CHANGE | IN_UPDATE;
404 bp->b_flags |= B_DONE;
405 vfs_bio_bzero_buf(bp, osize, nsize - osize);
406 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
407 vfs_bio_set_valid(bp, osize, nsize - osize);
414 * Restore user's disk quota because allocation failed.
416 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
423 if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
431 softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
437 if (reclaimed > 0 && ppsratecheck(&lastfail, &curfail, 1)) {
438 ffs_fserr(fs, ip->i_number, "filesystem full");
439 uprintf("\n%s: write failed, filesystem is full\n",
446 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
448 * The vnode and an array of buffer pointers for a range of sequential
449 * logical blocks to be made contiguous is given. The allocator attempts
450 * to find a range of sequential blocks starting as close as possible
451 * from the end of the allocation for the logical block immediately
452 * preceding the current range. If successful, the physical block numbers
453 * in the buffer pointers and in the inode are changed to reflect the new
454 * allocation. If unsuccessful, the allocation is left unchanged. The
455 * success in doing the reallocation is returned. Note that the error
456 * return is not reflected back to the user. Rather the previous block
457 * allocation will be used.
460 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
462 static int doasyncfree = 1;
463 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
464 "do not force synchronous writes when blocks are reallocated");
466 static int doreallocblks = 1;
467 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
468 "enable block reallocation");
470 static int maxclustersearch = 10;
471 SYSCTL_INT(_vfs_ffs, OID_AUTO, maxclustersearch, CTLFLAG_RW, &maxclustersearch,
472 0, "max number of cylinder group to search for contigous blocks");
475 static volatile int prtrealloc = 0;
480 struct vop_reallocblks_args /* {
482 struct cluster_save *a_buflist;
485 struct ufsmount *ump;
488 * If the underlying device can do deletes, then skip reallocating
489 * the blocks of this file into contiguous sequences. Devices that
490 * benefit from BIO_DELETE also benefit from not moving the data.
491 * These devices are flash and therefore work less well with this
492 * optimization. Also skip if reallocblks has been disabled globally.
494 ump = ap->a_vp->v_mount->mnt_data;
495 if (ump->um_candelete || doreallocblks == 0)
499 * We can't wait in softdep prealloc as it may fsync and recurse
500 * here. Instead we simply fail to reallocate blocks if this
501 * rare condition arises.
503 if (DOINGSOFTDEP(ap->a_vp))
504 if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
506 if (ump->um_fstype == UFS1)
507 return (ffs_reallocblks_ufs1(ap));
508 return (ffs_reallocblks_ufs2(ap));
512 ffs_reallocblks_ufs1(ap)
513 struct vop_reallocblks_args /* {
515 struct cluster_save *a_buflist;
521 struct buf *sbp, *ebp;
522 ufs1_daddr_t *bap, *sbap, *ebap;
523 struct cluster_save *buflist;
524 struct ufsmount *ump;
525 ufs_lbn_t start_lbn, end_lbn;
526 ufs1_daddr_t soff, newblk, blkno;
528 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
529 int i, cg, len, start_lvl, end_lvl, ssize;
536 * If we are not tracking block clusters or if we have less than 4%
537 * free blocks left, then do not attempt to cluster. Running with
538 * less than 5% free block reserve is not recommended and those that
539 * choose to do so do not expect to have good file layout.
541 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
543 buflist = ap->a_buflist;
544 len = buflist->bs_nchildren;
545 start_lbn = buflist->bs_children[0]->b_lblkno;
546 end_lbn = start_lbn + len - 1;
548 for (i = 0; i < len; i++)
549 if (!ffs_checkblk(ip,
550 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
551 panic("ffs_reallocblks: unallocated block 1");
552 for (i = 1; i < len; i++)
553 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
554 panic("ffs_reallocblks: non-logical cluster");
555 blkno = buflist->bs_children[0]->b_blkno;
556 ssize = fsbtodb(fs, fs->fs_frag);
557 for (i = 1; i < len - 1; i++)
558 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
559 panic("ffs_reallocblks: non-physical cluster %d", i);
562 * If the cluster crosses the boundary for the first indirect
563 * block, leave space for the indirect block. Indirect blocks
564 * are initially laid out in a position after the last direct
565 * block. Block reallocation would usually destroy locality by
566 * moving the indirect block out of the way to make room for
567 * data blocks if we didn't compensate here. We should also do
568 * this for other indirect block boundaries, but it is only
569 * important for the first one.
571 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
574 * If the latest allocation is in a new cylinder group, assume that
575 * the filesystem has decided to move and do not force it back to
576 * the previous cylinder group.
578 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
579 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
581 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
582 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
585 * Get the starting offset and block map for the first block.
587 if (start_lvl == 0) {
588 sbap = &ip->i_din1->di_db[0];
591 idp = &start_ap[start_lvl - 1];
592 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
596 sbap = (ufs1_daddr_t *)sbp->b_data;
600 * If the block range spans two block maps, get the second map.
603 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
608 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
609 panic("ffs_reallocblk: start == end");
611 ssize = len - (idp->in_off + 1);
612 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
614 ebap = (ufs1_daddr_t *)ebp->b_data;
617 * Find the preferred location for the cluster. If we have not
618 * previously failed at this endeavor, then follow our standard
619 * preference calculation. If we have failed at it, then pick up
620 * where we last ended our search.
623 if (ip->i_nextclustercg == -1)
624 pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
626 pref = cgdata(fs, ip->i_nextclustercg);
628 * Search the block map looking for an allocation of the desired size.
629 * To avoid wasting too much time, we limit the number of cylinder
630 * groups that we will search.
633 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
634 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
637 if (cg >= fs->fs_ncg)
641 * If we have failed in our search, record where we gave up for
642 * next time. Otherwise, fall back to our usual search citerion.
645 ip->i_nextclustercg = cg;
649 ip->i_nextclustercg = -1;
651 * We have found a new contiguous block.
653 * First we have to replace the old block pointers with the new
654 * block pointers in the inode and indirect blocks associated
659 printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
660 (uintmax_t)ip->i_number,
661 (intmax_t)start_lbn, (intmax_t)end_lbn);
664 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
670 if (!ffs_checkblk(ip,
671 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
672 panic("ffs_reallocblks: unallocated block 2");
673 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
674 panic("ffs_reallocblks: alloc mismatch");
678 printf(" %d,", *bap);
680 if (DOINGSOFTDEP(vp)) {
681 if (sbap == &ip->i_din1->di_db[0] && i < ssize)
682 softdep_setup_allocdirect(ip, start_lbn + i,
683 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
684 buflist->bs_children[i]);
686 softdep_setup_allocindir_page(ip, start_lbn + i,
687 i < ssize ? sbp : ebp, soff + i, blkno,
688 *bap, buflist->bs_children[i]);
693 * Next we must write out the modified inode and indirect blocks.
694 * For strict correctness, the writes should be synchronous since
695 * the old block values may have been written to disk. In practise
696 * they are almost never written, but if we are concerned about
697 * strict correctness, the `doasyncfree' flag should be set to zero.
699 * The test on `doasyncfree' should be changed to test a flag
700 * that shows whether the associated buffers and inodes have
701 * been written. The flag should be set when the cluster is
702 * started and cleared whenever the buffer or inode is flushed.
703 * We can then check below to see if it is set, and do the
704 * synchronous write only when it has been cleared.
706 if (sbap != &ip->i_din1->di_db[0]) {
712 ip->i_flag |= IN_CHANGE | IN_UPDATE;
723 * Last, free the old blocks and assign the new blocks to the buffers.
729 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
730 if (!DOINGSOFTDEP(vp))
731 ffs_blkfree(ump, fs, ump->um_devvp,
732 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
733 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
734 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
736 if (!ffs_checkblk(ip,
737 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
738 panic("ffs_reallocblks: unallocated block 3");
742 printf(" %d,", blkno);
756 if (sbap != &ip->i_din1->di_db[0])
762 ffs_reallocblks_ufs2(ap)
763 struct vop_reallocblks_args /* {
765 struct cluster_save *a_buflist;
771 struct buf *sbp, *ebp;
772 ufs2_daddr_t *bap, *sbap, *ebap;
773 struct cluster_save *buflist;
774 struct ufsmount *ump;
775 ufs_lbn_t start_lbn, end_lbn;
776 ufs2_daddr_t soff, newblk, blkno, pref;
777 struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
778 int i, cg, len, start_lvl, end_lvl, ssize;
785 * If we are not tracking block clusters or if we have less than 4%
786 * free blocks left, then do not attempt to cluster. Running with
787 * less than 5% free block reserve is not recommended and those that
788 * choose to do so do not expect to have good file layout.
790 if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
792 buflist = ap->a_buflist;
793 len = buflist->bs_nchildren;
794 start_lbn = buflist->bs_children[0]->b_lblkno;
795 end_lbn = start_lbn + len - 1;
797 for (i = 0; i < len; i++)
798 if (!ffs_checkblk(ip,
799 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
800 panic("ffs_reallocblks: unallocated block 1");
801 for (i = 1; i < len; i++)
802 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
803 panic("ffs_reallocblks: non-logical cluster");
804 blkno = buflist->bs_children[0]->b_blkno;
805 ssize = fsbtodb(fs, fs->fs_frag);
806 for (i = 1; i < len - 1; i++)
807 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
808 panic("ffs_reallocblks: non-physical cluster %d", i);
811 * If the cluster crosses the boundary for the first indirect
812 * block, do not move anything in it. Indirect blocks are
813 * usually initially laid out in a position between the data
814 * blocks. Block reallocation would usually destroy locality by
815 * moving the indirect block out of the way to make room for
816 * data blocks if we didn't compensate here. We should also do
817 * this for other indirect block boundaries, but it is only
818 * important for the first one.
820 if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
823 * If the latest allocation is in a new cylinder group, assume that
824 * the filesystem has decided to move and do not force it back to
825 * the previous cylinder group.
827 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
828 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
830 if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
831 ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
834 * Get the starting offset and block map for the first block.
836 if (start_lvl == 0) {
837 sbap = &ip->i_din2->di_db[0];
840 idp = &start_ap[start_lvl - 1];
841 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
845 sbap = (ufs2_daddr_t *)sbp->b_data;
849 * If the block range spans two block maps, get the second map.
852 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
857 start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
858 panic("ffs_reallocblk: start == end");
860 ssize = len - (idp->in_off + 1);
861 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
863 ebap = (ufs2_daddr_t *)ebp->b_data;
866 * Find the preferred location for the cluster. If we have not
867 * previously failed at this endeavor, then follow our standard
868 * preference calculation. If we have failed at it, then pick up
869 * where we last ended our search.
872 if (ip->i_nextclustercg == -1)
873 pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
875 pref = cgdata(fs, ip->i_nextclustercg);
877 * Search the block map looking for an allocation of the desired size.
878 * To avoid wasting too much time, we limit the number of cylinder
879 * groups that we will search.
882 for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
883 if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
886 if (cg >= fs->fs_ncg)
890 * If we have failed in our search, record where we gave up for
891 * next time. Otherwise, fall back to our usual search citerion.
894 ip->i_nextclustercg = cg;
898 ip->i_nextclustercg = -1;
900 * We have found a new contiguous block.
902 * First we have to replace the old block pointers with the new
903 * block pointers in the inode and indirect blocks associated
908 printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
909 (intmax_t)start_lbn, (intmax_t)end_lbn);
912 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
918 if (!ffs_checkblk(ip,
919 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
920 panic("ffs_reallocblks: unallocated block 2");
921 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
922 panic("ffs_reallocblks: alloc mismatch");
926 printf(" %jd,", (intmax_t)*bap);
928 if (DOINGSOFTDEP(vp)) {
929 if (sbap == &ip->i_din2->di_db[0] && i < ssize)
930 softdep_setup_allocdirect(ip, start_lbn + i,
931 blkno, *bap, fs->fs_bsize, fs->fs_bsize,
932 buflist->bs_children[i]);
934 softdep_setup_allocindir_page(ip, start_lbn + i,
935 i < ssize ? sbp : ebp, soff + i, blkno,
936 *bap, buflist->bs_children[i]);
941 * Next we must write out the modified inode and indirect blocks.
942 * For strict correctness, the writes should be synchronous since
943 * the old block values may have been written to disk. In practise
944 * they are almost never written, but if we are concerned about
945 * strict correctness, the `doasyncfree' flag should be set to zero.
947 * The test on `doasyncfree' should be changed to test a flag
948 * that shows whether the associated buffers and inodes have
949 * been written. The flag should be set when the cluster is
950 * started and cleared whenever the buffer or inode is flushed.
951 * We can then check below to see if it is set, and do the
952 * synchronous write only when it has been cleared.
954 if (sbap != &ip->i_din2->di_db[0]) {
960 ip->i_flag |= IN_CHANGE | IN_UPDATE;
971 * Last, free the old blocks and assign the new blocks to the buffers.
977 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
978 if (!DOINGSOFTDEP(vp))
979 ffs_blkfree(ump, fs, ump->um_devvp,
980 dbtofsb(fs, buflist->bs_children[i]->b_blkno),
981 fs->fs_bsize, ip->i_number, vp->v_type, NULL);
982 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
984 if (!ffs_checkblk(ip,
985 dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
986 panic("ffs_reallocblks: unallocated block 3");
990 printf(" %jd,", (intmax_t)blkno);
1004 if (sbap != &ip->i_din2->di_db[0])
1010 * Allocate an inode in the filesystem.
1012 * If allocating a directory, use ffs_dirpref to select the inode.
1013 * If allocating in a directory, the following hierarchy is followed:
1014 * 1) allocate the preferred inode.
1015 * 2) allocate an inode in the same cylinder group.
1016 * 3) quadradically rehash into other cylinder groups, until an
1017 * available inode is located.
1018 * If no inode preference is given the following hierarchy is used
1019 * to allocate an inode:
1020 * 1) allocate an inode in cylinder group 0.
1021 * 2) quadradically rehash into other cylinder groups, until an
1022 * available inode is located.
1025 ffs_valloc(pvp, mode, cred, vpp)
1035 struct ufsmount *ump;
1038 int error, error1, reclaimed;
1039 static struct timeval lastfail;
1050 if (fs->fs_cstotal.cs_nifree == 0)
1053 if ((mode & IFMT) == IFDIR)
1054 ipref = ffs_dirpref(pip);
1056 ipref = pip->i_number;
1057 if (ipref >= fs->fs_ncg * fs->fs_ipg)
1059 cg = ino_to_cg(fs, ipref);
1061 * Track number of dirs created one after another
1062 * in a same cg without intervening by files.
1064 if ((mode & IFMT) == IFDIR) {
1065 if (fs->fs_contigdirs[cg] < 255)
1066 fs->fs_contigdirs[cg]++;
1068 if (fs->fs_contigdirs[cg] > 0)
1069 fs->fs_contigdirs[cg]--;
1071 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1072 (allocfcn_t *)ffs_nodealloccg);
1075 error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
1077 error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
1079 ffs_vfree(pvp, ino, mode);
1084 ip->i_flag |= IN_MODIFIED;
1092 printf("mode = 0%o, inum = %ju, fs = %s\n",
1093 ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1094 panic("ffs_valloc: dup alloc");
1096 if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) { /* XXX */
1097 printf("free inode %s/%lu had %ld blocks\n",
1098 fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1099 DIP_SET(ip, i_blocks, 0);
1102 DIP_SET(ip, i_flags, 0);
1104 * Set up a new generation number for this inode.
1106 while (ip->i_gen == 0 || ++ip->i_gen == 0)
1107 ip->i_gen = arc4random();
1108 DIP_SET(ip, i_gen, ip->i_gen);
1109 if (fs->fs_magic == FS_UFS2_MAGIC) {
1111 ip->i_din2->di_birthtime = ts.tv_sec;
1112 ip->i_din2->di_birthnsec = ts.tv_nsec;
1114 ufs_prepare_reclaim(*vpp);
1116 (*vpp)->v_vflag = 0;
1117 (*vpp)->v_type = VNON;
1118 if (fs->fs_magic == FS_UFS2_MAGIC) {
1119 (*vpp)->v_op = &ffs_vnodeops2;
1120 ip->i_flag |= IN_UFS2;
1122 (*vpp)->v_op = &ffs_vnodeops1;
1126 if (reclaimed == 0) {
1128 softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
1132 if (ppsratecheck(&lastfail, &curfail, 1)) {
1133 ffs_fserr(fs, pip->i_number, "out of inodes");
1134 uprintf("\n%s: create/symlink failed, no inodes free\n",
1141 * Find a cylinder group to place a directory.
1143 * The policy implemented by this algorithm is to allocate a
1144 * directory inode in the same cylinder group as its parent
1145 * directory, but also to reserve space for its files inodes
1146 * and data. Restrict the number of directories which may be
1147 * allocated one after another in the same cylinder group
1148 * without intervening allocation of files.
1150 * If we allocate a first level directory then force allocation
1151 * in another cylinder group.
1158 int cg, prefcg, dirsize, cgsize;
1159 u_int avgifree, avgbfree, avgndir, curdirsize;
1160 u_int minifree, minbfree, maxndir;
1161 u_int mincg, minndir;
1162 u_int maxcontigdirs;
1164 mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1167 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1168 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1169 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1172 * Force allocation in another cg if creating a first level dir.
1174 ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1175 if (ITOV(pip)->v_vflag & VV_ROOT) {
1176 prefcg = arc4random() % fs->fs_ncg;
1178 minndir = fs->fs_ipg;
1179 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1180 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1181 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1182 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1184 minndir = fs->fs_cs(fs, cg).cs_ndir;
1186 for (cg = 0; cg < prefcg; cg++)
1187 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1188 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1189 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1191 minndir = fs->fs_cs(fs, cg).cs_ndir;
1193 return ((ino_t)(fs->fs_ipg * mincg));
1197 * Count various limits which used for
1198 * optimal allocation of a directory inode.
1200 maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1201 minifree = avgifree - avgifree / 4;
1204 minbfree = avgbfree - avgbfree / 4;
1207 cgsize = fs->fs_fsize * fs->fs_fpg;
1208 dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1209 curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1210 if (dirsize < curdirsize)
1211 dirsize = curdirsize;
1213 maxcontigdirs = 0; /* dirsize overflowed */
1215 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1216 if (fs->fs_avgfpdir > 0)
1217 maxcontigdirs = min(maxcontigdirs,
1218 fs->fs_ipg / fs->fs_avgfpdir);
1219 if (maxcontigdirs == 0)
1223 * Limit number of dirs in one cg and reserve space for
1224 * regular files, but only if we have no deficit in
1227 * We are trying to find a suitable cylinder group nearby
1228 * our preferred cylinder group to place a new directory.
1229 * We scan from our preferred cylinder group forward looking
1230 * for a cylinder group that meets our criterion. If we get
1231 * to the final cylinder group and do not find anything,
1232 * we start scanning forwards from the beginning of the
1233 * filesystem. While it might seem sensible to start scanning
1234 * backwards or even to alternate looking forward and backward,
1235 * this approach fails badly when the filesystem is nearly full.
1236 * Specifically, we first search all the areas that have no space
1237 * and finally try the one preceding that. We repeat this on
1238 * every request and in the case of the final block end up
1239 * searching the entire filesystem. By jumping to the front
1240 * of the filesystem, our future forward searches always look
1241 * in new cylinder groups so finds every possible block after
1242 * one pass over the filesystem.
1244 prefcg = ino_to_cg(fs, pip->i_number);
1245 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1246 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1247 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1248 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1249 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1250 return ((ino_t)(fs->fs_ipg * cg));
1252 for (cg = 0; cg < prefcg; cg++)
1253 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1254 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1255 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1256 if (fs->fs_contigdirs[cg] < maxcontigdirs)
1257 return ((ino_t)(fs->fs_ipg * cg));
1260 * This is a backstop when we have deficit in space.
1262 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1263 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1264 return ((ino_t)(fs->fs_ipg * cg));
1265 for (cg = 0; cg < prefcg; cg++)
1266 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1268 return ((ino_t)(fs->fs_ipg * cg));
1272 * Select the desired position for the next block in a file. The file is
1273 * logically divided into sections. The first section is composed of the
1274 * direct blocks and the next fs_maxbpg blocks. Each additional section
1275 * contains fs_maxbpg blocks.
1277 * If no blocks have been allocated in the first section, the policy is to
1278 * request a block in the same cylinder group as the inode that describes
1279 * the file. The first indirect is allocated immediately following the last
1280 * direct block and the data blocks for the first indirect immediately
1283 * If no blocks have been allocated in any other section, the indirect
1284 * block(s) are allocated in the same cylinder group as its inode in an
1285 * area reserved immediately following the inode blocks. The policy for
1286 * the data blocks is to place them in a cylinder group with a greater than
1287 * average number of free blocks. An appropriate cylinder group is found
1288 * by using a rotor that sweeps the cylinder groups. When a new group of
1289 * blocks is needed, the sweep begins in the cylinder group following the
1290 * cylinder group from which the previous allocation was made. The sweep
1291 * continues until a cylinder group with greater than the average number
1292 * of free blocks is found. If the allocation is for the first block in an
1293 * indirect block or the previous block is a hole, then the information on
1294 * the previous allocation is unavailable; here a best guess is made based
1295 * on the logical block number being allocated.
1297 * If a section is already partially allocated, the policy is to
1298 * allocate blocks contiguously within the section if possible.
1301 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1309 u_int avgbfree, startcg;
1312 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1313 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1316 * Allocation of indirect blocks is indicated by passing negative
1317 * values in indx: -1 for single indirect, -2 for double indirect,
1318 * -3 for triple indirect. As noted below, we attempt to allocate
1319 * the first indirect inline with the file data. For all later
1320 * indirect blocks, the data is often allocated in other cylinder
1321 * groups. However to speed random file access and to speed up
1322 * fsck, the filesystem reserves the first fs_metaspace blocks
1323 * (typically half of fs_minfree) of the data area of each cylinder
1324 * group to hold these later indirect blocks.
1326 inocg = ino_to_cg(fs, ip->i_number);
1329 * Our preference for indirect blocks is the zone at the
1330 * beginning of the inode's cylinder group data area that
1331 * we try to reserve for indirect blocks.
1333 pref = cgmeta(fs, inocg);
1335 * If we are allocating the first indirect block, try to
1336 * place it immediately following the last direct block.
1338 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1339 ip->i_din1->di_db[UFS_NDADDR - 1] != 0)
1340 pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1344 * If we are allocating the first data block in the first indirect
1345 * block and the indirect has been allocated in the data block area,
1346 * try to place it immediately following the indirect block.
1348 if (lbn == UFS_NDADDR) {
1349 pref = ip->i_din1->di_ib[0];
1350 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1351 pref < cgbase(fs, inocg + 1))
1352 return (pref + fs->fs_frag);
1355 * If we are at the beginning of a file, or we have already allocated
1356 * the maximum number of blocks per cylinder group, or we do not
1357 * have a block allocated immediately preceding us, then we need
1358 * to decide where to start allocating new blocks.
1360 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1362 * If we are allocating a directory data block, we want
1363 * to place it in the metadata area.
1365 if ((ip->i_mode & IFMT) == IFDIR)
1366 return (cgmeta(fs, inocg));
1368 * Until we fill all the direct and all the first indirect's
1369 * blocks, we try to allocate in the data area of the inode's
1372 if (lbn < UFS_NDADDR + NINDIR(fs))
1373 return (cgdata(fs, inocg));
1375 * Find a cylinder with greater than average number of
1376 * unused data blocks.
1378 if (indx == 0 || bap[indx - 1] == 0)
1379 startcg = inocg + lbn / fs->fs_maxbpg;
1381 startcg = dtog(fs, bap[indx - 1]) + 1;
1382 startcg %= fs->fs_ncg;
1383 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1384 for (cg = startcg; cg < fs->fs_ncg; cg++)
1385 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1386 fs->fs_cgrotor = cg;
1387 return (cgdata(fs, cg));
1389 for (cg = 0; cg <= startcg; cg++)
1390 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1391 fs->fs_cgrotor = cg;
1392 return (cgdata(fs, cg));
1397 * Otherwise, we just always try to lay things out contiguously.
1399 return (bap[indx - 1] + fs->fs_frag);
1403 * Same as above, but for UFS2
1406 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1414 u_int avgbfree, startcg;
1417 KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1418 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1421 * Allocation of indirect blocks is indicated by passing negative
1422 * values in indx: -1 for single indirect, -2 for double indirect,
1423 * -3 for triple indirect. As noted below, we attempt to allocate
1424 * the first indirect inline with the file data. For all later
1425 * indirect blocks, the data is often allocated in other cylinder
1426 * groups. However to speed random file access and to speed up
1427 * fsck, the filesystem reserves the first fs_metaspace blocks
1428 * (typically half of fs_minfree) of the data area of each cylinder
1429 * group to hold these later indirect blocks.
1431 inocg = ino_to_cg(fs, ip->i_number);
1434 * Our preference for indirect blocks is the zone at the
1435 * beginning of the inode's cylinder group data area that
1436 * we try to reserve for indirect blocks.
1438 pref = cgmeta(fs, inocg);
1440 * If we are allocating the first indirect block, try to
1441 * place it immediately following the last direct block.
1443 if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1444 ip->i_din2->di_db[UFS_NDADDR - 1] != 0)
1445 pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1449 * If we are allocating the first data block in the first indirect
1450 * block and the indirect has been allocated in the data block area,
1451 * try to place it immediately following the indirect block.
1453 if (lbn == UFS_NDADDR) {
1454 pref = ip->i_din2->di_ib[0];
1455 if (pref != 0 && pref >= cgdata(fs, inocg) &&
1456 pref < cgbase(fs, inocg + 1))
1457 return (pref + fs->fs_frag);
1460 * If we are at the beginning of a file, or we have already allocated
1461 * the maximum number of blocks per cylinder group, or we do not
1462 * have a block allocated immediately preceding us, then we need
1463 * to decide where to start allocating new blocks.
1465 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1467 * If we are allocating a directory data block, we want
1468 * to place it in the metadata area.
1470 if ((ip->i_mode & IFMT) == IFDIR)
1471 return (cgmeta(fs, inocg));
1473 * Until we fill all the direct and all the first indirect's
1474 * blocks, we try to allocate in the data area of the inode's
1477 if (lbn < UFS_NDADDR + NINDIR(fs))
1478 return (cgdata(fs, inocg));
1480 * Find a cylinder with greater than average number of
1481 * unused data blocks.
1483 if (indx == 0 || bap[indx - 1] == 0)
1484 startcg = inocg + lbn / fs->fs_maxbpg;
1486 startcg = dtog(fs, bap[indx - 1]) + 1;
1487 startcg %= fs->fs_ncg;
1488 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1489 for (cg = startcg; cg < fs->fs_ncg; cg++)
1490 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1491 fs->fs_cgrotor = cg;
1492 return (cgdata(fs, cg));
1494 for (cg = 0; cg <= startcg; cg++)
1495 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1496 fs->fs_cgrotor = cg;
1497 return (cgdata(fs, cg));
1502 * Otherwise, we just always try to lay things out contiguously.
1504 return (bap[indx - 1] + fs->fs_frag);
1508 * Implement the cylinder overflow algorithm.
1510 * The policy implemented by this algorithm is:
1511 * 1) allocate the block in its requested cylinder group.
1512 * 2) quadradically rehash on the cylinder group number.
1513 * 3) brute force search for a free block.
1515 * Must be called with the UFS lock held. Will release the lock on success
1516 * and return with it held on failure.
1520 ffs_hashalloc(ip, cg, pref, size, rsize, allocator)
1524 int size; /* Search size for data blocks, mode for inodes */
1525 int rsize; /* Real allocated size. */
1526 allocfcn_t *allocator;
1529 ufs2_daddr_t result;
1532 mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1534 if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1535 panic("ffs_hashalloc: allocation on suspended filesystem");
1539 * 1: preferred cylinder group
1541 result = (*allocator)(ip, cg, pref, size, rsize);
1545 * 2: quadratic rehash
1547 for (i = 1; i < fs->fs_ncg; i *= 2) {
1549 if (cg >= fs->fs_ncg)
1551 result = (*allocator)(ip, cg, 0, size, rsize);
1556 * 3: brute force search
1557 * Note that we start at i == 2, since 0 was checked initially,
1558 * and 1 is always checked in the quadratic rehash.
1560 cg = (icg + 2) % fs->fs_ncg;
1561 for (i = 2; i < fs->fs_ncg; i++) {
1562 result = (*allocator)(ip, cg, 0, size, rsize);
1566 if (cg == fs->fs_ncg)
1573 * Determine whether a fragment can be extended.
1575 * Check to see if the necessary fragments are available, and
1576 * if they are, allocate them.
1579 ffs_fragextend(ip, cg, bprev, osize, nsize)
1588 struct ufsmount *ump;
1597 if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1599 frags = numfrags(fs, nsize);
1600 bbase = fragnum(fs, bprev);
1601 if (bbase > fragnum(fs, (bprev + frags - 1))) {
1602 /* cannot extend across a block boundary */
1606 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0)
1608 bno = dtogd(fs, bprev);
1609 blksfree = cg_blksfree(cgp);
1610 for (i = numfrags(fs, osize); i < frags; i++)
1611 if (isclr(blksfree, bno + i))
1614 * the current fragment can be extended
1615 * deduct the count on fragment being extended into
1616 * increase the count on the remaining fragment (if any)
1617 * allocate the extended piece
1619 for (i = frags; i < fs->fs_frag - bbase; i++)
1620 if (isclr(blksfree, bno + i))
1622 cgp->cg_frsum[i - numfrags(fs, osize)]--;
1624 cgp->cg_frsum[i - frags]++;
1625 for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1626 clrbit(blksfree, bno + i);
1627 cgp->cg_cs.cs_nffree--;
1631 fs->fs_cstotal.cs_nffree -= nffree;
1632 fs->fs_cs(fs, cg).cs_nffree -= nffree;
1634 ACTIVECLEAR(fs, cg);
1636 if (DOINGSOFTDEP(ITOV(ip)))
1637 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1638 frags, numfrags(fs, osize));
1650 * Determine whether a block can be allocated.
1652 * Check to see if a block of the appropriate size is available,
1653 * and if it is, allocate it.
1656 ffs_alloccg(ip, cg, bpref, size, rsize)
1666 struct ufsmount *ump;
1669 int i, allocsiz, error, frags;
1674 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1677 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0 ||
1678 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1680 if (size == fs->fs_bsize) {
1682 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1683 ACTIVECLEAR(fs, cg);
1689 * check to see if any fragments are already available
1690 * allocsiz is the size which will be allocated, hacking
1691 * it down to a smaller size if necessary
1693 blksfree = cg_blksfree(cgp);
1694 frags = numfrags(fs, size);
1695 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1696 if (cgp->cg_frsum[allocsiz] != 0)
1698 if (allocsiz == fs->fs_frag) {
1700 * no fragments were available, so a block will be
1701 * allocated, and hacked up
1703 if (cgp->cg_cs.cs_nbfree == 0)
1706 blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
1707 ACTIVECLEAR(fs, cg);
1712 KASSERT(size == rsize,
1713 ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1714 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1717 for (i = 0; i < frags; i++)
1718 clrbit(blksfree, bno + i);
1719 cgp->cg_cs.cs_nffree -= frags;
1720 cgp->cg_frsum[allocsiz]--;
1721 if (frags != allocsiz)
1722 cgp->cg_frsum[allocsiz - frags]++;
1724 fs->fs_cstotal.cs_nffree -= frags;
1725 fs->fs_cs(fs, cg).cs_nffree -= frags;
1727 blkno = cgbase(fs, cg) + bno;
1728 ACTIVECLEAR(fs, cg);
1730 if (DOINGSOFTDEP(ITOV(ip)))
1731 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1742 * Allocate a block in a cylinder group.
1744 * This algorithm implements the following policy:
1745 * 1) allocate the requested block.
1746 * 2) allocate a rotationally optimal block in the same cylinder.
1747 * 3) allocate the next available block on the block rotor for the
1748 * specified cylinder group.
1749 * Note that this routine only allocates fs_bsize blocks; these
1750 * blocks may be fragmented by the routine that allocates them.
1753 ffs_alloccgblk(ip, bp, bpref, size)
1761 struct ufsmount *ump;
1769 mtx_assert(UFS_MTX(ump), MA_OWNED);
1770 cgp = (struct cg *)bp->b_data;
1771 blksfree = cg_blksfree(cgp);
1773 bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1774 } else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1775 /* map bpref to correct zone in this cg */
1776 if (bpref < cgdata(fs, cgbpref))
1777 bpref = cgmeta(fs, cgp->cg_cgx);
1779 bpref = cgdata(fs, cgp->cg_cgx);
1782 * if the requested block is available, use it
1784 bno = dtogd(fs, blknum(fs, bpref));
1785 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1788 * Take the next available block in this cylinder group.
1790 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1793 /* Update cg_rotor only if allocated from the data zone */
1794 if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1795 cgp->cg_rotor = bno;
1797 blkno = fragstoblks(fs, bno);
1798 ffs_clrblock(fs, blksfree, (long)blkno);
1799 ffs_clusteracct(fs, cgp, blkno, -1);
1800 cgp->cg_cs.cs_nbfree--;
1801 fs->fs_cstotal.cs_nbfree--;
1802 fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1804 blkno = cgbase(fs, cgp->cg_cgx) + bno;
1806 * If the caller didn't want the whole block free the frags here.
1808 size = numfrags(fs, size);
1809 if (size != fs->fs_frag) {
1810 bno = dtogd(fs, blkno);
1811 for (i = size; i < fs->fs_frag; i++)
1812 setbit(blksfree, bno + i);
1813 i = fs->fs_frag - size;
1814 cgp->cg_cs.cs_nffree += i;
1815 fs->fs_cstotal.cs_nffree += i;
1816 fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1822 if (DOINGSOFTDEP(ITOV(ip)))
1823 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno,
1830 * Determine whether a cluster can be allocated.
1832 * We do not currently check for optimal rotational layout if there
1833 * are multiple choices in the same cylinder group. Instead we just
1834 * take the first one that we find following bpref.
1837 ffs_clusteralloc(ip, cg, bpref, len)
1846 struct ufsmount *ump;
1847 int i, run, bit, map, got, error;
1855 if (fs->fs_maxcluster[cg] < len)
1858 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0) {
1863 * Check to see if a cluster of the needed size (or bigger) is
1864 * available in this cylinder group.
1866 lp = &cg_clustersum(cgp)[len];
1867 for (i = len; i <= fs->fs_contigsumsize; i++)
1870 if (i > fs->fs_contigsumsize) {
1872 * This is the first time looking for a cluster in this
1873 * cylinder group. Update the cluster summary information
1874 * to reflect the true maximum sized cluster so that
1875 * future cluster allocation requests can avoid reading
1876 * the cylinder group map only to find no clusters.
1878 lp = &cg_clustersum(cgp)[len - 1];
1879 for (i = len - 1; i > 0; i--)
1883 fs->fs_maxcluster[cg] = i;
1888 * Search the cluster map to find a big enough cluster.
1889 * We take the first one that we find, even if it is larger
1890 * than we need as we prefer to get one close to the previous
1891 * block allocation. We do not search before the current
1892 * preference point as we do not want to allocate a block
1893 * that is allocated before the previous one (as we will
1894 * then have to wait for another pass of the elevator
1895 * algorithm before it will be read). We prefer to fail and
1896 * be recalled to try an allocation in the next cylinder group.
1898 if (dtog(fs, bpref) != cg)
1899 bpref = cgdata(fs, cg);
1901 bpref = blknum(fs, bpref);
1902 bpref = fragstoblks(fs, dtogd(fs, bpref));
1903 mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1905 bit = 1 << (bpref % NBBY);
1906 for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1907 if ((map & bit) == 0) {
1914 if ((got & (NBBY - 1)) != (NBBY - 1)) {
1921 if (got >= cgp->cg_nclusterblks) {
1927 * Allocate the cluster that we have found.
1929 blksfree = cg_blksfree(cgp);
1930 for (i = 1; i <= len; i++)
1931 if (!ffs_isblock(fs, blksfree, got - run + i))
1932 panic("ffs_clusteralloc: map mismatch");
1933 bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1934 if (dtog(fs, bno) != cg)
1935 panic("ffs_clusteralloc: allocated out of group");
1936 len = blkstofrags(fs, len);
1938 for (i = 0; i < len; i += fs->fs_frag)
1939 if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
1940 panic("ffs_clusteralloc: lost block");
1941 ACTIVECLEAR(fs, cg);
1947 static inline struct buf *
1948 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
1953 return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
1954 cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
1959 * Determine whether an inode can be allocated.
1961 * Check to see if an inode is available, and if it is,
1962 * allocate it using the following policy:
1963 * 1) allocate the requested inode.
1964 * 2) allocate the next available inode after the requested
1965 * inode in the specified cylinder group.
1968 ffs_nodealloccg(ip, cg, ipref, mode, unused)
1977 struct buf *bp, *ibp;
1978 struct ufsmount *ump;
1979 u_int8_t *inosused, *loc;
1980 struct ufs2_dinode *dp2;
1981 int error, start, len, i;
1982 u_int32_t old_initediblk;
1987 if (fs->fs_cs(fs, cg).cs_nifree == 0)
1990 if ((error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp)) != 0) {
1995 if (cgp->cg_cs.cs_nifree == 0) {
2000 inosused = cg_inosused(cgp);
2002 ipref %= fs->fs_ipg;
2003 if (isclr(inosused, ipref))
2006 start = cgp->cg_irotor / NBBY;
2007 len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
2008 loc = memcchr(&inosused[start], 0xff, len);
2012 loc = memcchr(&inosused[start], 0xff, len);
2014 printf("cg = %d, irotor = %ld, fs = %s\n",
2015 cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2016 panic("ffs_nodealloccg: map corrupted");
2020 ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2023 * Check to see if we need to initialize more inodes.
2025 if (fs->fs_magic == FS_UFS2_MAGIC &&
2026 ipref + INOPB(fs) > cgp->cg_initediblk &&
2027 cgp->cg_initediblk < cgp->cg_niblk) {
2028 old_initediblk = cgp->cg_initediblk;
2031 * Free the cylinder group lock before writing the
2032 * initialized inode block. Entering the
2033 * babarrierwrite() with the cylinder group lock
2034 * causes lock order violation between the lock and
2037 * Another thread can decide to initialize the same
2038 * inode block, but whichever thread first gets the
2039 * cylinder group lock after writing the newly
2040 * allocated inode block will update it and the other
2041 * will realize that it has lost and leave the
2042 * cylinder group unchanged.
2044 ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
2048 * The inode block buffer is already owned by
2049 * another thread, which must initialize it.
2050 * Wait on the buffer to allow another thread
2051 * to finish the updates, with dropped cg
2052 * buffer lock, then retry.
2054 ibp = getinobuf(ip, cg, old_initediblk, 0);
2059 bzero(ibp->b_data, (int)fs->fs_bsize);
2060 dp2 = (struct ufs2_dinode *)(ibp->b_data);
2061 for (i = 0; i < INOPB(fs); i++) {
2062 while (dp2->di_gen == 0)
2063 dp2->di_gen = arc4random();
2067 * Rather than adding a soft updates dependency to ensure
2068 * that the new inode block is written before it is claimed
2069 * by the cylinder group map, we just do a barrier write
2070 * here. The barrier write will ensure that the inode block
2071 * gets written before the updated cylinder group map can be
2072 * written. The barrier write should only slow down bulk
2073 * loading of newly created filesystems.
2075 babarrierwrite(ibp);
2078 * After the inode block is written, try to update the
2079 * cg initediblk pointer. If another thread beat us
2080 * to it, then leave it unchanged as the other thread
2081 * has already set it correctly.
2083 error = ffs_getcg(fs, ump->um_devvp, cg, &bp, &cgp);
2085 ACTIVECLEAR(fs, cg);
2089 if (cgp->cg_initediblk == old_initediblk)
2090 cgp->cg_initediblk += INOPB(fs);
2093 cgp->cg_irotor = ipref;
2095 ACTIVECLEAR(fs, cg);
2096 setbit(inosused, ipref);
2097 cgp->cg_cs.cs_nifree--;
2098 fs->fs_cstotal.cs_nifree--;
2099 fs->fs_cs(fs, cg).cs_nifree--;
2101 if ((mode & IFMT) == IFDIR) {
2102 cgp->cg_cs.cs_ndir++;
2103 fs->fs_cstotal.cs_ndir++;
2104 fs->fs_cs(fs, cg).cs_ndir++;
2107 if (DOINGSOFTDEP(ITOV(ip)))
2108 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2110 return ((ino_t)(cg * fs->fs_ipg + ipref));
2114 * Free a block or fragment.
2116 * The specified block or fragment is placed back in the
2117 * free map. If a fragment is deallocated, a possible
2118 * block reassembly is checked.
2121 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd)
2122 struct ufsmount *ump;
2124 struct vnode *devvp;
2128 struct workhead *dephd;
2133 ufs1_daddr_t fragno, cgbno;
2134 int i, blk, frags, bbase, error;
2140 if (devvp->v_type == VREG) {
2141 /* devvp is a snapshot */
2142 MPASS(devvp->v_mount->mnt_data == ump);
2143 dev = ump->um_devvp->v_rdev;
2144 } else if (devvp->v_type == VCHR) {
2145 /* devvp is a normal disk device */
2146 dev = devvp->v_rdev;
2147 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
2151 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2152 fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
2153 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
2154 devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2155 size, fs->fs_fsmnt);
2156 panic("ffs_blkfree_cg: bad size");
2159 if ((u_int)bno >= fs->fs_size) {
2160 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
2162 ffs_fserr(fs, inum, "bad block");
2165 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2167 cgbno = dtogd(fs, bno);
2168 blksfree = cg_blksfree(cgp);
2170 if (size == fs->fs_bsize) {
2171 fragno = fragstoblks(fs, cgbno);
2172 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
2173 if (devvp->v_type == VREG) {
2175 /* devvp is a snapshot */
2179 printf("dev = %s, block = %jd, fs = %s\n",
2180 devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
2181 panic("ffs_blkfree_cg: freeing free block");
2183 ffs_setblock(fs, blksfree, fragno);
2184 ffs_clusteracct(fs, cgp, fragno, 1);
2185 cgp->cg_cs.cs_nbfree++;
2186 fs->fs_cstotal.cs_nbfree++;
2187 fs->fs_cs(fs, cg).cs_nbfree++;
2189 bbase = cgbno - fragnum(fs, cgbno);
2191 * decrement the counts associated with the old frags
2193 blk = blkmap(fs, blksfree, bbase);
2194 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2196 * deallocate the fragment
2198 frags = numfrags(fs, size);
2199 for (i = 0; i < frags; i++) {
2200 if (isset(blksfree, cgbno + i)) {
2201 printf("dev = %s, block = %jd, fs = %s\n",
2202 devtoname(dev), (intmax_t)(bno + i),
2204 panic("ffs_blkfree_cg: freeing free frag");
2206 setbit(blksfree, cgbno + i);
2208 cgp->cg_cs.cs_nffree += i;
2209 fs->fs_cstotal.cs_nffree += i;
2210 fs->fs_cs(fs, cg).cs_nffree += i;
2212 * add back in counts associated with the new frags
2214 blk = blkmap(fs, blksfree, bbase);
2215 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2217 * if a complete block has been reassembled, account for it
2219 fragno = fragstoblks(fs, bbase);
2220 if (ffs_isblock(fs, blksfree, fragno)) {
2221 cgp->cg_cs.cs_nffree -= fs->fs_frag;
2222 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2223 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2224 ffs_clusteracct(fs, cgp, fragno, 1);
2225 cgp->cg_cs.cs_nbfree++;
2226 fs->fs_cstotal.cs_nbfree++;
2227 fs->fs_cs(fs, cg).cs_nbfree++;
2231 ACTIVECLEAR(fs, cg);
2234 if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2235 softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2236 numfrags(fs, size), dephd);
2240 struct ffs_blkfree_trim_params {
2242 struct ufsmount *ump;
2243 struct vnode *devvp;
2247 struct workhead *pdephd;
2248 struct workhead dephd;
2252 ffs_blkfree_trim_task(ctx, pending)
2256 struct ffs_blkfree_trim_params *tp;
2259 ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
2260 tp->inum, tp->pdephd);
2261 vn_finished_secondary_write(UFSTOVFS(tp->ump));
2262 atomic_add_int(&tp->ump->um_trim_inflight, -1);
2267 ffs_blkfree_trim_completed(bip)
2270 struct ffs_blkfree_trim_params *tp;
2272 tp = bip->bio_caller2;
2274 TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2275 taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
2279 ffs_blkfree(ump, fs, devvp, bno, size, inum, vtype, dephd)
2280 struct ufsmount *ump;
2282 struct vnode *devvp;
2287 struct workhead *dephd;
2291 struct ffs_blkfree_trim_params *tp;
2294 * Check to see if a snapshot wants to claim the block.
2295 * Check that devvp is a normal disk device, not a snapshot,
2296 * it has a snapshot(s) associated with it, and one of the
2297 * snapshots wants to claim the block.
2299 if (devvp->v_type == VCHR &&
2300 (devvp->v_vflag & VV_COPYONWRITE) &&
2301 ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
2305 * Nothing to delay if TRIM is disabled, or the operation is
2306 * performed on the snapshot.
2308 if (!ump->um_candelete || devvp->v_type == VREG) {
2309 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
2314 * Postpone the set of the free bit in the cg bitmap until the
2315 * BIO_DELETE is completed. Otherwise, due to disk queue
2316 * reordering, TRIM might be issued after we reuse the block
2317 * and write some new data into it.
2319 atomic_add_int(&ump->um_trim_inflight, 1);
2320 tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2326 if (dephd != NULL) {
2327 LIST_INIT(&tp->dephd);
2328 LIST_SWAP(dephd, &tp->dephd, worklist, wk_list);
2329 tp->pdephd = &tp->dephd;
2333 bip = g_alloc_bio();
2334 bip->bio_cmd = BIO_DELETE;
2335 bip->bio_offset = dbtob(fsbtodb(fs, bno));
2336 bip->bio_done = ffs_blkfree_trim_completed;
2337 bip->bio_length = size;
2338 bip->bio_caller2 = tp;
2341 vn_start_secondary_write(NULL, &mp, 0);
2342 g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2347 * Verify allocation of a block or fragment. Returns true if block or
2348 * fragment is allocated, false if it is free.
2351 ffs_checkblk(ip, bno, size)
2360 int i, error, frags, free;
2364 if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2365 printf("bsize = %ld, size = %ld, fs = %s\n",
2366 (long)fs->fs_bsize, size, fs->fs_fsmnt);
2367 panic("ffs_checkblk: bad size");
2369 if ((u_int)bno >= fs->fs_size)
2370 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2371 error = ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), &bp, &cgp);
2373 panic("ffs_checkblk: cylinder group read failed");
2374 blksfree = cg_blksfree(cgp);
2375 cgbno = dtogd(fs, bno);
2376 if (size == fs->fs_bsize) {
2377 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2379 frags = numfrags(fs, size);
2380 for (free = 0, i = 0; i < frags; i++)
2381 if (isset(blksfree, cgbno + i))
2383 if (free != 0 && free != frags)
2384 panic("ffs_checkblk: partially free fragment");
2389 #endif /* INVARIANTS */
2395 ffs_vfree(pvp, ino, mode)
2400 struct ufsmount *ump;
2403 if (DOINGSOFTDEP(pvp)) {
2404 softdep_freefile(pvp, ino, mode);
2408 ump = VFSTOUFS(pvp->v_mount);
2409 return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2413 * Do the actual free operation.
2414 * The specified inode is placed back in the free map.
2417 ffs_freefile(ump, fs, devvp, ino, mode, wkhd)
2418 struct ufsmount *ump;
2420 struct vnode *devvp;
2423 struct workhead *wkhd;
2433 cg = ino_to_cg(fs, ino);
2434 if (devvp->v_type == VREG) {
2435 /* devvp is a snapshot */
2436 MPASS(devvp->v_mount->mnt_data == ump);
2437 dev = ump->um_devvp->v_rdev;
2438 cgbno = fragstoblks(fs, cgtod(fs, cg));
2439 } else if (devvp->v_type == VCHR) {
2440 /* devvp is a normal disk device */
2441 dev = devvp->v_rdev;
2442 cgbno = fsbtodb(fs, cgtod(fs, cg));
2447 if (ino >= fs->fs_ipg * fs->fs_ncg)
2448 panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2449 devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2450 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2452 inosused = cg_inosused(cgp);
2454 if (isclr(inosused, ino)) {
2455 printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
2456 (uintmax_t)(ino + cg * fs->fs_ipg), fs->fs_fsmnt);
2457 if (fs->fs_ronly == 0)
2458 panic("ffs_freefile: freeing free inode");
2460 clrbit(inosused, ino);
2461 if (ino < cgp->cg_irotor)
2462 cgp->cg_irotor = ino;
2463 cgp->cg_cs.cs_nifree++;
2465 fs->fs_cstotal.cs_nifree++;
2466 fs->fs_cs(fs, cg).cs_nifree++;
2467 if ((mode & IFMT) == IFDIR) {
2468 cgp->cg_cs.cs_ndir--;
2469 fs->fs_cstotal.cs_ndir--;
2470 fs->fs_cs(fs, cg).cs_ndir--;
2473 ACTIVECLEAR(fs, cg);
2475 if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2476 softdep_setup_inofree(UFSTOVFS(ump), bp,
2477 ino + cg * fs->fs_ipg, wkhd);
2483 * Check to see if a file is free.
2484 * Used to check for allocated files in snapshots.
2487 ffs_checkfreefile(fs, devvp, ino)
2489 struct vnode *devvp;
2499 cg = ino_to_cg(fs, ino);
2500 if (devvp->v_type == VREG) {
2501 /* devvp is a snapshot */
2502 cgbno = fragstoblks(fs, cgtod(fs, cg));
2503 } else if (devvp->v_type == VCHR) {
2504 /* devvp is a normal disk device */
2505 cgbno = fsbtodb(fs, cgtod(fs, cg));
2509 if (ino >= fs->fs_ipg * fs->fs_ncg)
2511 if ((error = ffs_getcg(fs, devvp, cg, &bp, &cgp)) != 0)
2513 inosused = cg_inosused(cgp);
2515 ret = isclr(inosused, ino);
2521 * Find a block of the specified size in the specified cylinder group.
2523 * It is a panic if a request is made to find a block if none are
2527 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2534 int start, len, loc, i;
2535 int blk, field, subfield, pos;
2539 * find the fragment by searching through the free block
2540 * map for an appropriate bit pattern
2543 start = dtogd(fs, bpref) / NBBY;
2545 start = cgp->cg_frotor / NBBY;
2546 blksfree = cg_blksfree(cgp);
2547 len = howmany(fs->fs_fpg, NBBY) - start;
2548 loc = scanc((u_int)len, (u_char *)&blksfree[start],
2549 fragtbl[fs->fs_frag],
2550 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2554 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2555 fragtbl[fs->fs_frag],
2556 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2558 printf("start = %d, len = %d, fs = %s\n",
2559 start, len, fs->fs_fsmnt);
2560 panic("ffs_alloccg: map corrupted");
2564 bno = (start + len - loc) * NBBY;
2565 cgp->cg_frotor = bno;
2567 * found the byte in the map
2568 * sift through the bits to find the selected frag
2570 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2571 blk = blkmap(fs, blksfree, bno);
2573 field = around[allocsiz];
2574 subfield = inside[allocsiz];
2575 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2576 if ((blk & field) == subfield)
2582 printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2583 panic("ffs_alloccg: block not in map");
2588 * Fetch and verify a cylinder group.
2591 ffs_getcg(fs, devvp, cg, bpp, cgpp)
2593 struct vnode *devvp;
2605 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
2607 error = breadn_flags(devvp, devvp->v_type == VREG ?
2608 fragstoblks(fs, cgtod(fs, cg)) : fsbtodb(fs, cgtod(fs, cg)),
2609 (int)fs->fs_cgsize, NULL, NULL, 0, NOCRED, flags,
2610 ffs_ckhash_cg, &bp);
2613 cgp = (struct cg *)bp->b_data;
2614 if (((fs->fs_metackhash & CK_CYLGRP) != 0 &&
2615 (bp->b_flags & B_CKHASH) != 0 &&
2616 cgp->cg_ckhash != bp->b_ckhash) ||
2617 !cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
2618 printf("checksum failed: cg %u, cgp: 0x%x != bp: 0x%lx\n",
2619 cg, cgp->cg_ckhash, bp->b_ckhash);
2620 bp->b_flags &= ~B_CKHASH;
2621 bp->b_flags |= B_INVAL | B_NOCACHE;
2625 bp->b_flags &= ~B_CKHASH;
2626 bp->b_xflags |= BX_BKGRDWRITE;
2627 if ((fs->fs_metackhash & CK_CYLGRP) != 0)
2628 bp->b_xflags |= BX_CYLGRP;
2629 cgp->cg_old_time = cgp->cg_time = time_second;
2642 cgp = (struct cg *)bp->b_data;
2643 ckhash = cgp->cg_ckhash;
2645 bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
2646 cgp->cg_ckhash = ckhash;
2650 * Fserr prints the name of a filesystem with an error diagnostic.
2652 * The form of the error message is:
2656 ffs_fserr(fs, inum, cp)
2661 struct thread *td = curthread; /* XXX */
2662 struct proc *p = td->td_proc;
2664 log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
2665 p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
2670 * This function provides the capability for the fsck program to
2671 * update an active filesystem. Fourteen operations are provided:
2673 * adjrefcnt(inode, amt) - adjusts the reference count on the
2674 * specified inode by the specified amount. Under normal
2675 * operation the count should always go down. Decrementing
2676 * the count to zero will cause the inode to be freed.
2677 * adjblkcnt(inode, amt) - adjust the number of blocks used by the
2678 * inode by the specified amount.
2679 * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2680 * adjust the superblock summary.
2681 * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2682 * are marked as free. Inodes should never have to be marked
2684 * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2685 * are marked as free. Inodes should never have to be marked
2687 * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2688 * are marked as free. Blocks should never have to be marked
2690 * setflags(flags, set/clear) - the fs_flags field has the specified
2691 * flags set (second parameter +1) or cleared (second parameter -1).
2692 * setcwd(dirinode) - set the current directory to dirinode in the
2693 * filesystem associated with the snapshot.
2694 * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
2695 * in the current directory is oldvalue then change it to newvalue.
2696 * unlink(nameptr, oldvalue) - Verify that the inode number associated
2697 * with nameptr in the current directory is oldvalue then unlink it.
2699 * The following functions may only be used on a quiescent filesystem
2700 * by the soft updates journal. They are not safe to be run on an active
2703 * setinode(inode, dip) - the specified disk inode is replaced with the
2704 * contents pointed to by dip.
2705 * setbufoutput(fd, flags) - output associated with the specified file
2706 * descriptor (which must reference the character device supporting
2707 * the filesystem) switches from using physio to running through the
2708 * buffer cache when flags is set to 1. The descriptor reverts to
2709 * physio for output when flags is set to zero.
2712 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2714 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2715 0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2717 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2718 sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2720 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2721 sysctl_ffs_fsck, "Adjust number of directories");
2723 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2724 sysctl_ffs_fsck, "Adjust number of free blocks");
2726 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2727 sysctl_ffs_fsck, "Adjust number of free inodes");
2729 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2730 sysctl_ffs_fsck, "Adjust number of free frags");
2732 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2733 sysctl_ffs_fsck, "Adjust number of free clusters");
2735 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2736 sysctl_ffs_fsck, "Free Range of Directory Inodes");
2738 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2739 sysctl_ffs_fsck, "Free Range of File Inodes");
2741 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2742 sysctl_ffs_fsck, "Free Range of Blocks");
2744 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2745 sysctl_ffs_fsck, "Change Filesystem Flags");
2747 static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd, CTLFLAG_WR,
2748 sysctl_ffs_fsck, "Set Current Working Directory");
2750 static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot, CTLFLAG_WR,
2751 sysctl_ffs_fsck, "Change Value of .. Entry");
2753 static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink, CTLFLAG_WR,
2754 sysctl_ffs_fsck, "Unlink a Duplicate Name");
2756 static SYSCTL_NODE(_vfs_ffs, FFS_SET_INODE, setinode, CTLFLAG_WR,
2757 sysctl_ffs_fsck, "Update an On-Disk Inode");
2759 static SYSCTL_NODE(_vfs_ffs, FFS_SET_BUFOUTPUT, setbufoutput, CTLFLAG_WR,
2760 sysctl_ffs_fsck, "Set Buffered Writing for Descriptor");
2764 static int fsckcmds = 0;
2765 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2768 static int buffered_write(struct file *, struct uio *, struct ucred *,
2769 int, struct thread *);
2772 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2774 struct thread *td = curthread;
2775 struct fsck_cmd cmd;
2776 struct ufsmount *ump;
2777 struct vnode *vp, *dvp, *fdvp;
2778 struct inode *ip, *dp;
2782 long blkcnt, blksize;
2783 struct file *fp, *vfp;
2784 cap_rights_t rights;
2785 int filetype, error;
2786 static struct fileops *origops, bufferedops;
2788 if (req->newlen > sizeof cmd)
2790 if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2792 if (cmd.version != FFS_CMD_VERSION)
2793 return (ERPCMISMATCH);
2794 if ((error = getvnode(td, cmd.handle,
2795 cap_rights_init(&rights, CAP_FSCK), &fp)) != 0)
2798 if (vp->v_type != VREG && vp->v_type != VDIR) {
2802 vn_start_write(vp, &mp, V_WAIT);
2804 strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2805 vn_finished_write(mp);
2810 if ((mp->mnt_flag & MNT_RDONLY) &&
2811 ump->um_fsckpid != td->td_proc->p_pid) {
2812 vn_finished_write(mp);
2819 switch (oidp->oid_number) {
2824 printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2825 cmd.size > 0 ? "set" : "clear");
2828 fs->fs_flags |= (long)cmd.value;
2830 fs->fs_flags &= ~(long)cmd.value;
2833 case FFS_ADJ_REFCNT:
2836 printf("%s: adjust inode %jd link count by %jd\n",
2837 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2838 (intmax_t)cmd.size);
2841 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2844 ip->i_nlink += cmd.size;
2845 DIP_SET(ip, i_nlink, ip->i_nlink);
2846 ip->i_effnlink += cmd.size;
2847 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2848 error = ffs_update(vp, 1);
2849 if (DOINGSOFTDEP(vp))
2850 softdep_change_linkcnt(ip);
2854 case FFS_ADJ_BLKCNT:
2857 printf("%s: adjust inode %jd block count by %jd\n",
2858 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2859 (intmax_t)cmd.size);
2862 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2865 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2866 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
2867 error = ffs_update(vp, 1);
2879 printf("%s: free %s inode %ju\n",
2880 mp->mnt_stat.f_mntonname,
2881 filetype == IFDIR ? "directory" : "file",
2882 (uintmax_t)cmd.value);
2884 printf("%s: free %s inodes %ju-%ju\n",
2885 mp->mnt_stat.f_mntonname,
2886 filetype == IFDIR ? "directory" : "file",
2887 (uintmax_t)cmd.value,
2888 (uintmax_t)(cmd.value + cmd.size - 1));
2891 while (cmd.size > 0) {
2892 if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2893 cmd.value, filetype, NULL)))
2904 printf("%s: free block %jd\n",
2905 mp->mnt_stat.f_mntonname,
2906 (intmax_t)cmd.value);
2908 printf("%s: free blocks %jd-%jd\n",
2909 mp->mnt_stat.f_mntonname,
2910 (intmax_t)cmd.value,
2911 (intmax_t)cmd.value + cmd.size - 1);
2916 blksize = fs->fs_frag - (blkno % fs->fs_frag);
2917 while (blkcnt > 0) {
2918 if (blksize > blkcnt)
2920 ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2921 blksize * fs->fs_fsize, UFS_ROOTINO, VDIR, NULL);
2924 blksize = fs->fs_frag;
2929 * Adjust superblock summaries. fsck(8) is expected to
2930 * submit deltas when necessary.
2935 printf("%s: adjust number of directories by %jd\n",
2936 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2939 fs->fs_cstotal.cs_ndir += cmd.value;
2942 case FFS_ADJ_NBFREE:
2945 printf("%s: adjust number of free blocks by %+jd\n",
2946 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2949 fs->fs_cstotal.cs_nbfree += cmd.value;
2952 case FFS_ADJ_NIFREE:
2955 printf("%s: adjust number of free inodes by %+jd\n",
2956 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2959 fs->fs_cstotal.cs_nifree += cmd.value;
2962 case FFS_ADJ_NFFREE:
2965 printf("%s: adjust number of free frags by %+jd\n",
2966 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2969 fs->fs_cstotal.cs_nffree += cmd.value;
2972 case FFS_ADJ_NUMCLUSTERS:
2975 printf("%s: adjust number of free clusters by %+jd\n",
2976 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2979 fs->fs_cstotal.cs_numclusters += cmd.value;
2985 printf("%s: set current directory to inode %jd\n",
2986 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2989 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
2991 AUDIT_ARG_VNODE1(vp);
2992 if ((error = change_dir(vp, td)) != 0) {
3000 case FFS_SET_DOTDOT:
3003 printf("%s: change .. in cwd from %jd to %jd\n",
3004 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3005 (intmax_t)cmd.size);
3009 * First we have to get and lock the parent directory
3010 * to which ".." points.
3012 error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3016 * Now we get and lock the child directory containing "..".
3018 FILEDESC_SLOCK(td->td_proc->p_fd);
3019 dvp = td->td_proc->p_fd->fd_cdir;
3020 FILEDESC_SUNLOCK(td->td_proc->p_fd);
3021 if ((error = vget(dvp, LK_EXCLUSIVE, td)) != 0) {
3026 dp->i_offset = 12; /* XXX mastertemplate.dot_reclen */
3027 error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3040 if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3041 strncpy(buf, "Name_too_long", 32);
3042 printf("%s: unlink %s (inode %jd)\n",
3043 mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3047 * kern_unlinkat will do its own start/finish writes and
3048 * they do not nest, so drop ours here. Setting mp == NULL
3049 * indicates that vn_finished_write is not needed down below.
3051 vn_finished_write(mp);
3053 error = kern_unlinkat(td, AT_FDCWD, (char *)(intptr_t)cmd.value,
3054 UIO_USERSPACE, (ino_t)cmd.size);
3058 if (ump->um_fsckpid != td->td_proc->p_pid) {
3064 printf("%s: update inode %jd\n",
3065 mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3068 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3070 AUDIT_ARG_VNODE1(vp);
3073 error = copyin((void *)(intptr_t)cmd.size, ip->i_din1,
3074 sizeof(struct ufs1_dinode));
3076 error = copyin((void *)(intptr_t)cmd.size, ip->i_din2,
3077 sizeof(struct ufs2_dinode));
3082 ip->i_flag |= IN_CHANGE | IN_MODIFIED;
3083 error = ffs_update(vp, 1);
3087 case FFS_SET_BUFOUTPUT:
3088 if (ump->um_fsckpid != td->td_proc->p_pid) {
3092 if (ITOUMP(VTOI(vp)) != ump) {
3098 printf("%s: %s buffered output for descriptor %jd\n",
3099 mp->mnt_stat.f_mntonname,
3100 cmd.size == 1 ? "enable" : "disable",
3101 (intmax_t)cmd.value);
3104 if ((error = getvnode(td, cmd.value,
3105 cap_rights_init(&rights, CAP_FSCK), &vfp)) != 0)
3107 if (vfp->f_vnode->v_type != VCHR) {
3112 if (origops == NULL) {
3113 origops = vfp->f_ops;
3114 bcopy((void *)origops, (void *)&bufferedops,
3115 sizeof(bufferedops));
3116 bufferedops.fo_write = buffered_write;
3119 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3120 (uintptr_t)&bufferedops);
3122 atomic_store_rel_ptr((volatile uintptr_t *)&vfp->f_ops,
3123 (uintptr_t)origops);
3130 printf("Invalid request %d from fsck\n",
3139 vn_finished_write(mp);
3144 * Function to switch a descriptor to use the buffer cache to stage
3145 * its I/O. This is needed so that writes to the filesystem device
3146 * will give snapshots a chance to copy modified blocks for which it
3147 * needs to retain copies.
3150 buffered_write(fp, uio, active_cred, flags, td)
3153 struct ucred *active_cred;
3157 struct vnode *devvp, *vp;
3161 struct filedesc *fdp;
3166 * The devvp is associated with the /dev filesystem. To discover
3167 * the filesystem with which the device is associated, we depend
3168 * on the application setting the current directory to a location
3169 * within the filesystem being written. Yes, this is an ugly hack.
3171 devvp = fp->f_vnode;
3172 if (!vn_isdisk(devvp, NULL))
3174 fdp = td->td_proc->p_fd;
3175 FILEDESC_SLOCK(fdp);
3178 FILEDESC_SUNLOCK(fdp);
3179 vn_lock(vp, LK_SHARED | LK_RETRY);
3181 * Check that the current directory vnode indeed belongs to
3182 * UFS before trying to dereference UFS-specific v_data fields.
3184 if (vp->v_op != &ffs_vnodeops1 && vp->v_op != &ffs_vnodeops2) {
3189 if (ITODEVVP(ip) != devvp) {
3195 foffset_lock_uio(fp, uio, flags);
3196 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
3199 printf("%s: buffered write for block %jd\n",
3200 fs->fs_fsmnt, (intmax_t)btodb(uio->uio_offset));
3204 * All I/O must be contained within a filesystem block, start on
3205 * a fragment boundary, and be a multiple of fragments in length.
3207 if (uio->uio_resid > fs->fs_bsize - (uio->uio_offset % fs->fs_bsize) ||
3208 fragoff(fs, uio->uio_offset) != 0 ||
3209 fragoff(fs, uio->uio_resid) != 0) {
3213 lbn = numfrags(fs, uio->uio_offset);
3214 bp = getblk(devvp, lbn, uio->uio_resid, 0, 0, 0);
3215 bp->b_flags |= B_RELBUF;
3216 if ((error = uiomove((char *)bp->b_data, uio->uio_resid, uio)) != 0) {
3222 VOP_UNLOCK(devvp, 0);
3223 foffset_unlock_uio(fp, uio, flags | FOF_NEXTOFF);