root/fs/ext4/super.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. ext4_sb_bread
  2. ext4_verify_csum_type
  3. ext4_superblock_csum
  4. ext4_superblock_csum_verify
  5. ext4_superblock_csum_set
  6. ext4_kvmalloc
  7. ext4_kvzalloc
  8. ext4_block_bitmap
  9. ext4_inode_bitmap
  10. ext4_inode_table
  11. ext4_free_group_clusters
  12. ext4_free_inodes_count
  13. ext4_used_dirs_count
  14. ext4_itable_unused_count
  15. ext4_block_bitmap_set
  16. ext4_inode_bitmap_set
  17. ext4_inode_table_set
  18. ext4_free_group_clusters_set
  19. ext4_free_inodes_set
  20. ext4_used_dirs_set
  21. ext4_itable_unused_set
  22. __ext4_update_tstamp
  23. __ext4_get_tstamp
  24. __save_error_info
  25. save_error_info
  26. block_device_ejected
  27. ext4_journal_commit_callback
  28. system_going_down
  29. ext4_handle_error
  30. __ext4_error
  31. __ext4_error_inode
  32. __ext4_error_file
  33. ext4_decode_error
  34. __ext4_std_error
  35. __ext4_abort
  36. __ext4_msg
  37. __ext4_warning
  38. __ext4_warning_inode
  39. __ext4_grp_locked_error
  40. ext4_mark_group_bitmap_corrupted
  41. ext4_update_dynamic_rev
  42. ext4_blkdev_get
  43. ext4_blkdev_put
  44. ext4_blkdev_remove
  45. orphan_list_entry
  46. dump_orphan_list
  47. ext4_quota_off_umount
  48. get_qf_name
  49. ext4_quota_off_umount
  50. ext4_put_super
  51. ext4_alloc_inode
  52. ext4_drop_inode
  53. ext4_free_in_core_inode
  54. ext4_destroy_inode
  55. init_once
  56. init_inodecache
  57. destroy_inodecache
  58. ext4_clear_inode
  59. ext4_nfs_get_inode
  60. ext4_fh_to_dentry
  61. ext4_fh_to_parent
  62. ext4_nfs_commit_metadata
  63. bdev_try_to_free_page
  64. ext4_get_context
  65. ext4_set_context
  66. ext4_dummy_context
  67. ext4_get_dquots
  68. get_sb_block
  69. set_qf_name
  70. clear_qf_name
  71. ext4_sb_read_encoding
  72. handle_mount_opt
  73. parse_options
  74. ext4_show_quota_options
  75. token2str
  76. _ext4_show_options
  77. ext4_show_options
  78. ext4_seq_options_show
  79. ext4_setup_super
  80. ext4_alloc_flex_bg_array
  81. ext4_fill_flex_info
  82. ext4_group_desc_csum
  83. ext4_group_desc_csum_verify
  84. ext4_group_desc_csum_set
  85. ext4_check_descriptors
  86. ext4_orphan_cleanup
  87. ext4_max_size
  88. ext4_max_bitmap_size
  89. descriptor_loc
  90. ext4_get_stripe_size
  91. ext4_feature_set_ok
  92. print_daily_error_info
  93. ext4_run_li_request
  94. ext4_remove_li_request
  95. ext4_unregister_li_request
  96. ext4_lazyinit_thread
  97. ext4_clear_request_list
  98. ext4_run_lazyinit_thread
  99. ext4_has_uninit_itable
  100. ext4_li_info_new
  101. ext4_li_request_new
  102. ext4_register_li_request
  103. ext4_destroy_lazyinit_thread
  104. set_journal_csum_feature_set
  105. count_overhead
  106. ext4_calculate_overhead
  107. ext4_set_resv_clusters
  108. ext4_fill_super
  109. ext4_init_journal_params
  110. ext4_get_journal_inode
  111. ext4_get_journal
  112. ext4_get_dev_journal
  113. ext4_load_journal
  114. ext4_commit_super
  115. ext4_mark_recovery_complete
  116. ext4_clear_journal_err
  117. ext4_force_commit
  118. ext4_sync_fs
  119. ext4_freeze
  120. ext4_unfreeze
  121. ext4_remount
  122. ext4_statfs_project
  123. ext4_statfs
  124. dquot_to_inode
  125. ext4_write_dquot
  126. ext4_acquire_dquot
  127. ext4_release_dquot
  128. ext4_mark_dquot_dirty
  129. ext4_write_info
  130. ext4_quota_on_mount
  131. lockdep_set_quota_inode
  132. ext4_quota_on
  133. ext4_quota_enable
  134. ext4_enable_quotas
  135. ext4_quota_off
  136. ext4_quota_read
  137. ext4_quota_write
  138. ext4_get_next_id
  139. ext4_mount
  140. register_as_ext2
  141. unregister_as_ext2
  142. ext2_feature_set_ok
  143. register_as_ext2
  144. unregister_as_ext2
  145. ext2_feature_set_ok
  146. register_as_ext3
  147. unregister_as_ext3
  148. ext3_feature_set_ok
  149. ext4_init_fs
  150. ext4_exit_fs

   1 // SPDX-License-Identifier: GPL-2.0
   2 /*
   3  *  linux/fs/ext4/super.c
   4  *
   5  * Copyright (C) 1992, 1993, 1994, 1995
   6  * Remy Card (card@masi.ibp.fr)
   7  * Laboratoire MASI - Institut Blaise Pascal
   8  * Universite Pierre et Marie Curie (Paris VI)
   9  *
  10  *  from
  11  *
  12  *  linux/fs/minix/inode.c
  13  *
  14  *  Copyright (C) 1991, 1992  Linus Torvalds
  15  *
  16  *  Big-endian to little-endian byte-swapping/bitmaps by
  17  *        David S. Miller (davem@caip.rutgers.edu), 1995
  18  */
  19 
  20 #include <linux/module.h>
  21 #include <linux/string.h>
  22 #include <linux/fs.h>
  23 #include <linux/time.h>
  24 #include <linux/vmalloc.h>
  25 #include <linux/slab.h>
  26 #include <linux/init.h>
  27 #include <linux/blkdev.h>
  28 #include <linux/backing-dev.h>
  29 #include <linux/parser.h>
  30 #include <linux/buffer_head.h>
  31 #include <linux/exportfs.h>
  32 #include <linux/vfs.h>
  33 #include <linux/random.h>
  34 #include <linux/mount.h>
  35 #include <linux/namei.h>
  36 #include <linux/quotaops.h>
  37 #include <linux/seq_file.h>
  38 #include <linux/ctype.h>
  39 #include <linux/log2.h>
  40 #include <linux/crc16.h>
  41 #include <linux/dax.h>
  42 #include <linux/cleancache.h>
  43 #include <linux/uaccess.h>
  44 #include <linux/iversion.h>
  45 #include <linux/unicode.h>
  46 
  47 #include <linux/kthread.h>
  48 #include <linux/freezer.h>
  49 
  50 #include "ext4.h"
  51 #include "ext4_extents.h"       /* Needed for trace points definition */
  52 #include "ext4_jbd2.h"
  53 #include "xattr.h"
  54 #include "acl.h"
  55 #include "mballoc.h"
  56 #include "fsmap.h"
  57 
  58 #define CREATE_TRACE_POINTS
  59 #include <trace/events/ext4.h>
  60 
  61 static struct ext4_lazy_init *ext4_li_info;
  62 static struct mutex ext4_li_mtx;
  63 static struct ratelimit_state ext4_mount_msg_ratelimit;
  64 
  65 static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
  66                              unsigned long journal_devnum);
  67 static int ext4_show_options(struct seq_file *seq, struct dentry *root);
  68 static int ext4_commit_super(struct super_block *sb, int sync);
  69 static void ext4_mark_recovery_complete(struct super_block *sb,
  70                                         struct ext4_super_block *es);
  71 static void ext4_clear_journal_err(struct super_block *sb,
  72                                    struct ext4_super_block *es);
  73 static int ext4_sync_fs(struct super_block *sb, int wait);
  74 static int ext4_remount(struct super_block *sb, int *flags, char *data);
  75 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
  76 static int ext4_unfreeze(struct super_block *sb);
  77 static int ext4_freeze(struct super_block *sb);
  78 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
  79                        const char *dev_name, void *data);
  80 static inline int ext2_feature_set_ok(struct super_block *sb);
  81 static inline int ext3_feature_set_ok(struct super_block *sb);
  82 static int ext4_feature_set_ok(struct super_block *sb, int readonly);
  83 static void ext4_destroy_lazyinit_thread(void);
  84 static void ext4_unregister_li_request(struct super_block *sb);
  85 static void ext4_clear_request_list(void);
  86 static struct inode *ext4_get_journal_inode(struct super_block *sb,
  87                                             unsigned int journal_inum);
  88 
  89 /*
  90  * Lock ordering
  91  *
  92  * Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
  93  * i_mmap_rwsem (inode->i_mmap_rwsem)!
  94  *
  95  * page fault path:
  96  * mmap_sem -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
  97  *   page lock -> i_data_sem (rw)
  98  *
  99  * buffered write path:
 100  * sb_start_write -> i_mutex -> mmap_sem
 101  * sb_start_write -> i_mutex -> transaction start -> page lock ->
 102  *   i_data_sem (rw)
 103  *
 104  * truncate:
 105  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> i_mmap_rwsem (w) -> page lock
 106  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> transaction start ->
 107  *   i_data_sem (rw)
 108  *
 109  * direct IO:
 110  * sb_start_write -> i_mutex -> mmap_sem
 111  * sb_start_write -> i_mutex -> transaction start -> i_data_sem (rw)
 112  *
 113  * writepages:
 114  * transaction start -> page lock(s) -> i_data_sem (rw)
 115  */
 116 
 117 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
 118 static struct file_system_type ext2_fs_type = {
 119         .owner          = THIS_MODULE,
 120         .name           = "ext2",
 121         .mount          = ext4_mount,
 122         .kill_sb        = kill_block_super,
 123         .fs_flags       = FS_REQUIRES_DEV,
 124 };
 125 MODULE_ALIAS_FS("ext2");
 126 MODULE_ALIAS("ext2");
 127 #define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
 128 #else
 129 #define IS_EXT2_SB(sb) (0)
 130 #endif
 131 
 132 
 133 static struct file_system_type ext3_fs_type = {
 134         .owner          = THIS_MODULE,
 135         .name           = "ext3",
 136         .mount          = ext4_mount,
 137         .kill_sb        = kill_block_super,
 138         .fs_flags       = FS_REQUIRES_DEV,
 139 };
 140 MODULE_ALIAS_FS("ext3");
 141 MODULE_ALIAS("ext3");
 142 #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
 143 
 144 /*
 145  * This works like sb_bread() except it uses ERR_PTR for error
 146  * returns.  Currently with sb_bread it's impossible to distinguish
 147  * between ENOMEM and EIO situations (since both result in a NULL
 148  * return.
 149  */
 150 struct buffer_head *
 151 ext4_sb_bread(struct super_block *sb, sector_t block, int op_flags)
 152 {
 153         struct buffer_head *bh = sb_getblk(sb, block);
 154 
 155         if (bh == NULL)
 156                 return ERR_PTR(-ENOMEM);
 157         if (buffer_uptodate(bh))
 158                 return bh;
 159         ll_rw_block(REQ_OP_READ, REQ_META | op_flags, 1, &bh);
 160         wait_on_buffer(bh);
 161         if (buffer_uptodate(bh))
 162                 return bh;
 163         put_bh(bh);
 164         return ERR_PTR(-EIO);
 165 }
 166 
 167 static int ext4_verify_csum_type(struct super_block *sb,
 168                                  struct ext4_super_block *es)
 169 {
 170         if (!ext4_has_feature_metadata_csum(sb))
 171                 return 1;
 172 
 173         return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
 174 }
 175 
 176 static __le32 ext4_superblock_csum(struct super_block *sb,
 177                                    struct ext4_super_block *es)
 178 {
 179         struct ext4_sb_info *sbi = EXT4_SB(sb);
 180         int offset = offsetof(struct ext4_super_block, s_checksum);
 181         __u32 csum;
 182 
 183         csum = ext4_chksum(sbi, ~0, (char *)es, offset);
 184 
 185         return cpu_to_le32(csum);
 186 }
 187 
 188 static int ext4_superblock_csum_verify(struct super_block *sb,
 189                                        struct ext4_super_block *es)
 190 {
 191         if (!ext4_has_metadata_csum(sb))
 192                 return 1;
 193 
 194         return es->s_checksum == ext4_superblock_csum(sb, es);
 195 }
 196 
 197 void ext4_superblock_csum_set(struct super_block *sb)
 198 {
 199         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
 200 
 201         if (!ext4_has_metadata_csum(sb))
 202                 return;
 203 
 204         es->s_checksum = ext4_superblock_csum(sb, es);
 205 }
 206 
 207 void *ext4_kvmalloc(size_t size, gfp_t flags)
 208 {
 209         void *ret;
 210 
 211         ret = kmalloc(size, flags | __GFP_NOWARN);
 212         if (!ret)
 213                 ret = __vmalloc(size, flags, PAGE_KERNEL);
 214         return ret;
 215 }
 216 
 217 void *ext4_kvzalloc(size_t size, gfp_t flags)
 218 {
 219         void *ret;
 220 
 221         ret = kzalloc(size, flags | __GFP_NOWARN);
 222         if (!ret)
 223                 ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
 224         return ret;
 225 }
 226 
 227 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
 228                                struct ext4_group_desc *bg)
 229 {
 230         return le32_to_cpu(bg->bg_block_bitmap_lo) |
 231                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 232                  (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
 233 }
 234 
 235 ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
 236                                struct ext4_group_desc *bg)
 237 {
 238         return le32_to_cpu(bg->bg_inode_bitmap_lo) |
 239                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 240                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
 241 }
 242 
 243 ext4_fsblk_t ext4_inode_table(struct super_block *sb,
 244                               struct ext4_group_desc *bg)
 245 {
 246         return le32_to_cpu(bg->bg_inode_table_lo) |
 247                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 248                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
 249 }
 250 
 251 __u32 ext4_free_group_clusters(struct super_block *sb,
 252                                struct ext4_group_desc *bg)
 253 {
 254         return le16_to_cpu(bg->bg_free_blocks_count_lo) |
 255                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 256                  (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
 257 }
 258 
 259 __u32 ext4_free_inodes_count(struct super_block *sb,
 260                               struct ext4_group_desc *bg)
 261 {
 262         return le16_to_cpu(bg->bg_free_inodes_count_lo) |
 263                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 264                  (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
 265 }
 266 
 267 __u32 ext4_used_dirs_count(struct super_block *sb,
 268                               struct ext4_group_desc *bg)
 269 {
 270         return le16_to_cpu(bg->bg_used_dirs_count_lo) |
 271                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 272                  (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
 273 }
 274 
 275 __u32 ext4_itable_unused_count(struct super_block *sb,
 276                               struct ext4_group_desc *bg)
 277 {
 278         return le16_to_cpu(bg->bg_itable_unused_lo) |
 279                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
 280                  (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
 281 }
 282 
 283 void ext4_block_bitmap_set(struct super_block *sb,
 284                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
 285 {
 286         bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
 287         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 288                 bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
 289 }
 290 
 291 void ext4_inode_bitmap_set(struct super_block *sb,
 292                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
 293 {
 294         bg->bg_inode_bitmap_lo  = cpu_to_le32((u32)blk);
 295         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 296                 bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
 297 }
 298 
 299 void ext4_inode_table_set(struct super_block *sb,
 300                           struct ext4_group_desc *bg, ext4_fsblk_t blk)
 301 {
 302         bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
 303         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 304                 bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
 305 }
 306 
 307 void ext4_free_group_clusters_set(struct super_block *sb,
 308                                   struct ext4_group_desc *bg, __u32 count)
 309 {
 310         bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
 311         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 312                 bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
 313 }
 314 
 315 void ext4_free_inodes_set(struct super_block *sb,
 316                           struct ext4_group_desc *bg, __u32 count)
 317 {
 318         bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
 319         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 320                 bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
 321 }
 322 
 323 void ext4_used_dirs_set(struct super_block *sb,
 324                           struct ext4_group_desc *bg, __u32 count)
 325 {
 326         bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
 327         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 328                 bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
 329 }
 330 
 331 void ext4_itable_unused_set(struct super_block *sb,
 332                           struct ext4_group_desc *bg, __u32 count)
 333 {
 334         bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
 335         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
 336                 bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
 337 }
 338 
 339 static void __ext4_update_tstamp(__le32 *lo, __u8 *hi)
 340 {
 341         time64_t now = ktime_get_real_seconds();
 342 
 343         now = clamp_val(now, 0, (1ull << 40) - 1);
 344 
 345         *lo = cpu_to_le32(lower_32_bits(now));
 346         *hi = upper_32_bits(now);
 347 }
 348 
 349 static time64_t __ext4_get_tstamp(__le32 *lo, __u8 *hi)
 350 {
 351         return ((time64_t)(*hi) << 32) + le32_to_cpu(*lo);
 352 }
 353 #define ext4_update_tstamp(es, tstamp) \
 354         __ext4_update_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
 355 #define ext4_get_tstamp(es, tstamp) \
 356         __ext4_get_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
 357 
 358 static void __save_error_info(struct super_block *sb, const char *func,
 359                             unsigned int line)
 360 {
 361         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
 362 
 363         EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
 364         if (bdev_read_only(sb->s_bdev))
 365                 return;
 366         es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
 367         ext4_update_tstamp(es, s_last_error_time);
 368         strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
 369         es->s_last_error_line = cpu_to_le32(line);
 370         if (!es->s_first_error_time) {
 371                 es->s_first_error_time = es->s_last_error_time;
 372                 es->s_first_error_time_hi = es->s_last_error_time_hi;
 373                 strncpy(es->s_first_error_func, func,
 374                         sizeof(es->s_first_error_func));
 375                 es->s_first_error_line = cpu_to_le32(line);
 376                 es->s_first_error_ino = es->s_last_error_ino;
 377                 es->s_first_error_block = es->s_last_error_block;
 378         }
 379         /*
 380          * Start the daily error reporting function if it hasn't been
 381          * started already
 382          */
 383         if (!es->s_error_count)
 384                 mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
 385         le32_add_cpu(&es->s_error_count, 1);
 386 }
 387 
 388 static void save_error_info(struct super_block *sb, const char *func,
 389                             unsigned int line)
 390 {
 391         __save_error_info(sb, func, line);
 392         if (!bdev_read_only(sb->s_bdev))
 393                 ext4_commit_super(sb, 1);
 394 }
 395 
 396 /*
 397  * The del_gendisk() function uninitializes the disk-specific data
 398  * structures, including the bdi structure, without telling anyone
 399  * else.  Once this happens, any attempt to call mark_buffer_dirty()
 400  * (for example, by ext4_commit_super), will cause a kernel OOPS.
 401  * This is a kludge to prevent these oops until we can put in a proper
 402  * hook in del_gendisk() to inform the VFS and file system layers.
 403  */
 404 static int block_device_ejected(struct super_block *sb)
 405 {
 406         struct inode *bd_inode = sb->s_bdev->bd_inode;
 407         struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
 408 
 409         return bdi->dev == NULL;
 410 }
 411 
 412 static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
 413 {
 414         struct super_block              *sb = journal->j_private;
 415         struct ext4_sb_info             *sbi = EXT4_SB(sb);
 416         int                             error = is_journal_aborted(journal);
 417         struct ext4_journal_cb_entry    *jce;
 418 
 419         BUG_ON(txn->t_state == T_FINISHED);
 420 
 421         ext4_process_freed_data(sb, txn->t_tid);
 422 
 423         spin_lock(&sbi->s_md_lock);
 424         while (!list_empty(&txn->t_private_list)) {
 425                 jce = list_entry(txn->t_private_list.next,
 426                                  struct ext4_journal_cb_entry, jce_list);
 427                 list_del_init(&jce->jce_list);
 428                 spin_unlock(&sbi->s_md_lock);
 429                 jce->jce_func(sb, jce, error);
 430                 spin_lock(&sbi->s_md_lock);
 431         }
 432         spin_unlock(&sbi->s_md_lock);
 433 }
 434 
 435 static bool system_going_down(void)
 436 {
 437         return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
 438                 || system_state == SYSTEM_RESTART;
 439 }
 440 
 441 /* Deal with the reporting of failure conditions on a filesystem such as
 442  * inconsistencies detected or read IO failures.
 443  *
 444  * On ext2, we can store the error state of the filesystem in the
 445  * superblock.  That is not possible on ext4, because we may have other
 446  * write ordering constraints on the superblock which prevent us from
 447  * writing it out straight away; and given that the journal is about to
 448  * be aborted, we can't rely on the current, or future, transactions to
 449  * write out the superblock safely.
 450  *
 451  * We'll just use the jbd2_journal_abort() error code to record an error in
 452  * the journal instead.  On recovery, the journal will complain about
 453  * that error until we've noted it down and cleared it.
 454  */
 455 
 456 static void ext4_handle_error(struct super_block *sb)
 457 {
 458         if (test_opt(sb, WARN_ON_ERROR))
 459                 WARN_ON_ONCE(1);
 460 
 461         if (sb_rdonly(sb))
 462                 return;
 463 
 464         if (!test_opt(sb, ERRORS_CONT)) {
 465                 journal_t *journal = EXT4_SB(sb)->s_journal;
 466 
 467                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
 468                 if (journal)
 469                         jbd2_journal_abort(journal, -EIO);
 470         }
 471         /*
 472          * We force ERRORS_RO behavior when system is rebooting. Otherwise we
 473          * could panic during 'reboot -f' as the underlying device got already
 474          * disabled.
 475          */
 476         if (test_opt(sb, ERRORS_RO) || system_going_down()) {
 477                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
 478                 /*
 479                  * Make sure updated value of ->s_mount_flags will be visible
 480                  * before ->s_flags update
 481                  */
 482                 smp_wmb();
 483                 sb->s_flags |= SB_RDONLY;
 484         } else if (test_opt(sb, ERRORS_PANIC)) {
 485                 if (EXT4_SB(sb)->s_journal &&
 486                   !(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
 487                         return;
 488                 panic("EXT4-fs (device %s): panic forced after error\n",
 489                         sb->s_id);
 490         }
 491 }
 492 
 493 #define ext4_error_ratelimit(sb)                                        \
 494                 ___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state),     \
 495                              "EXT4-fs error")
 496 
 497 void __ext4_error(struct super_block *sb, const char *function,
 498                   unsigned int line, const char *fmt, ...)
 499 {
 500         struct va_format vaf;
 501         va_list args;
 502 
 503         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
 504                 return;
 505 
 506         trace_ext4_error(sb, function, line);
 507         if (ext4_error_ratelimit(sb)) {
 508                 va_start(args, fmt);
 509                 vaf.fmt = fmt;
 510                 vaf.va = &args;
 511                 printk(KERN_CRIT
 512                        "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
 513                        sb->s_id, function, line, current->comm, &vaf);
 514                 va_end(args);
 515         }
 516         save_error_info(sb, function, line);
 517         ext4_handle_error(sb);
 518 }
 519 
 520 void __ext4_error_inode(struct inode *inode, const char *function,
 521                         unsigned int line, ext4_fsblk_t block,
 522                         const char *fmt, ...)
 523 {
 524         va_list args;
 525         struct va_format vaf;
 526         struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
 527 
 528         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
 529                 return;
 530 
 531         trace_ext4_error(inode->i_sb, function, line);
 532         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
 533         es->s_last_error_block = cpu_to_le64(block);
 534         if (ext4_error_ratelimit(inode->i_sb)) {
 535                 va_start(args, fmt);
 536                 vaf.fmt = fmt;
 537                 vaf.va = &args;
 538                 if (block)
 539                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
 540                                "inode #%lu: block %llu: comm %s: %pV\n",
 541                                inode->i_sb->s_id, function, line, inode->i_ino,
 542                                block, current->comm, &vaf);
 543                 else
 544                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
 545                                "inode #%lu: comm %s: %pV\n",
 546                                inode->i_sb->s_id, function, line, inode->i_ino,
 547                                current->comm, &vaf);
 548                 va_end(args);
 549         }
 550         save_error_info(inode->i_sb, function, line);
 551         ext4_handle_error(inode->i_sb);
 552 }
 553 
 554 void __ext4_error_file(struct file *file, const char *function,
 555                        unsigned int line, ext4_fsblk_t block,
 556                        const char *fmt, ...)
 557 {
 558         va_list args;
 559         struct va_format vaf;
 560         struct ext4_super_block *es;
 561         struct inode *inode = file_inode(file);
 562         char pathname[80], *path;
 563 
 564         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
 565                 return;
 566 
 567         trace_ext4_error(inode->i_sb, function, line);
 568         es = EXT4_SB(inode->i_sb)->s_es;
 569         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
 570         if (ext4_error_ratelimit(inode->i_sb)) {
 571                 path = file_path(file, pathname, sizeof(pathname));
 572                 if (IS_ERR(path))
 573                         path = "(unknown)";
 574                 va_start(args, fmt);
 575                 vaf.fmt = fmt;
 576                 vaf.va = &args;
 577                 if (block)
 578                         printk(KERN_CRIT
 579                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
 580                                "block %llu: comm %s: path %s: %pV\n",
 581                                inode->i_sb->s_id, function, line, inode->i_ino,
 582                                block, current->comm, path, &vaf);
 583                 else
 584                         printk(KERN_CRIT
 585                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
 586                                "comm %s: path %s: %pV\n",
 587                                inode->i_sb->s_id, function, line, inode->i_ino,
 588                                current->comm, path, &vaf);
 589                 va_end(args);
 590         }
 591         save_error_info(inode->i_sb, function, line);
 592         ext4_handle_error(inode->i_sb);
 593 }
 594 
 595 const char *ext4_decode_error(struct super_block *sb, int errno,
 596                               char nbuf[16])
 597 {
 598         char *errstr = NULL;
 599 
 600         switch (errno) {
 601         case -EFSCORRUPTED:
 602                 errstr = "Corrupt filesystem";
 603                 break;
 604         case -EFSBADCRC:
 605                 errstr = "Filesystem failed CRC";
 606                 break;
 607         case -EIO:
 608                 errstr = "IO failure";
 609                 break;
 610         case -ENOMEM:
 611                 errstr = "Out of memory";
 612                 break;
 613         case -EROFS:
 614                 if (!sb || (EXT4_SB(sb)->s_journal &&
 615                             EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
 616                         errstr = "Journal has aborted";
 617                 else
 618                         errstr = "Readonly filesystem";
 619                 break;
 620         default:
 621                 /* If the caller passed in an extra buffer for unknown
 622                  * errors, textualise them now.  Else we just return
 623                  * NULL. */
 624                 if (nbuf) {
 625                         /* Check for truncated error codes... */
 626                         if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
 627                                 errstr = nbuf;
 628                 }
 629                 break;
 630         }
 631 
 632         return errstr;
 633 }
 634 
 635 /* __ext4_std_error decodes expected errors from journaling functions
 636  * automatically and invokes the appropriate error response.  */
 637 
 638 void __ext4_std_error(struct super_block *sb, const char *function,
 639                       unsigned int line, int errno)
 640 {
 641         char nbuf[16];
 642         const char *errstr;
 643 
 644         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
 645                 return;
 646 
 647         /* Special case: if the error is EROFS, and we're not already
 648          * inside a transaction, then there's really no point in logging
 649          * an error. */
 650         if (errno == -EROFS && journal_current_handle() == NULL && sb_rdonly(sb))
 651                 return;
 652 
 653         if (ext4_error_ratelimit(sb)) {
 654                 errstr = ext4_decode_error(sb, errno, nbuf);
 655                 printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
 656                        sb->s_id, function, line, errstr);
 657         }
 658 
 659         save_error_info(sb, function, line);
 660         ext4_handle_error(sb);
 661 }
 662 
 663 /*
 664  * ext4_abort is a much stronger failure handler than ext4_error.  The
 665  * abort function may be used to deal with unrecoverable failures such
 666  * as journal IO errors or ENOMEM at a critical moment in log management.
 667  *
 668  * We unconditionally force the filesystem into an ABORT|READONLY state,
 669  * unless the error response on the fs has been set to panic in which
 670  * case we take the easy way out and panic immediately.
 671  */
 672 
 673 void __ext4_abort(struct super_block *sb, const char *function,
 674                 unsigned int line, const char *fmt, ...)
 675 {
 676         struct va_format vaf;
 677         va_list args;
 678 
 679         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
 680                 return;
 681 
 682         save_error_info(sb, function, line);
 683         va_start(args, fmt);
 684         vaf.fmt = fmt;
 685         vaf.va = &args;
 686         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: %pV\n",
 687                sb->s_id, function, line, &vaf);
 688         va_end(args);
 689 
 690         if (sb_rdonly(sb) == 0) {
 691                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
 692                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
 693                 /*
 694                  * Make sure updated value of ->s_mount_flags will be visible
 695                  * before ->s_flags update
 696                  */
 697                 smp_wmb();
 698                 sb->s_flags |= SB_RDONLY;
 699                 if (EXT4_SB(sb)->s_journal)
 700                         jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
 701                 save_error_info(sb, function, line);
 702         }
 703         if (test_opt(sb, ERRORS_PANIC) && !system_going_down()) {
 704                 if (EXT4_SB(sb)->s_journal &&
 705                   !(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
 706                         return;
 707                 panic("EXT4-fs panic from previous error\n");
 708         }
 709 }
 710 
 711 void __ext4_msg(struct super_block *sb,
 712                 const char *prefix, const char *fmt, ...)
 713 {
 714         struct va_format vaf;
 715         va_list args;
 716 
 717         if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
 718                 return;
 719 
 720         va_start(args, fmt);
 721         vaf.fmt = fmt;
 722         vaf.va = &args;
 723         printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
 724         va_end(args);
 725 }
 726 
 727 #define ext4_warning_ratelimit(sb)                                      \
 728                 ___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state), \
 729                              "EXT4-fs warning")
 730 
 731 void __ext4_warning(struct super_block *sb, const char *function,
 732                     unsigned int line, const char *fmt, ...)
 733 {
 734         struct va_format vaf;
 735         va_list args;
 736 
 737         if (!ext4_warning_ratelimit(sb))
 738                 return;
 739 
 740         va_start(args, fmt);
 741         vaf.fmt = fmt;
 742         vaf.va = &args;
 743         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
 744                sb->s_id, function, line, &vaf);
 745         va_end(args);
 746 }
 747 
 748 void __ext4_warning_inode(const struct inode *inode, const char *function,
 749                           unsigned int line, const char *fmt, ...)
 750 {
 751         struct va_format vaf;
 752         va_list args;
 753 
 754         if (!ext4_warning_ratelimit(inode->i_sb))
 755                 return;
 756 
 757         va_start(args, fmt);
 758         vaf.fmt = fmt;
 759         vaf.va = &args;
 760         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
 761                "inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
 762                function, line, inode->i_ino, current->comm, &vaf);
 763         va_end(args);
 764 }
 765 
 766 void __ext4_grp_locked_error(const char *function, unsigned int line,
 767                              struct super_block *sb, ext4_group_t grp,
 768                              unsigned long ino, ext4_fsblk_t block,
 769                              const char *fmt, ...)
 770 __releases(bitlock)
 771 __acquires(bitlock)
 772 {
 773         struct va_format vaf;
 774         va_list args;
 775         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
 776 
 777         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
 778                 return;
 779 
 780         trace_ext4_error(sb, function, line);
 781         es->s_last_error_ino = cpu_to_le32(ino);
 782         es->s_last_error_block = cpu_to_le64(block);
 783         __save_error_info(sb, function, line);
 784 
 785         if (ext4_error_ratelimit(sb)) {
 786                 va_start(args, fmt);
 787                 vaf.fmt = fmt;
 788                 vaf.va = &args;
 789                 printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
 790                        sb->s_id, function, line, grp);
 791                 if (ino)
 792                         printk(KERN_CONT "inode %lu: ", ino);
 793                 if (block)
 794                         printk(KERN_CONT "block %llu:",
 795                                (unsigned long long) block);
 796                 printk(KERN_CONT "%pV\n", &vaf);
 797                 va_end(args);
 798         }
 799 
 800         if (test_opt(sb, WARN_ON_ERROR))
 801                 WARN_ON_ONCE(1);
 802 
 803         if (test_opt(sb, ERRORS_CONT)) {
 804                 ext4_commit_super(sb, 0);
 805                 return;
 806         }
 807 
 808         ext4_unlock_group(sb, grp);
 809         ext4_commit_super(sb, 1);
 810         ext4_handle_error(sb);
 811         /*
 812          * We only get here in the ERRORS_RO case; relocking the group
 813          * may be dangerous, but nothing bad will happen since the
 814          * filesystem will have already been marked read/only and the
 815          * journal has been aborted.  We return 1 as a hint to callers
 816          * who might what to use the return value from
 817          * ext4_grp_locked_error() to distinguish between the
 818          * ERRORS_CONT and ERRORS_RO case, and perhaps return more
 819          * aggressively from the ext4 function in question, with a
 820          * more appropriate error code.
 821          */
 822         ext4_lock_group(sb, grp);
 823         return;
 824 }
 825 
 826 void ext4_mark_group_bitmap_corrupted(struct super_block *sb,
 827                                      ext4_group_t group,
 828                                      unsigned int flags)
 829 {
 830         struct ext4_sb_info *sbi = EXT4_SB(sb);
 831         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
 832         struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
 833         int ret;
 834 
 835         if (flags & EXT4_GROUP_INFO_BBITMAP_CORRUPT) {
 836                 ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
 837                                             &grp->bb_state);
 838                 if (!ret)
 839                         percpu_counter_sub(&sbi->s_freeclusters_counter,
 840                                            grp->bb_free);
 841         }
 842 
 843         if (flags & EXT4_GROUP_INFO_IBITMAP_CORRUPT) {
 844                 ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT,
 845                                             &grp->bb_state);
 846                 if (!ret && gdp) {
 847                         int count;
 848 
 849                         count = ext4_free_inodes_count(sb, gdp);
 850                         percpu_counter_sub(&sbi->s_freeinodes_counter,
 851                                            count);
 852                 }
 853         }
 854 }
 855 
 856 void ext4_update_dynamic_rev(struct super_block *sb)
 857 {
 858         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
 859 
 860         if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
 861                 return;
 862 
 863         ext4_warning(sb,
 864                      "updating to rev %d because of new feature flag, "
 865                      "running e2fsck is recommended",
 866                      EXT4_DYNAMIC_REV);
 867 
 868         es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
 869         es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
 870         es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
 871         /* leave es->s_feature_*compat flags alone */
 872         /* es->s_uuid will be set by e2fsck if empty */
 873 
 874         /*
 875          * The rest of the superblock fields should be zero, and if not it
 876          * means they are likely already in use, so leave them alone.  We
 877          * can leave it up to e2fsck to clean up any inconsistencies there.
 878          */
 879 }
 880 
 881 /*
 882  * Open the external journal device
 883  */
 884 static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
 885 {
 886         struct block_device *bdev;
 887         char b[BDEVNAME_SIZE];
 888 
 889         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
 890         if (IS_ERR(bdev))
 891                 goto fail;
 892         return bdev;
 893 
 894 fail:
 895         ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
 896                         __bdevname(dev, b), PTR_ERR(bdev));
 897         return NULL;
 898 }
 899 
 900 /*
 901  * Release the journal device
 902  */
 903 static void ext4_blkdev_put(struct block_device *bdev)
 904 {
 905         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
 906 }
 907 
 908 static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
 909 {
 910         struct block_device *bdev;
 911         bdev = sbi->journal_bdev;
 912         if (bdev) {
 913                 ext4_blkdev_put(bdev);
 914                 sbi->journal_bdev = NULL;
 915         }
 916 }
 917 
 918 static inline struct inode *orphan_list_entry(struct list_head *l)
 919 {
 920         return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
 921 }
 922 
 923 static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
 924 {
 925         struct list_head *l;
 926 
 927         ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
 928                  le32_to_cpu(sbi->s_es->s_last_orphan));
 929 
 930         printk(KERN_ERR "sb_info orphan list:\n");
 931         list_for_each(l, &sbi->s_orphan) {
 932                 struct inode *inode = orphan_list_entry(l);
 933                 printk(KERN_ERR "  "
 934                        "inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
 935                        inode->i_sb->s_id, inode->i_ino, inode,
 936                        inode->i_mode, inode->i_nlink,
 937                        NEXT_ORPHAN(inode));
 938         }
 939 }
 940 
 941 #ifdef CONFIG_QUOTA
 942 static int ext4_quota_off(struct super_block *sb, int type);
 943 
 944 static inline void ext4_quota_off_umount(struct super_block *sb)
 945 {
 946         int type;
 947 
 948         /* Use our quota_off function to clear inode flags etc. */
 949         for (type = 0; type < EXT4_MAXQUOTAS; type++)
 950                 ext4_quota_off(sb, type);
 951 }
 952 
 953 /*
 954  * This is a helper function which is used in the mount/remount
 955  * codepaths (which holds s_umount) to fetch the quota file name.
 956  */
 957 static inline char *get_qf_name(struct super_block *sb,
 958                                 struct ext4_sb_info *sbi,
 959                                 int type)
 960 {
 961         return rcu_dereference_protected(sbi->s_qf_names[type],
 962                                          lockdep_is_held(&sb->s_umount));
 963 }
 964 #else
 965 static inline void ext4_quota_off_umount(struct super_block *sb)
 966 {
 967 }
 968 #endif
 969 
 970 static void ext4_put_super(struct super_block *sb)
 971 {
 972         struct ext4_sb_info *sbi = EXT4_SB(sb);
 973         struct ext4_super_block *es = sbi->s_es;
 974         struct buffer_head **group_desc;
 975         struct flex_groups **flex_groups;
 976         int aborted = 0;
 977         int i, err;
 978 
 979         ext4_unregister_li_request(sb);
 980         ext4_quota_off_umount(sb);
 981 
 982         destroy_workqueue(sbi->rsv_conversion_wq);
 983 
 984         if (sbi->s_journal) {
 985                 aborted = is_journal_aborted(sbi->s_journal);
 986                 err = jbd2_journal_destroy(sbi->s_journal);
 987                 sbi->s_journal = NULL;
 988                 if ((err < 0) && !aborted)
 989                         ext4_abort(sb, "Couldn't clean up the journal");
 990         }
 991 
 992         ext4_unregister_sysfs(sb);
 993         ext4_es_unregister_shrinker(sbi);
 994         del_timer_sync(&sbi->s_err_report);
 995         ext4_release_system_zone(sb);
 996         ext4_mb_release(sb);
 997         ext4_ext_release(sb);
 998 
 999         if (!sb_rdonly(sb) && !aborted) {
1000                 ext4_clear_feature_journal_needs_recovery(sb);
1001                 es->s_state = cpu_to_le16(sbi->s_mount_state);
1002         }
1003         if (!sb_rdonly(sb))
1004                 ext4_commit_super(sb, 1);
1005 
1006         rcu_read_lock();
1007         group_desc = rcu_dereference(sbi->s_group_desc);
1008         for (i = 0; i < sbi->s_gdb_count; i++)
1009                 brelse(group_desc[i]);
1010         kvfree(group_desc);
1011         flex_groups = rcu_dereference(sbi->s_flex_groups);
1012         if (flex_groups) {
1013                 for (i = 0; i < sbi->s_flex_groups_allocated; i++)
1014                         kvfree(flex_groups[i]);
1015                 kvfree(flex_groups);
1016         }
1017         rcu_read_unlock();
1018         percpu_counter_destroy(&sbi->s_freeclusters_counter);
1019         percpu_counter_destroy(&sbi->s_freeinodes_counter);
1020         percpu_counter_destroy(&sbi->s_dirs_counter);
1021         percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
1022         percpu_free_rwsem(&sbi->s_writepages_rwsem);
1023 #ifdef CONFIG_QUOTA
1024         for (i = 0; i < EXT4_MAXQUOTAS; i++)
1025                 kfree(get_qf_name(sb, sbi, i));
1026 #endif
1027 
1028         /* Debugging code just in case the in-memory inode orphan list
1029          * isn't empty.  The on-disk one can be non-empty if we've
1030          * detected an error and taken the fs readonly, but the
1031          * in-memory list had better be clean by this point. */
1032         if (!list_empty(&sbi->s_orphan))
1033                 dump_orphan_list(sb, sbi);
1034         J_ASSERT(list_empty(&sbi->s_orphan));
1035 
1036         sync_blockdev(sb->s_bdev);
1037         invalidate_bdev(sb->s_bdev);
1038         if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
1039                 /*
1040                  * Invalidate the journal device's buffers.  We don't want them
1041                  * floating about in memory - the physical journal device may
1042                  * hotswapped, and it breaks the `ro-after' testing code.
1043                  */
1044                 sync_blockdev(sbi->journal_bdev);
1045                 invalidate_bdev(sbi->journal_bdev);
1046                 ext4_blkdev_remove(sbi);
1047         }
1048 
1049         ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
1050         sbi->s_ea_inode_cache = NULL;
1051 
1052         ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
1053         sbi->s_ea_block_cache = NULL;
1054 
1055         if (sbi->s_mmp_tsk)
1056                 kthread_stop(sbi->s_mmp_tsk);
1057         brelse(sbi->s_sbh);
1058         sb->s_fs_info = NULL;
1059         /*
1060          * Now that we are completely done shutting down the
1061          * superblock, we need to actually destroy the kobject.
1062          */
1063         kobject_put(&sbi->s_kobj);
1064         wait_for_completion(&sbi->s_kobj_unregister);
1065         if (sbi->s_chksum_driver)
1066                 crypto_free_shash(sbi->s_chksum_driver);
1067         kfree(sbi->s_blockgroup_lock);
1068         fs_put_dax(sbi->s_daxdev);
1069 #ifdef CONFIG_UNICODE
1070         utf8_unload(sbi->s_encoding);
1071 #endif
1072         kfree(sbi);
1073 }
1074 
1075 static struct kmem_cache *ext4_inode_cachep;
1076 
1077 /*
1078  * Called inside transaction, so use GFP_NOFS
1079  */
1080 static struct inode *ext4_alloc_inode(struct super_block *sb)
1081 {
1082         struct ext4_inode_info *ei;
1083 
1084         ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
1085         if (!ei)
1086                 return NULL;
1087 
1088         inode_set_iversion(&ei->vfs_inode, 1);
1089         spin_lock_init(&ei->i_raw_lock);
1090         INIT_LIST_HEAD(&ei->i_prealloc_list);
1091         spin_lock_init(&ei->i_prealloc_lock);
1092         ext4_es_init_tree(&ei->i_es_tree);
1093         rwlock_init(&ei->i_es_lock);
1094         INIT_LIST_HEAD(&ei->i_es_list);
1095         ei->i_es_all_nr = 0;
1096         ei->i_es_shk_nr = 0;
1097         ei->i_es_shrink_lblk = 0;
1098         ei->i_reserved_data_blocks = 0;
1099         ei->i_da_metadata_calc_len = 0;
1100         ei->i_da_metadata_calc_last_lblock = 0;
1101         spin_lock_init(&(ei->i_block_reservation_lock));
1102         ext4_init_pending_tree(&ei->i_pending_tree);
1103 #ifdef CONFIG_QUOTA
1104         ei->i_reserved_quota = 0;
1105         memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
1106 #endif
1107         ei->jinode = NULL;
1108         INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
1109         spin_lock_init(&ei->i_completed_io_lock);
1110         ei->i_sync_tid = 0;
1111         ei->i_datasync_tid = 0;
1112         atomic_set(&ei->i_unwritten, 0);
1113         INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
1114         return &ei->vfs_inode;
1115 }
1116 
1117 static int ext4_drop_inode(struct inode *inode)
1118 {
1119         int drop = generic_drop_inode(inode);
1120 
1121         if (!drop)
1122                 drop = fscrypt_drop_inode(inode);
1123 
1124         trace_ext4_drop_inode(inode, drop);
1125         return drop;
1126 }
1127 
1128 static void ext4_free_in_core_inode(struct inode *inode)
1129 {
1130         fscrypt_free_inode(inode);
1131         kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
1132 }
1133 
1134 static void ext4_destroy_inode(struct inode *inode)
1135 {
1136         if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
1137                 ext4_msg(inode->i_sb, KERN_ERR,
1138                          "Inode %lu (%p): orphan list check failed!",
1139                          inode->i_ino, EXT4_I(inode));
1140                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
1141                                 EXT4_I(inode), sizeof(struct ext4_inode_info),
1142                                 true);
1143                 dump_stack();
1144         }
1145 }
1146 
1147 static void init_once(void *foo)
1148 {
1149         struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
1150 
1151         INIT_LIST_HEAD(&ei->i_orphan);
1152         init_rwsem(&ei->xattr_sem);
1153         init_rwsem(&ei->i_data_sem);
1154         init_rwsem(&ei->i_mmap_sem);
1155         inode_init_once(&ei->vfs_inode);
1156 }
1157 
1158 static int __init init_inodecache(void)
1159 {
1160         ext4_inode_cachep = kmem_cache_create_usercopy("ext4_inode_cache",
1161                                 sizeof(struct ext4_inode_info), 0,
1162                                 (SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
1163                                         SLAB_ACCOUNT),
1164                                 offsetof(struct ext4_inode_info, i_data),
1165                                 sizeof_field(struct ext4_inode_info, i_data),
1166                                 init_once);
1167         if (ext4_inode_cachep == NULL)
1168                 return -ENOMEM;
1169         return 0;
1170 }
1171 
1172 static void destroy_inodecache(void)
1173 {
1174         /*
1175          * Make sure all delayed rcu free inodes are flushed before we
1176          * destroy cache.
1177          */
1178         rcu_barrier();
1179         kmem_cache_destroy(ext4_inode_cachep);
1180 }
1181 
1182 void ext4_clear_inode(struct inode *inode)
1183 {
1184         invalidate_inode_buffers(inode);
1185         clear_inode(inode);
1186         ext4_discard_preallocations(inode);
1187         ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
1188         dquot_drop(inode);
1189         if (EXT4_I(inode)->jinode) {
1190                 jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
1191                                                EXT4_I(inode)->jinode);
1192                 jbd2_free_inode(EXT4_I(inode)->jinode);
1193                 EXT4_I(inode)->jinode = NULL;
1194         }
1195         fscrypt_put_encryption_info(inode);
1196         fsverity_cleanup_inode(inode);
1197 }
1198 
1199 static struct inode *ext4_nfs_get_inode(struct super_block *sb,
1200                                         u64 ino, u32 generation)
1201 {
1202         struct inode *inode;
1203 
1204         /*
1205          * Currently we don't know the generation for parent directory, so
1206          * a generation of 0 means "accept any"
1207          */
1208         inode = ext4_iget(sb, ino, EXT4_IGET_HANDLE);
1209         if (IS_ERR(inode))
1210                 return ERR_CAST(inode);
1211         if (generation && inode->i_generation != generation) {
1212                 iput(inode);
1213                 return ERR_PTR(-ESTALE);
1214         }
1215 
1216         return inode;
1217 }
1218 
1219 static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
1220                                         int fh_len, int fh_type)
1221 {
1222         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1223                                     ext4_nfs_get_inode);
1224 }
1225 
1226 static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
1227                                         int fh_len, int fh_type)
1228 {
1229         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1230                                     ext4_nfs_get_inode);
1231 }
1232 
1233 static int ext4_nfs_commit_metadata(struct inode *inode)
1234 {
1235         struct writeback_control wbc = {
1236                 .sync_mode = WB_SYNC_ALL
1237         };
1238 
1239         trace_ext4_nfs_commit_metadata(inode);
1240         return ext4_write_inode(inode, &wbc);
1241 }
1242 
1243 /*
1244  * Try to release metadata pages (indirect blocks, directories) which are
1245  * mapped via the block device.  Since these pages could have journal heads
1246  * which would prevent try_to_free_buffers() from freeing them, we must use
1247  * jbd2 layer's try_to_free_buffers() function to release them.
1248  */
1249 static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
1250                                  gfp_t wait)
1251 {
1252         journal_t *journal = EXT4_SB(sb)->s_journal;
1253 
1254         WARN_ON(PageChecked(page));
1255         if (!page_has_buffers(page))
1256                 return 0;
1257         if (journal)
1258                 return jbd2_journal_try_to_free_buffers(journal, page,
1259                                                 wait & ~__GFP_DIRECT_RECLAIM);
1260         return try_to_free_buffers(page);
1261 }
1262 
1263 #ifdef CONFIG_FS_ENCRYPTION
1264 static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
1265 {
1266         return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
1267                                  EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
1268 }
1269 
1270 static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
1271                                                         void *fs_data)
1272 {
1273         handle_t *handle = fs_data;
1274         int res, res2, credits, retries = 0;
1275 
1276         /*
1277          * Encrypting the root directory is not allowed because e2fsck expects
1278          * lost+found to exist and be unencrypted, and encrypting the root
1279          * directory would imply encrypting the lost+found directory as well as
1280          * the filename "lost+found" itself.
1281          */
1282         if (inode->i_ino == EXT4_ROOT_INO)
1283                 return -EPERM;
1284 
1285         if (WARN_ON_ONCE(IS_DAX(inode) && i_size_read(inode)))
1286                 return -EINVAL;
1287 
1288         res = ext4_convert_inline_data(inode);
1289         if (res)
1290                 return res;
1291 
1292         /*
1293          * If a journal handle was specified, then the encryption context is
1294          * being set on a new inode via inheritance and is part of a larger
1295          * transaction to create the inode.  Otherwise the encryption context is
1296          * being set on an existing inode in its own transaction.  Only in the
1297          * latter case should the "retry on ENOSPC" logic be used.
1298          */
1299 
1300         if (handle) {
1301                 res = ext4_xattr_set_handle(handle, inode,
1302                                             EXT4_XATTR_INDEX_ENCRYPTION,
1303                                             EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1304                                             ctx, len, 0);
1305                 if (!res) {
1306                         ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1307                         ext4_clear_inode_state(inode,
1308                                         EXT4_STATE_MAY_INLINE_DATA);
1309                         /*
1310                          * Update inode->i_flags - S_ENCRYPTED will be enabled,
1311                          * S_DAX may be disabled
1312                          */
1313                         ext4_set_inode_flags(inode);
1314                 }
1315                 return res;
1316         }
1317 
1318         res = dquot_initialize(inode);
1319         if (res)
1320                 return res;
1321 retry:
1322         res = ext4_xattr_set_credits(inode, len, false /* is_create */,
1323                                      &credits);
1324         if (res)
1325                 return res;
1326 
1327         handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
1328         if (IS_ERR(handle))
1329                 return PTR_ERR(handle);
1330 
1331         res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
1332                                     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1333                                     ctx, len, 0);
1334         if (!res) {
1335                 ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1336                 /*
1337                  * Update inode->i_flags - S_ENCRYPTED will be enabled,
1338                  * S_DAX may be disabled
1339                  */
1340                 ext4_set_inode_flags(inode);
1341                 res = ext4_mark_inode_dirty(handle, inode);
1342                 if (res)
1343                         EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
1344         }
1345         res2 = ext4_journal_stop(handle);
1346 
1347         if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1348                 goto retry;
1349         if (!res)
1350                 res = res2;
1351         return res;
1352 }
1353 
1354 static bool ext4_dummy_context(struct inode *inode)
1355 {
1356         return DUMMY_ENCRYPTION_ENABLED(EXT4_SB(inode->i_sb));
1357 }
1358 
1359 static const struct fscrypt_operations ext4_cryptops = {
1360         .key_prefix             = "ext4:",
1361         .get_context            = ext4_get_context,
1362         .set_context            = ext4_set_context,
1363         .dummy_context          = ext4_dummy_context,
1364         .empty_dir              = ext4_empty_dir,
1365         .max_namelen            = EXT4_NAME_LEN,
1366 };
1367 #endif
1368 
1369 #ifdef CONFIG_QUOTA
1370 static const char * const quotatypes[] = INITQFNAMES;
1371 #define QTYPE2NAME(t) (quotatypes[t])
1372 
1373 static int ext4_write_dquot(struct dquot *dquot);
1374 static int ext4_acquire_dquot(struct dquot *dquot);
1375 static int ext4_release_dquot(struct dquot *dquot);
1376 static int ext4_mark_dquot_dirty(struct dquot *dquot);
1377 static int ext4_write_info(struct super_block *sb, int type);
1378 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
1379                          const struct path *path);
1380 static int ext4_quota_on_mount(struct super_block *sb, int type);
1381 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
1382                                size_t len, loff_t off);
1383 static ssize_t ext4_quota_write(struct super_block *sb, int type,
1384                                 const char *data, size_t len, loff_t off);
1385 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
1386                              unsigned int flags);
1387 static int ext4_enable_quotas(struct super_block *sb);
1388 static int ext4_get_next_id(struct super_block *sb, struct kqid *qid);
1389 
1390 static struct dquot **ext4_get_dquots(struct inode *inode)
1391 {
1392         return EXT4_I(inode)->i_dquot;
1393 }
1394 
1395 static const struct dquot_operations ext4_quota_operations = {
1396         .get_reserved_space     = ext4_get_reserved_space,
1397         .write_dquot            = ext4_write_dquot,
1398         .acquire_dquot          = ext4_acquire_dquot,
1399         .release_dquot          = ext4_release_dquot,
1400         .mark_dirty             = ext4_mark_dquot_dirty,
1401         .write_info             = ext4_write_info,
1402         .alloc_dquot            = dquot_alloc,
1403         .destroy_dquot          = dquot_destroy,
1404         .get_projid             = ext4_get_projid,
1405         .get_inode_usage        = ext4_get_inode_usage,
1406         .get_next_id            = ext4_get_next_id,
1407 };
1408 
1409 static const struct quotactl_ops ext4_qctl_operations = {
1410         .quota_on       = ext4_quota_on,
1411         .quota_off      = ext4_quota_off,
1412         .quota_sync     = dquot_quota_sync,
1413         .get_state      = dquot_get_state,
1414         .set_info       = dquot_set_dqinfo,
1415         .get_dqblk      = dquot_get_dqblk,
1416         .set_dqblk      = dquot_set_dqblk,
1417         .get_nextdqblk  = dquot_get_next_dqblk,
1418 };
1419 #endif
1420 
1421 static const struct super_operations ext4_sops = {
1422         .alloc_inode    = ext4_alloc_inode,
1423         .free_inode     = ext4_free_in_core_inode,
1424         .destroy_inode  = ext4_destroy_inode,
1425         .write_inode    = ext4_write_inode,
1426         .dirty_inode    = ext4_dirty_inode,
1427         .drop_inode     = ext4_drop_inode,
1428         .evict_inode    = ext4_evict_inode,
1429         .put_super      = ext4_put_super,
1430         .sync_fs        = ext4_sync_fs,
1431         .freeze_fs      = ext4_freeze,
1432         .unfreeze_fs    = ext4_unfreeze,
1433         .statfs         = ext4_statfs,
1434         .remount_fs     = ext4_remount,
1435         .show_options   = ext4_show_options,
1436 #ifdef CONFIG_QUOTA
1437         .quota_read     = ext4_quota_read,
1438         .quota_write    = ext4_quota_write,
1439         .get_dquots     = ext4_get_dquots,
1440 #endif
1441         .bdev_try_to_free_page = bdev_try_to_free_page,
1442 };
1443 
1444 static const struct export_operations ext4_export_ops = {
1445         .fh_to_dentry = ext4_fh_to_dentry,
1446         .fh_to_parent = ext4_fh_to_parent,
1447         .get_parent = ext4_get_parent,
1448         .commit_metadata = ext4_nfs_commit_metadata,
1449 };
1450 
1451 enum {
1452         Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
1453         Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
1454         Opt_nouid32, Opt_debug, Opt_removed,
1455         Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
1456         Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
1457         Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
1458         Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
1459         Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
1460         Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
1461         Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
1462         Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
1463         Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
1464         Opt_usrquota, Opt_grpquota, Opt_prjquota, Opt_i_version, Opt_dax,
1465         Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_warn_on_error,
1466         Opt_nowarn_on_error, Opt_mblk_io_submit,
1467         Opt_lazytime, Opt_nolazytime, Opt_debug_want_extra_isize,
1468         Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
1469         Opt_inode_readahead_blks, Opt_journal_ioprio,
1470         Opt_dioread_nolock, Opt_dioread_lock,
1471         Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
1472         Opt_max_dir_size_kb, Opt_nojournal_checksum, Opt_nombcache,
1473 };
1474 
1475 static const match_table_t tokens = {
1476         {Opt_bsd_df, "bsddf"},
1477         {Opt_minix_df, "minixdf"},
1478         {Opt_grpid, "grpid"},
1479         {Opt_grpid, "bsdgroups"},
1480         {Opt_nogrpid, "nogrpid"},
1481         {Opt_nogrpid, "sysvgroups"},
1482         {Opt_resgid, "resgid=%u"},
1483         {Opt_resuid, "resuid=%u"},
1484         {Opt_sb, "sb=%u"},
1485         {Opt_err_cont, "errors=continue"},
1486         {Opt_err_panic, "errors=panic"},
1487         {Opt_err_ro, "errors=remount-ro"},
1488         {Opt_nouid32, "nouid32"},
1489         {Opt_debug, "debug"},
1490         {Opt_removed, "oldalloc"},
1491         {Opt_removed, "orlov"},
1492         {Opt_user_xattr, "user_xattr"},
1493         {Opt_nouser_xattr, "nouser_xattr"},
1494         {Opt_acl, "acl"},
1495         {Opt_noacl, "noacl"},
1496         {Opt_noload, "norecovery"},
1497         {Opt_noload, "noload"},
1498         {Opt_removed, "nobh"},
1499         {Opt_removed, "bh"},
1500         {Opt_commit, "commit=%u"},
1501         {Opt_min_batch_time, "min_batch_time=%u"},
1502         {Opt_max_batch_time, "max_batch_time=%u"},
1503         {Opt_journal_dev, "journal_dev=%u"},
1504         {Opt_journal_path, "journal_path=%s"},
1505         {Opt_journal_checksum, "journal_checksum"},
1506         {Opt_nojournal_checksum, "nojournal_checksum"},
1507         {Opt_journal_async_commit, "journal_async_commit"},
1508         {Opt_abort, "abort"},
1509         {Opt_data_journal, "data=journal"},
1510         {Opt_data_ordered, "data=ordered"},
1511         {Opt_data_writeback, "data=writeback"},
1512         {Opt_data_err_abort, "data_err=abort"},
1513         {Opt_data_err_ignore, "data_err=ignore"},
1514         {Opt_offusrjquota, "usrjquota="},
1515         {Opt_usrjquota, "usrjquota=%s"},
1516         {Opt_offgrpjquota, "grpjquota="},
1517         {Opt_grpjquota, "grpjquota=%s"},
1518         {Opt_jqfmt_vfsold, "jqfmt=vfsold"},
1519         {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
1520         {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
1521         {Opt_grpquota, "grpquota"},
1522         {Opt_noquota, "noquota"},
1523         {Opt_quota, "quota"},
1524         {Opt_usrquota, "usrquota"},
1525         {Opt_prjquota, "prjquota"},
1526         {Opt_barrier, "barrier=%u"},
1527         {Opt_barrier, "barrier"},
1528         {Opt_nobarrier, "nobarrier"},
1529         {Opt_i_version, "i_version"},
1530         {Opt_dax, "dax"},
1531         {Opt_stripe, "stripe=%u"},
1532         {Opt_delalloc, "delalloc"},
1533         {Opt_warn_on_error, "warn_on_error"},
1534         {Opt_nowarn_on_error, "nowarn_on_error"},
1535         {Opt_lazytime, "lazytime"},
1536         {Opt_nolazytime, "nolazytime"},
1537         {Opt_debug_want_extra_isize, "debug_want_extra_isize=%u"},
1538         {Opt_nodelalloc, "nodelalloc"},
1539         {Opt_removed, "mblk_io_submit"},
1540         {Opt_removed, "nomblk_io_submit"},
1541         {Opt_block_validity, "block_validity"},
1542         {Opt_noblock_validity, "noblock_validity"},
1543         {Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
1544         {Opt_journal_ioprio, "journal_ioprio=%u"},
1545         {Opt_auto_da_alloc, "auto_da_alloc=%u"},
1546         {Opt_auto_da_alloc, "auto_da_alloc"},
1547         {Opt_noauto_da_alloc, "noauto_da_alloc"},
1548         {Opt_dioread_nolock, "dioread_nolock"},
1549         {Opt_dioread_lock, "dioread_lock"},
1550         {Opt_discard, "discard"},
1551         {Opt_nodiscard, "nodiscard"},
1552         {Opt_init_itable, "init_itable=%u"},
1553         {Opt_init_itable, "init_itable"},
1554         {Opt_noinit_itable, "noinit_itable"},
1555         {Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
1556         {Opt_test_dummy_encryption, "test_dummy_encryption"},
1557         {Opt_nombcache, "nombcache"},
1558         {Opt_nombcache, "no_mbcache"},  /* for backward compatibility */
1559         {Opt_removed, "check=none"},    /* mount option from ext2/3 */
1560         {Opt_removed, "nocheck"},       /* mount option from ext2/3 */
1561         {Opt_removed, "reservation"},   /* mount option from ext2/3 */
1562         {Opt_removed, "noreservation"}, /* mount option from ext2/3 */
1563         {Opt_removed, "journal=%u"},    /* mount option from ext2/3 */
1564         {Opt_err, NULL},
1565 };
1566 
1567 static ext4_fsblk_t get_sb_block(void **data)
1568 {
1569         ext4_fsblk_t    sb_block;
1570         char            *options = (char *) *data;
1571 
1572         if (!options || strncmp(options, "sb=", 3) != 0)
1573                 return 1;       /* Default location */
1574 
1575         options += 3;
1576         /* TODO: use simple_strtoll with >32bit ext4 */
1577         sb_block = simple_strtoul(options, &options, 0);
1578         if (*options && *options != ',') {
1579                 printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
1580                        (char *) *data);
1581                 return 1;
1582         }
1583         if (*options == ',')
1584                 options++;
1585         *data = (void *) options;
1586 
1587         return sb_block;
1588 }
1589 
1590 #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
1591 static const char deprecated_msg[] =
1592         "Mount option \"%s\" will be removed by %s\n"
1593         "Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
1594 
1595 #ifdef CONFIG_QUOTA
1596 static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
1597 {
1598         struct ext4_sb_info *sbi = EXT4_SB(sb);
1599         char *qname, *old_qname = get_qf_name(sb, sbi, qtype);
1600         int ret = -1;
1601 
1602         if (sb_any_quota_loaded(sb) && !old_qname) {
1603                 ext4_msg(sb, KERN_ERR,
1604                         "Cannot change journaled "
1605                         "quota options when quota turned on");
1606                 return -1;
1607         }
1608         if (ext4_has_feature_quota(sb)) {
1609                 ext4_msg(sb, KERN_INFO, "Journaled quota options "
1610                          "ignored when QUOTA feature is enabled");
1611                 return 1;
1612         }
1613         qname = match_strdup(args);
1614         if (!qname) {
1615                 ext4_msg(sb, KERN_ERR,
1616                         "Not enough memory for storing quotafile name");
1617                 return -1;
1618         }
1619         if (old_qname) {
1620                 if (strcmp(old_qname, qname) == 0)
1621                         ret = 1;
1622                 else
1623                         ext4_msg(sb, KERN_ERR,
1624                                  "%s quota file already specified",
1625                                  QTYPE2NAME(qtype));
1626                 goto errout;
1627         }
1628         if (strchr(qname, '/')) {
1629                 ext4_msg(sb, KERN_ERR,
1630                         "quotafile must be on filesystem root");
1631                 goto errout;
1632         }
1633         rcu_assign_pointer(sbi->s_qf_names[qtype], qname);
1634         set_opt(sb, QUOTA);
1635         return 1;
1636 errout:
1637         kfree(qname);
1638         return ret;
1639 }
1640 
1641 static int clear_qf_name(struct super_block *sb, int qtype)
1642 {
1643 
1644         struct ext4_sb_info *sbi = EXT4_SB(sb);
1645         char *old_qname = get_qf_name(sb, sbi, qtype);
1646 
1647         if (sb_any_quota_loaded(sb) && old_qname) {
1648                 ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
1649                         " when quota turned on");
1650                 return -1;
1651         }
1652         rcu_assign_pointer(sbi->s_qf_names[qtype], NULL);
1653         synchronize_rcu();
1654         kfree(old_qname);
1655         return 1;
1656 }
1657 #endif
1658 
1659 #define MOPT_SET        0x0001
1660 #define MOPT_CLEAR      0x0002
1661 #define MOPT_NOSUPPORT  0x0004
1662 #define MOPT_EXPLICIT   0x0008
1663 #define MOPT_CLEAR_ERR  0x0010
1664 #define MOPT_GTE0       0x0020
1665 #ifdef CONFIG_QUOTA
1666 #define MOPT_Q          0
1667 #define MOPT_QFMT       0x0040
1668 #else
1669 #define MOPT_Q          MOPT_NOSUPPORT
1670 #define MOPT_QFMT       MOPT_NOSUPPORT
1671 #endif
1672 #define MOPT_DATAJ      0x0080
1673 #define MOPT_NO_EXT2    0x0100
1674 #define MOPT_NO_EXT3    0x0200
1675 #define MOPT_EXT4_ONLY  (MOPT_NO_EXT2 | MOPT_NO_EXT3)
1676 #define MOPT_STRING     0x0400
1677 
1678 static const struct mount_opts {
1679         int     token;
1680         int     mount_opt;
1681         int     flags;
1682 } ext4_mount_opts[] = {
1683         {Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
1684         {Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
1685         {Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
1686         {Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
1687         {Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
1688         {Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
1689         {Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
1690          MOPT_EXT4_ONLY | MOPT_SET},
1691         {Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
1692          MOPT_EXT4_ONLY | MOPT_CLEAR},
1693         {Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
1694         {Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
1695         {Opt_delalloc, EXT4_MOUNT_DELALLOC,
1696          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1697         {Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
1698          MOPT_EXT4_ONLY | MOPT_CLEAR},
1699         {Opt_warn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_SET},
1700         {Opt_nowarn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_CLEAR},
1701         {Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1702          MOPT_EXT4_ONLY | MOPT_CLEAR},
1703         {Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1704          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1705         {Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
1706                                     EXT4_MOUNT_JOURNAL_CHECKSUM),
1707          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1708         {Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
1709         {Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
1710         {Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
1711         {Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
1712         {Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
1713          MOPT_NO_EXT2},
1714         {Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
1715          MOPT_NO_EXT2},
1716         {Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
1717         {Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
1718         {Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
1719         {Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
1720         {Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
1721         {Opt_commit, 0, MOPT_GTE0},
1722         {Opt_max_batch_time, 0, MOPT_GTE0},
1723         {Opt_min_batch_time, 0, MOPT_GTE0},
1724         {Opt_inode_readahead_blks, 0, MOPT_GTE0},
1725         {Opt_init_itable, 0, MOPT_GTE0},
1726         {Opt_dax, EXT4_MOUNT_DAX, MOPT_SET},
1727         {Opt_stripe, 0, MOPT_GTE0},
1728         {Opt_resuid, 0, MOPT_GTE0},
1729         {Opt_resgid, 0, MOPT_GTE0},
1730         {Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1731         {Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
1732         {Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1733         {Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1734         {Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1735         {Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
1736          MOPT_NO_EXT2 | MOPT_DATAJ},
1737         {Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
1738         {Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
1739 #ifdef CONFIG_EXT4_FS_POSIX_ACL
1740         {Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
1741         {Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
1742 #else
1743         {Opt_acl, 0, MOPT_NOSUPPORT},
1744         {Opt_noacl, 0, MOPT_NOSUPPORT},
1745 #endif
1746         {Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
1747         {Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
1748         {Opt_debug_want_extra_isize, 0, MOPT_GTE0},
1749         {Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
1750         {Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
1751                                                         MOPT_SET | MOPT_Q},
1752         {Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
1753                                                         MOPT_SET | MOPT_Q},
1754         {Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
1755                                                         MOPT_SET | MOPT_Q},
1756         {Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
1757                        EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
1758                                                         MOPT_CLEAR | MOPT_Q},
1759         {Opt_usrjquota, 0, MOPT_Q},
1760         {Opt_grpjquota, 0, MOPT_Q},
1761         {Opt_offusrjquota, 0, MOPT_Q},
1762         {Opt_offgrpjquota, 0, MOPT_Q},
1763         {Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
1764         {Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
1765         {Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
1766         {Opt_max_dir_size_kb, 0, MOPT_GTE0},
1767         {Opt_test_dummy_encryption, 0, MOPT_GTE0},
1768         {Opt_nombcache, EXT4_MOUNT_NO_MBCACHE, MOPT_SET},
1769         {Opt_err, 0, 0}
1770 };
1771 
1772 #ifdef CONFIG_UNICODE
1773 static const struct ext4_sb_encodings {
1774         __u16 magic;
1775         char *name;
1776         char *version;
1777 } ext4_sb_encoding_map[] = {
1778         {EXT4_ENC_UTF8_12_1, "utf8", "12.1.0"},
1779 };
1780 
1781 static int ext4_sb_read_encoding(const struct ext4_super_block *es,
1782                                  const struct ext4_sb_encodings **encoding,
1783                                  __u16 *flags)
1784 {
1785         __u16 magic = le16_to_cpu(es->s_encoding);
1786         int i;
1787 
1788         for (i = 0; i < ARRAY_SIZE(ext4_sb_encoding_map); i++)
1789                 if (magic == ext4_sb_encoding_map[i].magic)
1790                         break;
1791 
1792         if (i >= ARRAY_SIZE(ext4_sb_encoding_map))
1793                 return -EINVAL;
1794 
1795         *encoding = &ext4_sb_encoding_map[i];
1796         *flags = le16_to_cpu(es->s_encoding_flags);
1797 
1798         return 0;
1799 }
1800 #endif
1801 
1802 static int handle_mount_opt(struct super_block *sb, char *opt, int token,
1803                             substring_t *args, unsigned long *journal_devnum,
1804                             unsigned int *journal_ioprio, int is_remount)
1805 {
1806         struct ext4_sb_info *sbi = EXT4_SB(sb);
1807         const struct mount_opts *m;
1808         kuid_t uid;
1809         kgid_t gid;
1810         int arg = 0;
1811 
1812 #ifdef CONFIG_QUOTA
1813         if (token == Opt_usrjquota)
1814                 return set_qf_name(sb, USRQUOTA, &args[0]);
1815         else if (token == Opt_grpjquota)
1816                 return set_qf_name(sb, GRPQUOTA, &args[0]);
1817         else if (token == Opt_offusrjquota)
1818                 return clear_qf_name(sb, USRQUOTA);
1819         else if (token == Opt_offgrpjquota)
1820                 return clear_qf_name(sb, GRPQUOTA);
1821 #endif
1822         switch (token) {
1823         case Opt_noacl:
1824         case Opt_nouser_xattr:
1825                 ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
1826                 break;
1827         case Opt_sb:
1828                 return 1;       /* handled by get_sb_block() */
1829         case Opt_removed:
1830                 ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
1831                 return 1;
1832         case Opt_abort:
1833                 sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
1834                 return 1;
1835         case Opt_i_version:
1836                 sb->s_flags |= SB_I_VERSION;
1837                 return 1;
1838         case Opt_lazytime:
1839                 sb->s_flags |= SB_LAZYTIME;
1840                 return 1;
1841         case Opt_nolazytime:
1842                 sb->s_flags &= ~SB_LAZYTIME;
1843                 return 1;
1844         }
1845 
1846         for (m = ext4_mount_opts; m->token != Opt_err; m++)
1847                 if (token == m->token)
1848                         break;
1849 
1850         if (m->token == Opt_err) {
1851                 ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
1852                          "or missing value", opt);
1853                 return -1;
1854         }
1855 
1856         if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
1857                 ext4_msg(sb, KERN_ERR,
1858                          "Mount option \"%s\" incompatible with ext2", opt);
1859                 return -1;
1860         }
1861         if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
1862                 ext4_msg(sb, KERN_ERR,
1863                          "Mount option \"%s\" incompatible with ext3", opt);
1864                 return -1;
1865         }
1866 
1867         if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
1868                 return -1;
1869         if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
1870                 return -1;
1871         if (m->flags & MOPT_EXPLICIT) {
1872                 if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
1873                         set_opt2(sb, EXPLICIT_DELALLOC);
1874                 } else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
1875                         set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
1876                 } else
1877                         return -1;
1878         }
1879         if (m->flags & MOPT_CLEAR_ERR)
1880                 clear_opt(sb, ERRORS_MASK);
1881         if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
1882                 ext4_msg(sb, KERN_ERR, "Cannot change quota "
1883                          "options when quota turned on");
1884                 return -1;
1885         }
1886 
1887         if (m->flags & MOPT_NOSUPPORT) {
1888                 ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
1889         } else if (token == Opt_commit) {
1890                 if (arg == 0)
1891                         arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
1892                 else if (arg > INT_MAX / HZ) {
1893                         ext4_msg(sb, KERN_ERR,
1894                                  "Invalid commit interval %d, "
1895                                  "must be smaller than %d",
1896                                  arg, INT_MAX / HZ);
1897                         return -1;
1898                 }
1899                 sbi->s_commit_interval = HZ * arg;
1900         } else if (token == Opt_debug_want_extra_isize) {
1901                 if ((arg & 1) ||
1902                     (arg < 4) ||
1903                     (arg > (sbi->s_inode_size - EXT4_GOOD_OLD_INODE_SIZE))) {
1904                         ext4_msg(sb, KERN_ERR,
1905                                  "Invalid want_extra_isize %d", arg);
1906                         return -1;
1907                 }
1908                 sbi->s_want_extra_isize = arg;
1909         } else if (token == Opt_max_batch_time) {
1910                 sbi->s_max_batch_time = arg;
1911         } else if (token == Opt_min_batch_time) {
1912                 sbi->s_min_batch_time = arg;
1913         } else if (token == Opt_inode_readahead_blks) {
1914                 if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
1915                         ext4_msg(sb, KERN_ERR,
1916                                  "EXT4-fs: inode_readahead_blks must be "
1917                                  "0 or a power of 2 smaller than 2^31");
1918                         return -1;
1919                 }
1920                 sbi->s_inode_readahead_blks = arg;
1921         } else if (token == Opt_init_itable) {
1922                 set_opt(sb, INIT_INODE_TABLE);
1923                 if (!args->from)
1924                         arg = EXT4_DEF_LI_WAIT_MULT;
1925                 sbi->s_li_wait_mult = arg;
1926         } else if (token == Opt_max_dir_size_kb) {
1927                 sbi->s_max_dir_size_kb = arg;
1928         } else if (token == Opt_stripe) {
1929                 sbi->s_stripe = arg;
1930         } else if (token == Opt_resuid) {
1931                 uid = make_kuid(current_user_ns(), arg);
1932                 if (!uid_valid(uid)) {
1933                         ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
1934                         return -1;
1935                 }
1936                 sbi->s_resuid = uid;
1937         } else if (token == Opt_resgid) {
1938                 gid = make_kgid(current_user_ns(), arg);
1939                 if (!gid_valid(gid)) {
1940                         ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
1941                         return -1;
1942                 }
1943                 sbi->s_resgid = gid;
1944         } else if (token == Opt_journal_dev) {
1945                 if (is_remount) {
1946                         ext4_msg(sb, KERN_ERR,
1947                                  "Cannot specify journal on remount");
1948                         return -1;
1949                 }
1950                 *journal_devnum = arg;
1951         } else if (token == Opt_journal_path) {
1952                 char *journal_path;
1953                 struct inode *journal_inode;
1954                 struct path path;
1955                 int error;
1956 
1957                 if (is_remount) {
1958                         ext4_msg(sb, KERN_ERR,
1959                                  "Cannot specify journal on remount");
1960                         return -1;
1961                 }
1962                 journal_path = match_strdup(&args[0]);
1963                 if (!journal_path) {
1964                         ext4_msg(sb, KERN_ERR, "error: could not dup "
1965                                 "journal device string");
1966                         return -1;
1967                 }
1968 
1969                 error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
1970                 if (error) {
1971                         ext4_msg(sb, KERN_ERR, "error: could not find "
1972                                 "journal device path: error %d", error);
1973                         kfree(journal_path);
1974                         return -1;
1975                 }
1976 
1977                 journal_inode = d_inode(path.dentry);
1978                 if (!S_ISBLK(journal_inode->i_mode)) {
1979                         ext4_msg(sb, KERN_ERR, "error: journal path %s "
1980                                 "is not a block device", journal_path);
1981                         path_put(&path);
1982                         kfree(journal_path);
1983                         return -1;
1984                 }
1985 
1986                 *journal_devnum = new_encode_dev(journal_inode->i_rdev);
1987                 path_put(&path);
1988                 kfree(journal_path);
1989         } else if (token == Opt_journal_ioprio) {
1990                 if (arg > 7) {
1991                         ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
1992                                  " (must be 0-7)");
1993                         return -1;
1994                 }
1995                 *journal_ioprio =
1996                         IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
1997         } else if (token == Opt_test_dummy_encryption) {
1998 #ifdef CONFIG_FS_ENCRYPTION
1999                 sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
2000                 ext4_msg(sb, KERN_WARNING,
2001                          "Test dummy encryption mode enabled");
2002 #else
2003                 ext4_msg(sb, KERN_WARNING,
2004                          "Test dummy encryption mount option ignored");
2005 #endif
2006         } else if (m->flags & MOPT_DATAJ) {
2007                 if (is_remount) {
2008                         if (!sbi->s_journal)
2009                                 ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
2010                         else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
2011                                 ext4_msg(sb, KERN_ERR,
2012                                          "Cannot change data mode on remount");
2013                                 return -1;
2014                         }
2015                 } else {
2016                         clear_opt(sb, DATA_FLAGS);
2017                         sbi->s_mount_opt |= m->mount_opt;
2018                 }
2019 #ifdef CONFIG_QUOTA
2020         } else if (m->flags & MOPT_QFMT) {
2021                 if (sb_any_quota_loaded(sb) &&
2022                     sbi->s_jquota_fmt != m->mount_opt) {
2023                         ext4_msg(sb, KERN_ERR, "Cannot change journaled "
2024                                  "quota options when quota turned on");
2025                         return -1;
2026                 }
2027                 if (ext4_has_feature_quota(sb)) {
2028                         ext4_msg(sb, KERN_INFO,
2029                                  "Quota format mount options ignored "
2030                                  "when QUOTA feature is enabled");
2031                         return 1;
2032                 }
2033                 sbi->s_jquota_fmt = m->mount_opt;
2034 #endif
2035         } else if (token == Opt_dax) {
2036 #ifdef CONFIG_FS_DAX
2037                 ext4_msg(sb, KERN_WARNING,
2038                 "DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
2039                 sbi->s_mount_opt |= m->mount_opt;
2040 #else
2041                 ext4_msg(sb, KERN_INFO, "dax option not supported");
2042                 return -1;
2043 #endif
2044         } else if (token == Opt_data_err_abort) {
2045                 sbi->s_mount_opt |= m->mount_opt;
2046         } else if (token == Opt_data_err_ignore) {
2047                 sbi->s_mount_opt &= ~m->mount_opt;
2048         } else {
2049                 if (!args->from)
2050                         arg = 1;
2051                 if (m->flags & MOPT_CLEAR)
2052                         arg = !arg;
2053                 else if (unlikely(!(m->flags & MOPT_SET))) {
2054                         ext4_msg(sb, KERN_WARNING,
2055                                  "buggy handling of option %s", opt);
2056                         WARN_ON(1);
2057                         return -1;
2058                 }
2059                 if (arg != 0)
2060                         sbi->s_mount_opt |= m->mount_opt;
2061                 else
2062                         sbi->s_mount_opt &= ~m->mount_opt;
2063         }
2064         return 1;
2065 }
2066 
2067 static int parse_options(char *options, struct super_block *sb,
2068                          unsigned long *journal_devnum,
2069                          unsigned int *journal_ioprio,
2070                          int is_remount)
2071 {
2072         struct ext4_sb_info *sbi = EXT4_SB(sb);
2073         char *p, __maybe_unused *usr_qf_name, __maybe_unused *grp_qf_name;
2074         substring_t args[MAX_OPT_ARGS];
2075         int token;
2076 
2077         if (!options)
2078                 return 1;
2079 
2080         while ((p = strsep(&options, ",")) != NULL) {
2081                 if (!*p)
2082                         continue;
2083                 /*
2084                  * Initialize args struct so we know whether arg was
2085                  * found; some options take optional arguments.
2086                  */
2087                 args[0].to = args[0].from = NULL;
2088                 token = match_token(p, tokens, args);
2089                 if (handle_mount_opt(sb, p, token, args, journal_devnum,
2090                                      journal_ioprio, is_remount) < 0)
2091                         return 0;
2092         }
2093 #ifdef CONFIG_QUOTA
2094         /*
2095          * We do the test below only for project quotas. 'usrquota' and
2096          * 'grpquota' mount options are allowed even without quota feature
2097          * to support legacy quotas in quota files.
2098          */
2099         if (test_opt(sb, PRJQUOTA) && !ext4_has_feature_project(sb)) {
2100                 ext4_msg(sb, KERN_ERR, "Project quota feature not enabled. "
2101                          "Cannot enable project quota enforcement.");
2102                 return 0;
2103         }
2104         usr_qf_name = get_qf_name(sb, sbi, USRQUOTA);
2105         grp_qf_name = get_qf_name(sb, sbi, GRPQUOTA);
2106         if (usr_qf_name || grp_qf_name) {
2107                 if (test_opt(sb, USRQUOTA) && usr_qf_name)
2108                         clear_opt(sb, USRQUOTA);
2109 
2110                 if (test_opt(sb, GRPQUOTA) && grp_qf_name)
2111                         clear_opt(sb, GRPQUOTA);
2112 
2113                 if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
2114                         ext4_msg(sb, KERN_ERR, "old and new quota "
2115                                         "format mixing");
2116                         return 0;
2117                 }
2118 
2119                 if (!sbi->s_jquota_fmt) {
2120                         ext4_msg(sb, KERN_ERR, "journaled quota format "
2121                                         "not specified");
2122                         return 0;
2123                 }
2124         }
2125 #endif
2126         if (test_opt(sb, DIOREAD_NOLOCK)) {
2127                 int blocksize =
2128                         BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
2129 
2130                 if (blocksize < PAGE_SIZE) {
2131                         ext4_msg(sb, KERN_ERR, "can't mount with "
2132                                  "dioread_nolock if block size != PAGE_SIZE");
2133                         return 0;
2134                 }
2135         }
2136         return 1;
2137 }
2138 
2139 static inline void ext4_show_quota_options(struct seq_file *seq,
2140                                            struct super_block *sb)
2141 {
2142 #if defined(CONFIG_QUOTA)
2143         struct ext4_sb_info *sbi = EXT4_SB(sb);
2144         char *usr_qf_name, *grp_qf_name;
2145 
2146         if (sbi->s_jquota_fmt) {
2147                 char *fmtname = "";
2148 
2149                 switch (sbi->s_jquota_fmt) {
2150                 case QFMT_VFS_OLD:
2151                         fmtname = "vfsold";
2152                         break;
2153                 case QFMT_VFS_V0:
2154                         fmtname = "vfsv0";
2155                         break;
2156                 case QFMT_VFS_V1:
2157                         fmtname = "vfsv1";
2158                         break;
2159                 }
2160                 seq_printf(seq, ",jqfmt=%s", fmtname);
2161         }
2162 
2163         rcu_read_lock();
2164         usr_qf_name = rcu_dereference(sbi->s_qf_names[USRQUOTA]);
2165         grp_qf_name = rcu_dereference(sbi->s_qf_names[GRPQUOTA]);
2166         if (usr_qf_name)
2167                 seq_show_option(seq, "usrjquota", usr_qf_name);
2168         if (grp_qf_name)
2169                 seq_show_option(seq, "grpjquota", grp_qf_name);
2170         rcu_read_unlock();
2171 #endif
2172 }
2173 
2174 static const char *token2str(int token)
2175 {
2176         const struct match_token *t;
2177 
2178         for (t = tokens; t->token != Opt_err; t++)
2179                 if (t->token == token && !strchr(t->pattern, '='))
2180                         break;
2181         return t->pattern;
2182 }
2183 
2184 /*
2185  * Show an option if
2186  *  - it's set to a non-default value OR
2187  *  - if the per-sb default is different from the global default
2188  */
2189 static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
2190                               int nodefs)
2191 {
2192         struct ext4_sb_info *sbi = EXT4_SB(sb);
2193         struct ext4_super_block *es = sbi->s_es;
2194         int def_errors, def_mount_opt = sbi->s_def_mount_opt;
2195         const struct mount_opts *m;
2196         char sep = nodefs ? '\n' : ',';
2197 
2198 #define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
2199 #define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
2200 
2201         if (sbi->s_sb_block != 1)
2202                 SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
2203 
2204         for (m = ext4_mount_opts; m->token != Opt_err; m++) {
2205                 int want_set = m->flags & MOPT_SET;
2206                 if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
2207                     (m->flags & MOPT_CLEAR_ERR))
2208                         continue;
2209                 if (!nodefs && !(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
2210                         continue; /* skip if same as the default */
2211                 if ((want_set &&
2212                      (sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
2213                     (!want_set && (sbi->s_mount_opt & m->mount_opt)))
2214                         continue; /* select Opt_noFoo vs Opt_Foo */
2215                 SEQ_OPTS_PRINT("%s", token2str(m->token));
2216         }
2217 
2218         if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
2219             le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
2220                 SEQ_OPTS_PRINT("resuid=%u",
2221                                 from_kuid_munged(&init_user_ns, sbi->s_resuid));
2222         if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
2223             le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
2224                 SEQ_OPTS_PRINT("resgid=%u",
2225                                 from_kgid_munged(&init_user_ns, sbi->s_resgid));
2226         def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
2227         if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
2228                 SEQ_OPTS_PUTS("errors=remount-ro");
2229         if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
2230                 SEQ_OPTS_PUTS("errors=continue");
2231         if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
2232                 SEQ_OPTS_PUTS("errors=panic");
2233         if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
2234                 SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
2235         if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
2236                 SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
2237         if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
2238                 SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
2239         if (sb->s_flags & SB_I_VERSION)
2240                 SEQ_OPTS_PUTS("i_version");
2241         if (nodefs || sbi->s_stripe)
2242                 SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
2243         if (nodefs || EXT4_MOUNT_DATA_FLAGS &
2244                         (sbi->s_mount_opt ^ def_mount_opt)) {
2245                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
2246                         SEQ_OPTS_PUTS("data=journal");
2247                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
2248                         SEQ_OPTS_PUTS("data=ordered");
2249                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
2250                         SEQ_OPTS_PUTS("data=writeback");
2251         }
2252         if (nodefs ||
2253             sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
2254                 SEQ_OPTS_PRINT("inode_readahead_blks=%u",
2255                                sbi->s_inode_readahead_blks);
2256 
2257         if (test_opt(sb, INIT_INODE_TABLE) && (nodefs ||
2258                        (sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
2259                 SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
2260         if (nodefs || sbi->s_max_dir_size_kb)
2261                 SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
2262         if (test_opt(sb, DATA_ERR_ABORT))
2263                 SEQ_OPTS_PUTS("data_err=abort");
2264         if (DUMMY_ENCRYPTION_ENABLED(sbi))
2265                 SEQ_OPTS_PUTS("test_dummy_encryption");
2266 
2267         ext4_show_quota_options(seq, sb);
2268         return 0;
2269 }
2270 
2271 static int ext4_show_options(struct seq_file *seq, struct dentry *root)
2272 {
2273         return _ext4_show_options(seq, root->d_sb, 0);
2274 }
2275 
2276 int ext4_seq_options_show(struct seq_file *seq, void *offset)
2277 {
2278         struct super_block *sb = seq->private;
2279         int rc;
2280 
2281         seq_puts(seq, sb_rdonly(sb) ? "ro" : "rw");
2282         rc = _ext4_show_options(seq, sb, 1);
2283         seq_puts(seq, "\n");
2284         return rc;
2285 }
2286 
2287 static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
2288                             int read_only)
2289 {
2290         struct ext4_sb_info *sbi = EXT4_SB(sb);
2291         int err = 0;
2292 
2293         if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
2294                 ext4_msg(sb, KERN_ERR, "revision level too high, "
2295                          "forcing read-only mode");
2296                 err = -EROFS;
2297         }
2298         if (read_only)
2299                 goto done;
2300         if (!(sbi->s_mount_state & EXT4_VALID_FS))
2301                 ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
2302                          "running e2fsck is recommended");
2303         else if (sbi->s_mount_state & EXT4_ERROR_FS)
2304                 ext4_msg(sb, KERN_WARNING,
2305                          "warning: mounting fs with errors, "
2306                          "running e2fsck is recommended");
2307         else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
2308                  le16_to_cpu(es->s_mnt_count) >=
2309                  (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
2310                 ext4_msg(sb, KERN_WARNING,
2311                          "warning: maximal mount count reached, "
2312                          "running e2fsck is recommended");
2313         else if (le32_to_cpu(es->s_checkinterval) &&
2314                  (ext4_get_tstamp(es, s_lastcheck) +
2315                   le32_to_cpu(es->s_checkinterval) <= ktime_get_real_seconds()))
2316                 ext4_msg(sb, KERN_WARNING,
2317                          "warning: checktime reached, "
2318                          "running e2fsck is recommended");
2319         if (!sbi->s_journal)
2320                 es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
2321         if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
2322                 es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
2323         le16_add_cpu(&es->s_mnt_count, 1);
2324         ext4_update_tstamp(es, s_mtime);
2325         if (sbi->s_journal)
2326                 ext4_set_feature_journal_needs_recovery(sb);
2327 
2328         err = ext4_commit_super(sb, 1);
2329 done:
2330         if (test_opt(sb, DEBUG))
2331                 printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
2332                                 "bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
2333                         sb->s_blocksize,
2334                         sbi->s_groups_count,
2335                         EXT4_BLOCKS_PER_GROUP(sb),
2336                         EXT4_INODES_PER_GROUP(sb),
2337                         sbi->s_mount_opt, sbi->s_mount_opt2);
2338 
2339         cleancache_init_fs(sb);
2340         return err;
2341 }
2342 
2343 int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
2344 {
2345         struct ext4_sb_info *sbi = EXT4_SB(sb);
2346         struct flex_groups **old_groups, **new_groups;
2347         int size, i, j;
2348 
2349         if (!sbi->s_log_groups_per_flex)
2350                 return 0;
2351 
2352         size = ext4_flex_group(sbi, ngroup - 1) + 1;
2353         if (size <= sbi->s_flex_groups_allocated)
2354                 return 0;
2355 
2356         new_groups = kvzalloc(roundup_pow_of_two(size *
2357                               sizeof(*sbi->s_flex_groups)), GFP_KERNEL);
2358         if (!new_groups) {
2359                 ext4_msg(sb, KERN_ERR,
2360                          "not enough memory for %d flex group pointers", size);
2361                 return -ENOMEM;
2362         }
2363         for (i = sbi->s_flex_groups_allocated; i < size; i++) {
2364                 new_groups[i] = kvzalloc(roundup_pow_of_two(
2365                                          sizeof(struct flex_groups)),
2366                                          GFP_KERNEL);
2367                 if (!new_groups[i]) {
2368                         for (j = sbi->s_flex_groups_allocated; j < i; j++)
2369                                 kvfree(new_groups[j]);
2370                         kvfree(new_groups);
2371                         ext4_msg(sb, KERN_ERR,
2372                                  "not enough memory for %d flex groups", size);
2373                         return -ENOMEM;
2374                 }
2375         }
2376         rcu_read_lock();
2377         old_groups = rcu_dereference(sbi->s_flex_groups);
2378         if (old_groups)
2379                 memcpy(new_groups, old_groups,
2380                        (sbi->s_flex_groups_allocated *
2381                         sizeof(struct flex_groups *)));
2382         rcu_read_unlock();
2383         rcu_assign_pointer(sbi->s_flex_groups, new_groups);
2384         sbi->s_flex_groups_allocated = size;
2385         if (old_groups)
2386                 ext4_kvfree_array_rcu(old_groups);
2387         return 0;
2388 }
2389 
2390 static int ext4_fill_flex_info(struct super_block *sb)
2391 {
2392         struct ext4_sb_info *sbi = EXT4_SB(sb);
2393         struct ext4_group_desc *gdp = NULL;
2394         struct flex_groups *fg;
2395         ext4_group_t flex_group;
2396         int i, err;
2397 
2398         sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
2399         if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
2400                 sbi->s_log_groups_per_flex = 0;
2401                 return 1;
2402         }
2403 
2404         err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
2405         if (err)
2406                 goto failed;
2407 
2408         for (i = 0; i < sbi->s_groups_count; i++) {
2409                 gdp = ext4_get_group_desc(sb, i, NULL);
2410 
2411                 flex_group = ext4_flex_group(sbi, i);
2412                 fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
2413                 atomic_add(ext4_free_inodes_count(sb, gdp), &fg->free_inodes);
2414                 atomic64_add(ext4_free_group_clusters(sb, gdp),
2415                              &fg->free_clusters);
2416                 atomic_add(ext4_used_dirs_count(sb, gdp), &fg->used_dirs);
2417         }
2418 
2419         return 1;
2420 failed:
2421         return 0;
2422 }
2423 
2424 static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
2425                                    struct ext4_group_desc *gdp)
2426 {
2427         int offset = offsetof(struct ext4_group_desc, bg_checksum);
2428         __u16 crc = 0;
2429         __le32 le_group = cpu_to_le32(block_group);
2430         struct ext4_sb_info *sbi = EXT4_SB(sb);
2431 
2432         if (ext4_has_metadata_csum(sbi->s_sb)) {
2433                 /* Use new metadata_csum algorithm */
2434                 __u32 csum32;
2435                 __u16 dummy_csum = 0;
2436 
2437                 csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
2438                                      sizeof(le_group));
2439                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
2440                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
2441                                      sizeof(dummy_csum));
2442                 offset += sizeof(dummy_csum);
2443                 if (offset < sbi->s_desc_size)
2444                         csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
2445                                              sbi->s_desc_size - offset);
2446 
2447                 crc = csum32 & 0xFFFF;
2448                 goto out;
2449         }
2450 
2451         /* old crc16 code */
2452         if (!ext4_has_feature_gdt_csum(sb))
2453                 return 0;
2454 
2455         crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
2456         crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
2457         crc = crc16(crc, (__u8 *)gdp, offset);
2458         offset += sizeof(gdp->bg_checksum); /* skip checksum */
2459         /* for checksum of struct ext4_group_desc do the rest...*/
2460         if (ext4_has_feature_64bit(sb) &&
2461             offset < le16_to_cpu(sbi->s_es->s_desc_size))
2462                 crc = crc16(crc, (__u8 *)gdp + offset,
2463                             le16_to_cpu(sbi->s_es->s_desc_size) -
2464                                 offset);
2465 
2466 out:
2467         return cpu_to_le16(crc);
2468 }
2469 
2470 int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
2471                                 struct ext4_group_desc *gdp)
2472 {
2473         if (ext4_has_group_desc_csum(sb) &&
2474             (gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
2475                 return 0;
2476 
2477         return 1;
2478 }
2479 
2480 void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
2481                               struct ext4_group_desc *gdp)
2482 {
2483         if (!ext4_has_group_desc_csum(sb))
2484                 return;
2485         gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
2486 }
2487 
2488 /* Called at mount-time, super-block is locked */
2489 static int ext4_check_descriptors(struct super_block *sb,
2490                                   ext4_fsblk_t sb_block,
2491                                   ext4_group_t *first_not_zeroed)
2492 {
2493         struct ext4_sb_info *sbi = EXT4_SB(sb);
2494         ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
2495         ext4_fsblk_t last_block;
2496         ext4_fsblk_t last_bg_block = sb_block + ext4_bg_num_gdb(sb, 0);
2497         ext4_fsblk_t block_bitmap;
2498         ext4_fsblk_t inode_bitmap;
2499         ext4_fsblk_t inode_table;
2500         int flexbg_flag = 0;
2501         ext4_group_t i, grp = sbi->s_groups_count;
2502 
2503         if (ext4_has_feature_flex_bg(sb))
2504                 flexbg_flag = 1;
2505 
2506         ext4_debug("Checking group descriptors");
2507 
2508         for (i = 0; i < sbi->s_groups_count; i++) {
2509                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
2510 
2511                 if (i == sbi->s_groups_count - 1 || flexbg_flag)
2512                         last_block = ext4_blocks_count(sbi->s_es) - 1;
2513                 else
2514                         last_block = first_block +
2515                                 (EXT4_BLOCKS_PER_GROUP(sb) - 1);
2516 
2517                 if ((grp == sbi->s_groups_count) &&
2518                    !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
2519                         grp = i;
2520 
2521                 block_bitmap = ext4_block_bitmap(sb, gdp);
2522                 if (block_bitmap == sb_block) {
2523                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2524                                  "Block bitmap for group %u overlaps "
2525                                  "superblock", i);
2526                         if (!sb_rdonly(sb))
2527                                 return 0;
2528                 }
2529                 if (block_bitmap >= sb_block + 1 &&
2530                     block_bitmap <= last_bg_block) {
2531                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2532                                  "Block bitmap for group %u overlaps "
2533                                  "block group descriptors", i);
2534                         if (!sb_rdonly(sb))
2535                                 return 0;
2536                 }
2537                 if (block_bitmap < first_block || block_bitmap > last_block) {
2538                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2539                                "Block bitmap for group %u not in group "
2540                                "(block %llu)!", i, block_bitmap);
2541                         return 0;
2542                 }
2543                 inode_bitmap = ext4_inode_bitmap(sb, gdp);
2544                 if (inode_bitmap == sb_block) {
2545                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2546                                  "Inode bitmap for group %u overlaps "
2547                                  "superblock", i);
2548                         if (!sb_rdonly(sb))
2549                                 return 0;
2550                 }
2551                 if (inode_bitmap >= sb_block + 1 &&
2552                     inode_bitmap <= last_bg_block) {
2553                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2554                                  "Inode bitmap for group %u overlaps "
2555                                  "block group descriptors", i);
2556                         if (!sb_rdonly(sb))
2557                                 return 0;
2558                 }
2559                 if (inode_bitmap < first_block || inode_bitmap > last_block) {
2560                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2561                                "Inode bitmap for group %u not in group "
2562                                "(block %llu)!", i, inode_bitmap);
2563                         return 0;
2564                 }
2565                 inode_table = ext4_inode_table(sb, gdp);
2566                 if (inode_table == sb_block) {
2567                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2568                                  "Inode table for group %u overlaps "
2569                                  "superblock", i);
2570                         if (!sb_rdonly(sb))
2571                                 return 0;
2572                 }
2573                 if (inode_table >= sb_block + 1 &&
2574                     inode_table <= last_bg_block) {
2575                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2576                                  "Inode table for group %u overlaps "
2577                                  "block group descriptors", i);
2578                         if (!sb_rdonly(sb))
2579                                 return 0;
2580                 }
2581                 if (inode_table < first_block ||
2582                     inode_table + sbi->s_itb_per_group - 1 > last_block) {
2583                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2584                                "Inode table for group %u not in group "
2585                                "(block %llu)!", i, inode_table);
2586                         return 0;
2587                 }
2588                 ext4_lock_group(sb, i);
2589                 if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
2590                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2591                                  "Checksum for group %u failed (%u!=%u)",
2592                                  i, le16_to_cpu(ext4_group_desc_csum(sb, i,
2593                                      gdp)), le16_to_cpu(gdp->bg_checksum));
2594                         if (!sb_rdonly(sb)) {
2595                                 ext4_unlock_group(sb, i);
2596                                 return 0;
2597                         }
2598                 }
2599                 ext4_unlock_group(sb, i);
2600                 if (!flexbg_flag)
2601                         first_block += EXT4_BLOCKS_PER_GROUP(sb);
2602         }
2603         if (NULL != first_not_zeroed)
2604                 *first_not_zeroed = grp;
2605         return 1;
2606 }
2607 
2608 /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
2609  * the superblock) which were deleted from all directories, but held open by
2610  * a process at the time of a crash.  We walk the list and try to delete these
2611  * inodes at recovery time (only with a read-write filesystem).
2612  *
2613  * In order to keep the orphan inode chain consistent during traversal (in
2614  * case of crash during recovery), we link each inode into the superblock
2615  * orphan list_head and handle it the same way as an inode deletion during
2616  * normal operation (which journals the operations for us).
2617  *
2618  * We only do an iget() and an iput() on each inode, which is very safe if we
2619  * accidentally point at an in-use or already deleted inode.  The worst that
2620  * can happen in this case is that we get a "bit already cleared" message from
2621  * ext4_free_inode().  The only reason we would point at a wrong inode is if
2622  * e2fsck was run on this filesystem, and it must have already done the orphan
2623  * inode cleanup for us, so we can safely abort without any further action.
2624  */
2625 static void ext4_orphan_cleanup(struct super_block *sb,
2626                                 struct ext4_super_block *es)
2627 {
2628         unsigned int s_flags = sb->s_flags;
2629         int ret, nr_orphans = 0, nr_truncates = 0;
2630 #ifdef CONFIG_QUOTA
2631         int quota_update = 0;
2632         int i;
2633 #endif
2634         if (!es->s_last_orphan) {
2635                 jbd_debug(4, "no orphan inodes to clean up\n");
2636                 return;
2637         }
2638 
2639         if (bdev_read_only(sb->s_bdev)) {
2640                 ext4_msg(sb, KERN_ERR, "write access "
2641                         "unavailable, skipping orphan cleanup");
2642                 return;
2643         }
2644 
2645         /* Check if feature set would not allow a r/w mount */
2646         if (!ext4_feature_set_ok(sb, 0)) {
2647                 ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
2648                          "unknown ROCOMPAT features");
2649                 return;
2650         }
2651 
2652         if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2653                 /* don't clear list on RO mount w/ errors */
2654                 if (es->s_last_orphan && !(s_flags & SB_RDONLY)) {
2655                         ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
2656                                   "clearing orphan list.\n");
2657                         es->s_last_orphan = 0;
2658                 }
2659                 jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2660                 return;
2661         }
2662 
2663         if (s_flags & SB_RDONLY) {
2664                 ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
2665                 sb->s_flags &= ~SB_RDONLY;
2666         }
2667 #ifdef CONFIG_QUOTA
2668         /* Needed for iput() to work correctly and not trash data */
2669         sb->s_flags |= SB_ACTIVE;
2670 
2671         /*
2672          * Turn on quotas which were not enabled for read-only mounts if
2673          * filesystem has quota feature, so that they are updated correctly.
2674          */
2675         if (ext4_has_feature_quota(sb) && (s_flags & SB_RDONLY)) {
2676                 int ret = ext4_enable_quotas(sb);
2677 
2678                 if (!ret)
2679                         quota_update = 1;
2680                 else
2681                         ext4_msg(sb, KERN_ERR,
2682                                 "Cannot turn on quotas: error %d", ret);
2683         }
2684 
2685         /* Turn on journaled quotas used for old sytle */
2686         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2687                 if (EXT4_SB(sb)->s_qf_names[i]) {
2688                         int ret = ext4_quota_on_mount(sb, i);
2689 
2690                         if (!ret)
2691                                 quota_update = 1;
2692                         else
2693                                 ext4_msg(sb, KERN_ERR,
2694                                         "Cannot turn on journaled "
2695                                         "quota: type %d: error %d", i, ret);
2696                 }
2697         }
2698 #endif
2699 
2700         while (es->s_last_orphan) {
2701                 struct inode *inode;
2702 
2703                 /*
2704                  * We may have encountered an error during cleanup; if
2705                  * so, skip the rest.
2706                  */
2707                 if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2708                         jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2709                         es->s_last_orphan = 0;
2710                         break;
2711                 }
2712 
2713                 inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
2714                 if (IS_ERR(inode)) {
2715                         es->s_last_orphan = 0;
2716                         break;
2717                 }
2718 
2719                 list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
2720                 dquot_initialize(inode);
2721                 if (inode->i_nlink) {
2722                         if (test_opt(sb, DEBUG))
2723                                 ext4_msg(sb, KERN_DEBUG,
2724                                         "%s: truncating inode %lu to %lld bytes",
2725                                         __func__, inode->i_ino, inode->i_size);
2726                         jbd_debug(2, "truncating inode %lu to %lld bytes\n",
2727                                   inode->i_ino, inode->i_size);
2728                         inode_lock(inode);
2729                         truncate_inode_pages(inode->i_mapping, inode->i_size);
2730                         ret = ext4_truncate(inode);
2731                         if (ret)
2732                                 ext4_std_error(inode->i_sb, ret);
2733                         inode_unlock(inode);
2734                         nr_truncates++;
2735                 } else {
2736                         if (test_opt(sb, DEBUG))
2737                                 ext4_msg(sb, KERN_DEBUG,
2738                                         "%s: deleting unreferenced inode %lu",
2739                                         __func__, inode->i_ino);
2740                         jbd_debug(2, "deleting unreferenced inode %lu\n",
2741                                   inode->i_ino);
2742                         nr_orphans++;
2743                 }
2744                 iput(inode);  /* The delete magic happens here! */
2745         }
2746 
2747 #define PLURAL(x) (x), ((x) == 1) ? "" : "s"
2748 
2749         if (nr_orphans)
2750                 ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
2751                        PLURAL(nr_orphans));
2752         if (nr_truncates)
2753                 ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
2754                        PLURAL(nr_truncates));
2755 #ifdef CONFIG_QUOTA
2756         /* Turn off quotas if they were enabled for orphan cleanup */
2757         if (quota_update) {
2758                 for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2759                         if (sb_dqopt(sb)->files[i])
2760                                 dquot_quota_off(sb, i);
2761                 }
2762         }
2763 #endif
2764         sb->s_flags = s_flags; /* Restore SB_RDONLY status */
2765 }
2766 
2767 /*
2768  * Maximal extent format file size.
2769  * Resulting logical blkno at s_maxbytes must fit in our on-disk
2770  * extent format containers, within a sector_t, and within i_blocks
2771  * in the vfs.  ext4 inode has 48 bits of i_block in fsblock units,
2772  * so that won't be a limiting factor.
2773  *
2774  * However there is other limiting factor. We do store extents in the form
2775  * of starting block and length, hence the resulting length of the extent
2776  * covering maximum file size must fit into on-disk format containers as
2777  * well. Given that length is always by 1 unit bigger than max unit (because
2778  * we count 0 as well) we have to lower the s_maxbytes by one fs block.
2779  *
2780  * Note, this does *not* consider any metadata overhead for vfs i_blocks.
2781  */
2782 static loff_t ext4_max_size(int blkbits, int has_huge_files)
2783 {
2784         loff_t res;
2785         loff_t upper_limit = MAX_LFS_FILESIZE;
2786 
2787         BUILD_BUG_ON(sizeof(blkcnt_t) < sizeof(u64));
2788 
2789         if (!has_huge_files) {
2790                 upper_limit = (1LL << 32) - 1;
2791 
2792                 /* total blocks in file system block size */
2793                 upper_limit >>= (blkbits - 9);
2794                 upper_limit <<= blkbits;
2795         }
2796 
2797         /*
2798          * 32-bit extent-start container, ee_block. We lower the maxbytes
2799          * by one fs block, so ee_len can cover the extent of maximum file
2800          * size
2801          */
2802         res = (1LL << 32) - 1;
2803         res <<= blkbits;
2804 
2805         /* Sanity check against vm- & vfs- imposed limits */
2806         if (res > upper_limit)
2807                 res = upper_limit;
2808 
2809         return res;
2810 }
2811 
2812 /*
2813  * Maximal bitmap file size.  There is a direct, and {,double-,triple-}indirect
2814  * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
2815  * We need to be 1 filesystem block less than the 2^48 sector limit.
2816  */
2817 static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
2818 {
2819         loff_t res = EXT4_NDIR_BLOCKS;
2820         int meta_blocks;
2821         loff_t upper_limit;
2822         /* This is calculated to be the largest file size for a dense, block
2823          * mapped file such that the file's total number of 512-byte sectors,
2824          * including data and all indirect blocks, does not exceed (2^48 - 1).
2825          *
2826          * __u32 i_blocks_lo and _u16 i_blocks_high represent the total
2827          * number of 512-byte sectors of the file.
2828          */
2829 
2830         if (!has_huge_files) {
2831                 /*
2832                  * !has_huge_files or implies that the inode i_block field
2833                  * represents total file blocks in 2^32 512-byte sectors ==
2834                  * size of vfs inode i_blocks * 8
2835                  */
2836                 upper_limit = (1LL << 32) - 1;
2837 
2838                 /* total blocks in file system block size */
2839                 upper_limit >>= (bits - 9);
2840 
2841         } else {
2842                 /*
2843                  * We use 48 bit ext4_inode i_blocks
2844                  * With EXT4_HUGE_FILE_FL set the i_blocks
2845                  * represent total number of blocks in
2846                  * file system block size
2847                  */
2848                 upper_limit = (1LL << 48) - 1;
2849 
2850         }
2851 
2852         /* indirect blocks */
2853         meta_blocks = 1;
2854         /* double indirect blocks */
2855         meta_blocks += 1 + (1LL << (bits-2));
2856         /* tripple indirect blocks */
2857         meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
2858 
2859         upper_limit -= meta_blocks;
2860         upper_limit <<= bits;
2861 
2862         res += 1LL << (bits-2);
2863         res += 1LL << (2*(bits-2));
2864         res += 1LL << (3*(bits-2));
2865         res <<= bits;
2866         if (res > upper_limit)
2867                 res = upper_limit;
2868 
2869         if (res > MAX_LFS_FILESIZE)
2870                 res = MAX_LFS_FILESIZE;
2871 
2872         return res;
2873 }
2874 
2875 static ext4_fsblk_t descriptor_loc(struct super_block *sb,
2876                                    ext4_fsblk_t logical_sb_block, int nr)
2877 {
2878         struct ext4_sb_info *sbi = EXT4_SB(sb);
2879         ext4_group_t bg, first_meta_bg;
2880         int has_super = 0;
2881 
2882         first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
2883 
2884         if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
2885                 return logical_sb_block + nr + 1;
2886         bg = sbi->s_desc_per_block * nr;
2887         if (ext4_bg_has_super(sb, bg))
2888                 has_super = 1;
2889 
2890         /*
2891          * If we have a meta_bg fs with 1k blocks, group 0's GDT is at
2892          * block 2, not 1.  If s_first_data_block == 0 (bigalloc is enabled
2893          * on modern mke2fs or blksize > 1k on older mke2fs) then we must
2894          * compensate.
2895          */
2896         if (sb->s_blocksize == 1024 && nr == 0 &&
2897             le32_to_cpu(sbi->s_es->s_first_data_block) == 0)
2898                 has_super++;
2899 
2900         return (has_super + ext4_group_first_block_no(sb, bg));
2901 }
2902 
2903 /**
2904  * ext4_get_stripe_size: Get the stripe size.
2905  * @sbi: In memory super block info
2906  *
2907  * If we have specified it via mount option, then
2908  * use the mount option value. If the value specified at mount time is
2909  * greater than the blocks per group use the super block value.
2910  * If the super block value is greater than blocks per group return 0.
2911  * Allocator needs it be less than blocks per group.
2912  *
2913  */
2914 static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
2915 {
2916         unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
2917         unsigned long stripe_width =
2918                         le32_to_cpu(sbi->s_es->s_raid_stripe_width);
2919         int ret;
2920 
2921         if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
2922                 ret = sbi->s_stripe;
2923         else if (stripe_width && stripe_width <= sbi->s_blocks_per_group)
2924                 ret = stripe_width;
2925         else if (stride && stride <= sbi->s_blocks_per_group)
2926                 ret = stride;
2927         else
2928                 ret = 0;
2929 
2930         /*
2931          * If the stripe width is 1, this makes no sense and
2932          * we set it to 0 to turn off stripe handling code.
2933          */
2934         if (ret <= 1)
2935                 ret = 0;
2936 
2937         return ret;
2938 }
2939 
2940 /*
2941  * Check whether this filesystem can be mounted based on
2942  * the features present and the RDONLY/RDWR mount requested.
2943  * Returns 1 if this filesystem can be mounted as requested,
2944  * 0 if it cannot be.
2945  */
2946 static int ext4_feature_set_ok(struct super_block *sb, int readonly)
2947 {
2948         if (ext4_has_unknown_ext4_incompat_features(sb)) {
2949                 ext4_msg(sb, KERN_ERR,
2950                         "Couldn't mount because of "
2951                         "unsupported optional features (%x)",
2952                         (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
2953                         ~EXT4_FEATURE_INCOMPAT_SUPP));
2954                 return 0;
2955         }
2956 
2957 #ifndef CONFIG_UNICODE
2958         if (ext4_has_feature_casefold(sb)) {
2959                 ext4_msg(sb, KERN_ERR,
2960                          "Filesystem with casefold feature cannot be "
2961                          "mounted without CONFIG_UNICODE");
2962                 return 0;
2963         }
2964 #endif
2965 
2966         if (readonly)
2967                 return 1;
2968 
2969         if (ext4_has_feature_readonly(sb)) {
2970                 ext4_msg(sb, KERN_INFO, "filesystem is read-only");
2971                 sb->s_flags |= SB_RDONLY;
2972                 return 1;
2973         }
2974 
2975         /* Check that feature set is OK for a read-write mount */
2976         if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
2977                 ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
2978                          "unsupported optional features (%x)",
2979                          (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
2980                                 ~EXT4_FEATURE_RO_COMPAT_SUPP));
2981                 return 0;
2982         }
2983         if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
2984                 ext4_msg(sb, KERN_ERR,
2985                          "Can't support bigalloc feature without "
2986                          "extents feature\n");
2987                 return 0;
2988         }
2989 
2990 #if !IS_ENABLED(CONFIG_QUOTA) || !IS_ENABLED(CONFIG_QFMT_V2)
2991         if (!readonly && (ext4_has_feature_quota(sb) ||
2992                           ext4_has_feature_project(sb))) {
2993                 ext4_msg(sb, KERN_ERR,
2994                          "The kernel was not built with CONFIG_QUOTA and CONFIG_QFMT_V2");
2995                 return 0;
2996         }
2997 #endif  /* CONFIG_QUOTA */
2998         return 1;
2999 }
3000 
3001 /*
3002  * This function is called once a day if we have errors logged
3003  * on the file system
3004  */
3005 static void print_daily_error_info(struct timer_list *t)
3006 {
3007         struct ext4_sb_info *sbi = from_timer(sbi, t, s_err_report);
3008         struct super_block *sb = sbi->s_sb;
3009         struct ext4_super_block *es = sbi->s_es;
3010 
3011         if (es->s_error_count)
3012                 /* fsck newer than v1.41.13 is needed to clean this condition. */
3013                 ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
3014                          le32_to_cpu(es->s_error_count));
3015         if (es->s_first_error_time) {
3016                 printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %llu: %.*s:%d",
3017                        sb->s_id,
3018                        ext4_get_tstamp(es, s_first_error_time),
3019                        (int) sizeof(es->s_first_error_func),
3020                        es->s_first_error_func,
3021                        le32_to_cpu(es->s_first_error_line));
3022                 if (es->s_first_error_ino)
3023                         printk(KERN_CONT ": inode %u",
3024                                le32_to_cpu(es->s_first_error_ino));
3025                 if (es->s_first_error_block)
3026                         printk(KERN_CONT ": block %llu", (unsigned long long)
3027                                le64_to_cpu(es->s_first_error_block));
3028                 printk(KERN_CONT "\n");
3029         }
3030         if (es->s_last_error_time) {
3031                 printk(KERN_NOTICE "EXT4-fs (%s): last error at time %llu: %.*s:%d",
3032                        sb->s_id,
3033                        ext4_get_tstamp(es, s_last_error_time),
3034                        (int) sizeof(es->s_last_error_func),
3035                        es->s_last_error_func,
3036                        le32_to_cpu(es->s_last_error_line));
3037                 if (es->s_last_error_ino)
3038                         printk(KERN_CONT ": inode %u",
3039                                le32_to_cpu(es->s_last_error_ino));
3040                 if (es->s_last_error_block)
3041                         printk(KERN_CONT ": block %llu", (unsigned long long)
3042                                le64_to_cpu(es->s_last_error_block));
3043                 printk(KERN_CONT "\n");
3044         }
3045         mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);  /* Once a day */
3046 }
3047 
3048 /* Find next suitable group and run ext4_init_inode_table */
3049 static int ext4_run_li_request(struct ext4_li_request *elr)
3050 {
3051         struct ext4_group_desc *gdp = NULL;
3052         ext4_group_t group, ngroups;
3053         struct super_block *sb;
3054         unsigned long timeout = 0;
3055         int ret = 0;
3056 
3057         sb = elr->lr_super;
3058         ngroups = EXT4_SB(sb)->s_groups_count;
3059 
3060         for (group = elr->lr_next_group; group < ngroups; group++) {
3061                 gdp = ext4_get_group_desc(sb, group, NULL);
3062                 if (!gdp) {
3063                         ret = 1;
3064                         break;
3065                 }
3066 
3067                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3068                         break;
3069         }
3070 
3071         if (group >= ngroups)
3072                 ret = 1;
3073 
3074         if (!ret) {
3075                 timeout = jiffies;
3076                 ret = ext4_init_inode_table(sb, group,
3077                                             elr->lr_timeout ? 0 : 1);
3078                 if (elr->lr_timeout == 0) {
3079                         timeout = (jiffies - timeout) *
3080                                   elr->lr_sbi->s_li_wait_mult;
3081                         elr->lr_timeout = timeout;
3082                 }
3083                 elr->lr_next_sched = jiffies + elr->lr_timeout;
3084                 elr->lr_next_group = group + 1;
3085         }
3086         return ret;
3087 }
3088 
3089 /*
3090  * Remove lr_request from the list_request and free the
3091  * request structure. Should be called with li_list_mtx held
3092  */
3093 static void ext4_remove_li_request(struct ext4_li_request *elr)
3094 {
3095         struct ext4_sb_info *sbi;
3096 
3097         if (!elr)
3098                 return;
3099 
3100         sbi = elr->lr_sbi;
3101 
3102         list_del(&elr->lr_request);
3103         sbi->s_li_request = NULL;
3104         kfree(elr);
3105 }
3106 
3107 static void ext4_unregister_li_request(struct super_block *sb)
3108 {
3109         mutex_lock(&ext4_li_mtx);
3110         if (!ext4_li_info) {
3111                 mutex_unlock(&ext4_li_mtx);
3112                 return;
3113         }
3114 
3115         mutex_lock(&ext4_li_info->li_list_mtx);
3116         ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
3117         mutex_unlock(&ext4_li_info->li_list_mtx);
3118         mutex_unlock(&ext4_li_mtx);
3119 }
3120 
3121 static struct task_struct *ext4_lazyinit_task;
3122 
3123 /*
3124  * This is the function where ext4lazyinit thread lives. It walks
3125  * through the request list searching for next scheduled filesystem.
3126  * When such a fs is found, run the lazy initialization request
3127  * (ext4_rn_li_request) and keep track of the time spend in this
3128  * function. Based on that time we compute next schedule time of
3129  * the request. When walking through the list is complete, compute
3130  * next waking time and put itself into sleep.
3131  */
3132 static int ext4_lazyinit_thread(void *arg)
3133 {
3134         struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
3135         struct list_head *pos, *n;
3136         struct ext4_li_request *elr;
3137         unsigned long next_wakeup, cur;
3138 
3139         BUG_ON(NULL == eli);
3140 
3141 cont_thread:
3142         while (true) {
3143                 next_wakeup = MAX_JIFFY_OFFSET;
3144 
3145                 mutex_lock(&eli->li_list_mtx);
3146                 if (list_empty(&eli->li_request_list)) {
3147                         mutex_unlock(&eli->li_list_mtx);
3148                         goto exit_thread;
3149                 }
3150                 list_for_each_safe(pos, n, &eli->li_request_list) {
3151                         int err = 0;
3152                         int progress = 0;
3153                         elr = list_entry(pos, struct ext4_li_request,
3154                                          lr_request);
3155 
3156                         if (time_before(jiffies, elr->lr_next_sched)) {
3157                                 if (time_before(elr->lr_next_sched, next_wakeup))
3158                                         next_wakeup = elr->lr_next_sched;
3159                                 continue;
3160                         }
3161                         if (down_read_trylock(&elr->lr_super->s_umount)) {
3162                                 if (sb_start_write_trylock(elr->lr_super)) {
3163                                         progress = 1;
3164                                         /*
3165                                          * We hold sb->s_umount, sb can not
3166                                          * be removed from the list, it is
3167                                          * now safe to drop li_list_mtx
3168                                          */
3169                                         mutex_unlock(&eli->li_list_mtx);
3170                                         err = ext4_run_li_request(elr);
3171                                         sb_end_write(elr->lr_super);
3172                                         mutex_lock(&eli->li_list_mtx);
3173                                         n = pos->next;
3174                                 }
3175                                 up_read((&elr->lr_super->s_umount));
3176                         }
3177                         /* error, remove the lazy_init job */
3178                         if (err) {
3179                                 ext4_remove_li_request(elr);
3180                                 continue;
3181                         }
3182                         if (!progress) {
3183                                 elr->lr_next_sched = jiffies +
3184                                         (prandom_u32()
3185                                          % (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3186                         }
3187                         if (time_before(elr->lr_next_sched, next_wakeup))
3188                                 next_wakeup = elr->lr_next_sched;
3189                 }
3190                 mutex_unlock(&eli->li_list_mtx);
3191 
3192                 try_to_freeze();
3193 
3194                 cur = jiffies;
3195                 if ((time_after_eq(cur, next_wakeup)) ||
3196                     (MAX_JIFFY_OFFSET == next_wakeup)) {
3197                         cond_resched();
3198                         continue;
3199                 }
3200 
3201                 schedule_timeout_interruptible(next_wakeup - cur);
3202 
3203                 if (kthread_should_stop()) {
3204                         ext4_clear_request_list();
3205                         goto exit_thread;
3206                 }
3207         }
3208 
3209 exit_thread:
3210         /*
3211          * It looks like the request list is empty, but we need
3212          * to check it under the li_list_mtx lock, to prevent any
3213          * additions into it, and of course we should lock ext4_li_mtx
3214          * to atomically free the list and ext4_li_info, because at
3215          * this point another ext4 filesystem could be registering
3216          * new one.
3217          */
3218         mutex_lock(&ext4_li_mtx);
3219         mutex_lock(&eli->li_list_mtx);
3220         if (!list_empty(&eli->li_request_list)) {
3221                 mutex_unlock(&eli->li_list_mtx);
3222                 mutex_unlock(&ext4_li_mtx);
3223                 goto cont_thread;
3224         }
3225         mutex_unlock(&eli->li_list_mtx);
3226         kfree(ext4_li_info);
3227         ext4_li_info = NULL;
3228         mutex_unlock(&ext4_li_mtx);
3229 
3230         return 0;
3231 }
3232 
3233 static void ext4_clear_request_list(void)
3234 {
3235         struct list_head *pos, *n;
3236         struct ext4_li_request *elr;
3237 
3238         mutex_lock(&ext4_li_info->li_list_mtx);
3239         list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
3240                 elr = list_entry(pos, struct ext4_li_request,
3241                                  lr_request);
3242                 ext4_remove_li_request(elr);
3243         }
3244         mutex_unlock(&ext4_li_info->li_list_mtx);
3245 }
3246 
3247 static int ext4_run_lazyinit_thread(void)
3248 {
3249         ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
3250                                          ext4_li_info, "ext4lazyinit");
3251         if (IS_ERR(ext4_lazyinit_task)) {
3252                 int err = PTR_ERR(ext4_lazyinit_task);
3253                 ext4_clear_request_list();
3254                 kfree(ext4_li_info);
3255                 ext4_li_info = NULL;
3256                 printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
3257                                  "initialization thread\n",
3258                                  err);
3259                 return err;
3260         }
3261         ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
3262         return 0;
3263 }
3264 
3265 /*
3266  * Check whether it make sense to run itable init. thread or not.
3267  * If there is at least one uninitialized inode table, return
3268  * corresponding group number, else the loop goes through all
3269  * groups and return total number of groups.
3270  */
3271 static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
3272 {
3273         ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
3274         struct ext4_group_desc *gdp = NULL;
3275 
3276         if (!ext4_has_group_desc_csum(sb))
3277                 return ngroups;
3278 
3279         for (group = 0; group < ngroups; group++) {
3280                 gdp = ext4_get_group_desc(sb, group, NULL);
3281                 if (!gdp)
3282                         continue;
3283 
3284                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3285                         break;
3286         }
3287 
3288         return group;
3289 }
3290 
3291 static int ext4_li_info_new(void)
3292 {
3293         struct ext4_lazy_init *eli = NULL;
3294 
3295         eli = kzalloc(sizeof(*eli), GFP_KERNEL);
3296         if (!eli)
3297                 return -ENOMEM;
3298 
3299         INIT_LIST_HEAD(&eli->li_request_list);
3300         mutex_init(&eli->li_list_mtx);
3301 
3302         eli->li_state |= EXT4_LAZYINIT_QUIT;
3303 
3304         ext4_li_info = eli;
3305 
3306         return 0;
3307 }
3308 
3309 static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
3310                                             ext4_group_t start)
3311 {
3312         struct ext4_sb_info *sbi = EXT4_SB(sb);
3313         struct ext4_li_request *elr;
3314 
3315         elr = kzalloc(sizeof(*elr), GFP_KERNEL);
3316         if (!elr)
3317                 return NULL;
3318 
3319         elr->lr_super = sb;
3320         elr->lr_sbi = sbi;
3321         elr->lr_next_group = start;
3322 
3323         /*
3324          * Randomize first schedule time of the request to
3325          * spread the inode table initialization requests
3326          * better.
3327          */
3328         elr->lr_next_sched = jiffies + (prandom_u32() %
3329                                 (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3330         return elr;
3331 }
3332 
3333 int ext4_register_li_request(struct super_block *sb,
3334                              ext4_group_t first_not_zeroed)
3335 {
3336         struct ext4_sb_info *sbi = EXT4_SB(sb);
3337         struct ext4_li_request *elr = NULL;
3338         ext4_group_t ngroups = sbi->s_groups_count;
3339         int ret = 0;
3340 
3341         mutex_lock(&ext4_li_mtx);
3342         if (sbi->s_li_request != NULL) {
3343                 /*
3344                  * Reset timeout so it can be computed again, because
3345                  * s_li_wait_mult might have changed.
3346                  */
3347                 sbi->s_li_request->lr_timeout = 0;
3348                 goto out;
3349         }
3350 
3351         if (first_not_zeroed == ngroups || sb_rdonly(sb) ||
3352             !test_opt(sb, INIT_INODE_TABLE))
3353                 goto out;
3354 
3355         elr = ext4_li_request_new(sb, first_not_zeroed);
3356         if (!elr) {
3357                 ret = -ENOMEM;
3358                 goto out;
3359         }
3360 
3361         if (NULL == ext4_li_info) {
3362                 ret = ext4_li_info_new();
3363                 if (ret)
3364                         goto out;
3365         }
3366 
3367         mutex_lock(&ext4_li_info->li_list_mtx);
3368         list_add(&elr->lr_request, &ext4_li_info->li_request_list);
3369         mutex_unlock(&ext4_li_info->li_list_mtx);
3370 
3371         sbi->s_li_request = elr;
3372         /*
3373          * set elr to NULL here since it has been inserted to
3374          * the request_list and the removal and free of it is
3375          * handled by ext4_clear_request_list from now on.
3376          */
3377         elr = NULL;
3378 
3379         if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
3380                 ret = ext4_run_lazyinit_thread();
3381                 if (ret)
3382                         goto out;
3383         }
3384 out:
3385         mutex_unlock(&ext4_li_mtx);
3386         if (ret)
3387                 kfree(elr);
3388         return ret;
3389 }
3390 
3391 /*
3392  * We do not need to lock anything since this is called on
3393  * module unload.
3394  */
3395 static void ext4_destroy_lazyinit_thread(void)
3396 {
3397         /*
3398          * If thread exited earlier
3399          * there's nothing to be done.
3400          */
3401         if (!ext4_li_info || !ext4_lazyinit_task)
3402                 return;
3403 
3404         kthread_stop(ext4_lazyinit_task);
3405 }
3406 
3407 static int set_journal_csum_feature_set(struct super_block *sb)
3408 {
3409         int ret = 1;
3410         int compat, incompat;
3411         struct ext4_sb_info *sbi = EXT4_SB(sb);
3412 
3413         if (ext4_has_metadata_csum(sb)) {
3414                 /* journal checksum v3 */
3415                 compat = 0;
3416                 incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
3417         } else {
3418                 /* journal checksum v1 */
3419                 compat = JBD2_FEATURE_COMPAT_CHECKSUM;
3420                 incompat = 0;
3421         }
3422 
3423         jbd2_journal_clear_features(sbi->s_journal,
3424                         JBD2_FEATURE_COMPAT_CHECKSUM, 0,
3425                         JBD2_FEATURE_INCOMPAT_CSUM_V3 |
3426                         JBD2_FEATURE_INCOMPAT_CSUM_V2);
3427         if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
3428                 ret = jbd2_journal_set_features(sbi->s_journal,
3429                                 compat, 0,
3430                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
3431                                 incompat);
3432         } else if (test_opt(sb, JOURNAL_CHECKSUM)) {
3433                 ret = jbd2_journal_set_features(sbi->s_journal,
3434                                 compat, 0,
3435                                 incompat);
3436                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3437                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3438         } else {
3439                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3440                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3441         }
3442 
3443         return ret;
3444 }
3445 
3446 /*
3447  * Note: calculating the overhead so we can be compatible with
3448  * historical BSD practice is quite difficult in the face of
3449  * clusters/bigalloc.  This is because multiple metadata blocks from
3450  * different block group can end up in the same allocation cluster.
3451  * Calculating the exact overhead in the face of clustered allocation
3452  * requires either O(all block bitmaps) in memory or O(number of block
3453  * groups**2) in time.  We will still calculate the superblock for
3454  * older file systems --- and if we come across with a bigalloc file
3455  * system with zero in s_overhead_clusters the estimate will be close to
3456  * correct especially for very large cluster sizes --- but for newer
3457  * file systems, it's better to calculate this figure once at mkfs
3458  * time, and store it in the superblock.  If the superblock value is
3459  * present (even for non-bigalloc file systems), we will use it.
3460  */
3461 static int count_overhead(struct super_block *sb, ext4_group_t grp,
3462                           char *buf)
3463 {
3464         struct ext4_sb_info     *sbi = EXT4_SB(sb);
3465         struct ext4_group_desc  *gdp;
3466         ext4_fsblk_t            first_block, last_block, b;
3467         ext4_group_t            i, ngroups = ext4_get_groups_count(sb);
3468         int                     s, j, count = 0;
3469 
3470         if (!ext4_has_feature_bigalloc(sb))
3471                 return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
3472                         sbi->s_itb_per_group + 2);
3473 
3474         first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
3475                 (grp * EXT4_BLOCKS_PER_GROUP(sb));
3476         last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
3477         for (i = 0; i < ngroups; i++) {
3478                 gdp = ext4_get_group_desc(sb, i, NULL);
3479                 b = ext4_block_bitmap(sb, gdp);
3480                 if (b >= first_block && b <= last_block) {
3481                         ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3482                         count++;
3483                 }
3484                 b = ext4_inode_bitmap(sb, gdp);
3485                 if (b >= first_block && b <= last_block) {
3486                         ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3487                         count++;
3488                 }
3489                 b = ext4_inode_table(sb, gdp);
3490                 if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
3491                         for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
3492                                 int c = EXT4_B2C(sbi, b - first_block);
3493                                 ext4_set_bit(c, buf);
3494                                 count++;
3495                         }
3496                 if (i != grp)
3497                         continue;
3498                 s = 0;
3499                 if (ext4_bg_has_super(sb, grp)) {
3500                         ext4_set_bit(s++, buf);
3501                         count++;
3502                 }
3503                 j = ext4_bg_num_gdb(sb, grp);
3504                 if (s + j > EXT4_BLOCKS_PER_GROUP(sb)) {
3505                         ext4_error(sb, "Invalid number of block group "
3506                                    "descriptor blocks: %d", j);
3507                         j = EXT4_BLOCKS_PER_GROUP(sb) - s;
3508                 }
3509                 count += j;
3510                 for (; j > 0; j--)
3511                         ext4_set_bit(EXT4_B2C(sbi, s++), buf);
3512         }
3513         if (!count)
3514                 return 0;
3515         return EXT4_CLUSTERS_PER_GROUP(sb) -
3516                 ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
3517 }
3518 
3519 /*
3520  * Compute the overhead and stash it in sbi->s_overhead
3521  */
3522 int ext4_calculate_overhead(struct super_block *sb)
3523 {
3524         struct ext4_sb_info *sbi = EXT4_SB(sb);
3525         struct ext4_super_block *es = sbi->s_es;
3526         struct inode *j_inode;
3527         unsigned int j_blocks, j_inum = le32_to_cpu(es->s_journal_inum);
3528         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
3529         ext4_fsblk_t overhead = 0;
3530         char *buf = (char *) get_zeroed_page(GFP_NOFS);
3531 
3532         if (!buf)
3533                 return -ENOMEM;
3534 
3535         /*
3536          * Compute the overhead (FS structures).  This is constant
3537          * for a given filesystem unless the number of block groups
3538          * changes so we cache the previous value until it does.
3539          */
3540 
3541         /*
3542          * All of the blocks before first_data_block are overhead
3543          */
3544         overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
3545 
3546         /*
3547          * Add the overhead found in each block group
3548          */
3549         for (i = 0; i < ngroups; i++) {
3550                 int blks;
3551 
3552                 blks = count_overhead(sb, i, buf);
3553                 overhead += blks;
3554                 if (blks)
3555                         memset(buf, 0, PAGE_SIZE);
3556                 cond_resched();
3557         }
3558 
3559         /*
3560          * Add the internal journal blocks whether the journal has been
3561          * loaded or not
3562          */
3563         if (sbi->s_journal && !sbi->journal_bdev)
3564                 overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
3565         else if (ext4_has_feature_journal(sb) && !sbi->s_journal && j_inum) {
3566                 /* j_inum for internal journal is non-zero */
3567                 j_inode = ext4_get_journal_inode(sb, j_inum);
3568                 if (j_inode) {
3569                         j_blocks = j_inode->i_size >> sb->s_blocksize_bits;
3570                         overhead += EXT4_NUM_B2C(sbi, j_blocks);
3571                         iput(j_inode);
3572                 } else {
3573                         ext4_msg(sb, KERN_ERR, "can't get journal size");
3574                 }
3575         }
3576         sbi->s_overhead = overhead;
3577         smp_wmb();
3578         free_page((unsigned long) buf);
3579         return 0;
3580 }
3581 
3582 static void ext4_set_resv_clusters(struct super_block *sb)
3583 {
3584         ext4_fsblk_t resv_clusters;
3585         struct ext4_sb_info *sbi = EXT4_SB(sb);
3586 
3587         /*
3588          * There's no need to reserve anything when we aren't using extents.
3589          * The space estimates are exact, there are no unwritten extents,
3590          * hole punching doesn't need new metadata... This is needed especially
3591          * to keep ext2/3 backward compatibility.
3592          */
3593         if (!ext4_has_feature_extents(sb))
3594                 return;
3595         /*
3596          * By default we reserve 2% or 4096 clusters, whichever is smaller.
3597          * This should cover the situations where we can not afford to run
3598          * out of space like for example punch hole, or converting
3599          * unwritten extents in delalloc path. In most cases such
3600          * allocation would require 1, or 2 blocks, higher numbers are
3601          * very rare.
3602          */
3603         resv_clusters = (ext4_blocks_count(sbi->s_es) >>
3604                          sbi->s_cluster_bits);
3605 
3606         do_div(resv_clusters, 50);
3607         resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
3608 
3609         atomic64_set(&sbi->s_resv_clusters, resv_clusters);
3610 }
3611 
3612 static int ext4_fill_super(struct super_block *sb, void *data, int silent)
3613 {
3614         struct dax_device *dax_dev = fs_dax_get_by_bdev(sb->s_bdev);
3615         char *orig_data = kstrdup(data, GFP_KERNEL);
3616         struct buffer_head *bh, **group_desc;
3617         struct ext4_super_block *es = NULL;
3618         struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
3619         struct flex_groups **flex_groups;
3620         ext4_fsblk_t block;
3621         ext4_fsblk_t sb_block = get_sb_block(&data);
3622         ext4_fsblk_t logical_sb_block;
3623         unsigned long offset = 0;
3624         unsigned long journal_devnum = 0;
3625         unsigned long def_mount_opts;
3626         struct inode *root;
3627         const char *descr;
3628         int ret = -ENOMEM;
3629         int blocksize, clustersize;
3630         unsigned int db_count;
3631         unsigned int i;
3632         int needs_recovery, has_huge_files, has_bigalloc;
3633         __u64 blocks_count;
3634         int err = 0;
3635         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
3636         ext4_group_t first_not_zeroed;
3637 
3638         if ((data && !orig_data) || !sbi)
3639                 goto out_free_base;
3640 
3641         sbi->s_daxdev = dax_dev;
3642         sbi->s_blockgroup_lock =
3643                 kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
3644         if (!sbi->s_blockgroup_lock)
3645                 goto out_free_base;
3646 
3647         sb->s_fs_info = sbi;
3648         sbi->s_sb = sb;
3649         sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
3650         sbi->s_sb_block = sb_block;
3651         if (sb->s_bdev->bd_part)
3652                 sbi->s_sectors_written_start =
3653                         part_stat_read(sb->s_bdev->bd_part, sectors[STAT_WRITE]);
3654 
3655         /* Cleanup superblock name */
3656         strreplace(sb->s_id, '/', '!');
3657 
3658         /* -EINVAL is default */
3659         ret = -EINVAL;
3660         blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
3661         if (!blocksize) {
3662                 ext4_msg(sb, KERN_ERR, "unable to set blocksize");
3663                 goto out_fail;
3664         }
3665 
3666         /*
3667          * The ext4 superblock will not be buffer aligned for other than 1kB
3668          * block sizes.  We need to calculate the offset from buffer start.
3669          */
3670         if (blocksize != EXT4_MIN_BLOCK_SIZE) {
3671                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
3672                 offset = do_div(logical_sb_block, blocksize);
3673         } else {
3674                 logical_sb_block = sb_block;
3675         }
3676 
3677         if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
3678                 ext4_msg(sb, KERN_ERR, "unable to read superblock");
3679                 goto out_fail;
3680         }
3681         /*
3682          * Note: s_es must be initialized as soon as possible because
3683          *       some ext4 macro-instructions depend on its value
3684          */
3685         es = (struct ext4_super_block *) (bh->b_data + offset);
3686         sbi->s_es = es;
3687         sb->s_magic = le16_to_cpu(es->s_magic);
3688         if (sb->s_magic != EXT4_SUPER_MAGIC)
3689                 goto cantfind_ext4;
3690         sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
3691 
3692         /* Warn if metadata_csum and gdt_csum are both set. */
3693         if (ext4_has_feature_metadata_csum(sb) &&
3694             ext4_has_feature_gdt_csum(sb))
3695                 ext4_warning(sb, "metadata_csum and uninit_bg are "
3696                              "redundant flags; please run fsck.");
3697 
3698         /* Check for a known checksum algorithm */
3699         if (!ext4_verify_csum_type(sb, es)) {
3700                 ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
3701                          "unknown checksum algorithm.");
3702                 silent = 1;
3703                 goto cantfind_ext4;
3704         }
3705 
3706         /* Load the checksum driver */
3707         sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
3708         if (IS_ERR(sbi->s_chksum_driver)) {
3709                 ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
3710                 ret = PTR_ERR(sbi->s_chksum_driver);
3711                 sbi->s_chksum_driver = NULL;
3712                 goto failed_mount;
3713         }
3714 
3715         /* Check superblock checksum */
3716         if (!ext4_superblock_csum_verify(sb, es)) {
3717                 ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
3718                          "invalid superblock checksum.  Run e2fsck?");
3719                 silent = 1;
3720                 ret = -EFSBADCRC;
3721                 goto cantfind_ext4;
3722         }
3723 
3724         /* Precompute checksum seed for all metadata */
3725         if (ext4_has_feature_csum_seed(sb))
3726                 sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
3727         else if (ext4_has_metadata_csum(sb) || ext4_has_feature_ea_inode(sb))
3728                 sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
3729                                                sizeof(es->s_uuid));
3730 
3731         /* Set defaults before we parse the mount options */
3732         def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
3733         set_opt(sb, INIT_INODE_TABLE);
3734         if (def_mount_opts & EXT4_DEFM_DEBUG)
3735                 set_opt(sb, DEBUG);
3736         if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
3737                 set_opt(sb, GRPID);
3738         if (def_mount_opts & EXT4_DEFM_UID16)
3739                 set_opt(sb, NO_UID32);
3740         /* xattr user namespace & acls are now defaulted on */
3741         set_opt(sb, XATTR_USER);
3742 #ifdef CONFIG_EXT4_FS_POSIX_ACL
3743         set_opt(sb, POSIX_ACL);
3744 #endif
3745         /* don't forget to enable journal_csum when metadata_csum is enabled. */
3746         if (ext4_has_metadata_csum(sb))
3747                 set_opt(sb, JOURNAL_CHECKSUM);
3748 
3749         if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
3750                 set_opt(sb, JOURNAL_DATA);
3751         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
3752                 set_opt(sb, ORDERED_DATA);
3753         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
3754                 set_opt(sb, WRITEBACK_DATA);
3755 
3756         if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
3757                 set_opt(sb, ERRORS_PANIC);
3758         else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
3759                 set_opt(sb, ERRORS_CONT);
3760         else
3761                 set_opt(sb, ERRORS_RO);
3762         /* block_validity enabled by default; disable with noblock_validity */
3763         set_opt(sb, BLOCK_VALIDITY);
3764         if (def_mount_opts & EXT4_DEFM_DISCARD)
3765                 set_opt(sb, DISCARD);
3766 
3767         sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
3768         sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
3769         sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
3770         sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
3771         sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
3772 
3773         if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
3774                 set_opt(sb, BARRIER);
3775 
3776         /*
3777          * enable delayed allocation by default
3778          * Use -o nodelalloc to turn it off
3779          */
3780         if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
3781             ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
3782                 set_opt(sb, DELALLOC);
3783 
3784         /*
3785          * set default s_li_wait_mult for lazyinit, for the case there is
3786          * no mount option specified.
3787          */
3788         sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
3789 
3790         blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
3791         if (blocksize < EXT4_MIN_BLOCK_SIZE ||
3792             blocksize > EXT4_MAX_BLOCK_SIZE) {
3793                 ext4_msg(sb, KERN_ERR,
3794                        "Unsupported filesystem blocksize %d (%d log_block_size)",
3795                          blocksize, le32_to_cpu(es->s_log_block_size));
3796                 goto failed_mount;
3797         }
3798 
3799         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
3800                 sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
3801                 sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
3802         } else {
3803                 sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
3804                 sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
3805                 if (sbi->s_first_ino < EXT4_GOOD_OLD_FIRST_INO) {
3806                         ext4_msg(sb, KERN_ERR, "invalid first ino: %u",
3807                                  sbi->s_first_ino);
3808                         goto failed_mount;
3809                 }
3810                 if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
3811                     (!is_power_of_2(sbi->s_inode_size)) ||
3812                     (sbi->s_inode_size > blocksize)) {
3813                         ext4_msg(sb, KERN_ERR,
3814                                "unsupported inode size: %d",
3815                                sbi->s_inode_size);
3816                         ext4_msg(sb, KERN_ERR, "blocksize: %d", blocksize);
3817                         goto failed_mount;
3818                 }
3819                 /*
3820                  * i_atime_extra is the last extra field available for
3821                  * [acm]times in struct ext4_inode. Checking for that
3822                  * field should suffice to ensure we have extra space
3823                  * for all three.
3824                  */
3825                 if (sbi->s_inode_size >= offsetof(struct ext4_inode, i_atime_extra) +
3826                         sizeof(((struct ext4_inode *)0)->i_atime_extra)) {
3827                         sb->s_time_gran = 1;
3828                         sb->s_time_max = EXT4_EXTRA_TIMESTAMP_MAX;
3829                 } else {
3830                         sb->s_time_gran = NSEC_PER_SEC;
3831                         sb->s_time_max = EXT4_NON_EXTRA_TIMESTAMP_MAX;
3832                 }
3833                 sb->s_time_min = EXT4_TIMESTAMP_MIN;
3834         }
3835         if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
3836                 sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
3837                         EXT4_GOOD_OLD_INODE_SIZE;
3838                 if (ext4_has_feature_extra_isize(sb)) {
3839                         unsigned v, max = (sbi->s_inode_size -
3840                                            EXT4_GOOD_OLD_INODE_SIZE);
3841 
3842                         v = le16_to_cpu(es->s_want_extra_isize);
3843                         if (v > max) {
3844                                 ext4_msg(sb, KERN_ERR,
3845                                          "bad s_want_extra_isize: %d", v);
3846                                 goto failed_mount;
3847                         }
3848                         if (sbi->s_want_extra_isize < v)
3849                                 sbi->s_want_extra_isize = v;
3850 
3851                         v = le16_to_cpu(es->s_min_extra_isize);
3852                         if (v > max) {
3853                                 ext4_msg(sb, KERN_ERR,
3854                                          "bad s_min_extra_isize: %d", v);
3855                                 goto failed_mount;
3856                         }
3857                         if (sbi->s_want_extra_isize < v)
3858                                 sbi->s_want_extra_isize = v;
3859                 }
3860         }
3861 
3862         if (sbi->s_es->s_mount_opts[0]) {
3863                 char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
3864                                               sizeof(sbi->s_es->s_mount_opts),
3865                                               GFP_KERNEL);
3866                 if (!s_mount_opts)
3867                         goto failed_mount;
3868                 if (!parse_options(s_mount_opts, sb, &journal_devnum,
3869                                    &journal_ioprio, 0)) {
3870                         ext4_msg(sb, KERN_WARNING,
3871                                  "failed to parse options in superblock: %s",
3872                                  s_mount_opts);
3873                 }
3874                 kfree(s_mount_opts);
3875         }
3876         sbi->s_def_mount_opt = sbi->s_mount_opt;
3877         if (!parse_options((char *) data, sb, &journal_devnum,
3878                            &journal_ioprio, 0))
3879                 goto failed_mount;
3880 
3881 #ifdef CONFIG_UNICODE
3882         if (ext4_has_feature_casefold(sb) && !sbi->s_encoding) {
3883                 const struct ext4_sb_encodings *encoding_info;
3884                 struct unicode_map *encoding;
3885                 __u16 encoding_flags;
3886 
3887                 if (ext4_has_feature_encrypt(sb)) {
3888                         ext4_msg(sb, KERN_ERR,
3889                                  "Can't mount with encoding and encryption");
3890                         goto failed_mount;
3891                 }
3892 
3893                 if (ext4_sb_read_encoding(es, &encoding_info,
3894                                           &encoding_flags)) {
3895                         ext4_msg(sb, KERN_ERR,
3896                                  "Encoding requested by superblock is unknown");
3897                         goto failed_mount;
3898                 }
3899 
3900                 encoding = utf8_load(encoding_info->version);
3901                 if (IS_ERR(encoding)) {
3902                         ext4_msg(sb, KERN_ERR,
3903                                  "can't mount with superblock charset: %s-%s "
3904                                  "not supported by the kernel. flags: 0x%x.",
3905                                  encoding_info->name, encoding_info->version,
3906                                  encoding_flags);
3907                         goto failed_mount;
3908                 }
3909                 ext4_msg(sb, KERN_INFO,"Using encoding defined by superblock: "
3910                          "%s-%s with flags 0x%hx", encoding_info->name,
3911                          encoding_info->version?:"\b", encoding_flags);
3912 
3913                 sbi->s_encoding = encoding;
3914                 sbi->s_encoding_flags = encoding_flags;
3915         }
3916 #endif
3917 
3918         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
3919                 printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
3920                             "with data=journal disables delayed "
3921                             "allocation and O_DIRECT support!\n");
3922                 if (test_opt2(sb, EXPLICIT_DELALLOC)) {
3923                         ext4_msg(sb, KERN_ERR, "can't mount with "
3924                                  "both data=journal and delalloc");
3925                         goto failed_mount;
3926                 }
3927                 if (test_opt(sb, DIOREAD_NOLOCK)) {
3928                         ext4_msg(sb, KERN_ERR, "can't mount with "
3929                                  "both data=journal and dioread_nolock");
3930                         goto failed_mount;
3931                 }
3932                 if (test_opt(sb, DAX)) {
3933                         ext4_msg(sb, KERN_ERR, "can't mount with "
3934                                  "both data=journal and dax");
3935                         goto failed_mount;
3936                 }
3937                 if (ext4_has_feature_encrypt(sb)) {
3938                         ext4_msg(sb, KERN_WARNING,
3939                                  "encrypted files will use data=ordered "
3940                                  "instead of data journaling mode");
3941                 }
3942                 if (test_opt(sb, DELALLOC))
3943                         clear_opt(sb, DELALLOC);
3944         } else {
3945                 sb->s_iflags |= SB_I_CGROUPWB;
3946         }
3947 
3948         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
3949                 (test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
3950 
3951         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
3952             (ext4_has_compat_features(sb) ||
3953              ext4_has_ro_compat_features(sb) ||
3954              ext4_has_incompat_features(sb)))
3955                 ext4_msg(sb, KERN_WARNING,
3956                        "feature flags set on rev 0 fs, "
3957                        "running e2fsck is recommended");
3958 
3959         if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
3960                 set_opt2(sb, HURD_COMPAT);
3961                 if (ext4_has_feature_64bit(sb)) {
3962                         ext4_msg(sb, KERN_ERR,
3963                                  "The Hurd can't support 64-bit file systems");
3964                         goto failed_mount;
3965                 }
3966 
3967                 /*
3968                  * ea_inode feature uses l_i_version field which is not
3969                  * available in HURD_COMPAT mode.
3970                  */
3971                 if (ext4_has_feature_ea_inode(sb)) {
3972                         ext4_msg(sb, KERN_ERR,
3973                                  "ea_inode feature is not supported for Hurd");
3974                         goto failed_mount;
3975                 }
3976         }
3977 
3978         if (IS_EXT2_SB(sb)) {
3979                 if (ext2_feature_set_ok(sb))
3980                         ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
3981                                  "using the ext4 subsystem");
3982                 else {
3983                         /*
3984                          * If we're probing be silent, if this looks like
3985                          * it's actually an ext[34] filesystem.
3986                          */
3987                         if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
3988                                 goto failed_mount;
3989                         ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
3990                                  "to feature incompatibilities");
3991                         goto failed_mount;
3992                 }
3993         }
3994 
3995         if (IS_EXT3_SB(sb)) {
3996                 if (ext3_feature_set_ok(sb))
3997                         ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
3998                                  "using the ext4 subsystem");
3999                 else {
4000                         /*
4001                          * If we're probing be silent, if this looks like
4002                          * it's actually an ext4 filesystem.
4003                          */
4004                         if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
4005                                 goto failed_mount;
4006                         ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
4007                                  "to feature incompatibilities");
4008                         goto failed_mount;
4009                 }
4010         }
4011 
4012         /*
4013          * Check feature flags regardless of the revision level, since we
4014          * previously didn't change the revision level when setting the flags,
4015          * so there is a chance incompat flags are set on a rev 0 filesystem.
4016          */
4017         if (!ext4_feature_set_ok(sb, (sb_rdonly(sb))))
4018                 goto failed_mount;
4019 
4020         if (le32_to_cpu(es->s_log_block_size) >
4021             (EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4022                 ext4_msg(sb, KERN_ERR,
4023                          "Invalid log block size: %u",
4024                          le32_to_cpu(es->s_log_block_size));
4025                 goto failed_mount;
4026         }
4027         if (le32_to_cpu(es->s_log_cluster_size) >
4028             (EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4029                 ext4_msg(sb, KERN_ERR,
4030                          "Invalid log cluster size: %u",
4031                          le32_to_cpu(es->s_log_cluster_size));
4032                 goto failed_mount;
4033         }
4034 
4035         if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
4036                 ext4_msg(sb, KERN_ERR,
4037                          "Number of reserved GDT blocks insanely large: %d",
4038                          le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
4039                 goto failed_mount;
4040         }
4041 
4042         if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
4043                 if (ext4_has_feature_inline_data(sb)) {
4044                         ext4_msg(sb, KERN_ERR, "Cannot use DAX on a filesystem"
4045                                         " that may contain inline data");
4046                         goto failed_mount;
4047                 }
4048                 if (!bdev_dax_supported(sb->s_bdev, blocksize)) {
4049                         ext4_msg(sb, KERN_ERR,
4050                                 "DAX unsupported by block device.");
4051                         goto failed_mount;
4052                 }
4053         }
4054 
4055         if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
4056                 ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
4057                          es->s_encryption_level);
4058                 goto failed_mount;
4059         }
4060 
4061         if (sb->s_blocksize != blocksize) {
4062                 /* Validate the filesystem blocksize */
4063                 if (!sb_set_blocksize(sb, blocksize)) {
4064                         ext4_msg(sb, KERN_ERR, "bad block size %d",
4065                                         blocksize);
4066                         goto failed_mount;
4067                 }
4068 
4069                 brelse(bh);
4070                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
4071                 offset = do_div(logical_sb_block, blocksize);
4072                 bh = sb_bread_unmovable(sb, logical_sb_block);
4073                 if (!bh) {
4074                         ext4_msg(sb, KERN_ERR,
4075                                "Can't read superblock on 2nd try");
4076                         goto failed_mount;
4077                 }
4078                 es = (struct ext4_super_block *)(bh->b_data + offset);
4079                 sbi->s_es = es;
4080                 if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
4081                         ext4_msg(sb, KERN_ERR,
4082                                "Magic mismatch, very weird!");
4083                         goto failed_mount;
4084                 }
4085         }
4086 
4087         has_huge_files = ext4_has_feature_huge_file(sb);
4088         sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
4089                                                       has_huge_files);
4090         sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
4091 
4092         sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
4093         if (ext4_has_feature_64bit(sb)) {
4094                 if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
4095                     sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
4096                     !is_power_of_2(sbi->s_desc_size)) {
4097                         ext4_msg(sb, KERN_ERR,
4098                                "unsupported descriptor size %lu",
4099                                sbi->s_desc_size);
4100                         goto failed_mount;
4101                 }
4102         } else
4103                 sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
4104 
4105         sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
4106         sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
4107 
4108         sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
4109         if (sbi->s_inodes_per_block == 0)
4110                 goto cantfind_ext4;
4111         if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
4112             sbi->s_inodes_per_group > blocksize * 8) {
4113                 ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
4114                          sbi->s_inodes_per_group);
4115                 goto failed_mount;
4116         }
4117         sbi->s_itb_per_group = sbi->s_inodes_per_group /
4118                                         sbi->s_inodes_per_block;
4119         sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
4120         sbi->s_sbh = bh;
4121         sbi->s_mount_state = le16_to_cpu(es->s_state);
4122         sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
4123         sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
4124 
4125         for (i = 0; i < 4; i++)
4126                 sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
4127         sbi->s_def_hash_version = es->s_def_hash_version;
4128         if (ext4_has_feature_dir_index(sb)) {
4129                 i = le32_to_cpu(es->s_flags);
4130                 if (i & EXT2_FLAGS_UNSIGNED_HASH)
4131                         sbi->s_hash_unsigned = 3;
4132                 else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
4133 #ifdef __CHAR_UNSIGNED__
4134                         if (!sb_rdonly(sb))
4135                                 es->s_flags |=
4136                                         cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
4137                         sbi->s_hash_unsigned = 3;
4138 #else
4139                         if (!sb_rdonly(sb))
4140                                 es->s_flags |=
4141                                         cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
4142 #endif
4143                 }
4144         }
4145 
4146         /* Handle clustersize */
4147         clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
4148         has_bigalloc = ext4_has_feature_bigalloc(sb);
4149         if (has_bigalloc) {
4150                 if (clustersize < blocksize) {
4151                         ext4_msg(sb, KERN_ERR,
4152                                  "cluster size (%d) smaller than "
4153                                  "block size (%d)", clustersize, blocksize);
4154                         goto failed_mount;
4155                 }
4156                 sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
4157                         le32_to_cpu(es->s_log_block_size);
4158                 sbi->s_clusters_per_group =
4159                         le32_to_cpu(es->s_clusters_per_group);
4160                 if (sbi->s_clusters_per_group > blocksize * 8) {
4161                         ext4_msg(sb, KERN_ERR,
4162                                  "#clusters per group too big: %lu",
4163                                  sbi->s_clusters_per_group);
4164                         goto failed_mount;
4165                 }
4166                 if (sbi->s_blocks_per_group !=
4167                     (sbi->s_clusters_per_group * (clustersize / blocksize))) {
4168                         ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
4169                                  "clusters per group (%lu) inconsistent",
4170                                  sbi->s_blocks_per_group,
4171                                  sbi->s_clusters_per_group);
4172                         goto failed_mount;
4173                 }
4174         } else {
4175                 if (clustersize != blocksize) {
4176                         ext4_msg(sb, KERN_ERR,
4177                                  "fragment/cluster size (%d) != "
4178                                  "block size (%d)", clustersize, blocksize);
4179                         goto failed_mount;
4180                 }
4181                 if (sbi->s_blocks_per_group > blocksize * 8) {
4182                         ext4_msg(sb, KERN_ERR,
4183                                  "#blocks per group too big: %lu",
4184                                  sbi->s_blocks_per_group);
4185                         goto failed_mount;
4186                 }
4187                 sbi->s_clusters_per_group = sbi->s_blocks_per_group;
4188                 sbi->s_cluster_bits = 0;
4189         }
4190         sbi->s_cluster_ratio = clustersize / blocksize;
4191 
4192         /* Do we have standard group size of clustersize * 8 blocks ? */
4193         if (sbi->s_blocks_per_group == clustersize << 3)
4194                 set_opt2(sb, STD_GROUP_SIZE);
4195 
4196         /*
4197          * Test whether we have more sectors than will fit in sector_t,
4198          * and whether the max offset is addressable by the page cache.
4199          */
4200         err = generic_check_addressable(sb->s_blocksize_bits,
4201                                         ext4_blocks_count(es));
4202         if (err) {
4203                 ext4_msg(sb, KERN_ERR, "filesystem"
4204                          " too large to mount safely on this system");
4205                 goto failed_mount;
4206         }
4207 
4208         if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
4209                 goto cantfind_ext4;
4210 
4211         /* check blocks count against device size */
4212         blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
4213         if (blocks_count && ext4_blocks_count(es) > blocks_count) {
4214                 ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
4215                        "exceeds size of device (%llu blocks)",
4216                        ext4_blocks_count(es), blocks_count);
4217                 goto failed_mount;
4218         }
4219 
4220         /*
4221          * It makes no sense for the first data block to be beyond the end
4222          * of the filesystem.
4223          */
4224         if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
4225                 ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4226                          "block %u is beyond end of filesystem (%llu)",
4227                          le32_to_cpu(es->s_first_data_block),
4228                          ext4_blocks_count(es));
4229                 goto failed_mount;
4230         }
4231         if ((es->s_first_data_block == 0) && (es->s_log_block_size == 0) &&
4232             (sbi->s_cluster_ratio == 1)) {
4233                 ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4234                          "block is 0 with a 1k block and cluster size");
4235                 goto failed_mount;
4236         }
4237 
4238         blocks_count = (ext4_blocks_count(es) -
4239                         le32_to_cpu(es->s_first_data_block) +
4240                         EXT4_BLOCKS_PER_GROUP(sb) - 1);
4241         do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
4242         if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
4243                 ext4_msg(sb, KERN_WARNING, "groups count too large: %llu "
4244                        "(block count %llu, first data block %u, "
4245                        "blocks per group %lu)", blocks_count,
4246                        ext4_blocks_count(es),
4247                        le32_to_cpu(es->s_first_data_block),
4248                        EXT4_BLOCKS_PER_GROUP(sb));
4249                 goto failed_mount;
4250         }
4251         sbi->s_groups_count = blocks_count;
4252         sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
4253                         (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
4254         if (((u64)sbi->s_groups_count * sbi->s_inodes_per_group) !=
4255             le32_to_cpu(es->s_inodes_count)) {
4256                 ext4_msg(sb, KERN_ERR, "inodes count not valid: %u vs %llu",
4257                          le32_to_cpu(es->s_inodes_count),
4258                          ((u64)sbi->s_groups_count * sbi->s_inodes_per_group));
4259                 ret = -EINVAL;
4260                 goto failed_mount;
4261         }
4262         db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
4263                    EXT4_DESC_PER_BLOCK(sb);
4264         if (ext4_has_feature_meta_bg(sb)) {
4265                 if (le32_to_cpu(es->s_first_meta_bg) > db_count) {
4266                         ext4_msg(sb, KERN_WARNING,
4267                                  "first meta block group too large: %u "
4268                                  "(group descriptor block count %u)",
4269                                  le32_to_cpu(es->s_first_meta_bg), db_count);
4270                         goto failed_mount;
4271                 }
4272         }
4273         rcu_assign_pointer(sbi->s_group_desc,
4274                            kvmalloc_array(db_count,
4275                                           sizeof(struct buffer_head *),
4276                                           GFP_KERNEL));
4277         if (sbi->s_group_desc == NULL) {
4278                 ext4_msg(sb, KERN_ERR, "not enough memory");
4279                 ret = -ENOMEM;
4280                 goto failed_mount;
4281         }
4282 
4283         bgl_lock_init(sbi->s_blockgroup_lock);
4284 
4285         /* Pre-read the descriptors into the buffer cache */
4286         for (i = 0; i < db_count; i++) {
4287                 block = descriptor_loc(sb, logical_sb_block, i);
4288                 sb_breadahead_unmovable(sb, block);
4289         }
4290 
4291         for (i = 0; i < db_count; i++) {
4292                 struct buffer_head *bh;
4293 
4294                 block = descriptor_loc(sb, logical_sb_block, i);
4295                 bh = sb_bread_unmovable(sb, block);
4296                 if (!bh) {
4297                         ext4_msg(sb, KERN_ERR,
4298                                "can't read group descriptor %d", i);
4299                         db_count = i;
4300                         goto failed_mount2;
4301                 }
4302                 rcu_read_lock();
4303                 rcu_dereference(sbi->s_group_desc)[i] = bh;
4304                 rcu_read_unlock();
4305         }
4306         sbi->s_gdb_count = db_count;
4307         if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
4308                 ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
4309                 ret = -EFSCORRUPTED;
4310                 goto failed_mount2;
4311         }
4312 
4313         timer_setup(&sbi->s_err_report, print_daily_error_info, 0);
4314 
4315         /* Register extent status tree shrinker */
4316         if (ext4_es_register_shrinker(sbi))
4317                 goto failed_mount3;
4318 
4319         sbi->s_stripe = ext4_get_stripe_size(sbi);
4320         sbi->s_extent_max_zeroout_kb = 32;
4321 
4322         /*
4323          * set up enough so that it can read an inode
4324          */
4325         sb->s_op = &ext4_sops;
4326         sb->s_export_op = &ext4_export_ops;
4327         sb->s_xattr = ext4_xattr_handlers;
4328 #ifdef CONFIG_FS_ENCRYPTION
4329         sb->s_cop = &ext4_cryptops;
4330 #endif
4331 #ifdef CONFIG_FS_VERITY
4332         sb->s_vop = &ext4_verityops;
4333 #endif
4334 #ifdef CONFIG_QUOTA
4335         sb->dq_op = &ext4_quota_operations;
4336         if (ext4_has_feature_quota(sb))
4337                 sb->s_qcop = &dquot_quotactl_sysfile_ops;
4338         else
4339                 sb->s_qcop = &ext4_qctl_operations;
4340         sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
4341 #endif
4342         memcpy(&sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
4343 
4344         INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
4345         mutex_init(&sbi->s_orphan_lock);
4346 
4347         sb->s_root = NULL;
4348 
4349         needs_recovery = (es->s_last_orphan != 0 ||
4350                           ext4_has_feature_journal_needs_recovery(sb));
4351 
4352         if (ext4_has_feature_mmp(sb) && !sb_rdonly(sb))
4353                 if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
4354                         goto failed_mount3a;
4355 
4356         /*
4357          * The first inode we look at is the journal inode.  Don't try
4358          * root first: it may be modified in the journal!
4359          */
4360         if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
4361                 err = ext4_load_journal(sb, es, journal_devnum);
4362                 if (err)
4363                         goto failed_mount3a;
4364         } else if (test_opt(sb, NOLOAD) && !sb_rdonly(sb) &&
4365                    ext4_has_feature_journal_needs_recovery(sb)) {
4366                 ext4_msg(sb, KERN_ERR, "required journal recovery "
4367                        "suppressed and not mounted read-only");
4368                 goto failed_mount_wq;
4369         } else {
4370                 /* Nojournal mode, all journal mount options are illegal */
4371                 if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
4372                         ext4_msg(sb, KERN_ERR, "can't mount with "
4373                                  "journal_checksum, fs mounted w/o journal");
4374                         goto failed_mount_wq;
4375                 }
4376                 if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4377                         ext4_msg(sb, KERN_ERR, "can't mount with "
4378                                  "journal_async_commit, fs mounted w/o journal");
4379                         goto failed_mount_wq;
4380                 }
4381                 if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
4382                         ext4_msg(sb, KERN_ERR, "can't mount with "
4383                                  "commit=%lu, fs mounted w/o journal",
4384                                  sbi->s_commit_interval / HZ);
4385                         goto failed_mount_wq;
4386                 }
4387                 if (EXT4_MOUNT_DATA_FLAGS &
4388                     (sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
4389                         ext4_msg(sb, KERN_ERR, "can't mount with "
4390                                  "data=, fs mounted w/o journal");
4391                         goto failed_mount_wq;
4392                 }
4393                 sbi->s_def_mount_opt &= ~EXT4_MOUNT_JOURNAL_CHECKSUM;
4394                 clear_opt(sb, JOURNAL_CHECKSUM);
4395                 clear_opt(sb, DATA_FLAGS);
4396                 sbi->s_journal = NULL;
4397                 needs_recovery = 0;
4398                 goto no_journal;
4399         }
4400 
4401         if (ext4_has_feature_64bit(sb) &&
4402             !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
4403                                        JBD2_FEATURE_INCOMPAT_64BIT)) {
4404                 ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
4405                 goto failed_mount_wq;
4406         }
4407 
4408         if (!set_journal_csum_feature_set(sb)) {
4409                 ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
4410                          "feature set");
4411                 goto failed_mount_wq;
4412         }
4413 
4414         /* We have now updated the journal if required, so we can
4415          * validate the data journaling mode. */
4416         switch (test_opt(sb, DATA_FLAGS)) {
4417         case 0:
4418                 /* No mode set, assume a default based on the journal
4419                  * capabilities: ORDERED_DATA if the journal can
4420                  * cope, else JOURNAL_DATA
4421                  */
4422                 if (jbd2_journal_check_available_features
4423                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4424                         set_opt(sb, ORDERED_DATA);
4425                         sbi->s_def_mount_opt |= EXT4_MOUNT_ORDERED_DATA;
4426                 } else {
4427                         set_opt(sb, JOURNAL_DATA);
4428                         sbi->s_def_mount_opt |= EXT4_MOUNT_JOURNAL_DATA;
4429                 }
4430                 break;
4431 
4432         case EXT4_MOUNT_ORDERED_DATA:
4433         case EXT4_MOUNT_WRITEBACK_DATA:
4434                 if (!jbd2_journal_check_available_features
4435                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4436                         ext4_msg(sb, KERN_ERR, "Journal does not support "
4437                                "requested data journaling mode");
4438                         goto failed_mount_wq;
4439                 }
4440         default:
4441                 break;
4442         }
4443 
4444         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
4445             test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4446                 ext4_msg(sb, KERN_ERR, "can't mount with "
4447                         "journal_async_commit in data=ordered mode");
4448                 goto failed_mount_wq;
4449         }
4450 
4451         set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
4452 
4453         sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
4454 
4455 no_journal:
4456         if (!test_opt(sb, NO_MBCACHE)) {
4457                 sbi->s_ea_block_cache = ext4_xattr_create_cache();
4458                 if (!sbi->s_ea_block_cache) {
4459                         ext4_msg(sb, KERN_ERR,
4460                                  "Failed to create ea_block_cache");
4461                         goto failed_mount_wq;
4462                 }
4463 
4464                 if (ext4_has_feature_ea_inode(sb)) {
4465                         sbi->s_ea_inode_cache = ext4_xattr_create_cache();
4466                         if (!sbi->s_ea_inode_cache) {
4467                                 ext4_msg(sb, KERN_ERR,
4468                                          "Failed to create ea_inode_cache");
4469                                 goto failed_mount_wq;
4470                         }
4471                 }
4472         }
4473 
4474         if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
4475             (blocksize != PAGE_SIZE)) {
4476                 ext4_msg(sb, KERN_ERR,
4477                          "Unsupported blocksize for fs encryption");
4478                 goto failed_mount_wq;
4479         }
4480 
4481         if (ext4_has_feature_verity(sb) && blocksize != PAGE_SIZE) {
4482                 ext4_msg(sb, KERN_ERR, "Unsupported blocksize for fs-verity");
4483                 goto failed_mount_wq;
4484         }
4485 
4486         if (DUMMY_ENCRYPTION_ENABLED(sbi) && !sb_rdonly(sb) &&
4487             !ext4_has_feature_encrypt(sb)) {
4488                 ext4_set_feature_encrypt(sb);
4489                 ext4_commit_super(sb, 1);
4490         }
4491 
4492         /*
4493          * Get the # of file system overhead blocks from the
4494          * superblock if present.
4495          */
4496         if (es->s_overhead_clusters)
4497                 sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
4498         else {
4499                 err = ext4_calculate_overhead(sb);
4500                 if (err)
4501                         goto failed_mount_wq;
4502         }
4503 
4504         /*
4505          * The maximum number of concurrent works can be high and
4506          * concurrency isn't really necessary.  Limit it to 1.
4507          */
4508         EXT4_SB(sb)->rsv_conversion_wq =
4509                 alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
4510         if (!EXT4_SB(sb)->rsv_conversion_wq) {
4511                 printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
4512                 ret = -ENOMEM;
4513                 goto failed_mount4;
4514         }
4515 
4516         /*
4517          * The jbd2_journal_load will have done any necessary log recovery,
4518          * so we can safely mount the rest of the filesystem now.
4519          */
4520 
4521         root = ext4_iget(sb, EXT4_ROOT_INO, EXT4_IGET_SPECIAL);
4522         if (IS_ERR(root)) {
4523                 ext4_msg(sb, KERN_ERR, "get root inode failed");
4524                 ret = PTR_ERR(root);
4525                 root = NULL;
4526                 goto failed_mount4;
4527         }
4528         if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
4529                 ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
4530                 iput(root);
4531                 goto failed_mount4;
4532         }
4533 
4534 #ifdef CONFIG_UNICODE
4535         if (sbi->s_encoding)
4536                 sb->s_d_op = &ext4_dentry_ops;
4537 #endif
4538 
4539         sb->s_root = d_make_root(root);
4540         if (!sb->s_root) {
4541                 ext4_msg(sb, KERN_ERR, "get root dentry failed");
4542                 ret = -ENOMEM;
4543                 goto failed_mount4;
4544         }
4545 
4546         ret = ext4_setup_super(sb, es, sb_rdonly(sb));
4547         if (ret == -EROFS) {
4548                 sb->s_flags |= SB_RDONLY;
4549                 ret = 0;
4550         } else if (ret)
4551                 goto failed_mount4a;
4552 
4553         ext4_set_resv_clusters(sb);
4554 
4555         err = ext4_setup_system_zone(sb);
4556         if (err) {
4557                 ext4_msg(sb, KERN_ERR, "failed to initialize system "
4558                          "zone (%d)", err);
4559                 goto failed_mount4a;
4560         }
4561 
4562         ext4_ext_init(sb);
4563         err = ext4_mb_init(sb);
4564         if (err) {
4565                 ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
4566                          err);
4567                 goto failed_mount5;
4568         }
4569 
4570         block = ext4_count_free_clusters(sb);
4571         ext4_free_blocks_count_set(sbi->s_es, 
4572                                    EXT4_C2B(sbi, block));
4573         ext4_superblock_csum_set(sb);
4574         err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
4575                                   GFP_KERNEL);
4576         if (!err) {
4577                 unsigned long freei = ext4_count_free_inodes(sb);
4578                 sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
4579                 ext4_superblock_csum_set(sb);
4580                 err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
4581                                           GFP_KERNEL);
4582         }
4583         if (!err)
4584                 err = percpu_counter_init(&sbi->s_dirs_counter,
4585                                           ext4_count_dirs(sb), GFP_KERNEL);
4586         if (!err)
4587                 err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
4588                                           GFP_KERNEL);
4589         if (!err)
4590                 err = percpu_init_rwsem(&sbi->s_writepages_rwsem);
4591 
4592         if (err) {
4593                 ext4_msg(sb, KERN_ERR, "insufficient memory");
4594                 goto failed_mount6;
4595         }
4596 
4597         if (ext4_has_feature_flex_bg(sb))
4598                 if (!ext4_fill_flex_info(sb)) {
4599                         ext4_msg(sb, KERN_ERR,
4600                                "unable to initialize "
4601                                "flex_bg meta info!");
4602                         goto failed_mount6;
4603                 }
4604 
4605         err = ext4_register_li_request(sb, first_not_zeroed);
4606         if (err)
4607                 goto failed_mount6;
4608 
4609         err = ext4_register_sysfs(sb);
4610         if (err)
4611                 goto failed_mount7;
4612 
4613 #ifdef CONFIG_QUOTA
4614         /* Enable quota usage during mount. */
4615         if (ext4_has_feature_quota(sb) && !sb_rdonly(sb)) {
4616                 err = ext4_enable_quotas(sb);
4617                 if (err)
4618                         goto failed_mount8;
4619         }
4620 #endif  /* CONFIG_QUOTA */
4621 
4622         EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
4623         ext4_orphan_cleanup(sb, es);
4624         EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
4625         if (needs_recovery) {
4626                 ext4_msg(sb, KERN_INFO, "recovery complete");
4627                 ext4_mark_recovery_complete(sb, es);
4628         }
4629         if (EXT4_SB(sb)->s_journal) {
4630                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
4631                         descr = " journalled data mode";
4632                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
4633                         descr = " ordered data mode";
4634                 else
4635                         descr = " writeback data mode";
4636         } else
4637                 descr = "out journal";
4638 
4639         if (test_opt(sb, DISCARD)) {
4640                 struct request_queue *q = bdev_get_queue(sb->s_bdev);
4641                 if (!blk_queue_discard(q))
4642                         ext4_msg(sb, KERN_WARNING,
4643                                  "mounting with \"discard\" option, but "
4644                                  "the device does not support discard");
4645         }
4646 
4647         if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
4648                 ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
4649                          "Opts: %.*s%s%s", descr,
4650                          (int) sizeof(sbi->s_es->s_mount_opts),
4651                          sbi->s_es->s_mount_opts,
4652                          *sbi->s_es->s_mount_opts ? "; " : "", orig_data);
4653 
4654         if (es->s_error_count)
4655                 mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
4656 
4657         /* Enable message ratelimiting. Default is 10 messages per 5 secs. */
4658         ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
4659         ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
4660         ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
4661 
4662         kfree(orig_data);
4663         return 0;
4664 
4665 cantfind_ext4:
4666         if (!silent)
4667                 ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
4668         goto failed_mount;
4669 
4670 #ifdef CONFIG_QUOTA
4671 failed_mount8:
4672         ext4_unregister_sysfs(sb);
4673 #endif
4674 failed_mount7:
4675         ext4_unregister_li_request(sb);
4676 failed_mount6:
4677         ext4_mb_release(sb);
4678         rcu_read_lock();
4679         flex_groups = rcu_dereference(sbi->s_flex_groups);
4680         if (flex_groups) {
4681                 for (i = 0; i < sbi->s_flex_groups_allocated; i++)
4682                         kvfree(flex_groups[i]);
4683                 kvfree(flex_groups);
4684         }
4685         rcu_read_unlock();
4686         percpu_counter_destroy(&sbi->s_freeclusters_counter);
4687         percpu_counter_destroy(&sbi->s_freeinodes_counter);
4688         percpu_counter_destroy(&sbi->s_dirs_counter);
4689         percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
4690         percpu_free_rwsem(&sbi->s_writepages_rwsem);
4691 failed_mount5:
4692         ext4_ext_release(sb);
4693         ext4_release_system_zone(sb);
4694 failed_mount4a:
4695         dput(sb->s_root);
4696         sb->s_root = NULL;
4697 failed_mount4:
4698         ext4_msg(sb, KERN_ERR, "mount failed");
4699         if (EXT4_SB(sb)->rsv_conversion_wq)
4700                 destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
4701 failed_mount_wq:
4702         ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
4703         sbi->s_ea_inode_cache = NULL;
4704 
4705         ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
4706         sbi->s_ea_block_cache = NULL;
4707 
4708         if (sbi->s_journal) {
4709                 jbd2_journal_destroy(sbi->s_journal);
4710                 sbi->s_journal = NULL;
4711         }
4712 failed_mount3a:
4713         ext4_es_unregister_shrinker(sbi);
4714 failed_mount3:
4715         del_timer_sync(&sbi->s_err_report);
4716         if (sbi->s_mmp_tsk)
4717                 kthread_stop(sbi->s_mmp_tsk);
4718 failed_mount2:
4719         rcu_read_lock();
4720         group_desc = rcu_dereference(sbi->s_group_desc);
4721         for (i = 0; i < db_count; i++)
4722                 brelse(group_desc[i]);
4723         kvfree(group_desc);
4724         rcu_read_unlock();
4725 failed_mount:
4726         if (sbi->s_chksum_driver)
4727                 crypto_free_shash(sbi->s_chksum_driver);
4728 
4729 #ifdef CONFIG_UNICODE
4730         utf8_unload(sbi->s_encoding);
4731 #endif
4732 
4733 #ifdef CONFIG_QUOTA
4734         for (i = 0; i < EXT4_MAXQUOTAS; i++)
4735                 kfree(get_qf_name(sb, sbi, i));
4736 #endif
4737         ext4_blkdev_remove(sbi);
4738         brelse(bh);
4739 out_fail:
4740         sb->s_fs_info = NULL;
4741         kfree(sbi->s_blockgroup_lock);
4742 out_free_base:
4743         kfree(sbi);
4744         kfree(orig_data);
4745         fs_put_dax(dax_dev);
4746         return err ? err : ret;
4747 }
4748 
4749 /*
4750  * Setup any per-fs journal parameters now.  We'll do this both on
4751  * initial mount, once the journal has been initialised but before we've
4752  * done any recovery; and again on any subsequent remount.
4753  */
4754 static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
4755 {
4756         struct ext4_sb_info *sbi = EXT4_SB(sb);
4757 
4758         journal->j_commit_interval = sbi->s_commit_interval;
4759         journal->j_min_batch_time = sbi->s_min_batch_time;
4760         journal->j_max_batch_time = sbi->s_max_batch_time;
4761 
4762         write_lock(&journal->j_state_lock);
4763         if (test_opt(sb, BARRIER))
4764                 journal->j_flags |= JBD2_BARRIER;
4765         else
4766                 journal->j_flags &= ~JBD2_BARRIER;
4767         if (test_opt(sb, DATA_ERR_ABORT))
4768                 journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
4769         else
4770                 journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
4771         write_unlock(&journal->j_state_lock);
4772 }
4773 
4774 static struct inode *ext4_get_journal_inode(struct super_block *sb,
4775                                              unsigned int journal_inum)
4776 {
4777         struct inode *journal_inode;
4778 
4779         /*
4780          * Test for the existence of a valid inode on disk.  Bad things
4781          * happen if we iget() an unused inode, as the subsequent iput()
4782          * will try to delete it.
4783          */
4784         journal_inode = ext4_iget(sb, journal_inum, EXT4_IGET_SPECIAL);
4785         if (IS_ERR(journal_inode)) {
4786                 ext4_msg(sb, KERN_ERR, "no journal found");
4787                 return NULL;
4788         }
4789         if (!journal_inode->i_nlink) {
4790                 make_bad_inode(journal_inode);
4791                 iput(journal_inode);
4792                 ext4_msg(sb, KERN_ERR, "journal inode is deleted");
4793                 return NULL;
4794         }
4795 
4796         jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
4797                   journal_inode, journal_inode->i_size);
4798         if (!S_ISREG(journal_inode->i_mode)) {
4799                 ext4_msg(sb, KERN_ERR, "invalid journal inode");
4800                 iput(journal_inode);
4801                 return NULL;
4802         }
4803         return journal_inode;
4804 }
4805 
4806 static journal_t *ext4_get_journal(struct super_block *sb,
4807                                    unsigned int journal_inum)
4808 {
4809         struct inode *journal_inode;
4810         journal_t *journal;
4811 
4812         BUG_ON(!ext4_has_feature_journal(sb));
4813 
4814         journal_inode = ext4_get_journal_inode(sb, journal_inum);
4815         if (!journal_inode)
4816                 return NULL;
4817 
4818         journal = jbd2_journal_init_inode(journal_inode);
4819         if (!journal) {
4820                 ext4_msg(sb, KERN_ERR, "Could not load journal inode");
4821                 iput(journal_inode);
4822                 return NULL;
4823         }
4824         journal->j_private = sb;
4825         ext4_init_journal_params(sb, journal);
4826         return journal;
4827 }
4828 
4829 static journal_t *ext4_get_dev_journal(struct super_block *sb,
4830                                        dev_t j_dev)
4831 {
4832         struct buffer_head *bh;
4833         journal_t *journal;
4834         ext4_fsblk_t start;
4835         ext4_fsblk_t len;
4836         int hblock, blocksize;
4837         ext4_fsblk_t sb_block;
4838         unsigned long offset;
4839         struct ext4_super_block *es;
4840         struct block_device *bdev;
4841 
4842         BUG_ON(!ext4_has_feature_journal(sb));
4843 
4844         bdev = ext4_blkdev_get(j_dev, sb);
4845         if (bdev == NULL)
4846                 return NULL;
4847 
4848         blocksize = sb->s_blocksize;
4849         hblock = bdev_logical_block_size(bdev);
4850         if (blocksize < hblock) {
4851                 ext4_msg(sb, KERN_ERR,
4852                         "blocksize too small for journal device");
4853                 goto out_bdev;
4854         }
4855 
4856         sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
4857         offset = EXT4_MIN_BLOCK_SIZE % blocksize;
4858         set_blocksize(bdev, blocksize);
4859         if (!(bh = __bread(bdev, sb_block, blocksize))) {
4860                 ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
4861                        "external journal");
4862                 goto out_bdev;
4863         }
4864 
4865         es = (struct ext4_super_block *) (bh->b_data + offset);
4866         if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
4867             !(le32_to_cpu(es->s_feature_incompat) &
4868               EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
4869                 ext4_msg(sb, KERN_ERR, "external journal has "
4870                                         "bad superblock");
4871                 brelse(bh);
4872                 goto out_bdev;
4873         }
4874 
4875         if ((le32_to_cpu(es->s_feature_ro_compat) &
4876              EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
4877             es->s_checksum != ext4_superblock_csum(sb, es)) {
4878                 ext4_msg(sb, KERN_ERR, "external journal has "
4879                                        "corrupt superblock");
4880                 brelse(bh);
4881                 goto out_bdev;
4882         }
4883 
4884         if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
4885                 ext4_msg(sb, KERN_ERR, "journal UUID does not match");
4886                 brelse(bh);
4887                 goto out_bdev;
4888         }
4889 
4890         len = ext4_blocks_count(es);
4891         start = sb_block + 1;
4892         brelse(bh);     /* we're done with the superblock */
4893 
4894         journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
4895                                         start, len, blocksize);
4896         if (!journal) {
4897                 ext4_msg(sb, KERN_ERR, "failed to create device journal");
4898                 goto out_bdev;
4899         }
4900         journal->j_private = sb;
4901         ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
4902         wait_on_buffer(journal->j_sb_buffer);
4903         if (!buffer_uptodate(journal->j_sb_buffer)) {
4904                 ext4_msg(sb, KERN_ERR, "I/O error on journal device");
4905                 goto out_journal;
4906         }
4907         if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
4908                 ext4_msg(sb, KERN_ERR, "External journal has more than one "
4909                                         "user (unsupported) - %d",
4910                         be32_to_cpu(journal->j_superblock->s_nr_users));
4911                 goto out_journal;
4912         }
4913         EXT4_SB(sb)->journal_bdev = bdev;
4914         ext4_init_journal_params(sb, journal);
4915         return journal;
4916 
4917 out_journal:
4918         jbd2_journal_destroy(journal);
4919 out_bdev:
4920         ext4_blkdev_put(bdev);
4921         return NULL;
4922 }
4923 
4924 static int ext4_load_journal(struct super_block *sb,
4925                              struct ext4_super_block *es,
4926                              unsigned long journal_devnum)
4927 {
4928         journal_t *journal;
4929         unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
4930         dev_t journal_dev;
4931         int err = 0;
4932         int really_read_only;
4933 
4934         BUG_ON(!ext4_has_feature_journal(sb));
4935 
4936         if (journal_devnum &&
4937             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
4938                 ext4_msg(sb, KERN_INFO, "external journal device major/minor "
4939                         "numbers have changed");
4940                 journal_dev = new_decode_dev(journal_devnum);
4941         } else
4942                 journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
4943 
4944         really_read_only = bdev_read_only(sb->s_bdev);
4945 
4946         /*
4947          * Are we loading a blank journal or performing recovery after a
4948          * crash?  For recovery, we need to check in advance whether we
4949          * can get read-write access to the device.
4950          */
4951         if (ext4_has_feature_journal_needs_recovery(sb)) {
4952                 if (sb_rdonly(sb)) {
4953                         ext4_msg(sb, KERN_INFO, "INFO: recovery "
4954                                         "required on readonly filesystem");
4955                         if (really_read_only) {
4956                                 ext4_msg(sb, KERN_ERR, "write access "
4957                                         "unavailable, cannot proceed "
4958                                         "(try mounting with noload)");
4959                                 return -EROFS;
4960                         }
4961                         ext4_msg(sb, KERN_INFO, "write access will "
4962                                "be enabled during recovery");
4963                 }
4964         }
4965 
4966         if (journal_inum && journal_dev) {
4967                 ext4_msg(sb, KERN_ERR, "filesystem has both journal "
4968                        "and inode journals!");
4969                 return -EINVAL;
4970         }
4971 
4972         if (journal_inum) {
4973                 if (!(journal = ext4_get_journal(sb, journal_inum)))
4974                         return -EINVAL;
4975         } else {
4976                 if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
4977                         return -EINVAL;
4978         }
4979 
4980         if (!(journal->j_flags & JBD2_BARRIER))
4981                 ext4_msg(sb, KERN_INFO, "barriers disabled");
4982 
4983         if (!ext4_has_feature_journal_needs_recovery(sb))
4984                 err = jbd2_journal_wipe(journal, !really_read_only);
4985         if (!err) {
4986                 char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
4987                 if (save)
4988                         memcpy(save, ((char *) es) +
4989                                EXT4_S_ERR_START, EXT4_S_ERR_LEN);
4990                 err = jbd2_journal_load(journal);
4991                 if (save)
4992                         memcpy(((char *) es) + EXT4_S_ERR_START,
4993                                save, EXT4_S_ERR_LEN);
4994                 kfree(save);
4995         }
4996 
4997         if (err) {
4998                 ext4_msg(sb, KERN_ERR, "error loading journal");
4999                 jbd2_journal_destroy(journal);
5000                 return err;
5001         }
5002 
5003         EXT4_SB(sb)->s_journal = journal;
5004         ext4_clear_journal_err(sb, es);
5005 
5006         if (!really_read_only && journal_devnum &&
5007             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
5008                 es->s_journal_dev = cpu_to_le32(journal_devnum);
5009 
5010                 /* Make sure we flush the recovery flag to disk. */
5011                 ext4_commit_super(sb, 1);
5012         }
5013 
5014         return 0;
5015 }
5016 
5017 static int ext4_commit_super(struct super_block *sb, int sync)
5018 {
5019         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5020         struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
5021         int error = 0;
5022 
5023         if (!sbh || block_device_ejected(sb))
5024                 return error;
5025 
5026         /*
5027          * The superblock bh should be mapped, but it might not be if the
5028          * device was hot-removed. Not much we can do but fail the I/O.
5029          */
5030         if (!buffer_mapped(sbh))
5031                 return error;
5032 
5033         /*
5034          * If the file system is mounted read-only, don't update the
5035          * superblock write time.  This avoids updating the superblock
5036          * write time when we are mounting the root file system
5037          * read/only but we need to replay the journal; at that point,
5038          * for people who are east of GMT and who make their clock
5039          * tick in localtime for Windows bug-for-bug compatibility,
5040          * the clock is set in the future, and this will cause e2fsck
5041          * to complain and force a full file system check.
5042          */
5043         if (!(sb->s_flags & SB_RDONLY))
5044                 ext4_update_tstamp(es, s_wtime);
5045         if (sb->s_bdev->bd_part)
5046                 es->s_kbytes_written =
5047                         cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
5048                             ((part_stat_read(sb->s_bdev->bd_part,
5049                                              sectors[STAT_WRITE]) -
5050                               EXT4_SB(sb)->s_sectors_written_start) >> 1));
5051         else
5052                 es->s_kbytes_written =
5053                         cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
5054         if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
5055                 ext4_free_blocks_count_set(es,
5056                         EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
5057                                 &EXT4_SB(sb)->s_freeclusters_counter)));
5058         if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
5059                 es->s_free_inodes_count =
5060                         cpu_to_le32(percpu_counter_sum_positive(
5061                                 &EXT4_SB(sb)->s_freeinodes_counter));
5062         BUFFER_TRACE(sbh, "marking dirty");
5063         ext4_superblock_csum_set(sb);
5064         if (sync)
5065                 lock_buffer(sbh);
5066         if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
5067                 /*
5068                  * Oh, dear.  A previous attempt to write the
5069                  * superblock failed.  This could happen because the
5070                  * USB device was yanked out.  Or it could happen to
5071                  * be a transient write error and maybe the block will
5072                  * be remapped.  Nothing we can do but to retry the
5073                  * write and hope for the best.
5074                  */
5075                 ext4_msg(sb, KERN_ERR, "previous I/O error to "
5076                        "superblock detected");
5077                 clear_buffer_write_io_error(sbh);
5078                 set_buffer_uptodate(sbh);
5079         }
5080         mark_buffer_dirty(sbh);
5081         if (sync) {
5082                 unlock_buffer(sbh);
5083                 error = __sync_dirty_buffer(sbh,
5084                         REQ_SYNC | (test_opt(sb, BARRIER) ? REQ_FUA : 0));
5085                 if (buffer_write_io_error(sbh)) {
5086                         ext4_msg(sb, KERN_ERR, "I/O error while writing "
5087                                "superblock");
5088                         clear_buffer_write_io_error(sbh);
5089                         set_buffer_uptodate(sbh);
5090                 }
5091         }
5092         return error;
5093 }
5094 
5095 /*
5096  * Have we just finished recovery?  If so, and if we are mounting (or
5097  * remounting) the filesystem readonly, then we will end up with a
5098  * consistent fs on disk.  Record that fact.
5099  */
5100 static void ext4_mark_recovery_complete(struct super_block *sb,
5101                                         struct ext4_super_block *es)
5102 {
5103         journal_t *journal = EXT4_SB(sb)->s_journal;
5104 
5105         if (!ext4_has_feature_journal(sb)) {
5106                 BUG_ON(journal != NULL);
5107                 return;
5108         }
5109         jbd2_journal_lock_updates(journal);
5110         if (jbd2_journal_flush(journal) < 0)
5111                 goto out;
5112 
5113         if (ext4_has_feature_journal_needs_recovery(sb) && sb_rdonly(sb)) {
5114                 ext4_clear_feature_journal_needs_recovery(sb);
5115                 ext4_commit_super(sb, 1);
5116         }
5117 
5118 out:
5119         jbd2_journal_unlock_updates(journal);
5120 }
5121 
5122 /*
5123  * If we are mounting (or read-write remounting) a filesystem whose journal
5124  * has recorded an error from a previous lifetime, move that error to the
5125  * main filesystem now.
5126  */
5127 static void ext4_clear_journal_err(struct super_block *sb,
5128                                    struct ext4_super_block *es)
5129 {
5130         journal_t *journal;
5131         int j_errno;
5132         const char *errstr;
5133 
5134         BUG_ON(!ext4_has_feature_journal(sb));
5135 
5136         journal = EXT4_SB(sb)->s_journal;
5137 
5138         /*
5139          * Now check for any error status which may have been recorded in the
5140          * journal by a prior ext4_error() or ext4_abort()
5141          */
5142 
5143         j_errno = jbd2_journal_errno(journal);
5144         if (j_errno) {
5145                 char nbuf[16];
5146 
5147                 errstr = ext4_decode_error(sb, j_errno, nbuf);
5148                 ext4_warning(sb, "Filesystem error recorded "
5149                              "from previous mount: %s", errstr);
5150                 ext4_warning(sb, "Marking fs in need of filesystem check.");
5151 
5152                 EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
5153                 es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
5154                 ext4_commit_super(sb, 1);
5155 
5156                 jbd2_journal_clear_err(journal);
5157                 jbd2_journal_update_sb_errno(journal);
5158         }
5159 }
5160 
5161 /*
5162  * Force the running and committing transactions to commit,
5163  * and wait on the commit.
5164  */
5165 int ext4_force_commit(struct super_block *sb)
5166 {
5167         journal_t *journal;
5168 
5169         if (sb_rdonly(sb))
5170                 return 0;
5171 
5172         journal = EXT4_SB(sb)->s_journal;
5173         return ext4_journal_force_commit(journal);
5174 }
5175 
5176 static int ext4_sync_fs(struct super_block *sb, int wait)
5177 {
5178         int ret = 0;
5179         tid_t target;
5180         bool needs_barrier = false;
5181         struct ext4_sb_info *sbi = EXT4_SB(sb);
5182 
5183         if (unlikely(ext4_forced_shutdown(sbi)))
5184                 return 0;
5185 
5186         trace_ext4_sync_fs(sb, wait);
5187         flush_workqueue(sbi->rsv_conversion_wq);
5188         /*
5189          * Writeback quota in non-journalled quota case - journalled quota has
5190          * no dirty dquots
5191          */
5192         dquot_writeback_dquots(sb, -1);
5193         /*
5194          * Data writeback is possible w/o journal transaction, so barrier must
5195          * being sent at the end of the function. But we can skip it if
5196          * transaction_commit will do it for us.
5197          */
5198         if (sbi->s_journal) {
5199                 target = jbd2_get_latest_transaction(sbi->s_journal);
5200                 if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
5201                     !jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
5202                         needs_barrier = true;
5203 
5204                 if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
5205                         if (wait)
5206                                 ret = jbd2_log_wait_commit(sbi->s_journal,
5207                                                            target);
5208                 }
5209         } else if (wait && test_opt(sb, BARRIER))
5210                 needs_barrier = true;
5211         if (needs_barrier) {
5212                 int err;
5213                 err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
5214                 if (!ret)
5215                         ret = err;
5216         }
5217 
5218         return ret;
5219 }
5220 
5221 /*
5222  * LVM calls this function before a (read-only) snapshot is created.  This
5223  * gives us a chance to flush the journal completely and mark the fs clean.
5224  *
5225  * Note that only this function cannot bring a filesystem to be in a clean
5226  * state independently. It relies on upper layer to stop all data & metadata
5227  * modifications.
5228  */
5229 static int ext4_freeze(struct super_block *sb)
5230 {
5231         int error = 0;
5232         journal_t *journal;
5233 
5234         if (sb_rdonly(sb))
5235                 return 0;
5236 
5237         journal = EXT4_SB(sb)->s_journal;
5238 
5239         if (journal) {
5240                 /* Now we set up the journal barrier. */
5241                 jbd2_journal_lock_updates(journal);
5242 
5243                 /*
5244                  * Don't clear the needs_recovery flag if we failed to
5245                  * flush the journal.
5246                  */
5247                 error = jbd2_journal_flush(journal);
5248                 if (error < 0)
5249                         goto out;
5250 
5251                 /* Journal blocked and flushed, clear needs_recovery flag. */
5252                 ext4_clear_feature_journal_needs_recovery(sb);
5253         }
5254 
5255         error = ext4_commit_super(sb, 1);
5256 out:
5257         if (journal)
5258                 /* we rely on upper layer to stop further updates */
5259                 jbd2_journal_unlock_updates(journal);
5260         return error;
5261 }
5262 
5263 /*
5264  * Called by LVM after the snapshot is done.  We need to reset the RECOVER
5265  * flag here, even though the filesystem is not technically dirty yet.
5266  */
5267 static int ext4_unfreeze(struct super_block *sb)
5268 {
5269         if (sb_rdonly(sb) || ext4_forced_shutdown(EXT4_SB(sb)))
5270                 return 0;
5271 
5272         if (EXT4_SB(sb)->s_journal) {
5273                 /* Reset the needs_recovery flag before the fs is unlocked. */
5274                 ext4_set_feature_journal_needs_recovery(sb);
5275         }
5276 
5277         ext4_commit_super(sb, 1);
5278         return 0;
5279 }
5280 
5281 /*
5282  * Structure to save mount options for ext4_remount's benefit
5283  */
5284 struct ext4_mount_options {
5285         unsigned long s_mount_opt;
5286         unsigned long s_mount_opt2;
5287         kuid_t s_resuid;
5288         kgid_t s_resgid;
5289         unsigned long s_commit_interval;
5290         u32 s_min_batch_time, s_max_batch_time;
5291 #ifdef CONFIG_QUOTA
5292         int s_jquota_fmt;
5293         char *s_qf_names[EXT4_MAXQUOTAS];
5294 #endif
5295 };
5296 
5297 static int ext4_remount(struct super_block *sb, int *flags, char *data)
5298 {
5299         struct ext4_super_block *es;
5300         struct ext4_sb_info *sbi = EXT4_SB(sb);
5301         unsigned long old_sb_flags;
5302         struct ext4_mount_options old_opts;
5303         int enable_quota = 0;
5304         ext4_group_t g;
5305         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
5306         int err = 0;
5307 #ifdef CONFIG_QUOTA
5308         int i, j;
5309         char *to_free[EXT4_MAXQUOTAS];
5310 #endif
5311         char *orig_data = kstrdup(data, GFP_KERNEL);
5312 
5313         if (data && !orig_data)
5314                 return -ENOMEM;
5315 
5316         /* Store the original options */
5317         old_sb_flags = sb->s_flags;
5318         old_opts.s_mount_opt = sbi->s_mount_opt;
5319         old_opts.s_mount_opt2 = sbi->s_mount_opt2;
5320         old_opts.s_resuid = sbi->s_resuid;
5321         old_opts.s_resgid = sbi->s_resgid;
5322         old_opts.s_commit_interval = sbi->s_commit_interval;
5323         old_opts.s_min_batch_time = sbi->s_min_batch_time;
5324         old_opts.s_max_batch_time = sbi->s_max_batch_time;
5325 #ifdef CONFIG_QUOTA
5326         old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
5327         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5328                 if (sbi->s_qf_names[i]) {
5329                         char *qf_name = get_qf_name(sb, sbi, i);
5330 
5331                         old_opts.s_qf_names[i] = kstrdup(qf_name, GFP_KERNEL);
5332                         if (!old_opts.s_qf_names[i]) {
5333                                 for (j = 0; j < i; j++)
5334                                         kfree(old_opts.s_qf_names[j]);
5335                                 kfree(orig_data);
5336                                 return -ENOMEM;
5337                         }
5338                 } else
5339                         old_opts.s_qf_names[i] = NULL;
5340 #endif
5341         if (sbi->s_journal && sbi->s_journal->j_task->io_context)
5342                 journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
5343 
5344         if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
5345                 err = -EINVAL;
5346                 goto restore_opts;
5347         }
5348 
5349         if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
5350             test_opt(sb, JOURNAL_CHECKSUM)) {
5351                 ext4_msg(sb, KERN_ERR, "changing journal_checksum "
5352                          "during remount not supported; ignoring");
5353                 sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
5354         }
5355 
5356         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
5357                 if (test_opt2(sb, EXPLICIT_DELALLOC)) {
5358                         ext4_msg(sb, KERN_ERR, "can't mount with "
5359                                  "both data=journal and delalloc");
5360                         err = -EINVAL;
5361                         goto restore_opts;
5362                 }
5363                 if (test_opt(sb, DIOREAD_NOLOCK)) {
5364                         ext4_msg(sb, KERN_ERR, "can't mount with "
5365                                  "both data=journal and dioread_nolock");
5366                         err = -EINVAL;
5367                         goto restore_opts;
5368                 }
5369                 if (test_opt(sb, DAX)) {
5370                         ext4_msg(sb, KERN_ERR, "can't mount with "
5371                                  "both data=journal and dax");
5372                         err = -EINVAL;
5373                         goto restore_opts;
5374                 }
5375         } else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) {
5376                 if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
5377                         ext4_msg(sb, KERN_ERR, "can't mount with "
5378                                 "journal_async_commit in data=ordered mode");
5379                         err = -EINVAL;
5380                         goto restore_opts;
5381                 }
5382         }
5383 
5384         if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_NO_MBCACHE) {
5385                 ext4_msg(sb, KERN_ERR, "can't enable nombcache during remount");
5386                 err = -EINVAL;
5387                 goto restore_opts;
5388         }
5389 
5390         if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_DAX) {
5391                 ext4_msg(sb, KERN_WARNING, "warning: refusing change of "
5392                         "dax flag with busy inodes while remounting");
5393                 sbi->s_mount_opt ^= EXT4_MOUNT_DAX;
5394         }
5395 
5396         if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
5397                 ext4_abort(sb, "Abort forced by user");
5398 
5399         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
5400                 (test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
5401 
5402         es = sbi->s_es;
5403 
5404         if (sbi->s_journal) {
5405                 ext4_init_journal_params(sb, sbi->s_journal);
5406                 set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
5407         }
5408 
5409         if (*flags & SB_LAZYTIME)
5410                 sb->s_flags |= SB_LAZYTIME;
5411 
5412         if ((bool)(*flags & SB_RDONLY) != sb_rdonly(sb)) {
5413                 if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
5414                         err = -EROFS;
5415                         goto restore_opts;
5416                 }
5417 
5418                 if (*flags & SB_RDONLY) {
5419                         err = sync_filesystem(sb);
5420                         if (err < 0)
5421                                 goto restore_opts;
5422                         err = dquot_suspend(sb, -1);
5423                         if (err < 0)
5424                                 goto restore_opts;
5425 
5426                         /*
5427                          * First of all, the unconditional stuff we have to do
5428                          * to disable replay of the journal when we next remount
5429                          */
5430                         sb->s_flags |= SB_RDONLY;
5431 
5432                         /*
5433                          * OK, test if we are remounting a valid rw partition
5434                          * readonly, and if so set the rdonly flag and then
5435                          * mark the partition as valid again.
5436                          */
5437                         if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
5438                             (sbi->s_mount_state & EXT4_VALID_FS))
5439                                 es->s_state = cpu_to_le16(sbi->s_mount_state);
5440 
5441                         if (sbi->s_journal)
5442                                 ext4_mark_recovery_complete(sb, es);
5443                         if (sbi->s_mmp_tsk)
5444                                 kthread_stop(sbi->s_mmp_tsk);
5445                 } else {
5446                         /* Make sure we can mount this feature set readwrite */
5447                         if (ext4_has_feature_readonly(sb) ||
5448                             !ext4_feature_set_ok(sb, 0)) {
5449                                 err = -EROFS;
5450                                 goto restore_opts;
5451                         }
5452                         /*
5453                          * Make sure the group descriptor checksums
5454                          * are sane.  If they aren't, refuse to remount r/w.
5455                          */
5456                         for (g = 0; g < sbi->s_groups_count; g++) {
5457                                 struct ext4_group_desc *gdp =
5458                                         ext4_get_group_desc(sb, g, NULL);
5459 
5460                                 if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
5461                                         ext4_msg(sb, KERN_ERR,
5462                "ext4_remount: Checksum for group %u failed (%u!=%u)",
5463                 g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
5464                                                le16_to_cpu(gdp->bg_checksum));
5465                                         err = -EFSBADCRC;
5466                                         goto restore_opts;
5467                                 }
5468                         }
5469 
5470                         /*
5471                          * If we have an unprocessed orphan list hanging
5472                          * around from a previously readonly bdev mount,
5473                          * require a full umount/remount for now.
5474                          */
5475                         if (es->s_last_orphan) {
5476                                 ext4_msg(sb, KERN_WARNING, "Couldn't "
5477                                        "remount RDWR because of unprocessed "
5478                                        "orphan inode list.  Please "
5479                                        "umount/remount instead");
5480                                 err = -EINVAL;
5481                                 goto restore_opts;
5482                         }
5483 
5484                         /*
5485                          * Mounting a RDONLY partition read-write, so reread
5486                          * and store the current valid flag.  (It may have
5487                          * been changed by e2fsck since we originally mounted
5488                          * the partition.)
5489                          */
5490                         if (sbi->s_journal)
5491                                 ext4_clear_journal_err(sb, es);
5492                         sbi->s_mount_state = le16_to_cpu(es->s_state);
5493 
5494                         err = ext4_setup_super(sb, es, 0);
5495                         if (err)
5496                                 goto restore_opts;
5497 
5498                         sb->s_flags &= ~SB_RDONLY;
5499                         if (ext4_has_feature_mmp(sb))
5500                                 if (ext4_multi_mount_protect(sb,
5501                                                 le64_to_cpu(es->s_mmp_block))) {
5502                                         err = -EROFS;
5503                                         goto restore_opts;
5504                                 }
5505                         enable_quota = 1;
5506                 }
5507         }
5508 
5509         /*
5510          * Reinitialize lazy itable initialization thread based on
5511          * current settings
5512          */
5513         if (sb_rdonly(sb) || !test_opt(sb, INIT_INODE_TABLE))
5514                 ext4_unregister_li_request(sb);
5515         else {
5516                 ext4_group_t first_not_zeroed;
5517                 first_not_zeroed = ext4_has_uninit_itable(sb);
5518                 ext4_register_li_request(sb, first_not_zeroed);
5519         }
5520 
5521         ext4_setup_system_zone(sb);
5522         if (sbi->s_journal == NULL && !(old_sb_flags & SB_RDONLY)) {
5523                 err = ext4_commit_super(sb, 1);
5524                 if (err)
5525                         goto restore_opts;
5526         }
5527 
5528 #ifdef CONFIG_QUOTA
5529         /* Release old quota file names */
5530         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5531                 kfree(old_opts.s_qf_names[i]);
5532         if (enable_quota) {
5533                 if (sb_any_quota_suspended(sb))
5534                         dquot_resume(sb, -1);
5535                 else if (ext4_has_feature_quota(sb)) {
5536                         err = ext4_enable_quotas(sb);
5537                         if (err)
5538                                 goto restore_opts;
5539                 }
5540         }
5541 #endif
5542 
5543         *flags = (*flags & ~SB_LAZYTIME) | (sb->s_flags & SB_LAZYTIME);
5544         ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
5545         kfree(orig_data);
5546         return 0;
5547 
5548 restore_opts:
5549         sb->s_flags = old_sb_flags;
5550         sbi->s_mount_opt = old_opts.s_mount_opt;
5551         sbi->s_mount_opt2 = old_opts.s_mount_opt2;
5552         sbi->s_resuid = old_opts.s_resuid;
5553         sbi->s_resgid = old_opts.s_resgid;
5554         sbi->s_commit_interval = old_opts.s_commit_interval;
5555         sbi->s_min_batch_time = old_opts.s_min_batch_time;
5556         sbi->s_max_batch_time = old_opts.s_max_batch_time;
5557 #ifdef CONFIG_QUOTA
5558         sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
5559         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
5560                 to_free[i] = get_qf_name(sb, sbi, i);
5561                 rcu_assign_pointer(sbi->s_qf_names[i], old_opts.s_qf_names[i]);
5562         }
5563         synchronize_rcu();
5564         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5565                 kfree(to_free[i]);
5566 #endif
5567         kfree(orig_data);
5568         return err;
5569 }
5570 
5571 #ifdef CONFIG_QUOTA
5572 static int ext4_statfs_project(struct super_block *sb,
5573                                kprojid_t projid, struct kstatfs *buf)
5574 {
5575         struct kqid qid;
5576         struct dquot *dquot;
5577         u64 limit;
5578         u64 curblock;
5579 
5580         qid = make_kqid_projid(projid);
5581         dquot = dqget(sb, qid);
5582         if (IS_ERR(dquot))
5583                 return PTR_ERR(dquot);
5584         spin_lock(&dquot->dq_dqb_lock);
5585 
5586         limit = 0;
5587         if (dquot->dq_dqb.dqb_bsoftlimit &&
5588             (!limit || dquot->dq_dqb.dqb_bsoftlimit < limit))
5589                 limit = dquot->dq_dqb.dqb_bsoftlimit;
5590         if (dquot->dq_dqb.dqb_bhardlimit &&
5591             (!limit || dquot->dq_dqb.dqb_bhardlimit < limit))
5592                 limit = dquot->dq_dqb.dqb_bhardlimit;
5593         limit >>= sb->s_blocksize_bits;
5594 
5595         if (limit && buf->f_blocks > limit) {
5596                 curblock = (dquot->dq_dqb.dqb_curspace +
5597                             dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
5598                 buf->f_blocks = limit;
5599                 buf->f_bfree = buf->f_bavail =
5600                         (buf->f_blocks > curblock) ?
5601                          (buf->f_blocks - curblock) : 0;
5602         }
5603 
5604         limit = 0;
5605         if (dquot->dq_dqb.dqb_isoftlimit &&
5606             (!limit || dquot->dq_dqb.dqb_isoftlimit < limit))
5607                 limit = dquot->dq_dqb.dqb_isoftlimit;
5608         if (dquot->dq_dqb.dqb_ihardlimit &&
5609             (!limit || dquot->dq_dqb.dqb_ihardlimit < limit))
5610                 limit = dquot->dq_dqb.dqb_ihardlimit;
5611 
5612         if (limit && buf->f_files > limit) {
5613                 buf->f_files = limit;
5614                 buf->f_ffree =
5615                         (buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
5616                          (buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
5617         }
5618 
5619         spin_unlock(&dquot->dq_dqb_lock);
5620         dqput(dquot);
5621         return 0;
5622 }
5623 #endif
5624 
5625 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
5626 {
5627         struct super_block *sb = dentry->d_sb;
5628         struct ext4_sb_info *sbi = EXT4_SB(sb);
5629         struct ext4_super_block *es = sbi->s_es;
5630         ext4_fsblk_t overhead = 0, resv_blocks;
5631         u64 fsid;
5632         s64 bfree;
5633         resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
5634 
5635         if (!test_opt(sb, MINIX_DF))
5636                 overhead = sbi->s_overhead;
5637 
5638         buf->f_type = EXT4_SUPER_MAGIC;
5639         buf->f_bsize = sb->s_blocksize;
5640         buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
5641         bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
5642                 percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
5643         /* prevent underflow in case that few free space is available */
5644         buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
5645         buf->f_bavail = buf->f_bfree -
5646                         (ext4_r_blocks_count(es) + resv_blocks);
5647         if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
5648                 buf->f_bavail = 0;
5649         buf->f_files = le32_to_cpu(es->s_inodes_count);
5650         buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
5651         buf->f_namelen = EXT4_NAME_LEN;
5652         fsid = le64_to_cpup((void *)es->s_uuid) ^
5653                le64_to_cpup((void *)es->s_uuid + sizeof(u64));
5654         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
5655         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
5656 
5657 #ifdef CONFIG_QUOTA
5658         if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
5659             sb_has_quota_limits_enabled(sb, PRJQUOTA))
5660                 ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
5661 #endif
5662         return 0;
5663 }
5664 
5665 
5666 #ifdef CONFIG_QUOTA
5667 
5668 /*
5669  * Helper functions so that transaction is started before we acquire dqio_sem
5670  * to keep correct lock ordering of transaction > dqio_sem
5671  */
5672 static inline struct inode *dquot_to_inode(struct dquot *dquot)
5673 {
5674         return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
5675 }
5676 
5677 static int ext4_write_dquot(struct dquot *dquot)
5678 {
5679         int ret, err;
5680         handle_t *handle;
5681         struct inode *inode;
5682 
5683         inode = dquot_to_inode(dquot);
5684         handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5685                                     EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
5686         if (IS_ERR(handle))
5687                 return PTR_ERR(handle);
5688         ret = dquot_commit(dquot);
5689         err = ext4_journal_stop(handle);
5690         if (!ret)
5691                 ret = err;
5692         return ret;
5693 }
5694 
5695 static int ext4_acquire_dquot(struct dquot *dquot)
5696 {
5697         int ret, err;
5698         handle_t *handle;
5699 
5700         handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
5701                                     EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
5702         if (IS_ERR(handle))
5703                 return PTR_ERR(handle);
5704         ret = dquot_acquire(dquot);
5705         err = ext4_journal_stop(handle);
5706         if (!ret)
5707                 ret = err;
5708         return ret;
5709 }
5710 
5711 static int ext4_release_dquot(struct dquot *dquot)
5712 {
5713         int ret, err;
5714         handle_t *handle;
5715 
5716         handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
5717                                     EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
5718         if (IS_ERR(handle)) {
5719                 /* Release dquot anyway to avoid endless cycle in dqput() */
5720                 dquot_release(dquot);
5721                 return PTR_ERR(handle);
5722         }
5723         ret = dquot_release(dquot);
5724         err = ext4_journal_stop(handle);
5725         if (!ret)
5726                 ret = err;
5727         return ret;
5728 }
5729 
5730 static int ext4_mark_dquot_dirty(struct dquot *dquot)
5731 {
5732         struct super_block *sb = dquot->dq_sb;
5733         struct ext4_sb_info *sbi = EXT4_SB(sb);
5734 
5735         /* Are we journaling quotas? */
5736         if (ext4_has_feature_quota(sb) ||
5737             sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
5738                 dquot_mark_dquot_dirty(dquot);
5739                 return ext4_write_dquot(dquot);
5740         } else {
5741                 return dquot_mark_dquot_dirty(dquot);
5742         }
5743 }
5744 
5745 static int ext4_write_info(struct super_block *sb, int type)
5746 {
5747         int ret, err;
5748         handle_t *handle;
5749 
5750         /* Data block + inode block */
5751         handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
5752         if (IS_ERR(handle))
5753                 return PTR_ERR(handle);
5754         ret = dquot_commit_info(sb, type);
5755         err = ext4_journal_stop(handle);
5756         if (!ret)
5757                 ret = err;
5758         return ret;
5759 }
5760 
5761 /*
5762  * Turn on quotas during mount time - we need to find
5763  * the quota file and such...
5764  */
5765 static int ext4_quota_on_mount(struct super_block *sb, int type)
5766 {
5767         return dquot_quota_on_mount(sb, get_qf_name(sb, EXT4_SB(sb), type),
5768                                         EXT4_SB(sb)->s_jquota_fmt, type);
5769 }
5770 
5771 static void lockdep_set_quota_inode(struct inode *inode, int subclass)
5772 {
5773         struct ext4_inode_info *ei = EXT4_I(inode);
5774 
5775         /* The first argument of lockdep_set_subclass has to be
5776          * *exactly* the same as the argument to init_rwsem() --- in
5777          * this case, in init_once() --- or lockdep gets unhappy
5778          * because the name of the lock is set using the
5779          * stringification of the argument to init_rwsem().
5780          */
5781         (void) ei;      /* shut up clang warning if !CONFIG_LOCKDEP */
5782         lockdep_set_subclass(&ei->i_data_sem, subclass);
5783 }
5784 
5785 /*
5786  * Standard function to be called on quota_on
5787  */
5788 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
5789                          const struct path *path)
5790 {
5791         int err;
5792 
5793         if (!test_opt(sb, QUOTA))
5794                 return -EINVAL;
5795 
5796         /* Quotafile not on the same filesystem? */
5797         if (path->dentry->d_sb != sb)
5798                 return -EXDEV;
5799         /* Journaling quota? */
5800         if (EXT4_SB(sb)->s_qf_names[type]) {
5801                 /* Quotafile not in fs root? */
5802                 if (path->dentry->d_parent != sb->s_root)
5803                         ext4_msg(sb, KERN_WARNING,
5804                                 "Quota file not on filesystem root. "
5805                                 "Journaled quota will not work");
5806                 sb_dqopt(sb)->flags |= DQUOT_NOLIST_DIRTY;
5807         } else {
5808                 /*
5809                  * Clear the flag just in case mount options changed since
5810                  * last time.
5811                  */
5812                 sb_dqopt(sb)->flags &= ~DQUOT_NOLIST_DIRTY;
5813         }
5814 
5815         /*
5816          * When we journal data on quota file, we have to flush journal to see
5817          * all updates to the file when we bypass pagecache...
5818          */
5819         if (EXT4_SB(sb)->s_journal &&
5820             ext4_should_journal_data(d_inode(path->dentry))) {
5821                 /*
5822                  * We don't need to lock updates but journal_flush() could
5823                  * otherwise be livelocked...
5824                  */
5825                 jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
5826                 err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
5827                 jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
5828                 if (err)
5829                         return err;
5830         }
5831 
5832         lockdep_set_quota_inode(path->dentry->d_inode, I_DATA_SEM_QUOTA);
5833         err = dquot_quota_on(sb, type, format_id, path);
5834         if (err) {
5835                 lockdep_set_quota_inode(path->dentry->d_inode,
5836                                              I_DATA_SEM_NORMAL);
5837         } else {
5838                 struct inode *inode = d_inode(path->dentry);
5839                 handle_t *handle;
5840 
5841                 /*
5842                  * Set inode flags to prevent userspace from messing with quota
5843                  * files. If this fails, we return success anyway since quotas
5844                  * are already enabled and this is not a hard failure.
5845                  */
5846                 inode_lock(inode);
5847                 handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
5848                 if (IS_ERR(handle))
5849                         goto unlock_inode;
5850                 EXT4_I(inode)->i_flags |= EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL;
5851                 inode_set_flags(inode, S_NOATIME | S_IMMUTABLE,
5852                                 S_NOATIME | S_IMMUTABLE);
5853                 ext4_mark_inode_dirty(handle, inode);
5854                 ext4_journal_stop(handle);
5855         unlock_inode:
5856                 inode_unlock(inode);
5857         }
5858         return err;
5859 }
5860 
5861 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
5862                              unsigned int flags)
5863 {
5864         int err;
5865         struct inode *qf_inode;
5866         unsigned long qf_inums[EXT4_MAXQUOTAS] = {
5867                 le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
5868                 le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
5869                 le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
5870         };
5871 
5872         BUG_ON(!ext4_has_feature_quota(sb));
5873 
5874         if (!qf_inums[type])
5875                 return -EPERM;
5876 
5877         qf_inode = ext4_iget(sb, qf_inums[type], EXT4_IGET_SPECIAL);
5878         if (IS_ERR(qf_inode)) {
5879                 ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
5880                 return PTR_ERR(qf_inode);
5881         }
5882 
5883         /* Don't account quota for quota files to avoid recursion */
5884         qf_inode->i_flags |= S_NOQUOTA;
5885         lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA);
5886         err = dquot_enable(qf_inode, type, format_id, flags);
5887         if (err)
5888                 lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL);
5889         iput(qf_inode);
5890 
5891         return err;
5892 }
5893 
5894 /* Enable usage tracking for all quota types. */
5895 static int ext4_enable_quotas(struct super_block *sb)
5896 {
5897         int type, err = 0;
5898         unsigned long qf_inums[EXT4_MAXQUOTAS] = {
5899                 le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
5900                 le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
5901                 le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
5902         };
5903         bool quota_mopt[EXT4_MAXQUOTAS] = {
5904                 test_opt(sb, USRQUOTA),
5905                 test_opt(sb, GRPQUOTA),
5906                 test_opt(sb, PRJQUOTA),
5907         };
5908 
5909         sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
5910         for (type = 0; type < EXT4_MAXQUOTAS; type++) {
5911                 if (qf_inums[type]) {
5912                         err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
5913                                 DQUOT_USAGE_ENABLED |
5914                                 (quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
5915                         if (err) {
5916                                 ext4_warning(sb,
5917                                         "Failed to enable quota tracking "
5918                                         "(type=%d, err=%d). Please run "
5919                                         "e2fsck to fix.", type, err);
5920                                 for (type--; type >= 0; type--)
5921                                         dquot_quota_off(sb, type);
5922 
5923                                 return err;
5924                         }
5925                 }
5926         }
5927         return 0;
5928 }
5929 
5930 static int ext4_quota_off(struct super_block *sb, int type)
5931 {
5932         struct inode *inode = sb_dqopt(sb)->files[type];
5933         handle_t *handle;
5934         int err;
5935 
5936         /* Force all delayed allocation blocks to be allocated.
5937          * Caller already holds s_umount sem */
5938         if (test_opt(sb, DELALLOC))
5939                 sync_filesystem(sb);
5940 
5941         if (!inode || !igrab(inode))
5942                 goto out;
5943 
5944         err = dquot_quota_off(sb, type);
5945         if (err || ext4_has_feature_quota(sb))
5946                 goto out_put;
5947 
5948         inode_lock(inode);
5949         /*
5950          * Update modification times of quota files when userspace can
5951          * start looking at them. If we fail, we return success anyway since
5952          * this is not a hard failure and quotas are already disabled.
5953          */
5954         handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
5955         if (IS_ERR(handle))
5956                 goto out_unlock;
5957         EXT4_I(inode)->i_flags &= ~(EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL);
5958         inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
5959         inode->i_mtime = inode->i_ctime = current_time(inode);
5960         ext4_mark_inode_dirty(handle, inode);
5961         ext4_journal_stop(handle);
5962 out_unlock:
5963         inode_unlock(inode);
5964 out_put:
5965         lockdep_set_quota_inode(inode, I_DATA_SEM_NORMAL);
5966         iput(inode);
5967         return err;
5968 out:
5969         return dquot_quota_off(sb, type);
5970 }
5971 
5972 /* Read data from quotafile - avoid pagecache and such because we cannot afford
5973  * acquiring the locks... As quota files are never truncated and quota code
5974  * itself serializes the operations (and no one else should touch the files)
5975  * we don't have to be afraid of races */
5976 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
5977                                size_t len, loff_t off)
5978 {
5979         struct inode *inode = sb_dqopt(sb)->files[type];
5980         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
5981         int offset = off & (sb->s_blocksize - 1);
5982         int tocopy;
5983         size_t toread;
5984         struct buffer_head *bh;
5985         loff_t i_size = i_size_read(inode);
5986 
5987         if (off > i_size)
5988                 return 0;
5989         if (off+len > i_size)
5990                 len = i_size-off;
5991         toread = len;
5992         while (toread > 0) {
5993                 tocopy = sb->s_blocksize - offset < toread ?
5994                                 sb->s_blocksize - offset : toread;
5995                 bh = ext4_bread(NULL, inode, blk, 0);
5996                 if (IS_ERR(bh))
5997                         return PTR_ERR(bh);
5998                 if (!bh)        /* A hole? */
5999                         memset(data, 0, tocopy);
6000                 else
6001                         memcpy(data, bh->b_data+offset, tocopy);
6002                 brelse(bh);
6003                 offset = 0;
6004                 toread -= tocopy;
6005                 data += tocopy;
6006                 blk++;
6007         }
6008         return len;
6009 }
6010 
6011 /* Write to quotafile (we know the transaction is already started and has
6012  * enough credits) */
6013 static ssize_t ext4_quota_write(struct super_block *sb, int type,
6014                                 const char *data, size_t len, loff_t off)
6015 {
6016         struct inode *inode = sb_dqopt(sb)->files[type];
6017         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
6018         int err, offset = off & (sb->s_blocksize - 1);
6019         int retries = 0;
6020         struct buffer_head *bh;
6021         handle_t *handle = journal_current_handle();
6022 
6023         if (EXT4_SB(sb)->s_journal && !handle) {
6024                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6025                         " cancelled because transaction is not started",
6026                         (unsigned long long)off, (unsigned long long)len);
6027                 return -EIO;
6028         }
6029         /*
6030          * Since we account only one data block in transaction credits,
6031          * then it is impossible to cross a block boundary.
6032          */
6033         if (sb->s_blocksize - offset < len) {
6034                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6035                         " cancelled because not block aligned",
6036                         (unsigned long long)off, (unsigned long long)len);
6037                 return -EIO;
6038         }
6039 
6040         do {
6041                 bh = ext4_bread(handle, inode, blk,
6042                                 EXT4_GET_BLOCKS_CREATE |
6043                                 EXT4_GET_BLOCKS_METADATA_NOFAIL);
6044         } while (IS_ERR(bh) && (PTR_ERR(bh) == -ENOSPC) &&
6045                  ext4_should_retry_alloc(inode->i_sb, &retries));
6046         if (IS_ERR(bh))
6047                 return PTR_ERR(bh);
6048         if (!bh)
6049                 goto out;
6050         BUFFER_TRACE(bh, "get write access");
6051         err = ext4_journal_get_write_access(handle, bh);
6052         if (err) {
6053                 brelse(bh);
6054                 return err;
6055         }
6056         lock_buffer(bh);
6057         memcpy(bh->b_data+offset, data, len);
6058         flush_dcache_page(bh->b_page);
6059         unlock_buffer(bh);
6060         err = ext4_handle_dirty_metadata(handle, NULL, bh);
6061         brelse(bh);
6062 out:
6063         if (inode->i_size < off + len) {
6064                 i_size_write(inode, off + len);
6065                 EXT4_I(inode)->i_disksize = inode->i_size;
6066                 ext4_mark_inode_dirty(handle, inode);
6067         }
6068         return len;
6069 }
6070 
6071 static int ext4_get_next_id(struct super_block *sb, struct kqid *qid)
6072 {
6073         const struct quota_format_ops   *ops;
6074 
6075         if (!sb_has_quota_loaded(sb, qid->type))
6076                 return -ESRCH;
6077         ops = sb_dqopt(sb)->ops[qid->type];
6078         if (!ops || !ops->get_next_id)
6079                 return -ENOSYS;
6080         return dquot_get_next_id(sb, qid);
6081 }
6082 #endif
6083 
6084 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
6085                        const char *dev_name, void *data)
6086 {
6087         return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
6088 }
6089 
6090 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
6091 static inline void register_as_ext2(void)
6092 {
6093         int err = register_filesystem(&ext2_fs_type);
6094         if (err)
6095                 printk(KERN_WARNING
6096                        "EXT4-fs: Unable to register as ext2 (%d)\n", err);
6097 }
6098 
6099 static inline void unregister_as_ext2(void)
6100 {
6101         unregister_filesystem(&ext2_fs_type);
6102 }
6103 
6104 static inline int ext2_feature_set_ok(struct super_block *sb)
6105 {
6106         if (ext4_has_unknown_ext2_incompat_features(sb))
6107                 return 0;
6108         if (sb_rdonly(sb))
6109                 return 1;
6110         if (ext4_has_unknown_ext2_ro_compat_features(sb))
6111                 return 0;
6112         return 1;
6113 }
6114 #else
6115 static inline void register_as_ext2(void) { }
6116 static inline void unregister_as_ext2(void) { }
6117 static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
6118 #endif
6119 
6120 static inline void register_as_ext3(void)
6121 {
6122         int err = register_filesystem(&ext3_fs_type);
6123         if (err)
6124                 printk(KERN_WARNING
6125                        "EXT4-fs: Unable to register as ext3 (%d)\n", err);
6126 }
6127 
6128 static inline void unregister_as_ext3(void)
6129 {
6130         unregister_filesystem(&ext3_fs_type);
6131 }
6132 
6133 static inline int ext3_feature_set_ok(struct super_block *sb)
6134 {
6135         if (ext4_has_unknown_ext3_incompat_features(sb))
6136                 return 0;
6137         if (!ext4_has_feature_journal(sb))
6138                 return 0;
6139         if (sb_rdonly(sb))
6140                 return 1;
6141         if (ext4_has_unknown_ext3_ro_compat_features(sb))
6142                 return 0;
6143         return 1;
6144 }
6145 
6146 static struct file_system_type ext4_fs_type = {
6147         .owner          = THIS_MODULE,
6148         .name           = "ext4",
6149         .mount          = ext4_mount,
6150         .kill_sb        = kill_block_super,
6151         .fs_flags       = FS_REQUIRES_DEV,
6152 };
6153 MODULE_ALIAS_FS("ext4");
6154 
6155 /* Shared across all ext4 file systems */
6156 wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
6157 
6158 static int __init ext4_init_fs(void)
6159 {
6160         int i, err;
6161 
6162         ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
6163         ext4_li_info = NULL;
6164         mutex_init(&ext4_li_mtx);
6165 
6166         /* Build-time check for flags consistency */
6167         ext4_check_flag_values();
6168 
6169         for (i = 0; i < EXT4_WQ_HASH_SZ; i++)
6170                 init_waitqueue_head(&ext4__ioend_wq[i]);
6171 
6172         err = ext4_init_es();
6173         if (err)
6174                 return err;
6175 
6176         err = ext4_init_pending();
6177         if (err)
6178                 goto out7;
6179 
6180         err = ext4_init_post_read_processing();
6181         if (err)
6182                 goto out6;
6183 
6184         err = ext4_init_pageio();
6185         if (err)
6186                 goto out5;
6187 
6188         err = ext4_init_system_zone();
6189         if (err)
6190                 goto out4;
6191 
6192         err = ext4_init_sysfs();
6193         if (err)
6194                 goto out3;
6195 
6196         err = ext4_init_mballoc();
6197         if (err)
6198                 goto out2;
6199         err = init_inodecache();
6200         if (err)
6201                 goto out1;
6202         register_as_ext3();
6203         register_as_ext2();
6204         err = register_filesystem(&ext4_fs_type);
6205         if (err)
6206                 goto out;
6207 
6208         return 0;
6209 out:
6210         unregister_as_ext2();
6211         unregister_as_ext3();
6212         destroy_inodecache();
6213 out1:
6214         ext4_exit_mballoc();
6215 out2:
6216         ext4_exit_sysfs();
6217 out3:
6218         ext4_exit_system_zone();
6219 out4:
6220         ext4_exit_pageio();
6221 out5:
6222         ext4_exit_post_read_processing();
6223 out6:
6224         ext4_exit_pending();
6225 out7:
6226         ext4_exit_es();
6227 
6228         return err;
6229 }
6230 
6231 static void __exit ext4_exit_fs(void)
6232 {
6233         ext4_destroy_lazyinit_thread();
6234         unregister_as_ext2();
6235         unregister_as_ext3();
6236         unregister_filesystem(&ext4_fs_type);
6237         destroy_inodecache();
6238         ext4_exit_mballoc();
6239         ext4_exit_sysfs();
6240         ext4_exit_system_zone();
6241         ext4_exit_pageio();
6242         ext4_exit_post_read_processing();
6243         ext4_exit_es();
6244         ext4_exit_pending();
6245 }
6246 
6247 MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
6248 MODULE_DESCRIPTION("Fourth Extended Filesystem");
6249 MODULE_LICENSE("GPL");
6250 MODULE_SOFTDEP("pre: crc32c");
6251 module_init(ext4_init_fs)
6252 module_exit(ext4_exit_fs)

/* [<][>][^][v][top][bottom][index][help] */