Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  *  linux/fs/ext4/ialloc.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  *  BSD ufs-inspired inode and directory allocation by
0011  *  Stephen Tweedie (sct@redhat.com), 1993
0012  *  Big-endian to little-endian byte-swapping/bitmaps by
0013  *        David S. Miller (davem@caip.rutgers.edu), 1995
0014  */
0015 
0016 #include <linux/time.h>
0017 #include <linux/fs.h>
0018 #include <linux/stat.h>
0019 #include <linux/string.h>
0020 #include <linux/quotaops.h>
0021 #include <linux/buffer_head.h>
0022 #include <linux/random.h>
0023 #include <linux/bitops.h>
0024 #include <linux/blkdev.h>
0025 #include <linux/cred.h>
0026 
0027 #include <asm/byteorder.h>
0028 
0029 #include "ext4.h"
0030 #include "ext4_jbd2.h"
0031 #include "xattr.h"
0032 #include "acl.h"
0033 
0034 #include <trace/events/ext4.h>
0035 
0036 /*
0037  * ialloc.c contains the inodes allocation and deallocation routines
0038  */
0039 
0040 /*
0041  * The free inodes are managed by bitmaps.  A file system contains several
0042  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
0043  * block for inodes, N blocks for the inode table and data blocks.
0044  *
0045  * The file system contains group descriptors which are located after the
0046  * super block.  Each descriptor contains the number of the bitmap block and
0047  * the free blocks count in the block.
0048  */
0049 
0050 /*
0051  * To avoid calling the atomic setbit hundreds or thousands of times, we only
0052  * need to use it within a single byte (to ensure we get endianness right).
0053  * We can use memset for the rest of the bitmap as there are no other users.
0054  */
0055 void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
0056 {
0057     int i;
0058 
0059     if (start_bit >= end_bit)
0060         return;
0061 
0062     ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
0063     for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
0064         ext4_set_bit(i, bitmap);
0065     if (i < end_bit)
0066         memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
0067 }
0068 
0069 void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate)
0070 {
0071     if (uptodate) {
0072         set_buffer_uptodate(bh);
0073         set_bitmap_uptodate(bh);
0074     }
0075     unlock_buffer(bh);
0076     put_bh(bh);
0077 }
0078 
0079 static int ext4_validate_inode_bitmap(struct super_block *sb,
0080                       struct ext4_group_desc *desc,
0081                       ext4_group_t block_group,
0082                       struct buffer_head *bh)
0083 {
0084     ext4_fsblk_t    blk;
0085     struct ext4_group_info *grp;
0086 
0087     if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
0088         return 0;
0089 
0090     grp = ext4_get_group_info(sb, block_group);
0091 
0092     if (buffer_verified(bh))
0093         return 0;
0094     if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
0095         return -EFSCORRUPTED;
0096 
0097     ext4_lock_group(sb, block_group);
0098     if (buffer_verified(bh))
0099         goto verified;
0100     blk = ext4_inode_bitmap(sb, desc);
0101     if (!ext4_inode_bitmap_csum_verify(sb, block_group, desc, bh,
0102                        EXT4_INODES_PER_GROUP(sb) / 8) ||
0103         ext4_simulate_fail(sb, EXT4_SIM_IBITMAP_CRC)) {
0104         ext4_unlock_group(sb, block_group);
0105         ext4_error(sb, "Corrupt inode bitmap - block_group = %u, "
0106                "inode_bitmap = %llu", block_group, blk);
0107         ext4_mark_group_bitmap_corrupted(sb, block_group,
0108                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
0109         return -EFSBADCRC;
0110     }
0111     set_buffer_verified(bh);
0112 verified:
0113     ext4_unlock_group(sb, block_group);
0114     return 0;
0115 }
0116 
0117 /*
0118  * Read the inode allocation bitmap for a given block_group, reading
0119  * into the specified slot in the superblock's bitmap cache.
0120  *
0121  * Return buffer_head of bitmap on success, or an ERR_PTR on error.
0122  */
0123 static struct buffer_head *
0124 ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
0125 {
0126     struct ext4_group_desc *desc;
0127     struct ext4_sb_info *sbi = EXT4_SB(sb);
0128     struct buffer_head *bh = NULL;
0129     ext4_fsblk_t bitmap_blk;
0130     int err;
0131 
0132     desc = ext4_get_group_desc(sb, block_group, NULL);
0133     if (!desc)
0134         return ERR_PTR(-EFSCORRUPTED);
0135 
0136     bitmap_blk = ext4_inode_bitmap(sb, desc);
0137     if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
0138         (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
0139         ext4_error(sb, "Invalid inode bitmap blk %llu in "
0140                "block_group %u", bitmap_blk, block_group);
0141         ext4_mark_group_bitmap_corrupted(sb, block_group,
0142                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
0143         return ERR_PTR(-EFSCORRUPTED);
0144     }
0145     bh = sb_getblk(sb, bitmap_blk);
0146     if (unlikely(!bh)) {
0147         ext4_warning(sb, "Cannot read inode bitmap - "
0148                  "block_group = %u, inode_bitmap = %llu",
0149                  block_group, bitmap_blk);
0150         return ERR_PTR(-ENOMEM);
0151     }
0152     if (bitmap_uptodate(bh))
0153         goto verify;
0154 
0155     lock_buffer(bh);
0156     if (bitmap_uptodate(bh)) {
0157         unlock_buffer(bh);
0158         goto verify;
0159     }
0160 
0161     ext4_lock_group(sb, block_group);
0162     if (ext4_has_group_desc_csum(sb) &&
0163         (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
0164         if (block_group == 0) {
0165             ext4_unlock_group(sb, block_group);
0166             unlock_buffer(bh);
0167             ext4_error(sb, "Inode bitmap for bg 0 marked "
0168                    "uninitialized");
0169             err = -EFSCORRUPTED;
0170             goto out;
0171         }
0172         memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
0173         ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
0174                      sb->s_blocksize * 8, bh->b_data);
0175         set_bitmap_uptodate(bh);
0176         set_buffer_uptodate(bh);
0177         set_buffer_verified(bh);
0178         ext4_unlock_group(sb, block_group);
0179         unlock_buffer(bh);
0180         return bh;
0181     }
0182     ext4_unlock_group(sb, block_group);
0183 
0184     if (buffer_uptodate(bh)) {
0185         /*
0186          * if not uninit if bh is uptodate,
0187          * bitmap is also uptodate
0188          */
0189         set_bitmap_uptodate(bh);
0190         unlock_buffer(bh);
0191         goto verify;
0192     }
0193     /*
0194      * submit the buffer_head for reading
0195      */
0196     trace_ext4_load_inode_bitmap(sb, block_group);
0197     ext4_read_bh(bh, REQ_META | REQ_PRIO, ext4_end_bitmap_read);
0198     ext4_simulate_fail_bh(sb, bh, EXT4_SIM_IBITMAP_EIO);
0199     if (!buffer_uptodate(bh)) {
0200         put_bh(bh);
0201         ext4_error_err(sb, EIO, "Cannot read inode bitmap - "
0202                    "block_group = %u, inode_bitmap = %llu",
0203                    block_group, bitmap_blk);
0204         ext4_mark_group_bitmap_corrupted(sb, block_group,
0205                 EXT4_GROUP_INFO_IBITMAP_CORRUPT);
0206         return ERR_PTR(-EIO);
0207     }
0208 
0209 verify:
0210     err = ext4_validate_inode_bitmap(sb, desc, block_group, bh);
0211     if (err)
0212         goto out;
0213     return bh;
0214 out:
0215     put_bh(bh);
0216     return ERR_PTR(err);
0217 }
0218 
0219 /*
0220  * NOTE! When we get the inode, we're the only people
0221  * that have access to it, and as such there are no
0222  * race conditions we have to worry about. The inode
0223  * is not on the hash-lists, and it cannot be reached
0224  * through the filesystem because the directory entry
0225  * has been deleted earlier.
0226  *
0227  * HOWEVER: we must make sure that we get no aliases,
0228  * which means that we have to call "clear_inode()"
0229  * _before_ we mark the inode not in use in the inode
0230  * bitmaps. Otherwise a newly created file might use
0231  * the same inode number (not actually the same pointer
0232  * though), and then we'd have two inodes sharing the
0233  * same inode number and space on the harddisk.
0234  */
0235 void ext4_free_inode(handle_t *handle, struct inode *inode)
0236 {
0237     struct super_block *sb = inode->i_sb;
0238     int is_directory;
0239     unsigned long ino;
0240     struct buffer_head *bitmap_bh = NULL;
0241     struct buffer_head *bh2;
0242     ext4_group_t block_group;
0243     unsigned long bit;
0244     struct ext4_group_desc *gdp;
0245     struct ext4_super_block *es;
0246     struct ext4_sb_info *sbi;
0247     int fatal = 0, err, count, cleared;
0248     struct ext4_group_info *grp;
0249 
0250     if (!sb) {
0251         printk(KERN_ERR "EXT4-fs: %s:%d: inode on "
0252                "nonexistent device\n", __func__, __LINE__);
0253         return;
0254     }
0255     if (atomic_read(&inode->i_count) > 1) {
0256         ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d",
0257              __func__, __LINE__, inode->i_ino,
0258              atomic_read(&inode->i_count));
0259         return;
0260     }
0261     if (inode->i_nlink) {
0262         ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n",
0263              __func__, __LINE__, inode->i_ino, inode->i_nlink);
0264         return;
0265     }
0266     sbi = EXT4_SB(sb);
0267 
0268     ino = inode->i_ino;
0269     ext4_debug("freeing inode %lu\n", ino);
0270     trace_ext4_free_inode(inode);
0271 
0272     dquot_initialize(inode);
0273     dquot_free_inode(inode);
0274 
0275     is_directory = S_ISDIR(inode->i_mode);
0276 
0277     /* Do this BEFORE marking the inode not in use or returning an error */
0278     ext4_clear_inode(inode);
0279 
0280     es = sbi->s_es;
0281     if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
0282         ext4_error(sb, "reserved or nonexistent inode %lu", ino);
0283         goto error_return;
0284     }
0285     block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
0286     bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
0287     bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
0288     /* Don't bother if the inode bitmap is corrupt. */
0289     if (IS_ERR(bitmap_bh)) {
0290         fatal = PTR_ERR(bitmap_bh);
0291         bitmap_bh = NULL;
0292         goto error_return;
0293     }
0294     if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
0295         grp = ext4_get_group_info(sb, block_group);
0296         if (unlikely(EXT4_MB_GRP_IBITMAP_CORRUPT(grp))) {
0297             fatal = -EFSCORRUPTED;
0298             goto error_return;
0299         }
0300     }
0301 
0302     BUFFER_TRACE(bitmap_bh, "get_write_access");
0303     fatal = ext4_journal_get_write_access(handle, sb, bitmap_bh,
0304                           EXT4_JTR_NONE);
0305     if (fatal)
0306         goto error_return;
0307 
0308     fatal = -ESRCH;
0309     gdp = ext4_get_group_desc(sb, block_group, &bh2);
0310     if (gdp) {
0311         BUFFER_TRACE(bh2, "get_write_access");
0312         fatal = ext4_journal_get_write_access(handle, sb, bh2,
0313                               EXT4_JTR_NONE);
0314     }
0315     ext4_lock_group(sb, block_group);
0316     cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data);
0317     if (fatal || !cleared) {
0318         ext4_unlock_group(sb, block_group);
0319         goto out;
0320     }
0321 
0322     count = ext4_free_inodes_count(sb, gdp) + 1;
0323     ext4_free_inodes_set(sb, gdp, count);
0324     if (is_directory) {
0325         count = ext4_used_dirs_count(sb, gdp) - 1;
0326         ext4_used_dirs_set(sb, gdp, count);
0327         if (percpu_counter_initialized(&sbi->s_dirs_counter))
0328             percpu_counter_dec(&sbi->s_dirs_counter);
0329     }
0330     ext4_inode_bitmap_csum_set(sb, block_group, gdp, bitmap_bh,
0331                    EXT4_INODES_PER_GROUP(sb) / 8);
0332     ext4_group_desc_csum_set(sb, block_group, gdp);
0333     ext4_unlock_group(sb, block_group);
0334 
0335     if (percpu_counter_initialized(&sbi->s_freeinodes_counter))
0336         percpu_counter_inc(&sbi->s_freeinodes_counter);
0337     if (sbi->s_log_groups_per_flex) {
0338         struct flex_groups *fg;
0339 
0340         fg = sbi_array_rcu_deref(sbi, s_flex_groups,
0341                      ext4_flex_group(sbi, block_group));
0342         atomic_inc(&fg->free_inodes);
0343         if (is_directory)
0344             atomic_dec(&fg->used_dirs);
0345     }
0346     BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
0347     fatal = ext4_handle_dirty_metadata(handle, NULL, bh2);
0348 out:
0349     if (cleared) {
0350         BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata");
0351         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
0352         if (!fatal)
0353             fatal = err;
0354     } else {
0355         ext4_error(sb, "bit already cleared for inode %lu", ino);
0356         ext4_mark_group_bitmap_corrupted(sb, block_group,
0357                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
0358     }
0359 
0360 error_return:
0361     brelse(bitmap_bh);
0362     ext4_std_error(sb, fatal);
0363 }
0364 
0365 struct orlov_stats {
0366     __u64 free_clusters;
0367     __u32 free_inodes;
0368     __u32 used_dirs;
0369 };
0370 
0371 /*
0372  * Helper function for Orlov's allocator; returns critical information
0373  * for a particular block group or flex_bg.  If flex_size is 1, then g
0374  * is a block group number; otherwise it is flex_bg number.
0375  */
0376 static void get_orlov_stats(struct super_block *sb, ext4_group_t g,
0377                 int flex_size, struct orlov_stats *stats)
0378 {
0379     struct ext4_group_desc *desc;
0380 
0381     if (flex_size > 1) {
0382         struct flex_groups *fg = sbi_array_rcu_deref(EXT4_SB(sb),
0383                                  s_flex_groups, g);
0384         stats->free_inodes = atomic_read(&fg->free_inodes);
0385         stats->free_clusters = atomic64_read(&fg->free_clusters);
0386         stats->used_dirs = atomic_read(&fg->used_dirs);
0387         return;
0388     }
0389 
0390     desc = ext4_get_group_desc(sb, g, NULL);
0391     if (desc) {
0392         stats->free_inodes = ext4_free_inodes_count(sb, desc);
0393         stats->free_clusters = ext4_free_group_clusters(sb, desc);
0394         stats->used_dirs = ext4_used_dirs_count(sb, desc);
0395     } else {
0396         stats->free_inodes = 0;
0397         stats->free_clusters = 0;
0398         stats->used_dirs = 0;
0399     }
0400 }
0401 
0402 /*
0403  * Orlov's allocator for directories.
0404  *
0405  * We always try to spread first-level directories.
0406  *
0407  * If there are blockgroups with both free inodes and free clusters counts
0408  * not worse than average we return one with smallest directory count.
0409  * Otherwise we simply return a random group.
0410  *
0411  * For the rest rules look so:
0412  *
0413  * It's OK to put directory into a group unless
0414  * it has too many directories already (max_dirs) or
0415  * it has too few free inodes left (min_inodes) or
0416  * it has too few free clusters left (min_clusters) or
0417  * Parent's group is preferred, if it doesn't satisfy these
0418  * conditions we search cyclically through the rest. If none
0419  * of the groups look good we just look for a group with more
0420  * free inodes than average (starting at parent's group).
0421  */
0422 
0423 static int find_group_orlov(struct super_block *sb, struct inode *parent,
0424                 ext4_group_t *group, umode_t mode,
0425                 const struct qstr *qstr)
0426 {
0427     ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
0428     struct ext4_sb_info *sbi = EXT4_SB(sb);
0429     ext4_group_t real_ngroups = ext4_get_groups_count(sb);
0430     int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
0431     unsigned int freei, avefreei, grp_free;
0432     ext4_fsblk_t freec, avefreec;
0433     unsigned int ndirs;
0434     int max_dirs, min_inodes;
0435     ext4_grpblk_t min_clusters;
0436     ext4_group_t i, grp, g, ngroups;
0437     struct ext4_group_desc *desc;
0438     struct orlov_stats stats;
0439     int flex_size = ext4_flex_bg_size(sbi);
0440     struct dx_hash_info hinfo;
0441 
0442     ngroups = real_ngroups;
0443     if (flex_size > 1) {
0444         ngroups = (real_ngroups + flex_size - 1) >>
0445             sbi->s_log_groups_per_flex;
0446         parent_group >>= sbi->s_log_groups_per_flex;
0447     }
0448 
0449     freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
0450     avefreei = freei / ngroups;
0451     freec = percpu_counter_read_positive(&sbi->s_freeclusters_counter);
0452     avefreec = freec;
0453     do_div(avefreec, ngroups);
0454     ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
0455 
0456     if (S_ISDIR(mode) &&
0457         ((parent == d_inode(sb->s_root)) ||
0458          (ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) {
0459         int best_ndir = inodes_per_group;
0460         int ret = -1;
0461 
0462         if (qstr) {
0463             hinfo.hash_version = DX_HASH_HALF_MD4;
0464             hinfo.seed = sbi->s_hash_seed;
0465             ext4fs_dirhash(parent, qstr->name, qstr->len, &hinfo);
0466             grp = hinfo.hash;
0467         } else
0468             grp = prandom_u32();
0469         parent_group = (unsigned)grp % ngroups;
0470         for (i = 0; i < ngroups; i++) {
0471             g = (parent_group + i) % ngroups;
0472             get_orlov_stats(sb, g, flex_size, &stats);
0473             if (!stats.free_inodes)
0474                 continue;
0475             if (stats.used_dirs >= best_ndir)
0476                 continue;
0477             if (stats.free_inodes < avefreei)
0478                 continue;
0479             if (stats.free_clusters < avefreec)
0480                 continue;
0481             grp = g;
0482             ret = 0;
0483             best_ndir = stats.used_dirs;
0484         }
0485         if (ret)
0486             goto fallback;
0487     found_flex_bg:
0488         if (flex_size == 1) {
0489             *group = grp;
0490             return 0;
0491         }
0492 
0493         /*
0494          * We pack inodes at the beginning of the flexgroup's
0495          * inode tables.  Block allocation decisions will do
0496          * something similar, although regular files will
0497          * start at 2nd block group of the flexgroup.  See
0498          * ext4_ext_find_goal() and ext4_find_near().
0499          */
0500         grp *= flex_size;
0501         for (i = 0; i < flex_size; i++) {
0502             if (grp+i >= real_ngroups)
0503                 break;
0504             desc = ext4_get_group_desc(sb, grp+i, NULL);
0505             if (desc && ext4_free_inodes_count(sb, desc)) {
0506                 *group = grp+i;
0507                 return 0;
0508             }
0509         }
0510         goto fallback;
0511     }
0512 
0513     max_dirs = ndirs / ngroups + inodes_per_group*flex_size / 16;
0514     min_inodes = avefreei - inodes_per_group*flex_size / 4;
0515     if (min_inodes < 1)
0516         min_inodes = 1;
0517     min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4;
0518 
0519     /*
0520      * Start looking in the flex group where we last allocated an
0521      * inode for this parent directory
0522      */
0523     if (EXT4_I(parent)->i_last_alloc_group != ~0) {
0524         parent_group = EXT4_I(parent)->i_last_alloc_group;
0525         if (flex_size > 1)
0526             parent_group >>= sbi->s_log_groups_per_flex;
0527     }
0528 
0529     for (i = 0; i < ngroups; i++) {
0530         grp = (parent_group + i) % ngroups;
0531         get_orlov_stats(sb, grp, flex_size, &stats);
0532         if (stats.used_dirs >= max_dirs)
0533             continue;
0534         if (stats.free_inodes < min_inodes)
0535             continue;
0536         if (stats.free_clusters < min_clusters)
0537             continue;
0538         goto found_flex_bg;
0539     }
0540 
0541 fallback:
0542     ngroups = real_ngroups;
0543     avefreei = freei / ngroups;
0544 fallback_retry:
0545     parent_group = EXT4_I(parent)->i_block_group;
0546     for (i = 0; i < ngroups; i++) {
0547         grp = (parent_group + i) % ngroups;
0548         desc = ext4_get_group_desc(sb, grp, NULL);
0549         if (desc) {
0550             grp_free = ext4_free_inodes_count(sb, desc);
0551             if (grp_free && grp_free >= avefreei) {
0552                 *group = grp;
0553                 return 0;
0554             }
0555         }
0556     }
0557 
0558     if (avefreei) {
0559         /*
0560          * The free-inodes counter is approximate, and for really small
0561          * filesystems the above test can fail to find any blockgroups
0562          */
0563         avefreei = 0;
0564         goto fallback_retry;
0565     }
0566 
0567     return -1;
0568 }
0569 
0570 static int find_group_other(struct super_block *sb, struct inode *parent,
0571                 ext4_group_t *group, umode_t mode)
0572 {
0573     ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
0574     ext4_group_t i, last, ngroups = ext4_get_groups_count(sb);
0575     struct ext4_group_desc *desc;
0576     int flex_size = ext4_flex_bg_size(EXT4_SB(sb));
0577 
0578     /*
0579      * Try to place the inode is the same flex group as its
0580      * parent.  If we can't find space, use the Orlov algorithm to
0581      * find another flex group, and store that information in the
0582      * parent directory's inode information so that use that flex
0583      * group for future allocations.
0584      */
0585     if (flex_size > 1) {
0586         int retry = 0;
0587 
0588     try_again:
0589         parent_group &= ~(flex_size-1);
0590         last = parent_group + flex_size;
0591         if (last > ngroups)
0592             last = ngroups;
0593         for  (i = parent_group; i < last; i++) {
0594             desc = ext4_get_group_desc(sb, i, NULL);
0595             if (desc && ext4_free_inodes_count(sb, desc)) {
0596                 *group = i;
0597                 return 0;
0598             }
0599         }
0600         if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) {
0601             retry = 1;
0602             parent_group = EXT4_I(parent)->i_last_alloc_group;
0603             goto try_again;
0604         }
0605         /*
0606          * If this didn't work, use the Orlov search algorithm
0607          * to find a new flex group; we pass in the mode to
0608          * avoid the topdir algorithms.
0609          */
0610         *group = parent_group + flex_size;
0611         if (*group > ngroups)
0612             *group = 0;
0613         return find_group_orlov(sb, parent, group, mode, NULL);
0614     }
0615 
0616     /*
0617      * Try to place the inode in its parent directory
0618      */
0619     *group = parent_group;
0620     desc = ext4_get_group_desc(sb, *group, NULL);
0621     if (desc && ext4_free_inodes_count(sb, desc) &&
0622         ext4_free_group_clusters(sb, desc))
0623         return 0;
0624 
0625     /*
0626      * We're going to place this inode in a different blockgroup from its
0627      * parent.  We want to cause files in a common directory to all land in
0628      * the same blockgroup.  But we want files which are in a different
0629      * directory which shares a blockgroup with our parent to land in a
0630      * different blockgroup.
0631      *
0632      * So add our directory's i_ino into the starting point for the hash.
0633      */
0634     *group = (*group + parent->i_ino) % ngroups;
0635 
0636     /*
0637      * Use a quadratic hash to find a group with a free inode and some free
0638      * blocks.
0639      */
0640     for (i = 1; i < ngroups; i <<= 1) {
0641         *group += i;
0642         if (*group >= ngroups)
0643             *group -= ngroups;
0644         desc = ext4_get_group_desc(sb, *group, NULL);
0645         if (desc && ext4_free_inodes_count(sb, desc) &&
0646             ext4_free_group_clusters(sb, desc))
0647             return 0;
0648     }
0649 
0650     /*
0651      * That failed: try linear search for a free inode, even if that group
0652      * has no free blocks.
0653      */
0654     *group = parent_group;
0655     for (i = 0; i < ngroups; i++) {
0656         if (++*group >= ngroups)
0657             *group = 0;
0658         desc = ext4_get_group_desc(sb, *group, NULL);
0659         if (desc && ext4_free_inodes_count(sb, desc))
0660             return 0;
0661     }
0662 
0663     return -1;
0664 }
0665 
0666 /*
0667  * In no journal mode, if an inode has recently been deleted, we want
0668  * to avoid reusing it until we're reasonably sure the inode table
0669  * block has been written back to disk.  (Yes, these values are
0670  * somewhat arbitrary...)
0671  */
0672 #define RECENTCY_MIN    60
0673 #define RECENTCY_DIRTY  300
0674 
0675 static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino)
0676 {
0677     struct ext4_group_desc  *gdp;
0678     struct ext4_inode   *raw_inode;
0679     struct buffer_head  *bh;
0680     int inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
0681     int offset, ret = 0;
0682     int recentcy = RECENTCY_MIN;
0683     u32 dtime, now;
0684 
0685     gdp = ext4_get_group_desc(sb, group, NULL);
0686     if (unlikely(!gdp))
0687         return 0;
0688 
0689     bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) +
0690                (ino / inodes_per_block));
0691     if (!bh || !buffer_uptodate(bh))
0692         /*
0693          * If the block is not in the buffer cache, then it
0694          * must have been written out.
0695          */
0696         goto out;
0697 
0698     offset = (ino % inodes_per_block) * EXT4_INODE_SIZE(sb);
0699     raw_inode = (struct ext4_inode *) (bh->b_data + offset);
0700 
0701     /* i_dtime is only 32 bits on disk, but we only care about relative
0702      * times in the range of a few minutes (i.e. long enough to sync a
0703      * recently-deleted inode to disk), so using the low 32 bits of the
0704      * clock (a 68 year range) is enough, see time_before32() */
0705     dtime = le32_to_cpu(raw_inode->i_dtime);
0706     now = ktime_get_real_seconds();
0707     if (buffer_dirty(bh))
0708         recentcy += RECENTCY_DIRTY;
0709 
0710     if (dtime && time_before32(dtime, now) &&
0711         time_before32(now, dtime + recentcy))
0712         ret = 1;
0713 out:
0714     brelse(bh);
0715     return ret;
0716 }
0717 
0718 static int find_inode_bit(struct super_block *sb, ext4_group_t group,
0719               struct buffer_head *bitmap, unsigned long *ino)
0720 {
0721     bool check_recently_deleted = EXT4_SB(sb)->s_journal == NULL;
0722     unsigned long recently_deleted_ino = EXT4_INODES_PER_GROUP(sb);
0723 
0724 next:
0725     *ino = ext4_find_next_zero_bit((unsigned long *)
0726                        bitmap->b_data,
0727                        EXT4_INODES_PER_GROUP(sb), *ino);
0728     if (*ino >= EXT4_INODES_PER_GROUP(sb))
0729         goto not_found;
0730 
0731     if (check_recently_deleted && recently_deleted(sb, group, *ino)) {
0732         recently_deleted_ino = *ino;
0733         *ino = *ino + 1;
0734         if (*ino < EXT4_INODES_PER_GROUP(sb))
0735             goto next;
0736         goto not_found;
0737     }
0738     return 1;
0739 not_found:
0740     if (recently_deleted_ino >= EXT4_INODES_PER_GROUP(sb))
0741         return 0;
0742     /*
0743      * Not reusing recently deleted inodes is mostly a preference. We don't
0744      * want to report ENOSPC or skew allocation patterns because of that.
0745      * So return even recently deleted inode if we could find better in the
0746      * given range.
0747      */
0748     *ino = recently_deleted_ino;
0749     return 1;
0750 }
0751 
0752 int ext4_mark_inode_used(struct super_block *sb, int ino)
0753 {
0754     unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
0755     struct buffer_head *inode_bitmap_bh = NULL, *group_desc_bh = NULL;
0756     struct ext4_group_desc *gdp;
0757     ext4_group_t group;
0758     int bit;
0759     int err = -EFSCORRUPTED;
0760 
0761     if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
0762         goto out;
0763 
0764     group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
0765     bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
0766     inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
0767     if (IS_ERR(inode_bitmap_bh))
0768         return PTR_ERR(inode_bitmap_bh);
0769 
0770     if (ext4_test_bit(bit, inode_bitmap_bh->b_data)) {
0771         err = 0;
0772         goto out;
0773     }
0774 
0775     gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
0776     if (!gdp || !group_desc_bh) {
0777         err = -EINVAL;
0778         goto out;
0779     }
0780 
0781     ext4_set_bit(bit, inode_bitmap_bh->b_data);
0782 
0783     BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
0784     err = ext4_handle_dirty_metadata(NULL, NULL, inode_bitmap_bh);
0785     if (err) {
0786         ext4_std_error(sb, err);
0787         goto out;
0788     }
0789     err = sync_dirty_buffer(inode_bitmap_bh);
0790     if (err) {
0791         ext4_std_error(sb, err);
0792         goto out;
0793     }
0794 
0795     /* We may have to initialize the block bitmap if it isn't already */
0796     if (ext4_has_group_desc_csum(sb) &&
0797         gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
0798         struct buffer_head *block_bitmap_bh;
0799 
0800         block_bitmap_bh = ext4_read_block_bitmap(sb, group);
0801         if (IS_ERR(block_bitmap_bh)) {
0802             err = PTR_ERR(block_bitmap_bh);
0803             goto out;
0804         }
0805 
0806         BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
0807         err = ext4_handle_dirty_metadata(NULL, NULL, block_bitmap_bh);
0808         sync_dirty_buffer(block_bitmap_bh);
0809 
0810         /* recheck and clear flag under lock if we still need to */
0811         ext4_lock_group(sb, group);
0812         if (ext4_has_group_desc_csum(sb) &&
0813             (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
0814             gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
0815             ext4_free_group_clusters_set(sb, gdp,
0816                 ext4_free_clusters_after_init(sb, group, gdp));
0817             ext4_block_bitmap_csum_set(sb, group, gdp,
0818                            block_bitmap_bh);
0819             ext4_group_desc_csum_set(sb, group, gdp);
0820         }
0821         ext4_unlock_group(sb, group);
0822         brelse(block_bitmap_bh);
0823 
0824         if (err) {
0825             ext4_std_error(sb, err);
0826             goto out;
0827         }
0828     }
0829 
0830     /* Update the relevant bg descriptor fields */
0831     if (ext4_has_group_desc_csum(sb)) {
0832         int free;
0833 
0834         ext4_lock_group(sb, group); /* while we modify the bg desc */
0835         free = EXT4_INODES_PER_GROUP(sb) -
0836             ext4_itable_unused_count(sb, gdp);
0837         if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
0838             gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
0839             free = 0;
0840         }
0841 
0842         /*
0843          * Check the relative inode number against the last used
0844          * relative inode number in this group. if it is greater
0845          * we need to update the bg_itable_unused count
0846          */
0847         if (bit >= free)
0848             ext4_itable_unused_set(sb, gdp,
0849                     (EXT4_INODES_PER_GROUP(sb) - bit - 1));
0850     } else {
0851         ext4_lock_group(sb, group);
0852     }
0853 
0854     ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
0855     if (ext4_has_group_desc_csum(sb)) {
0856         ext4_inode_bitmap_csum_set(sb, group, gdp, inode_bitmap_bh,
0857                        EXT4_INODES_PER_GROUP(sb) / 8);
0858         ext4_group_desc_csum_set(sb, group, gdp);
0859     }
0860 
0861     ext4_unlock_group(sb, group);
0862     err = ext4_handle_dirty_metadata(NULL, NULL, group_desc_bh);
0863     sync_dirty_buffer(group_desc_bh);
0864 out:
0865     return err;
0866 }
0867 
0868 static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
0869                         bool encrypt)
0870 {
0871     struct super_block *sb = dir->i_sb;
0872     int nblocks = 0;
0873 #ifdef CONFIG_EXT4_FS_POSIX_ACL
0874     struct posix_acl *p = get_acl(dir, ACL_TYPE_DEFAULT);
0875 
0876     if (IS_ERR(p))
0877         return PTR_ERR(p);
0878     if (p) {
0879         int acl_size = p->a_count * sizeof(ext4_acl_entry);
0880 
0881         nblocks += (S_ISDIR(mode) ? 2 : 1) *
0882             __ext4_xattr_set_credits(sb, NULL /* inode */,
0883                          NULL /* block_bh */, acl_size,
0884                          true /* is_create */);
0885         posix_acl_release(p);
0886     }
0887 #endif
0888 
0889 #ifdef CONFIG_SECURITY
0890     {
0891         int num_security_xattrs = 1;
0892 
0893 #ifdef CONFIG_INTEGRITY
0894         num_security_xattrs++;
0895 #endif
0896         /*
0897          * We assume that security xattrs are never more than 1k.
0898          * In practice they are under 128 bytes.
0899          */
0900         nblocks += num_security_xattrs *
0901             __ext4_xattr_set_credits(sb, NULL /* inode */,
0902                          NULL /* block_bh */, 1024,
0903                          true /* is_create */);
0904     }
0905 #endif
0906     if (encrypt)
0907         nblocks += __ext4_xattr_set_credits(sb,
0908                             NULL /* inode */,
0909                             NULL /* block_bh */,
0910                             FSCRYPT_SET_CONTEXT_MAX_SIZE,
0911                             true /* is_create */);
0912     return nblocks;
0913 }
0914 
0915 /*
0916  * There are two policies for allocating an inode.  If the new inode is
0917  * a directory, then a forward search is made for a block group with both
0918  * free space and a low directory-to-inode ratio; if that fails, then of
0919  * the groups with above-average free space, that group with the fewest
0920  * directories already is chosen.
0921  *
0922  * For other inodes, search forward from the parent directory's block
0923  * group to find a free inode.
0924  */
0925 struct inode *__ext4_new_inode(struct user_namespace *mnt_userns,
0926                    handle_t *handle, struct inode *dir,
0927                    umode_t mode, const struct qstr *qstr,
0928                    __u32 goal, uid_t *owner, __u32 i_flags,
0929                    int handle_type, unsigned int line_no,
0930                    int nblocks)
0931 {
0932     struct super_block *sb;
0933     struct buffer_head *inode_bitmap_bh = NULL;
0934     struct buffer_head *group_desc_bh;
0935     ext4_group_t ngroups, group = 0;
0936     unsigned long ino = 0;
0937     struct inode *inode;
0938     struct ext4_group_desc *gdp = NULL;
0939     struct ext4_inode_info *ei;
0940     struct ext4_sb_info *sbi;
0941     int ret2, err;
0942     struct inode *ret;
0943     ext4_group_t i;
0944     ext4_group_t flex_group;
0945     struct ext4_group_info *grp = NULL;
0946     bool encrypt = false;
0947 
0948     /* Cannot create files in a deleted directory */
0949     if (!dir || !dir->i_nlink)
0950         return ERR_PTR(-EPERM);
0951 
0952     sb = dir->i_sb;
0953     sbi = EXT4_SB(sb);
0954 
0955     if (unlikely(ext4_forced_shutdown(sbi)))
0956         return ERR_PTR(-EIO);
0957 
0958     ngroups = ext4_get_groups_count(sb);
0959     trace_ext4_request_inode(dir, mode);
0960     inode = new_inode(sb);
0961     if (!inode)
0962         return ERR_PTR(-ENOMEM);
0963     ei = EXT4_I(inode);
0964 
0965     /*
0966      * Initialize owners and quota early so that we don't have to account
0967      * for quota initialization worst case in standard inode creating
0968      * transaction
0969      */
0970     if (owner) {
0971         inode->i_mode = mode;
0972         i_uid_write(inode, owner[0]);
0973         i_gid_write(inode, owner[1]);
0974     } else if (test_opt(sb, GRPID)) {
0975         inode->i_mode = mode;
0976         inode_fsuid_set(inode, mnt_userns);
0977         inode->i_gid = dir->i_gid;
0978     } else
0979         inode_init_owner(mnt_userns, inode, dir, mode);
0980 
0981     if (ext4_has_feature_project(sb) &&
0982         ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT))
0983         ei->i_projid = EXT4_I(dir)->i_projid;
0984     else
0985         ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID);
0986 
0987     if (!(i_flags & EXT4_EA_INODE_FL)) {
0988         err = fscrypt_prepare_new_inode(dir, inode, &encrypt);
0989         if (err)
0990             goto out;
0991     }
0992 
0993     err = dquot_initialize(inode);
0994     if (err)
0995         goto out;
0996 
0997     if (!handle && sbi->s_journal && !(i_flags & EXT4_EA_INODE_FL)) {
0998         ret2 = ext4_xattr_credits_for_new_inode(dir, mode, encrypt);
0999         if (ret2 < 0) {
1000             err = ret2;
1001             goto out;
1002         }
1003         nblocks += ret2;
1004     }
1005 
1006     if (!goal)
1007         goal = sbi->s_inode_goal;
1008 
1009     if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) {
1010         group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
1011         ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
1012         ret2 = 0;
1013         goto got_group;
1014     }
1015 
1016     if (S_ISDIR(mode))
1017         ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
1018     else
1019         ret2 = find_group_other(sb, dir, &group, mode);
1020 
1021 got_group:
1022     EXT4_I(dir)->i_last_alloc_group = group;
1023     err = -ENOSPC;
1024     if (ret2 == -1)
1025         goto out;
1026 
1027     /*
1028      * Normally we will only go through one pass of this loop,
1029      * unless we get unlucky and it turns out the group we selected
1030      * had its last inode grabbed by someone else.
1031      */
1032     for (i = 0; i < ngroups; i++, ino = 0) {
1033         err = -EIO;
1034 
1035         gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1036         if (!gdp)
1037             goto out;
1038 
1039         /*
1040          * Check free inodes count before loading bitmap.
1041          */
1042         if (ext4_free_inodes_count(sb, gdp) == 0)
1043             goto next_group;
1044 
1045         if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1046             grp = ext4_get_group_info(sb, group);
1047             /*
1048              * Skip groups with already-known suspicious inode
1049              * tables
1050              */
1051             if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
1052                 goto next_group;
1053         }
1054 
1055         brelse(inode_bitmap_bh);
1056         inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
1057         /* Skip groups with suspicious inode tables */
1058         if (((!(sbi->s_mount_state & EXT4_FC_REPLAY))
1059              && EXT4_MB_GRP_IBITMAP_CORRUPT(grp)) ||
1060             IS_ERR(inode_bitmap_bh)) {
1061             inode_bitmap_bh = NULL;
1062             goto next_group;
1063         }
1064 
1065 repeat_in_this_group:
1066         ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
1067         if (!ret2)
1068             goto next_group;
1069 
1070         if (group == 0 && (ino + 1) < EXT4_FIRST_INO(sb)) {
1071             ext4_error(sb, "reserved inode found cleared - "
1072                    "inode=%lu", ino + 1);
1073             ext4_mark_group_bitmap_corrupted(sb, group,
1074                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1075             goto next_group;
1076         }
1077 
1078         if ((!(sbi->s_mount_state & EXT4_FC_REPLAY)) && !handle) {
1079             BUG_ON(nblocks <= 0);
1080             handle = __ext4_journal_start_sb(dir->i_sb, line_no,
1081                  handle_type, nblocks, 0,
1082                  ext4_trans_default_revoke_credits(sb));
1083             if (IS_ERR(handle)) {
1084                 err = PTR_ERR(handle);
1085                 ext4_std_error(sb, err);
1086                 goto out;
1087             }
1088         }
1089         BUFFER_TRACE(inode_bitmap_bh, "get_write_access");
1090         err = ext4_journal_get_write_access(handle, sb, inode_bitmap_bh,
1091                             EXT4_JTR_NONE);
1092         if (err) {
1093             ext4_std_error(sb, err);
1094             goto out;
1095         }
1096         ext4_lock_group(sb, group);
1097         ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data);
1098         if (ret2) {
1099             /* Someone already took the bit. Repeat the search
1100              * with lock held.
1101              */
1102             ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
1103             if (ret2) {
1104                 ext4_set_bit(ino, inode_bitmap_bh->b_data);
1105                 ret2 = 0;
1106             } else {
1107                 ret2 = 1; /* we didn't grab the inode */
1108             }
1109         }
1110         ext4_unlock_group(sb, group);
1111         ino++;      /* the inode bitmap is zero-based */
1112         if (!ret2)
1113             goto got; /* we grabbed the inode! */
1114 
1115         if (ino < EXT4_INODES_PER_GROUP(sb))
1116             goto repeat_in_this_group;
1117 next_group:
1118         if (++group == ngroups)
1119             group = 0;
1120     }
1121     err = -ENOSPC;
1122     goto out;
1123 
1124 got:
1125     BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
1126     err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh);
1127     if (err) {
1128         ext4_std_error(sb, err);
1129         goto out;
1130     }
1131 
1132     BUFFER_TRACE(group_desc_bh, "get_write_access");
1133     err = ext4_journal_get_write_access(handle, sb, group_desc_bh,
1134                         EXT4_JTR_NONE);
1135     if (err) {
1136         ext4_std_error(sb, err);
1137         goto out;
1138     }
1139 
1140     /* We may have to initialize the block bitmap if it isn't already */
1141     if (ext4_has_group_desc_csum(sb) &&
1142         gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
1143         struct buffer_head *block_bitmap_bh;
1144 
1145         block_bitmap_bh = ext4_read_block_bitmap(sb, group);
1146         if (IS_ERR(block_bitmap_bh)) {
1147             err = PTR_ERR(block_bitmap_bh);
1148             goto out;
1149         }
1150         BUFFER_TRACE(block_bitmap_bh, "get block bitmap access");
1151         err = ext4_journal_get_write_access(handle, sb, block_bitmap_bh,
1152                             EXT4_JTR_NONE);
1153         if (err) {
1154             brelse(block_bitmap_bh);
1155             ext4_std_error(sb, err);
1156             goto out;
1157         }
1158 
1159         BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
1160         err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh);
1161 
1162         /* recheck and clear flag under lock if we still need to */
1163         ext4_lock_group(sb, group);
1164         if (ext4_has_group_desc_csum(sb) &&
1165             (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
1166             gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
1167             ext4_free_group_clusters_set(sb, gdp,
1168                 ext4_free_clusters_after_init(sb, group, gdp));
1169             ext4_block_bitmap_csum_set(sb, group, gdp,
1170                            block_bitmap_bh);
1171             ext4_group_desc_csum_set(sb, group, gdp);
1172         }
1173         ext4_unlock_group(sb, group);
1174         brelse(block_bitmap_bh);
1175 
1176         if (err) {
1177             ext4_std_error(sb, err);
1178             goto out;
1179         }
1180     }
1181 
1182     /* Update the relevant bg descriptor fields */
1183     if (ext4_has_group_desc_csum(sb)) {
1184         int free;
1185         struct ext4_group_info *grp = NULL;
1186 
1187         if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1188             grp = ext4_get_group_info(sb, group);
1189             down_read(&grp->alloc_sem); /*
1190                              * protect vs itable
1191                              * lazyinit
1192                              */
1193         }
1194         ext4_lock_group(sb, group); /* while we modify the bg desc */
1195         free = EXT4_INODES_PER_GROUP(sb) -
1196             ext4_itable_unused_count(sb, gdp);
1197         if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
1198             gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
1199             free = 0;
1200         }
1201         /*
1202          * Check the relative inode number against the last used
1203          * relative inode number in this group. if it is greater
1204          * we need to update the bg_itable_unused count
1205          */
1206         if (ino > free)
1207             ext4_itable_unused_set(sb, gdp,
1208                     (EXT4_INODES_PER_GROUP(sb) - ino));
1209         if (!(sbi->s_mount_state & EXT4_FC_REPLAY))
1210             up_read(&grp->alloc_sem);
1211     } else {
1212         ext4_lock_group(sb, group);
1213     }
1214 
1215     ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
1216     if (S_ISDIR(mode)) {
1217         ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
1218         if (sbi->s_log_groups_per_flex) {
1219             ext4_group_t f = ext4_flex_group(sbi, group);
1220 
1221             atomic_inc(&sbi_array_rcu_deref(sbi, s_flex_groups,
1222                             f)->used_dirs);
1223         }
1224     }
1225     if (ext4_has_group_desc_csum(sb)) {
1226         ext4_inode_bitmap_csum_set(sb, group, gdp, inode_bitmap_bh,
1227                        EXT4_INODES_PER_GROUP(sb) / 8);
1228         ext4_group_desc_csum_set(sb, group, gdp);
1229     }
1230     ext4_unlock_group(sb, group);
1231 
1232     BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
1233     err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
1234     if (err) {
1235         ext4_std_error(sb, err);
1236         goto out;
1237     }
1238 
1239     percpu_counter_dec(&sbi->s_freeinodes_counter);
1240     if (S_ISDIR(mode))
1241         percpu_counter_inc(&sbi->s_dirs_counter);
1242 
1243     if (sbi->s_log_groups_per_flex) {
1244         flex_group = ext4_flex_group(sbi, group);
1245         atomic_dec(&sbi_array_rcu_deref(sbi, s_flex_groups,
1246                         flex_group)->free_inodes);
1247     }
1248 
1249     inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
1250     /* This is the optimal IO size (for stat), not the fs block size */
1251     inode->i_blocks = 0;
1252     inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
1253     ei->i_crtime = inode->i_mtime;
1254 
1255     memset(ei->i_data, 0, sizeof(ei->i_data));
1256     ei->i_dir_start_lookup = 0;
1257     ei->i_disksize = 0;
1258 
1259     /* Don't inherit extent flag from directory, amongst others. */
1260     ei->i_flags =
1261         ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
1262     ei->i_flags |= i_flags;
1263     ei->i_file_acl = 0;
1264     ei->i_dtime = 0;
1265     ei->i_block_group = group;
1266     ei->i_last_alloc_group = ~0;
1267 
1268     ext4_set_inode_flags(inode, true);
1269     if (IS_DIRSYNC(inode))
1270         ext4_handle_sync(handle);
1271     if (insert_inode_locked(inode) < 0) {
1272         /*
1273          * Likely a bitmap corruption causing inode to be allocated
1274          * twice.
1275          */
1276         err = -EIO;
1277         ext4_error(sb, "failed to insert inode %lu: doubly allocated?",
1278                inode->i_ino);
1279         ext4_mark_group_bitmap_corrupted(sb, group,
1280                     EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1281         goto out;
1282     }
1283     inode->i_generation = prandom_u32();
1284 
1285     /* Precompute checksum seed for inode metadata */
1286     if (ext4_has_metadata_csum(sb)) {
1287         __u32 csum;
1288         __le32 inum = cpu_to_le32(inode->i_ino);
1289         __le32 gen = cpu_to_le32(inode->i_generation);
1290         csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
1291                    sizeof(inum));
1292         ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
1293                           sizeof(gen));
1294     }
1295 
1296     ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
1297     ext4_set_inode_state(inode, EXT4_STATE_NEW);
1298 
1299     ei->i_extra_isize = sbi->s_want_extra_isize;
1300     ei->i_inline_off = 0;
1301     if (ext4_has_feature_inline_data(sb) &&
1302         (!(ei->i_flags & EXT4_DAX_FL) || S_ISDIR(mode)))
1303         ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
1304     ret = inode;
1305     err = dquot_alloc_inode(inode);
1306     if (err)
1307         goto fail_drop;
1308 
1309     /*
1310      * Since the encryption xattr will always be unique, create it first so
1311      * that it's less likely to end up in an external xattr block and
1312      * prevent its deduplication.
1313      */
1314     if (encrypt) {
1315         err = fscrypt_set_context(inode, handle);
1316         if (err)
1317             goto fail_free_drop;
1318     }
1319 
1320     if (!(ei->i_flags & EXT4_EA_INODE_FL)) {
1321         err = ext4_init_acl(handle, inode, dir);
1322         if (err)
1323             goto fail_free_drop;
1324 
1325         err = ext4_init_security(handle, inode, dir, qstr);
1326         if (err)
1327             goto fail_free_drop;
1328     }
1329 
1330     if (ext4_has_feature_extents(sb)) {
1331         /* set extent flag only for directory, file and normal symlink*/
1332         if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
1333             ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
1334             ext4_ext_tree_init(handle, inode);
1335         }
1336     }
1337 
1338     if (ext4_handle_valid(handle)) {
1339         ei->i_sync_tid = handle->h_transaction->t_tid;
1340         ei->i_datasync_tid = handle->h_transaction->t_tid;
1341     }
1342 
1343     err = ext4_mark_inode_dirty(handle, inode);
1344     if (err) {
1345         ext4_std_error(sb, err);
1346         goto fail_free_drop;
1347     }
1348 
1349     ext4_debug("allocating inode %lu\n", inode->i_ino);
1350     trace_ext4_allocate_inode(inode, dir, mode);
1351     brelse(inode_bitmap_bh);
1352     return ret;
1353 
1354 fail_free_drop:
1355     dquot_free_inode(inode);
1356 fail_drop:
1357     clear_nlink(inode);
1358     unlock_new_inode(inode);
1359 out:
1360     dquot_drop(inode);
1361     inode->i_flags |= S_NOQUOTA;
1362     iput(inode);
1363     brelse(inode_bitmap_bh);
1364     return ERR_PTR(err);
1365 }
1366 
1367 /* Verify that we are loading a valid orphan from disk */
1368 struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
1369 {
1370     unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
1371     ext4_group_t block_group;
1372     int bit;
1373     struct buffer_head *bitmap_bh = NULL;
1374     struct inode *inode = NULL;
1375     int err = -EFSCORRUPTED;
1376 
1377     if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
1378         goto bad_orphan;
1379 
1380     block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
1381     bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
1382     bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
1383     if (IS_ERR(bitmap_bh))
1384         return ERR_CAST(bitmap_bh);
1385 
1386     /* Having the inode bit set should be a 100% indicator that this
1387      * is a valid orphan (no e2fsck run on fs).  Orphans also include
1388      * inodes that were being truncated, so we can't check i_nlink==0.
1389      */
1390     if (!ext4_test_bit(bit, bitmap_bh->b_data))
1391         goto bad_orphan;
1392 
1393     inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
1394     if (IS_ERR(inode)) {
1395         err = PTR_ERR(inode);
1396         ext4_error_err(sb, -err,
1397                    "couldn't read orphan inode %lu (err %d)",
1398                    ino, err);
1399         brelse(bitmap_bh);
1400         return inode;
1401     }
1402 
1403     /*
1404      * If the orphans has i_nlinks > 0 then it should be able to
1405      * be truncated, otherwise it won't be removed from the orphan
1406      * list during processing and an infinite loop will result.
1407      * Similarly, it must not be a bad inode.
1408      */
1409     if ((inode->i_nlink && !ext4_can_truncate(inode)) ||
1410         is_bad_inode(inode))
1411         goto bad_orphan;
1412 
1413     if (NEXT_ORPHAN(inode) > max_ino)
1414         goto bad_orphan;
1415     brelse(bitmap_bh);
1416     return inode;
1417 
1418 bad_orphan:
1419     ext4_error(sb, "bad orphan inode %lu", ino);
1420     if (bitmap_bh)
1421         printk(KERN_ERR "ext4_test_bit(bit=%d, block=%llu) = %d\n",
1422                bit, (unsigned long long)bitmap_bh->b_blocknr,
1423                ext4_test_bit(bit, bitmap_bh->b_data));
1424     if (inode) {
1425         printk(KERN_ERR "is_bad_inode(inode)=%d\n",
1426                is_bad_inode(inode));
1427         printk(KERN_ERR "NEXT_ORPHAN(inode)=%u\n",
1428                NEXT_ORPHAN(inode));
1429         printk(KERN_ERR "max_ino=%lu\n", max_ino);
1430         printk(KERN_ERR "i_nlink=%u\n", inode->i_nlink);
1431         /* Avoid freeing blocks if we got a bad deleted inode */
1432         if (inode->i_nlink == 0)
1433             inode->i_blocks = 0;
1434         iput(inode);
1435     }
1436     brelse(bitmap_bh);
1437     return ERR_PTR(err);
1438 }
1439 
1440 unsigned long ext4_count_free_inodes(struct super_block *sb)
1441 {
1442     unsigned long desc_count;
1443     struct ext4_group_desc *gdp;
1444     ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1445 #ifdef EXT4FS_DEBUG
1446     struct ext4_super_block *es;
1447     unsigned long bitmap_count, x;
1448     struct buffer_head *bitmap_bh = NULL;
1449 
1450     es = EXT4_SB(sb)->s_es;
1451     desc_count = 0;
1452     bitmap_count = 0;
1453     gdp = NULL;
1454     for (i = 0; i < ngroups; i++) {
1455         gdp = ext4_get_group_desc(sb, i, NULL);
1456         if (!gdp)
1457             continue;
1458         desc_count += ext4_free_inodes_count(sb, gdp);
1459         brelse(bitmap_bh);
1460         bitmap_bh = ext4_read_inode_bitmap(sb, i);
1461         if (IS_ERR(bitmap_bh)) {
1462             bitmap_bh = NULL;
1463             continue;
1464         }
1465 
1466         x = ext4_count_free(bitmap_bh->b_data,
1467                     EXT4_INODES_PER_GROUP(sb) / 8);
1468         printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1469             (unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
1470         bitmap_count += x;
1471     }
1472     brelse(bitmap_bh);
1473     printk(KERN_DEBUG "ext4_count_free_inodes: "
1474            "stored = %u, computed = %lu, %lu\n",
1475            le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1476     return desc_count;
1477 #else
1478     desc_count = 0;
1479     for (i = 0; i < ngroups; i++) {
1480         gdp = ext4_get_group_desc(sb, i, NULL);
1481         if (!gdp)
1482             continue;
1483         desc_count += ext4_free_inodes_count(sb, gdp);
1484         cond_resched();
1485     }
1486     return desc_count;
1487 #endif
1488 }
1489 
1490 /* Called at mount-time, super-block is locked */
1491 unsigned long ext4_count_dirs(struct super_block * sb)
1492 {
1493     unsigned long count = 0;
1494     ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1495 
1496     for (i = 0; i < ngroups; i++) {
1497         struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1498         if (!gdp)
1499             continue;
1500         count += ext4_used_dirs_count(sb, gdp);
1501     }
1502     return count;
1503 }
1504 
1505 /*
1506  * Zeroes not yet zeroed inode table - just write zeroes through the whole
1507  * inode table. Must be called without any spinlock held. The only place
1508  * where it is called from on active part of filesystem is ext4lazyinit
1509  * thread, so we do not need any special locks, however we have to prevent
1510  * inode allocation from the current group, so we take alloc_sem lock, to
1511  * block ext4_new_inode() until we are finished.
1512  */
1513 int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
1514                  int barrier)
1515 {
1516     struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1517     struct ext4_sb_info *sbi = EXT4_SB(sb);
1518     struct ext4_group_desc *gdp = NULL;
1519     struct buffer_head *group_desc_bh;
1520     handle_t *handle;
1521     ext4_fsblk_t blk;
1522     int num, ret = 0, used_blks = 0;
1523     unsigned long used_inos = 0;
1524 
1525     /* This should not happen, but just to be sure check this */
1526     if (sb_rdonly(sb)) {
1527         ret = 1;
1528         goto out;
1529     }
1530 
1531     gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1532     if (!gdp)
1533         goto out;
1534 
1535     /*
1536      * We do not need to lock this, because we are the only one
1537      * handling this flag.
1538      */
1539     if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
1540         goto out;
1541 
1542     handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
1543     if (IS_ERR(handle)) {
1544         ret = PTR_ERR(handle);
1545         goto out;
1546     }
1547 
1548     down_write(&grp->alloc_sem);
1549     /*
1550      * If inode bitmap was already initialized there may be some
1551      * used inodes so we need to skip blocks with used inodes in
1552      * inode table.
1553      */
1554     if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
1555         used_inos = EXT4_INODES_PER_GROUP(sb) -
1556                 ext4_itable_unused_count(sb, gdp);
1557         used_blks = DIV_ROUND_UP(used_inos, sbi->s_inodes_per_block);
1558 
1559         /* Bogus inode unused count? */
1560         if (used_blks < 0 || used_blks > sbi->s_itb_per_group) {
1561             ext4_error(sb, "Something is wrong with group %u: "
1562                    "used itable blocks: %d; "
1563                    "itable unused count: %u",
1564                    group, used_blks,
1565                    ext4_itable_unused_count(sb, gdp));
1566             ret = 1;
1567             goto err_out;
1568         }
1569 
1570         used_inos += group * EXT4_INODES_PER_GROUP(sb);
1571         /*
1572          * Are there some uninitialized inodes in the inode table
1573          * before the first normal inode?
1574          */
1575         if ((used_blks != sbi->s_itb_per_group) &&
1576              (used_inos < EXT4_FIRST_INO(sb))) {
1577             ext4_error(sb, "Something is wrong with group %u: "
1578                    "itable unused count: %u; "
1579                    "itables initialized count: %ld",
1580                    group, ext4_itable_unused_count(sb, gdp),
1581                    used_inos);
1582             ret = 1;
1583             goto err_out;
1584         }
1585     }
1586 
1587     blk = ext4_inode_table(sb, gdp) + used_blks;
1588     num = sbi->s_itb_per_group - used_blks;
1589 
1590     BUFFER_TRACE(group_desc_bh, "get_write_access");
1591     ret = ext4_journal_get_write_access(handle, sb, group_desc_bh,
1592                         EXT4_JTR_NONE);
1593     if (ret)
1594         goto err_out;
1595 
1596     /*
1597      * Skip zeroout if the inode table is full. But we set the ZEROED
1598      * flag anyway, because obviously, when it is full it does not need
1599      * further zeroing.
1600      */
1601     if (unlikely(num == 0))
1602         goto skip_zeroout;
1603 
1604     ext4_debug("going to zero out inode table in group %d\n",
1605            group);
1606     ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
1607     if (ret < 0)
1608         goto err_out;
1609     if (barrier)
1610         blkdev_issue_flush(sb->s_bdev);
1611 
1612 skip_zeroout:
1613     ext4_lock_group(sb, group);
1614     gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
1615     ext4_group_desc_csum_set(sb, group, gdp);
1616     ext4_unlock_group(sb, group);
1617 
1618     BUFFER_TRACE(group_desc_bh,
1619              "call ext4_handle_dirty_metadata");
1620     ret = ext4_handle_dirty_metadata(handle, NULL,
1621                      group_desc_bh);
1622 
1623 err_out:
1624     up_write(&grp->alloc_sem);
1625     ext4_journal_stop(handle);
1626 out:
1627     return ret;
1628 }