Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  *  linux/fs/ext4/balloc.c
0004  *
0005  * Copyright (C) 1992, 1993, 1994, 1995
0006  * Remy Card (card@masi.ibp.fr)
0007  * Laboratoire MASI - Institut Blaise Pascal
0008  * Universite Pierre et Marie Curie (Paris VI)
0009  *
0010  *  Enhanced block allocation by Stephen Tweedie (sct@redhat.com), 1993
0011  *  Big-endian to little-endian byte-swapping/bitmaps by
0012  *        David S. Miller (davem@caip.rutgers.edu), 1995
0013  */
0014 
0015 #include <linux/time.h>
0016 #include <linux/capability.h>
0017 #include <linux/fs.h>
0018 #include <linux/quotaops.h>
0019 #include <linux/buffer_head.h>
0020 #include "ext4.h"
0021 #include "ext4_jbd2.h"
0022 #include "mballoc.h"
0023 
0024 #include <trace/events/ext4.h>
0025 
0026 static unsigned ext4_num_base_meta_clusters(struct super_block *sb,
0027                         ext4_group_t block_group);
0028 /*
0029  * balloc.c contains the blocks allocation and deallocation routines
0030  */
0031 
0032 /*
0033  * Calculate block group number for a given block number
0034  */
0035 ext4_group_t ext4_get_group_number(struct super_block *sb,
0036                    ext4_fsblk_t block)
0037 {
0038     ext4_group_t group;
0039 
0040     if (test_opt2(sb, STD_GROUP_SIZE))
0041         group = (block -
0042              le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) >>
0043             (EXT4_BLOCK_SIZE_BITS(sb) + EXT4_CLUSTER_BITS(sb) + 3);
0044     else
0045         ext4_get_group_no_and_offset(sb, block, &group, NULL);
0046     return group;
0047 }
0048 
0049 /*
0050  * Calculate the block group number and offset into the block/cluster
0051  * allocation bitmap, given a block number
0052  */
0053 void ext4_get_group_no_and_offset(struct super_block *sb, ext4_fsblk_t blocknr,
0054         ext4_group_t *blockgrpp, ext4_grpblk_t *offsetp)
0055 {
0056     struct ext4_super_block *es = EXT4_SB(sb)->s_es;
0057     ext4_grpblk_t offset;
0058 
0059     blocknr = blocknr - le32_to_cpu(es->s_first_data_block);
0060     offset = do_div(blocknr, EXT4_BLOCKS_PER_GROUP(sb)) >>
0061         EXT4_SB(sb)->s_cluster_bits;
0062     if (offsetp)
0063         *offsetp = offset;
0064     if (blockgrpp)
0065         *blockgrpp = blocknr;
0066 
0067 }
0068 
0069 /*
0070  * Check whether the 'block' lives within the 'block_group'. Returns 1 if so
0071  * and 0 otherwise.
0072  */
0073 static inline int ext4_block_in_group(struct super_block *sb,
0074                       ext4_fsblk_t block,
0075                       ext4_group_t block_group)
0076 {
0077     ext4_group_t actual_group;
0078 
0079     actual_group = ext4_get_group_number(sb, block);
0080     return (actual_group == block_group) ? 1 : 0;
0081 }
0082 
0083 /* Return the number of clusters used for file system metadata; this
0084  * represents the overhead needed by the file system.
0085  */
0086 static unsigned ext4_num_overhead_clusters(struct super_block *sb,
0087                        ext4_group_t block_group,
0088                        struct ext4_group_desc *gdp)
0089 {
0090     unsigned num_clusters;
0091     int block_cluster = -1, inode_cluster = -1, itbl_cluster = -1, i, c;
0092     ext4_fsblk_t start = ext4_group_first_block_no(sb, block_group);
0093     ext4_fsblk_t itbl_blk;
0094     struct ext4_sb_info *sbi = EXT4_SB(sb);
0095 
0096     /* This is the number of clusters used by the superblock,
0097      * block group descriptors, and reserved block group
0098      * descriptor blocks */
0099     num_clusters = ext4_num_base_meta_clusters(sb, block_group);
0100 
0101     /*
0102      * For the allocation bitmaps and inode table, we first need
0103      * to check to see if the block is in the block group.  If it
0104      * is, then check to see if the cluster is already accounted
0105      * for in the clusters used for the base metadata cluster, or
0106      * if we can increment the base metadata cluster to include
0107      * that block.  Otherwise, we will have to track the cluster
0108      * used for the allocation bitmap or inode table explicitly.
0109      * Normally all of these blocks are contiguous, so the special
0110      * case handling shouldn't be necessary except for *very*
0111      * unusual file system layouts.
0112      */
0113     if (ext4_block_in_group(sb, ext4_block_bitmap(sb, gdp), block_group)) {
0114         block_cluster = EXT4_B2C(sbi,
0115                      ext4_block_bitmap(sb, gdp) - start);
0116         if (block_cluster < num_clusters)
0117             block_cluster = -1;
0118         else if (block_cluster == num_clusters) {
0119             num_clusters++;
0120             block_cluster = -1;
0121         }
0122     }
0123 
0124     if (ext4_block_in_group(sb, ext4_inode_bitmap(sb, gdp), block_group)) {
0125         inode_cluster = EXT4_B2C(sbi,
0126                      ext4_inode_bitmap(sb, gdp) - start);
0127         if (inode_cluster < num_clusters)
0128             inode_cluster = -1;
0129         else if (inode_cluster == num_clusters) {
0130             num_clusters++;
0131             inode_cluster = -1;
0132         }
0133     }
0134 
0135     itbl_blk = ext4_inode_table(sb, gdp);
0136     for (i = 0; i < sbi->s_itb_per_group; i++) {
0137         if (ext4_block_in_group(sb, itbl_blk + i, block_group)) {
0138             c = EXT4_B2C(sbi, itbl_blk + i - start);
0139             if ((c < num_clusters) || (c == inode_cluster) ||
0140                 (c == block_cluster) || (c == itbl_cluster))
0141                 continue;
0142             if (c == num_clusters) {
0143                 num_clusters++;
0144                 continue;
0145             }
0146             num_clusters++;
0147             itbl_cluster = c;
0148         }
0149     }
0150 
0151     if (block_cluster != -1)
0152         num_clusters++;
0153     if (inode_cluster != -1)
0154         num_clusters++;
0155 
0156     return num_clusters;
0157 }
0158 
0159 static unsigned int num_clusters_in_group(struct super_block *sb,
0160                       ext4_group_t block_group)
0161 {
0162     unsigned int blocks;
0163 
0164     if (block_group == ext4_get_groups_count(sb) - 1) {
0165         /*
0166          * Even though mke2fs always initializes the first and
0167          * last group, just in case some other tool was used,
0168          * we need to make sure we calculate the right free
0169          * blocks.
0170          */
0171         blocks = ext4_blocks_count(EXT4_SB(sb)->s_es) -
0172             ext4_group_first_block_no(sb, block_group);
0173     } else
0174         blocks = EXT4_BLOCKS_PER_GROUP(sb);
0175     return EXT4_NUM_B2C(EXT4_SB(sb), blocks);
0176 }
0177 
0178 /* Initializes an uninitialized block bitmap */
0179 static int ext4_init_block_bitmap(struct super_block *sb,
0180                    struct buffer_head *bh,
0181                    ext4_group_t block_group,
0182                    struct ext4_group_desc *gdp)
0183 {
0184     unsigned int bit, bit_max;
0185     struct ext4_sb_info *sbi = EXT4_SB(sb);
0186     ext4_fsblk_t start, tmp;
0187 
0188     ASSERT(buffer_locked(bh));
0189 
0190     /* If checksum is bad mark all blocks used to prevent allocation
0191      * essentially implementing a per-group read-only flag. */
0192     if (!ext4_group_desc_csum_verify(sb, block_group, gdp)) {
0193         ext4_mark_group_bitmap_corrupted(sb, block_group,
0194                     EXT4_GROUP_INFO_BBITMAP_CORRUPT |
0195                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
0196         return -EFSBADCRC;
0197     }
0198     memset(bh->b_data, 0, sb->s_blocksize);
0199 
0200     bit_max = ext4_num_base_meta_clusters(sb, block_group);
0201     if ((bit_max >> 3) >= bh->b_size)
0202         return -EFSCORRUPTED;
0203 
0204     for (bit = 0; bit < bit_max; bit++)
0205         ext4_set_bit(bit, bh->b_data);
0206 
0207     start = ext4_group_first_block_no(sb, block_group);
0208 
0209     /* Set bits for block and inode bitmaps, and inode table */
0210     tmp = ext4_block_bitmap(sb, gdp);
0211     if (ext4_block_in_group(sb, tmp, block_group))
0212         ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
0213 
0214     tmp = ext4_inode_bitmap(sb, gdp);
0215     if (ext4_block_in_group(sb, tmp, block_group))
0216         ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
0217 
0218     tmp = ext4_inode_table(sb, gdp);
0219     for (; tmp < ext4_inode_table(sb, gdp) +
0220              sbi->s_itb_per_group; tmp++) {
0221         if (ext4_block_in_group(sb, tmp, block_group))
0222             ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
0223     }
0224 
0225     /*
0226      * Also if the number of blocks within the group is less than
0227      * the blocksize * 8 ( which is the size of bitmap ), set rest
0228      * of the block bitmap to 1
0229      */
0230     ext4_mark_bitmap_end(num_clusters_in_group(sb, block_group),
0231                  sb->s_blocksize * 8, bh->b_data);
0232     return 0;
0233 }
0234 
0235 /* Return the number of free blocks in a block group.  It is used when
0236  * the block bitmap is uninitialized, so we can't just count the bits
0237  * in the bitmap. */
0238 unsigned ext4_free_clusters_after_init(struct super_block *sb,
0239                        ext4_group_t block_group,
0240                        struct ext4_group_desc *gdp)
0241 {
0242     return num_clusters_in_group(sb, block_group) -
0243         ext4_num_overhead_clusters(sb, block_group, gdp);
0244 }
0245 
0246 /*
0247  * The free blocks are managed by bitmaps.  A file system contains several
0248  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
0249  * block for inodes, N blocks for the inode table and data blocks.
0250  *
0251  * The file system contains group descriptors which are located after the
0252  * super block.  Each descriptor contains the number of the bitmap block and
0253  * the free blocks count in the block.  The descriptors are loaded in memory
0254  * when a file system is mounted (see ext4_fill_super).
0255  */
0256 
0257 /**
0258  * ext4_get_group_desc() -- load group descriptor from disk
0259  * @sb:         super block
0260  * @block_group:    given block group
0261  * @bh:         pointer to the buffer head to store the block
0262  *          group descriptor
0263  */
0264 struct ext4_group_desc * ext4_get_group_desc(struct super_block *sb,
0265                          ext4_group_t block_group,
0266                          struct buffer_head **bh)
0267 {
0268     unsigned int group_desc;
0269     unsigned int offset;
0270     ext4_group_t ngroups = ext4_get_groups_count(sb);
0271     struct ext4_group_desc *desc;
0272     struct ext4_sb_info *sbi = EXT4_SB(sb);
0273     struct buffer_head *bh_p;
0274 
0275     if (block_group >= ngroups) {
0276         ext4_error(sb, "block_group >= groups_count - block_group = %u,"
0277                " groups_count = %u", block_group, ngroups);
0278 
0279         return NULL;
0280     }
0281 
0282     group_desc = block_group >> EXT4_DESC_PER_BLOCK_BITS(sb);
0283     offset = block_group & (EXT4_DESC_PER_BLOCK(sb) - 1);
0284     bh_p = sbi_array_rcu_deref(sbi, s_group_desc, group_desc);
0285     /*
0286      * sbi_array_rcu_deref returns with rcu unlocked, this is ok since
0287      * the pointer being dereferenced won't be dereferenced again. By
0288      * looking at the usage in add_new_gdb() the value isn't modified,
0289      * just the pointer, and so it remains valid.
0290      */
0291     if (!bh_p) {
0292         ext4_error(sb, "Group descriptor not loaded - "
0293                "block_group = %u, group_desc = %u, desc = %u",
0294                block_group, group_desc, offset);
0295         return NULL;
0296     }
0297 
0298     desc = (struct ext4_group_desc *)(
0299         (__u8 *)bh_p->b_data +
0300         offset * EXT4_DESC_SIZE(sb));
0301     if (bh)
0302         *bh = bh_p;
0303     return desc;
0304 }
0305 
0306 /*
0307  * Return the block number which was discovered to be invalid, or 0 if
0308  * the block bitmap is valid.
0309  */
0310 static ext4_fsblk_t ext4_valid_block_bitmap(struct super_block *sb,
0311                         struct ext4_group_desc *desc,
0312                         ext4_group_t block_group,
0313                         struct buffer_head *bh)
0314 {
0315     struct ext4_sb_info *sbi = EXT4_SB(sb);
0316     ext4_grpblk_t offset;
0317     ext4_grpblk_t next_zero_bit;
0318     ext4_grpblk_t max_bit = EXT4_CLUSTERS_PER_GROUP(sb);
0319     ext4_fsblk_t blk;
0320     ext4_fsblk_t group_first_block;
0321 
0322     if (ext4_has_feature_flex_bg(sb)) {
0323         /* with FLEX_BG, the inode/block bitmaps and itable
0324          * blocks may not be in the group at all
0325          * so the bitmap validation will be skipped for those groups
0326          * or it has to also read the block group where the bitmaps
0327          * are located to verify they are set.
0328          */
0329         return 0;
0330     }
0331     group_first_block = ext4_group_first_block_no(sb, block_group);
0332 
0333     /* check whether block bitmap block number is set */
0334     blk = ext4_block_bitmap(sb, desc);
0335     offset = blk - group_first_block;
0336     if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
0337         !ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
0338         /* bad block bitmap */
0339         return blk;
0340 
0341     /* check whether the inode bitmap block number is set */
0342     blk = ext4_inode_bitmap(sb, desc);
0343     offset = blk - group_first_block;
0344     if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
0345         !ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
0346         /* bad block bitmap */
0347         return blk;
0348 
0349     /* check whether the inode table block number is set */
0350     blk = ext4_inode_table(sb, desc);
0351     offset = blk - group_first_block;
0352     if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
0353         EXT4_B2C(sbi, offset + sbi->s_itb_per_group) >= max_bit)
0354         return blk;
0355     next_zero_bit = ext4_find_next_zero_bit(bh->b_data,
0356             EXT4_B2C(sbi, offset + sbi->s_itb_per_group),
0357             EXT4_B2C(sbi, offset));
0358     if (next_zero_bit <
0359         EXT4_B2C(sbi, offset + sbi->s_itb_per_group))
0360         /* bad bitmap for inode tables */
0361         return blk;
0362     return 0;
0363 }
0364 
0365 static int ext4_validate_block_bitmap(struct super_block *sb,
0366                       struct ext4_group_desc *desc,
0367                       ext4_group_t block_group,
0368                       struct buffer_head *bh)
0369 {
0370     ext4_fsblk_t    blk;
0371     struct ext4_group_info *grp;
0372 
0373     if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
0374         return 0;
0375 
0376     grp = ext4_get_group_info(sb, block_group);
0377 
0378     if (buffer_verified(bh))
0379         return 0;
0380     if (EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
0381         return -EFSCORRUPTED;
0382 
0383     ext4_lock_group(sb, block_group);
0384     if (buffer_verified(bh))
0385         goto verified;
0386     if (unlikely(!ext4_block_bitmap_csum_verify(sb, block_group,
0387                             desc, bh) ||
0388              ext4_simulate_fail(sb, EXT4_SIM_BBITMAP_CRC))) {
0389         ext4_unlock_group(sb, block_group);
0390         ext4_error(sb, "bg %u: bad block bitmap checksum", block_group);
0391         ext4_mark_group_bitmap_corrupted(sb, block_group,
0392                     EXT4_GROUP_INFO_BBITMAP_CORRUPT);
0393         return -EFSBADCRC;
0394     }
0395     blk = ext4_valid_block_bitmap(sb, desc, block_group, bh);
0396     if (unlikely(blk != 0)) {
0397         ext4_unlock_group(sb, block_group);
0398         ext4_error(sb, "bg %u: block %llu: invalid block bitmap",
0399                block_group, blk);
0400         ext4_mark_group_bitmap_corrupted(sb, block_group,
0401                     EXT4_GROUP_INFO_BBITMAP_CORRUPT);
0402         return -EFSCORRUPTED;
0403     }
0404     set_buffer_verified(bh);
0405 verified:
0406     ext4_unlock_group(sb, block_group);
0407     return 0;
0408 }
0409 
0410 /**
0411  * ext4_read_block_bitmap_nowait()
0412  * @sb:         super block
0413  * @block_group:    given block group
0414  * @ignore_locked:  ignore locked buffers
0415  *
0416  * Read the bitmap for a given block_group,and validate the
0417  * bits for block/inode/inode tables are set in the bitmaps
0418  *
0419  * Return buffer_head on success or an ERR_PTR in case of failure.
0420  */
0421 struct buffer_head *
0422 ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group,
0423                   bool ignore_locked)
0424 {
0425     struct ext4_group_desc *desc;
0426     struct ext4_sb_info *sbi = EXT4_SB(sb);
0427     struct buffer_head *bh;
0428     ext4_fsblk_t bitmap_blk;
0429     int err;
0430 
0431     desc = ext4_get_group_desc(sb, block_group, NULL);
0432     if (!desc)
0433         return ERR_PTR(-EFSCORRUPTED);
0434     bitmap_blk = ext4_block_bitmap(sb, desc);
0435     if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
0436         (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
0437         ext4_error(sb, "Invalid block bitmap block %llu in "
0438                "block_group %u", bitmap_blk, block_group);
0439         ext4_mark_group_bitmap_corrupted(sb, block_group,
0440                     EXT4_GROUP_INFO_BBITMAP_CORRUPT);
0441         return ERR_PTR(-EFSCORRUPTED);
0442     }
0443     bh = sb_getblk(sb, bitmap_blk);
0444     if (unlikely(!bh)) {
0445         ext4_warning(sb, "Cannot get buffer for block bitmap - "
0446                  "block_group = %u, block_bitmap = %llu",
0447                  block_group, bitmap_blk);
0448         return ERR_PTR(-ENOMEM);
0449     }
0450 
0451     if (ignore_locked && buffer_locked(bh)) {
0452         /* buffer under IO already, return if called for prefetching */
0453         put_bh(bh);
0454         return NULL;
0455     }
0456 
0457     if (bitmap_uptodate(bh))
0458         goto verify;
0459 
0460     lock_buffer(bh);
0461     if (bitmap_uptodate(bh)) {
0462         unlock_buffer(bh);
0463         goto verify;
0464     }
0465     ext4_lock_group(sb, block_group);
0466     if (ext4_has_group_desc_csum(sb) &&
0467         (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
0468         if (block_group == 0) {
0469             ext4_unlock_group(sb, block_group);
0470             unlock_buffer(bh);
0471             ext4_error(sb, "Block bitmap for bg 0 marked "
0472                    "uninitialized");
0473             err = -EFSCORRUPTED;
0474             goto out;
0475         }
0476         err = ext4_init_block_bitmap(sb, bh, block_group, desc);
0477         set_bitmap_uptodate(bh);
0478         set_buffer_uptodate(bh);
0479         set_buffer_verified(bh);
0480         ext4_unlock_group(sb, block_group);
0481         unlock_buffer(bh);
0482         if (err) {
0483             ext4_error(sb, "Failed to init block bitmap for group "
0484                    "%u: %d", block_group, err);
0485             goto out;
0486         }
0487         goto verify;
0488     }
0489     ext4_unlock_group(sb, block_group);
0490     if (buffer_uptodate(bh)) {
0491         /*
0492          * if not uninit if bh is uptodate,
0493          * bitmap is also uptodate
0494          */
0495         set_bitmap_uptodate(bh);
0496         unlock_buffer(bh);
0497         goto verify;
0498     }
0499     /*
0500      * submit the buffer_head for reading
0501      */
0502     set_buffer_new(bh);
0503     trace_ext4_read_block_bitmap_load(sb, block_group, ignore_locked);
0504     ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO |
0505                 (ignore_locked ? REQ_RAHEAD : 0),
0506                 ext4_end_bitmap_read);
0507     return bh;
0508 verify:
0509     err = ext4_validate_block_bitmap(sb, desc, block_group, bh);
0510     if (err)
0511         goto out;
0512     return bh;
0513 out:
0514     put_bh(bh);
0515     return ERR_PTR(err);
0516 }
0517 
0518 /* Returns 0 on success, -errno on error */
0519 int ext4_wait_block_bitmap(struct super_block *sb, ext4_group_t block_group,
0520                struct buffer_head *bh)
0521 {
0522     struct ext4_group_desc *desc;
0523 
0524     if (!buffer_new(bh))
0525         return 0;
0526     desc = ext4_get_group_desc(sb, block_group, NULL);
0527     if (!desc)
0528         return -EFSCORRUPTED;
0529     wait_on_buffer(bh);
0530     ext4_simulate_fail_bh(sb, bh, EXT4_SIM_BBITMAP_EIO);
0531     if (!buffer_uptodate(bh)) {
0532         ext4_error_err(sb, EIO, "Cannot read block bitmap - "
0533                    "block_group = %u, block_bitmap = %llu",
0534                    block_group, (unsigned long long) bh->b_blocknr);
0535         ext4_mark_group_bitmap_corrupted(sb, block_group,
0536                     EXT4_GROUP_INFO_BBITMAP_CORRUPT);
0537         return -EIO;
0538     }
0539     clear_buffer_new(bh);
0540     /* Panic or remount fs read-only if block bitmap is invalid */
0541     return ext4_validate_block_bitmap(sb, desc, block_group, bh);
0542 }
0543 
0544 struct buffer_head *
0545 ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group)
0546 {
0547     struct buffer_head *bh;
0548     int err;
0549 
0550     bh = ext4_read_block_bitmap_nowait(sb, block_group, false);
0551     if (IS_ERR(bh))
0552         return bh;
0553     err = ext4_wait_block_bitmap(sb, block_group, bh);
0554     if (err) {
0555         put_bh(bh);
0556         return ERR_PTR(err);
0557     }
0558     return bh;
0559 }
0560 
0561 /**
0562  * ext4_has_free_clusters()
0563  * @sbi:    in-core super block structure.
0564  * @nclusters:  number of needed blocks
0565  * @flags:  flags from ext4_mb_new_blocks()
0566  *
0567  * Check if filesystem has nclusters free & available for allocation.
0568  * On success return 1, return 0 on failure.
0569  */
0570 static int ext4_has_free_clusters(struct ext4_sb_info *sbi,
0571                   s64 nclusters, unsigned int flags)
0572 {
0573     s64 free_clusters, dirty_clusters, rsv, resv_clusters;
0574     struct percpu_counter *fcc = &sbi->s_freeclusters_counter;
0575     struct percpu_counter *dcc = &sbi->s_dirtyclusters_counter;
0576 
0577     free_clusters  = percpu_counter_read_positive(fcc);
0578     dirty_clusters = percpu_counter_read_positive(dcc);
0579     resv_clusters = atomic64_read(&sbi->s_resv_clusters);
0580 
0581     /*
0582      * r_blocks_count should always be multiple of the cluster ratio so
0583      * we are safe to do a plane bit shift only.
0584      */
0585     rsv = (ext4_r_blocks_count(sbi->s_es) >> sbi->s_cluster_bits) +
0586           resv_clusters;
0587 
0588     if (free_clusters - (nclusters + rsv + dirty_clusters) <
0589                     EXT4_FREECLUSTERS_WATERMARK) {
0590         free_clusters  = percpu_counter_sum_positive(fcc);
0591         dirty_clusters = percpu_counter_sum_positive(dcc);
0592     }
0593     /* Check whether we have space after accounting for current
0594      * dirty clusters & root reserved clusters.
0595      */
0596     if (free_clusters >= (rsv + nclusters + dirty_clusters))
0597         return 1;
0598 
0599     /* Hm, nope.  Are (enough) root reserved clusters available? */
0600     if (uid_eq(sbi->s_resuid, current_fsuid()) ||
0601         (!gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) && in_group_p(sbi->s_resgid)) ||
0602         capable(CAP_SYS_RESOURCE) ||
0603         (flags & EXT4_MB_USE_ROOT_BLOCKS)) {
0604 
0605         if (free_clusters >= (nclusters + dirty_clusters +
0606                       resv_clusters))
0607             return 1;
0608     }
0609     /* No free blocks. Let's see if we can dip into reserved pool */
0610     if (flags & EXT4_MB_USE_RESERVED) {
0611         if (free_clusters >= (nclusters + dirty_clusters))
0612             return 1;
0613     }
0614 
0615     return 0;
0616 }
0617 
0618 int ext4_claim_free_clusters(struct ext4_sb_info *sbi,
0619                  s64 nclusters, unsigned int flags)
0620 {
0621     if (ext4_has_free_clusters(sbi, nclusters, flags)) {
0622         percpu_counter_add(&sbi->s_dirtyclusters_counter, nclusters);
0623         return 0;
0624     } else
0625         return -ENOSPC;
0626 }
0627 
0628 /**
0629  * ext4_should_retry_alloc() - check if a block allocation should be retried
0630  * @sb:         superblock
0631  * @retries:        number of retry attempts made so far
0632  *
0633  * ext4_should_retry_alloc() is called when ENOSPC is returned while
0634  * attempting to allocate blocks.  If there's an indication that a pending
0635  * journal transaction might free some space and allow another attempt to
0636  * succeed, this function will wait for the current or committing transaction
0637  * to complete and then return TRUE.
0638  */
0639 int ext4_should_retry_alloc(struct super_block *sb, int *retries)
0640 {
0641     struct ext4_sb_info *sbi = EXT4_SB(sb);
0642 
0643     if (!sbi->s_journal)
0644         return 0;
0645 
0646     if (++(*retries) > 3) {
0647         percpu_counter_inc(&sbi->s_sra_exceeded_retry_limit);
0648         return 0;
0649     }
0650 
0651     /*
0652      * if there's no indication that blocks are about to be freed it's
0653      * possible we just missed a transaction commit that did so
0654      */
0655     smp_mb();
0656     if (sbi->s_mb_free_pending == 0) {
0657         if (test_opt(sb, DISCARD)) {
0658             atomic_inc(&sbi->s_retry_alloc_pending);
0659             flush_work(&sbi->s_discard_work);
0660             atomic_dec(&sbi->s_retry_alloc_pending);
0661         }
0662         return ext4_has_free_clusters(sbi, 1, 0);
0663     }
0664 
0665     /*
0666      * it's possible we've just missed a transaction commit here,
0667      * so ignore the returned status
0668      */
0669     ext4_debug("%s: retrying operation after ENOSPC\n", sb->s_id);
0670     (void) jbd2_journal_force_commit_nested(sbi->s_journal);
0671     return 1;
0672 }
0673 
0674 /*
0675  * ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks
0676  *
0677  * @handle:             handle to this transaction
0678  * @inode:              file inode
0679  * @goal:               given target block(filesystem wide)
0680  * @count:      pointer to total number of clusters needed
0681  * @errp:               error code
0682  *
0683  * Return 1st allocated block number on success, *count stores total account
0684  * error stores in errp pointer
0685  */
0686 ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode,
0687                   ext4_fsblk_t goal, unsigned int flags,
0688                   unsigned long *count, int *errp)
0689 {
0690     struct ext4_allocation_request ar;
0691     ext4_fsblk_t ret;
0692 
0693     memset(&ar, 0, sizeof(ar));
0694     /* Fill with neighbour allocated blocks */
0695     ar.inode = inode;
0696     ar.goal = goal;
0697     ar.len = count ? *count : 1;
0698     ar.flags = flags;
0699 
0700     ret = ext4_mb_new_blocks(handle, &ar, errp);
0701     if (count)
0702         *count = ar.len;
0703     /*
0704      * Account for the allocated meta blocks.  We will never
0705      * fail EDQUOT for metdata, but we do account for it.
0706      */
0707     if (!(*errp) && (flags & EXT4_MB_DELALLOC_RESERVED)) {
0708         dquot_alloc_block_nofail(inode,
0709                 EXT4_C2B(EXT4_SB(inode->i_sb), ar.len));
0710     }
0711     return ret;
0712 }
0713 
0714 /**
0715  * ext4_count_free_clusters() -- count filesystem free clusters
0716  * @sb:     superblock
0717  *
0718  * Adds up the number of free clusters from each block group.
0719  */
0720 ext4_fsblk_t ext4_count_free_clusters(struct super_block *sb)
0721 {
0722     ext4_fsblk_t desc_count;
0723     struct ext4_group_desc *gdp;
0724     ext4_group_t i;
0725     ext4_group_t ngroups = ext4_get_groups_count(sb);
0726     struct ext4_group_info *grp;
0727 #ifdef EXT4FS_DEBUG
0728     struct ext4_super_block *es;
0729     ext4_fsblk_t bitmap_count;
0730     unsigned int x;
0731     struct buffer_head *bitmap_bh = NULL;
0732 
0733     es = EXT4_SB(sb)->s_es;
0734     desc_count = 0;
0735     bitmap_count = 0;
0736     gdp = NULL;
0737 
0738     for (i = 0; i < ngroups; i++) {
0739         gdp = ext4_get_group_desc(sb, i, NULL);
0740         if (!gdp)
0741             continue;
0742         grp = NULL;
0743         if (EXT4_SB(sb)->s_group_info)
0744             grp = ext4_get_group_info(sb, i);
0745         if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
0746             desc_count += ext4_free_group_clusters(sb, gdp);
0747         brelse(bitmap_bh);
0748         bitmap_bh = ext4_read_block_bitmap(sb, i);
0749         if (IS_ERR(bitmap_bh)) {
0750             bitmap_bh = NULL;
0751             continue;
0752         }
0753 
0754         x = ext4_count_free(bitmap_bh->b_data,
0755                     EXT4_CLUSTERS_PER_GROUP(sb) / 8);
0756         printk(KERN_DEBUG "group %u: stored = %d, counted = %u\n",
0757             i, ext4_free_group_clusters(sb, gdp), x);
0758         bitmap_count += x;
0759     }
0760     brelse(bitmap_bh);
0761     printk(KERN_DEBUG "ext4_count_free_clusters: stored = %llu"
0762            ", computed = %llu, %llu\n",
0763            EXT4_NUM_B2C(EXT4_SB(sb), ext4_free_blocks_count(es)),
0764            desc_count, bitmap_count);
0765     return bitmap_count;
0766 #else
0767     desc_count = 0;
0768     for (i = 0; i < ngroups; i++) {
0769         gdp = ext4_get_group_desc(sb, i, NULL);
0770         if (!gdp)
0771             continue;
0772         grp = NULL;
0773         if (EXT4_SB(sb)->s_group_info)
0774             grp = ext4_get_group_info(sb, i);
0775         if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
0776             desc_count += ext4_free_group_clusters(sb, gdp);
0777     }
0778 
0779     return desc_count;
0780 #endif
0781 }
0782 
0783 static inline int test_root(ext4_group_t a, int b)
0784 {
0785     while (1) {
0786         if (a < b)
0787             return 0;
0788         if (a == b)
0789             return 1;
0790         if ((a % b) != 0)
0791             return 0;
0792         a = a / b;
0793     }
0794 }
0795 
0796 /**
0797  *  ext4_bg_has_super - number of blocks used by the superblock in group
0798  *  @sb: superblock for filesystem
0799  *  @group: group number to check
0800  *
0801  *  Return the number of blocks used by the superblock (primary or backup)
0802  *  in this group.  Currently this will be only 0 or 1.
0803  */
0804 int ext4_bg_has_super(struct super_block *sb, ext4_group_t group)
0805 {
0806     struct ext4_super_block *es = EXT4_SB(sb)->s_es;
0807 
0808     if (group == 0)
0809         return 1;
0810     if (ext4_has_feature_sparse_super2(sb)) {
0811         if (group == le32_to_cpu(es->s_backup_bgs[0]) ||
0812             group == le32_to_cpu(es->s_backup_bgs[1]))
0813             return 1;
0814         return 0;
0815     }
0816     if ((group <= 1) || !ext4_has_feature_sparse_super(sb))
0817         return 1;
0818     if (!(group & 1))
0819         return 0;
0820     if (test_root(group, 3) || (test_root(group, 5)) ||
0821         test_root(group, 7))
0822         return 1;
0823 
0824     return 0;
0825 }
0826 
0827 static unsigned long ext4_bg_num_gdb_meta(struct super_block *sb,
0828                     ext4_group_t group)
0829 {
0830     unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
0831     ext4_group_t first = metagroup * EXT4_DESC_PER_BLOCK(sb);
0832     ext4_group_t last = first + EXT4_DESC_PER_BLOCK(sb) - 1;
0833 
0834     if (group == first || group == first + 1 || group == last)
0835         return 1;
0836     return 0;
0837 }
0838 
0839 static unsigned long ext4_bg_num_gdb_nometa(struct super_block *sb,
0840                     ext4_group_t group)
0841 {
0842     if (!ext4_bg_has_super(sb, group))
0843         return 0;
0844 
0845     if (ext4_has_feature_meta_bg(sb))
0846         return le32_to_cpu(EXT4_SB(sb)->s_es->s_first_meta_bg);
0847     else
0848         return EXT4_SB(sb)->s_gdb_count;
0849 }
0850 
0851 /**
0852  *  ext4_bg_num_gdb - number of blocks used by the group table in group
0853  *  @sb: superblock for filesystem
0854  *  @group: group number to check
0855  *
0856  *  Return the number of blocks used by the group descriptor table
0857  *  (primary or backup) in this group.  In the future there may be a
0858  *  different number of descriptor blocks in each group.
0859  */
0860 unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group)
0861 {
0862     unsigned long first_meta_bg =
0863             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_meta_bg);
0864     unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
0865 
0866     if (!ext4_has_feature_meta_bg(sb) || metagroup < first_meta_bg)
0867         return ext4_bg_num_gdb_nometa(sb, group);
0868 
0869     return ext4_bg_num_gdb_meta(sb,group);
0870 
0871 }
0872 
0873 /*
0874  * This function returns the number of file system metadata clusters at
0875  * the beginning of a block group, including the reserved gdt blocks.
0876  */
0877 static unsigned ext4_num_base_meta_clusters(struct super_block *sb,
0878                      ext4_group_t block_group)
0879 {
0880     struct ext4_sb_info *sbi = EXT4_SB(sb);
0881     unsigned num;
0882 
0883     /* Check for superblock and gdt backups in this group */
0884     num = ext4_bg_has_super(sb, block_group);
0885 
0886     if (!ext4_has_feature_meta_bg(sb) ||
0887         block_group < le32_to_cpu(sbi->s_es->s_first_meta_bg) *
0888               sbi->s_desc_per_block) {
0889         if (num) {
0890             num += ext4_bg_num_gdb(sb, block_group);
0891             num += le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks);
0892         }
0893     } else { /* For META_BG_BLOCK_GROUPS */
0894         num += ext4_bg_num_gdb(sb, block_group);
0895     }
0896     return EXT4_NUM_B2C(sbi, num);
0897 }
0898 /**
0899  *  ext4_inode_to_goal_block - return a hint for block allocation
0900  *  @inode: inode for block allocation
0901  *
0902  *  Return the ideal location to start allocating blocks for a
0903  *  newly created inode.
0904  */
0905 ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode)
0906 {
0907     struct ext4_inode_info *ei = EXT4_I(inode);
0908     ext4_group_t block_group;
0909     ext4_grpblk_t colour;
0910     int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
0911     ext4_fsblk_t bg_start;
0912     ext4_fsblk_t last_block;
0913 
0914     block_group = ei->i_block_group;
0915     if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
0916         /*
0917          * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
0918          * block groups per flexgroup, reserve the first block
0919          * group for directories and special files.  Regular
0920          * files will start at the second block group.  This
0921          * tends to speed up directory access and improves
0922          * fsck times.
0923          */
0924         block_group &= ~(flex_size-1);
0925         if (S_ISREG(inode->i_mode))
0926             block_group++;
0927     }
0928     bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
0929     last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
0930 
0931     /*
0932      * If we are doing delayed allocation, we don't need take
0933      * colour into account.
0934      */
0935     if (test_opt(inode->i_sb, DELALLOC))
0936         return bg_start;
0937 
0938     if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
0939         colour = (task_pid_nr(current) % 16) *
0940             (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
0941     else
0942         colour = (task_pid_nr(current) % 16) *
0943             ((last_block - bg_start) / 16);
0944     return bg_start + colour;
0945 }
0946