2 * modified for Lites 1.1
4 * Aug 1995, Godmar Back (gback@cs.utah.edu)
5 * University of Utah, Department of Computer Science
8 * SPDX-License-Identifier: BSD-3-Clause
10 * Copyright (c) 1982, 1986, 1989, 1993
11 * The Regents of the University of California. All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)ffs_alloc.c 8.8 (Berkeley) 2/21/94
41 #include <sys/param.h>
42 #include <sys/systm.h>
44 #include <sys/vnode.h>
46 #include <sys/mount.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
50 #include <sys/endian.h>
52 #include <fs/ext2fs/fs.h>
53 #include <fs/ext2fs/inode.h>
54 #include <fs/ext2fs/ext2_mount.h>
55 #include <fs/ext2fs/ext2fs.h>
56 #include <fs/ext2fs/ext2_extern.h>
58 static daddr_t ext2_alloccg(struct inode *, int, daddr_t, int);
59 static daddr_t ext2_clusteralloc(struct inode *, int, daddr_t, int);
60 static u_long ext2_dirpref(struct inode *);
61 static e4fs_daddr_t ext2_hashalloc(struct inode *, int, long, int,
62 daddr_t (*)(struct inode *, int, daddr_t,
64 static daddr_t ext2_nodealloccg(struct inode *, int, daddr_t, int);
65 static daddr_t ext2_mapsearch(struct m_ext2fs *, char *, daddr_t);
68 * Allocate a block in the filesystem.
70 * A preference may be optionally specified. If a preference is given
71 * the following hierarchy is used to allocate a block:
72 * 1) allocate the requested block.
73 * 2) allocate a rotationally optimal block in the same cylinder.
74 * 3) allocate a block in the same cylinder group.
75 * 4) quadradically rehash into other cylinder groups, until an
76 * available block is located.
77 * If no block preference is given the following hierarchy is used
78 * to allocate a block:
79 * 1) allocate a block in the cylinder group that contains the
81 * 2) quadradically rehash into other cylinder groups, until an
82 * available block is located.
85 ext2_alloc(struct inode *ip, daddr_t lbn, e4fs_daddr_t bpref, int size,
86 struct ucred *cred, e4fs_daddr_t *bnp)
89 struct ext2mount *ump;
96 mtx_assert(EXT2_MTX(ump), MA_OWNED);
98 if ((u_int)size > fs->e2fs_bsize || blkoff(fs, size) != 0) {
99 vn_printf(ip->i_devvp, "bsize = %lu, size = %d, fs = %s\n",
100 (long unsigned int)fs->e2fs_bsize, size, fs->e2fs_fsmnt);
101 panic("ext2_alloc: bad size");
104 panic("ext2_alloc: missing credential");
105 #endif /* INVARIANTS */
106 if (size == fs->e2fs_bsize && fs->e2fs_fbcount == 0)
108 if (cred->cr_uid != 0 &&
109 fs->e2fs_fbcount < fs->e2fs_rbcount)
111 if (bpref >= fs->e2fs_bcount)
114 cg = ino_to_cg(fs, ip->i_number);
116 cg = dtog(fs, bpref);
117 bno = (daddr_t)ext2_hashalloc(ip, cg, bpref, fs->e2fs_bsize,
120 /* set next_alloc fields as done in block_getblk */
121 ip->i_next_alloc_block = lbn;
122 ip->i_next_alloc_goal = bno;
124 ip->i_blocks += btodb(fs->e2fs_bsize);
125 ip->i_flag |= IN_CHANGE | IN_UPDATE;
131 ext2_fserr(fs, cred->cr_uid, "filesystem full");
132 uprintf("\n%s: write failed, filesystem is full\n", fs->e2fs_fsmnt);
137 * Allocate EA's block for inode.
140 ext2_alloc_meta(struct inode *ip)
147 EXT2_LOCK(ip->i_ump);
148 blk = ext2_hashalloc(ip, ino_to_cg(fs, ip->i_number), 0, fs->e2fs_bsize,
151 EXT2_UNLOCK(ip->i_ump);
157 * Reallocate a sequence of blocks into a contiguous sequence of blocks.
159 * The vnode and an array of buffer pointers for a range of sequential
160 * logical blocks to be made contiguous is given. The allocator attempts
161 * to find a range of sequential blocks starting as close as possible to
162 * an fs_rotdelay offset from the end of the allocation for the logical
163 * block immediately preceding the current range. If successful, the
164 * physical block numbers in the buffer pointers and in the inode are
165 * changed to reflect the new allocation. If unsuccessful, the allocation
166 * is left unchanged. The success in doing the reallocation is returned.
167 * Note that the error return is not reflected back to the user. Rather
168 * the previous block allocation will be used.
171 static SYSCTL_NODE(_vfs, OID_AUTO, ext2fs, CTLFLAG_RW, 0, "EXT2FS filesystem");
173 static int doasyncfree = 1;
175 SYSCTL_INT(_vfs_ext2fs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
176 "Use asychronous writes to update block pointers when freeing blocks");
178 static int doreallocblks = 0;
180 SYSCTL_INT(_vfs_ext2fs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
183 ext2_reallocblks(struct vop_reallocblks_args *ap)
188 struct buf *sbp, *ebp;
189 uint32_t *bap, *sbap, *ebap;
190 struct ext2mount *ump;
191 struct cluster_save *buflist;
192 struct indir start_ap[EXT2_NIADDR + 1], end_ap[EXT2_NIADDR + 1], *idp;
193 e2fs_lbn_t start_lbn, end_lbn;
195 e2fs_daddr_t newblk, blkno;
196 int i, len, start_lvl, end_lvl, pref, ssize;
198 if (doreallocblks == 0)
206 if (fs->e2fs_contigsumsize <= 0 || ip->i_flag & IN_E4EXTENTS)
209 buflist = ap->a_buflist;
210 len = buflist->bs_nchildren;
211 start_lbn = buflist->bs_children[0]->b_lblkno;
212 end_lbn = start_lbn + len - 1;
214 for (i = 1; i < len; i++)
215 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
216 panic("ext2_reallocblks: non-cluster");
219 * If the cluster crosses the boundary for the first indirect
220 * block, leave space for the indirect block. Indirect blocks
221 * are initially laid out in a position after the last direct
222 * block. Block reallocation would usually destroy locality by
223 * moving the indirect block out of the way to make room for
224 * data blocks if we didn't compensate here. We should also do
225 * this for other indirect block boundaries, but it is only
226 * important for the first one.
228 if (start_lbn < EXT2_NDADDR && end_lbn >= EXT2_NDADDR)
231 * If the latest allocation is in a new cylinder group, assume that
232 * the filesystem has decided to move and do not force it back to
233 * the previous cylinder group.
235 if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
236 dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
238 if (ext2_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
239 ext2_getlbns(vp, end_lbn, end_ap, &end_lvl))
242 * Get the starting offset and block map for the first block.
244 if (start_lvl == 0) {
248 idp = &start_ap[start_lvl - 1];
249 if (bread(vp, idp->in_lbn, (int)fs->e2fs_bsize, NOCRED, &sbp)) {
253 sbap = (u_int *)sbp->b_data;
257 * If the block range spans two block maps, get the second map.
260 if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
264 if (start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
265 panic("ext2_reallocblks: start == end");
267 ssize = len - (idp->in_off + 1);
268 if (bread(vp, idp->in_lbn, (int)fs->e2fs_bsize, NOCRED, &ebp))
270 ebap = (u_int *)ebp->b_data;
273 * Find the preferred location for the cluster.
276 pref = ext2_blkpref(ip, start_lbn, soff, sbap, 0);
278 * Search the block map looking for an allocation of the desired size.
280 if ((newblk = (e2fs_daddr_t)ext2_hashalloc(ip, dtog(fs, pref), pref,
281 len, ext2_clusteralloc)) == 0) {
286 * We have found a new contiguous block.
288 * First we have to replace the old block pointers with the new
289 * block pointers in the inode and indirect blocks associated
293 printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
294 (uintmax_t)ip->i_number, (intmax_t)start_lbn, (intmax_t)end_lbn);
297 for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->e2fs_fpb) {
303 if (buflist->bs_children[i]->b_blkno != fsbtodb(fs, *bap))
304 panic("ext2_reallocblks: alloc mismatch");
307 printf(" %d,", *bap);
312 * Next we must write out the modified inode and indirect blocks.
313 * For strict correctness, the writes should be synchronous since
314 * the old block values may have been written to disk. In practise
315 * they are almost never written, but if we are concerned about
316 * strict correctness, the `doasyncfree' flag should be set to zero.
318 * The test on `doasyncfree' should be changed to test a flag
319 * that shows whether the associated buffers and inodes have
320 * been written. The flag should be set when the cluster is
321 * started and cleared whenever the buffer or inode is flushed.
322 * We can then check below to see if it is set, and do the
323 * synchronous write only when it has been cleared.
325 if (sbap != &ip->i_db[0]) {
331 ip->i_flag |= IN_CHANGE | IN_UPDATE;
342 * Last, free the old blocks and assign the new blocks to the buffers.
347 for (blkno = newblk, i = 0; i < len; i++, blkno += fs->e2fs_fpb) {
348 ext2_blkfree(ip, dbtofsb(fs, buflist->bs_children[i]->b_blkno),
350 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
352 printf(" %d,", blkno);
363 if (sbap != &ip->i_db[0])
369 * Allocate an inode in the filesystem.
373 ext2_valloc(struct vnode *pvp, int mode, struct ucred *cred, struct vnode **vpp)
379 struct ext2mount *ump;
389 if (fs->e2fs->e2fs_ficount == 0)
392 * If it is a directory then obtain a cylinder group based on
393 * ext2_dirpref else obtain it using ino_to_cg. The preferred inode is
394 * always the next inode.
396 if ((mode & IFMT) == IFDIR) {
397 cg = ext2_dirpref(pip);
398 if (fs->e2fs_contigdirs[cg] < 255)
399 fs->e2fs_contigdirs[cg]++;
401 cg = ino_to_cg(fs, pip->i_number);
402 if (fs->e2fs_contigdirs[cg] > 0)
403 fs->e2fs_contigdirs[cg]--;
405 ipref = cg * fs->e2fs->e2fs_ipg + 1;
406 ino = (ino_t)ext2_hashalloc(pip, cg, (long)ipref, mode, ext2_nodealloccg);
410 error = VFS_VGET(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
412 ext2_vfree(pvp, ino, mode);
418 * The question is whether using VGET was such good idea at all:
419 * Linux doesn't read the old inode in when it is allocating a
420 * new one. I will set at least i_size and i_blocks to zero.
427 if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_EXTENTS)
428 && (S_ISREG(mode) || S_ISDIR(mode)))
429 ext4_ext_tree_init(ip);
431 memset(ip->i_data, 0, sizeof(ip->i_data));
435 * Set up a new generation number for this inode.
439 ip->i_gen = arc4random();
440 } while (ip->i_gen == 0);
443 ip->i_birthtime = ts.tv_sec;
444 ip->i_birthnsec = ts.tv_nsec;
447 printf("ext2_valloc: allocated inode %d\n", ino);
452 ext2_fserr(fs, cred->cr_uid, "out of inodes");
453 uprintf("\n%s: create/symlink failed, no inodes free\n", fs->e2fs_fsmnt);
458 * 64-bit compatible getters and setters for struct ext2_gd from ext2fs.h
461 e2fs_gd_get_b_bitmap(struct ext2_gd *gd)
464 return (((uint64_t)(gd->ext4bgd_b_bitmap_hi) << 32) |
465 gd->ext2bgd_b_bitmap);
469 e2fs_gd_get_i_bitmap(struct ext2_gd *gd)
472 return (((uint64_t)(gd->ext4bgd_i_bitmap_hi) << 32) |
473 gd->ext2bgd_i_bitmap);
477 e2fs_gd_get_i_tables(struct ext2_gd *gd)
480 return (((uint64_t)(gd->ext4bgd_i_tables_hi) << 32) |
481 gd->ext2bgd_i_tables);
485 e2fs_gd_get_nbfree(struct ext2_gd *gd)
488 return (((uint32_t)(gd->ext4bgd_nbfree_hi) << 16) |
493 e2fs_gd_set_nbfree(struct ext2_gd *gd, uint32_t val)
496 gd->ext2bgd_nbfree = val & 0xffff;
497 gd->ext4bgd_nbfree_hi = val >> 16;
501 e2fs_gd_get_nifree(struct ext2_gd *gd)
504 return (((uint32_t)(gd->ext4bgd_nifree_hi) << 16) |
509 e2fs_gd_set_nifree(struct ext2_gd *gd, uint32_t val)
512 gd->ext2bgd_nifree = val & 0xffff;
513 gd->ext4bgd_nifree_hi = val >> 16;
517 e2fs_gd_get_ndirs(struct ext2_gd *gd)
520 return (((uint32_t)(gd->ext4bgd_ndirs_hi) << 16) |
525 e2fs_gd_set_ndirs(struct ext2_gd *gd, uint32_t val)
528 gd->ext2bgd_ndirs = val & 0xffff;
529 gd->ext4bgd_ndirs_hi = val >> 16;
533 e2fs_gd_get_i_unused(struct ext2_gd *gd)
535 return (((uint32_t)(gd->ext4bgd_i_unused_hi) << 16) |
536 gd->ext4bgd_i_unused);
540 e2fs_gd_set_i_unused(struct ext2_gd *gd, uint32_t val)
543 gd->ext4bgd_i_unused = val & 0xffff;
544 gd->ext4bgd_i_unused_hi = val >> 16;
548 * Find a cylinder to place a directory.
550 * The policy implemented by this algorithm is to allocate a
551 * directory inode in the same cylinder group as its parent
552 * directory, but also to reserve space for its files inodes
553 * and data. Restrict the number of directories which may be
554 * allocated one after another in the same cylinder group
555 * without intervening allocation of files.
557 * If we allocate a first level directory then force allocation
558 * in another cylinder group.
562 ext2_dirpref(struct inode *pip)
565 int cg, prefcg, cgsize;
566 uint64_t avgbfree, minbfree;
567 u_int avgifree, avgndir, curdirsize;
568 u_int minifree, maxndir;
569 u_int mincg, minndir;
570 u_int dirsize, maxcontigdirs;
572 mtx_assert(EXT2_MTX(pip->i_ump), MA_OWNED);
575 avgifree = fs->e2fs->e2fs_ficount / fs->e2fs_gcount;
576 avgbfree = fs->e2fs_fbcount / fs->e2fs_gcount;
577 avgndir = fs->e2fs_total_dir / fs->e2fs_gcount;
580 * Force allocation in another cg if creating a first level dir.
582 ASSERT_VOP_LOCKED(ITOV(pip), "ext2fs_dirpref");
583 if (ITOV(pip)->v_vflag & VV_ROOT) {
584 prefcg = arc4random() % fs->e2fs_gcount;
586 minndir = fs->e2fs_ipg;
587 for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
588 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
589 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
590 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
592 minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
594 for (cg = 0; cg < prefcg; cg++)
595 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
596 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
597 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
599 minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
604 * Count various limits which used for
605 * optimal allocation of a directory inode.
607 maxndir = min(avgndir + fs->e2fs_ipg / 16, fs->e2fs_ipg);
608 minifree = avgifree - avgifree / 4;
611 minbfree = avgbfree - avgbfree / 4;
614 cgsize = fs->e2fs_fsize * fs->e2fs_fpg;
615 dirsize = AVGDIRSIZE;
616 curdirsize = avgndir ? (cgsize - avgbfree * fs->e2fs_bsize) / avgndir : 0;
617 if (dirsize < curdirsize)
618 dirsize = curdirsize;
619 maxcontigdirs = min((avgbfree * fs->e2fs_bsize) / dirsize, 255);
620 maxcontigdirs = min(maxcontigdirs, fs->e2fs_ipg / AFPDIR);
621 if (maxcontigdirs == 0)
625 * Limit number of dirs in one cg and reserve space for
626 * regular files, but only if we have no deficit in
629 prefcg = ino_to_cg(fs, pip->i_number);
630 for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
631 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
632 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
633 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
634 if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
637 for (cg = 0; cg < prefcg; cg++)
638 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
639 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
640 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
641 if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
645 * This is a backstop when we have deficit in space.
647 for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
648 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
650 for (cg = 0; cg < prefcg; cg++)
651 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
657 * Select the desired position for the next block in a file.
659 * we try to mimic what Remy does in inode_getblk/block_getblk
661 * we note: blocknr == 0 means that we're about to allocate either
662 * a direct block or a pointer block at the first level of indirection
663 * (In other words, stuff that will go in i_db[] or i_ib[])
665 * blocknr != 0 means that we're allocating a block that is none
666 * of the above. Then, blocknr tells us the number of the block
667 * that will hold the pointer
670 ext2_blkpref(struct inode *ip, e2fs_lbn_t lbn, int indx, e2fs_daddr_t *bap,
671 e2fs_daddr_t blocknr)
678 mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
681 * If the next block is actually what we thought it is, then set the
682 * goal to what we thought it should be.
684 if (ip->i_next_alloc_block == lbn && ip->i_next_alloc_goal != 0)
685 return ip->i_next_alloc_goal;
688 * Now check whether we were provided with an array that basically
689 * tells us previous blocks to which we want to stay close.
692 for (tmp = indx - 1; tmp >= 0; tmp--)
697 * Else lets fall back to the blocknr or, if there is none, follow
698 * the rule that a block should be allocated near its inode.
700 return (blocknr ? blocknr :
701 (e2fs_daddr_t)(ip->i_block_group *
702 EXT2_BLOCKS_PER_GROUP(fs)) + fs->e2fs->e2fs_first_dblock);
706 * Implement the cylinder overflow algorithm.
708 * The policy implemented by this algorithm is:
709 * 1) allocate the block in its requested cylinder group.
710 * 2) quadradically rehash on the cylinder group number.
711 * 3) brute force search for a free block.
714 ext2_hashalloc(struct inode *ip, int cg, long pref, int size,
715 daddr_t (*allocator) (struct inode *, int, daddr_t, int))
721 mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
724 * 1: preferred cylinder group
726 result = (*allocator)(ip, cg, pref, size);
730 * 2: quadratic rehash
732 for (i = 1; i < fs->e2fs_gcount; i *= 2) {
734 if (cg >= fs->e2fs_gcount)
735 cg -= fs->e2fs_gcount;
736 result = (*allocator)(ip, cg, 0, size);
741 * 3: brute force search
742 * Note that we start at i == 2, since 0 was checked initially,
743 * and 1 is always checked in the quadratic rehash.
745 cg = (icg + 2) % fs->e2fs_gcount;
746 for (i = 2; i < fs->e2fs_gcount; i++) {
747 result = (*allocator)(ip, cg, 0, size);
751 if (cg == fs->e2fs_gcount)
758 ext2_cg_number_gdb_nometa(struct m_ext2fs *fs, int cg)
761 if (!ext2_cg_has_sb(fs, cg))
764 if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG))
765 return (fs->e2fs->e3fs_first_meta_bg);
767 return ((fs->e2fs_gcount + EXT2_DESCS_PER_BLOCK(fs) - 1) /
768 EXT2_DESCS_PER_BLOCK(fs));
772 ext2_cg_number_gdb_meta(struct m_ext2fs *fs, int cg)
774 unsigned long metagroup;
777 metagroup = cg / EXT2_DESCS_PER_BLOCK(fs);
778 first = metagroup * EXT2_DESCS_PER_BLOCK(fs);
779 last = first + EXT2_DESCS_PER_BLOCK(fs) - 1;
781 if (cg == first || cg == first + 1 || cg == last)
788 ext2_cg_number_gdb(struct m_ext2fs *fs, int cg)
790 unsigned long first_meta_bg, metagroup;
792 first_meta_bg = fs->e2fs->e3fs_first_meta_bg;
793 metagroup = cg / EXT2_DESCS_PER_BLOCK(fs);
795 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
796 metagroup < first_meta_bg)
797 return (ext2_cg_number_gdb_nometa(fs, cg));
799 return ext2_cg_number_gdb_meta(fs, cg);
803 ext2_number_base_meta_blocks(struct m_ext2fs *fs, int cg)
807 number = ext2_cg_has_sb(fs, cg);
809 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
810 cg < fs->e2fs->e3fs_first_meta_bg * EXT2_DESCS_PER_BLOCK(fs)) {
812 number += ext2_cg_number_gdb(fs, cg);
813 number += fs->e2fs->e2fs_reserved_ngdb;
816 number += ext2_cg_number_gdb(fs, cg);
823 ext2_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
827 if (start_bit >= end_bit)
830 for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
833 memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
837 ext2_get_group_number(struct m_ext2fs *fs, e4fs_daddr_t block)
840 return ((block - fs->e2fs->e2fs_first_dblock) / fs->e2fs_bsize);
844 ext2_block_in_group(struct m_ext2fs *fs, e4fs_daddr_t block, int cg)
847 return ((ext2_get_group_number(fs, block) == cg) ? 1 : 0);
851 ext2_cg_block_bitmap_init(struct m_ext2fs *fs, int cg, struct buf *bp)
853 int bit, bit_max, inodes_per_block;
856 if (!(fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_BLOCK_UNINIT))
859 memset(bp->b_data, 0, fs->e2fs_bsize);
861 bit_max = ext2_number_base_meta_blocks(fs, cg);
862 if ((bit_max >> 3) >= fs->e2fs_bsize)
865 for (bit = 0; bit < bit_max; bit++)
866 setbit(bp->b_data, bit);
868 start = (uint64_t)cg * fs->e2fs->e2fs_bpg + fs->e2fs->e2fs_first_dblock;
870 /* Set bits for block and inode bitmaps, and inode table. */
871 tmp = e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg]);
872 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
873 ext2_block_in_group(fs, tmp, cg))
874 setbit(bp->b_data, tmp - start);
876 tmp = e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg]);
877 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
878 ext2_block_in_group(fs, tmp, cg))
879 setbit(bp->b_data, tmp - start);
881 tmp = e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]);
882 inodes_per_block = fs->e2fs_bsize/EXT2_INODE_SIZE(fs);
883 while( tmp < e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) +
884 fs->e2fs->e2fs_ipg / inodes_per_block ) {
885 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
886 ext2_block_in_group(fs, tmp, cg))
887 setbit(bp->b_data, tmp - start);
892 * Also if the number of blocks within the group is less than
893 * the blocksize * 8 ( which is the size of bitmap ), set rest
894 * of the block bitmap to 1
896 ext2_mark_bitmap_end(fs->e2fs->e2fs_bpg, fs->e2fs_bsize * 8,
900 fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_BLOCK_UNINIT;
906 ext2_b_bitmap_validate(struct m_ext2fs *fs, struct buf *bp, int cg)
909 uint64_t group_first_block;
910 unsigned int offset, max_bit;
912 if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG)) {
914 * It is not possible to check block bitmap in case of this feature,
915 * because the inode and block bitmaps and inode table
916 * blocks may not be in the group at all.
917 * So, skip check in this case.
922 gd = &fs->e2fs_gd[cg];
923 max_bit = fs->e2fs_fpg;
924 group_first_block = ((uint64_t)cg) * fs->e2fs->e2fs_fpg +
925 fs->e2fs->e2fs_first_dblock;
927 /* Check block bitmap block number */
928 offset = e2fs_gd_get_b_bitmap(gd) - group_first_block;
929 if (offset >= max_bit || !isset(bp->b_data, offset)) {
930 printf("ext2fs: bad block bitmap, group %d\n", cg);
934 /* Check inode bitmap block number */
935 offset = e2fs_gd_get_i_bitmap(gd) - group_first_block;
936 if (offset >= max_bit || !isset(bp->b_data, offset)) {
937 printf("ext2fs: bad inode bitmap, group %d\n", cg);
941 /* Check inode table */
942 offset = e2fs_gd_get_i_tables(gd) - group_first_block;
943 if (offset >= max_bit || offset + fs->e2fs_itpg >= max_bit) {
944 printf("ext2fs: bad inode table, group %d\n", cg);
952 * Determine whether a block can be allocated.
954 * Check to see if a block of the appropriate size is available,
955 * and if it is, allocate it.
958 ext2_alloccg(struct inode *ip, int cg, daddr_t bpref, int size)
962 struct ext2mount *ump;
963 daddr_t bno, runstart, runlen;
964 int bit, loc, end, error, start;
969 if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0)
973 error = bread(ip->i_devvp, fsbtodb(fs,
974 e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
975 (int)fs->e2fs_bsize, NOCRED, &bp);
979 if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
980 EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
981 error = ext2_cg_block_bitmap_init(fs, cg, bp);
985 ext2_gd_b_bitmap_csum_set(fs, cg, bp);
987 error = ext2_gd_b_bitmap_csum_verify(fs, cg, bp);
991 error = ext2_b_bitmap_validate(fs,bp, cg);
996 * Check, that another thread did not not allocate the last block in this
997 * group while we were waiting for the buffer.
999 if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0)
1002 bbp = (char *)bp->b_data;
1004 if (dtog(fs, bpref) != cg)
1007 bpref = dtogd(fs, bpref);
1009 * if the requested block is available, use it
1011 if (isclr(bbp, bpref)) {
1017 * no blocks in the requested cylinder, so take next
1018 * available one in this cylinder group.
1019 * first try to get 8 contigous blocks, then fall back to a single
1023 start = dtogd(fs, bpref) / NBBY;
1026 end = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
1030 for (loc = start; loc < end; loc++) {
1031 if (bbp[loc] == (char)0xff) {
1036 /* Start of a run, find the number of high clear bits. */
1038 bit = fls(bbp[loc]);
1039 runlen = NBBY - bit;
1040 runstart = loc * NBBY + bit;
1041 } else if (bbp[loc] == 0) {
1042 /* Continue a run. */
1046 * Finish the current run. If it isn't long
1047 * enough, start a new one.
1049 bit = ffs(bbp[loc]) - 1;
1056 /* Run was too short, start a new one. */
1057 bit = fls(bbp[loc]);
1058 runlen = NBBY - bit;
1059 runstart = loc * NBBY + bit;
1062 /* If the current run is long enough, use it. */
1073 bno = ext2_mapsearch(fs, bbp, bpref);
1079 if (isset(bbp, bno)) {
1080 printf("ext2fs_alloccgblk: cg=%d bno=%jd fs=%s\n",
1081 cg, (intmax_t)bno, fs->e2fs_fsmnt);
1082 panic("ext2fs_alloccg: dup alloc");
1087 ext2_clusteracct(fs, bbp, cg, bno, -1);
1089 e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1090 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1093 ext2_gd_b_bitmap_csum_set(fs, cg, bp);
1095 return (((uint64_t)cg) * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1104 * Determine whether a cluster can be allocated.
1107 ext2_clusteralloc(struct inode *ip, int cg, daddr_t bpref, int len)
1109 struct m_ext2fs *fs;
1110 struct ext2mount *ump;
1113 int bit, error, got, i, loc, run;
1120 if (fs->e2fs_maxcluster[cg] < len)
1124 error = bread(ip->i_devvp,
1125 fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1126 (int)fs->e2fs_bsize, NOCRED, &bp);
1130 bbp = (char *)bp->b_data;
1133 * Check to see if a cluster of the needed size (or bigger) is
1134 * available in this cylinder group.
1136 lp = &fs->e2fs_clustersum[cg].cs_sum[len];
1137 for (i = len; i <= fs->e2fs_contigsumsize; i++)
1140 if (i > fs->e2fs_contigsumsize) {
1142 * Update the cluster summary information to reflect
1143 * the true maximum-sized cluster so that future cluster
1144 * allocation requests can avoid reading the bitmap only
1145 * to find no cluster.
1147 lp = &fs->e2fs_clustersum[cg].cs_sum[len - 1];
1148 for (i = len - 1; i > 0; i--)
1151 fs->e2fs_maxcluster[cg] = i;
1156 /* Search the bitmap to find a big enough cluster like in FFS. */
1157 if (dtog(fs, bpref) != cg)
1160 bpref = dtogd(fs, bpref);
1162 bit = 1 << (bpref % NBBY);
1163 for (run = 0, got = bpref; got < fs->e2fs->e2fs_fpg; got++) {
1164 if ((bbp[loc] & bit) != 0)
1171 if ((got & (NBBY - 1)) != (NBBY - 1))
1179 if (got >= fs->e2fs->e2fs_fpg)
1182 /* Allocate the cluster that we found. */
1183 for (i = 1; i < len; i++)
1184 if (!isclr(bbp, got - run + i))
1185 panic("ext2_clusteralloc: map mismatch");
1187 bno = got - run + 1;
1188 if (bno >= fs->e2fs->e2fs_fpg)
1189 panic("ext2_clusteralloc: allocated out of group");
1192 for (i = 0; i < len; i += fs->e2fs_fpb) {
1193 setbit(bbp, bno + i);
1194 ext2_clusteracct(fs, bbp, cg, bno + i, -1);
1196 e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1197 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1203 return (cg * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1213 ext2_zero_inode_table(struct inode *ip, int cg)
1215 struct m_ext2fs *fs;
1217 int i, all_blks, used_blks;
1221 if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_ZEROED)
1224 all_blks = fs->e2fs->e2fs_inode_size * fs->e2fs->e2fs_ipg /
1227 used_blks = howmany(fs->e2fs->e2fs_ipg -
1228 e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]),
1229 fs->e2fs_bsize / EXT2_INODE_SIZE(fs));
1231 for (i = 0; i < all_blks - used_blks; i++) {
1232 bp = getblk(ip->i_devvp, fsbtodb(fs,
1233 e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) + used_blks + i),
1234 fs->e2fs_bsize, 0, 0, 0);
1238 vfs_bio_bzero_buf(bp, 0, fs->e2fs_bsize);
1242 fs->e2fs_gd[cg].ext4bgd_flags |= EXT2_BG_INODE_ZEROED;
1248 * Determine whether an inode can be allocated.
1250 * Check to see if an inode is available, and if it is,
1251 * allocate it using tode in the specified cylinder group.
1254 ext2_nodealloccg(struct inode *ip, int cg, daddr_t ipref, int mode)
1256 struct m_ext2fs *fs;
1258 struct ext2mount *ump;
1259 int error, start, len, ifree;
1262 ipref--; /* to avoid a lot of (ipref -1) */
1267 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0)
1270 error = bread(ip->i_devvp, fsbtodb(fs,
1271 e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1272 (int)fs->e2fs_bsize, NOCRED, &bp);
1278 if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
1279 EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
1280 if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_UNINIT) {
1281 memset(bp->b_data, 0, fs->e2fs_bsize);
1282 fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_INODE_UNINIT;
1284 ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1285 error = ext2_zero_inode_table(ip, cg);
1292 error = ext2_gd_i_bitmap_csum_verify(fs, cg, bp);
1298 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0) {
1300 * Another thread allocated the last i-node in this
1301 * group while we were waiting for the buffer.
1307 ibp = (char *)bp->b_data;
1309 ipref %= fs->e2fs->e2fs_ipg;
1310 if (isclr(ibp, ipref))
1313 start = ipref / NBBY;
1314 len = howmany(fs->e2fs->e2fs_ipg - ipref, NBBY);
1315 loc = memcchr(&ibp[start], 0xff, len);
1319 loc = memcchr(&ibp[start], 0xff, len);
1321 printf("cg = %d, ipref = %lld, fs = %s\n",
1322 cg, (long long)ipref, fs->e2fs_fsmnt);
1323 panic("ext2fs_nodealloccg: map corrupted");
1327 ipref = (loc - ibp) * NBBY + ffs(~*loc) - 1;
1331 e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1332 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) - 1);
1333 if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
1334 EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
1335 ifree = fs->e2fs->e2fs_ipg - e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]);
1336 if (ipref + 1 > ifree)
1337 e2fs_gd_set_i_unused(&fs->e2fs_gd[cg],
1338 fs->e2fs->e2fs_ipg - (ipref + 1));
1340 fs->e2fs->e2fs_ficount--;
1342 if ((mode & IFMT) == IFDIR) {
1343 e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1344 e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) + 1);
1345 fs->e2fs_total_dir++;
1348 ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1350 return ((uint64_t)cg * fs->e2fs_ipg + ipref + 1);
1354 * Free a block or fragment.
1358 ext2_blkfree(struct inode *ip, e4fs_daddr_t bno, long size)
1360 struct m_ext2fs *fs;
1362 struct ext2mount *ump;
1369 if (bno >= fs->e2fs_bcount) {
1370 printf("bad block %lld, ino %ju\n", (long long)bno,
1371 (uintmax_t)ip->i_number);
1372 ext2_fserr(fs, ip->i_uid, "bad block");
1375 error = bread(ip->i_devvp,
1376 fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1377 (int)fs->e2fs_bsize, NOCRED, &bp);
1382 bbp = (char *)bp->b_data;
1383 bno = dtogd(fs, bno);
1384 if (isclr(bbp, bno)) {
1385 printf("block = %lld, fs = %s\n",
1386 (long long)bno, fs->e2fs_fsmnt);
1387 panic("ext2_blkfree: freeing free block");
1391 ext2_clusteracct(fs, bbp, cg, bno, 1);
1393 e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1394 e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) + 1);
1397 ext2_gd_b_bitmap_csum_set(fs, cg, bp);
1406 ext2_vfree(struct vnode *pvp, ino_t ino, int mode)
1408 struct m_ext2fs *fs;
1411 struct ext2mount *ump;
1418 if ((u_int)ino > fs->e2fs_ipg * fs->e2fs_gcount)
1419 panic("ext2_vfree: range: devvp = %p, ino = %ju, fs = %s",
1420 pip->i_devvp, (uintmax_t)ino, fs->e2fs_fsmnt);
1422 cg = ino_to_cg(fs, ino);
1423 error = bread(pip->i_devvp,
1424 fsbtodb(fs, e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1425 (int)fs->e2fs_bsize, NOCRED, &bp);
1430 ibp = (char *)bp->b_data;
1431 ino = (ino - 1) % fs->e2fs->e2fs_ipg;
1432 if (isclr(ibp, ino)) {
1433 printf("ino = %ju, fs = %s\n",
1434 ino, fs->e2fs_fsmnt);
1435 if (fs->e2fs_ronly == 0)
1436 panic("ext2_vfree: freeing free inode");
1440 fs->e2fs->e2fs_ficount++;
1441 e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1442 e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) + 1);
1443 if ((mode & IFMT) == IFDIR) {
1444 e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1445 e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) - 1);
1446 fs->e2fs_total_dir--;
1450 ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1456 * Find a block in the specified cylinder group.
1458 * It is a panic if a request is made to find a block if none are
1462 ext2_mapsearch(struct m_ext2fs *fs, char *bbp, daddr_t bpref)
1468 * find the fragment by searching through the free block
1469 * map for an appropriate bit pattern
1472 start = dtogd(fs, bpref) / NBBY;
1475 len = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
1476 loc = memcchr(&bbp[start], 0xff, len);
1480 loc = memcchr(&bbp[start], 0xff, len);
1482 printf("start = %d, len = %d, fs = %s\n",
1483 start, len, fs->e2fs_fsmnt);
1484 panic("ext2_mapsearch: map corrupted");
1488 return ((loc - bbp) * NBBY + ffs(~*loc) - 1);
1492 * Fserr prints the name of a filesystem with an error diagnostic.
1494 * The form of the error message is:
1498 ext2_fserr(struct m_ext2fs *fs, uid_t uid, char *cp)
1501 log(LOG_ERR, "uid %u on %s: %s\n", uid, fs->e2fs_fsmnt, cp);
1505 ext2_cg_has_sb(struct m_ext2fs *fs, int cg)
1512 if (EXT2_HAS_COMPAT_FEATURE(fs, EXT2F_COMPAT_SPARSESUPER2)) {
1513 if (cg == fs->e2fs->e4fs_backup_bgs[0] ||
1514 cg == fs->e2fs->e4fs_backup_bgs[1])
1520 !EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_SPARSESUPER))
1526 for (a3 = 3, a5 = 5, a7 = 7;
1527 a3 <= cg || a5 <= cg || a7 <= cg;
1528 a3 *= 3, a5 *= 5, a7 *= 7)
1529 if (cg == a3 || cg == a5 || cg == a7)