~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/ext4/super.c

Version: ~ [ linux-5.13-rc5 ] ~ [ linux-5.12.9 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.42 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.124 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.193 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.235 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.271 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.271 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp