ext4: clear lockdep subtype for quota files on quota off
[sfrench/cifs-2.6.git] / fs / ext4 / super.c
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/ctype.h>
38 #include <linux/log2.h>
39 #include <linux/crc16.h>
40 #include <linux/dax.h>
41 #include <linux/cleancache.h>
42 #include <linux/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 #include "fsmap.h"
54
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/ext4.h>
57
58 static struct ext4_lazy_init *ext4_li_info;
59 static struct mutex ext4_li_mtx;
60 static struct ratelimit_state ext4_mount_msg_ratelimit;
61
62 static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
63                              unsigned long journal_devnum);
64 static int ext4_show_options(struct seq_file *seq, struct dentry *root);
65 static int ext4_commit_super(struct super_block *sb, int sync);
66 static void ext4_mark_recovery_complete(struct super_block *sb,
67                                         struct ext4_super_block *es);
68 static void ext4_clear_journal_err(struct super_block *sb,
69                                    struct ext4_super_block *es);
70 static int ext4_sync_fs(struct super_block *sb, int wait);
71 static int ext4_remount(struct super_block *sb, int *flags, char *data);
72 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
73 static int ext4_unfreeze(struct super_block *sb);
74 static int ext4_freeze(struct super_block *sb);
75 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
76                        const char *dev_name, void *data);
77 static inline int ext2_feature_set_ok(struct super_block *sb);
78 static inline int ext3_feature_set_ok(struct super_block *sb);
79 static int ext4_feature_set_ok(struct super_block *sb, int readonly);
80 static void ext4_destroy_lazyinit_thread(void);
81 static void ext4_unregister_li_request(struct super_block *sb);
82 static void ext4_clear_request_list(void);
83 static struct inode *ext4_get_journal_inode(struct super_block *sb,
84                                             unsigned int journal_inum);
85
86 /*
87  * Lock ordering
88  *
89  * Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
90  * i_mmap_rwsem (inode->i_mmap_rwsem)!
91  *
92  * page fault path:
93  * mmap_sem -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
94  *   page lock -> i_data_sem (rw)
95  *
96  * buffered write path:
97  * sb_start_write -> i_mutex -> mmap_sem
98  * sb_start_write -> i_mutex -> transaction start -> page lock ->
99  *   i_data_sem (rw)
100  *
101  * truncate:
102  * sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
103  *   i_mmap_rwsem (w) -> page lock
104  * sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
105  *   transaction start -> i_data_sem (rw)
106  *
107  * direct IO:
108  * sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) -> mmap_sem
109  * sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) ->
110  *   transaction start -> i_data_sem (rw)
111  *
112  * writepages:
113  * transaction start -> page lock(s) -> i_data_sem (rw)
114  */
115
116 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
117 static struct file_system_type ext2_fs_type = {
118         .owner          = THIS_MODULE,
119         .name           = "ext2",
120         .mount          = ext4_mount,
121         .kill_sb        = kill_block_super,
122         .fs_flags       = FS_REQUIRES_DEV,
123 };
124 MODULE_ALIAS_FS("ext2");
125 MODULE_ALIAS("ext2");
126 #define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
127 #else
128 #define IS_EXT2_SB(sb) (0)
129 #endif
130
131
132 static struct file_system_type ext3_fs_type = {
133         .owner          = THIS_MODULE,
134         .name           = "ext3",
135         .mount          = ext4_mount,
136         .kill_sb        = kill_block_super,
137         .fs_flags       = FS_REQUIRES_DEV,
138 };
139 MODULE_ALIAS_FS("ext3");
140 MODULE_ALIAS("ext3");
141 #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
142
143 static int ext4_verify_csum_type(struct super_block *sb,
144                                  struct ext4_super_block *es)
145 {
146         if (!ext4_has_feature_metadata_csum(sb))
147                 return 1;
148
149         return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
150 }
151
152 static __le32 ext4_superblock_csum(struct super_block *sb,
153                                    struct ext4_super_block *es)
154 {
155         struct ext4_sb_info *sbi = EXT4_SB(sb);
156         int offset = offsetof(struct ext4_super_block, s_checksum);
157         __u32 csum;
158
159         csum = ext4_chksum(sbi, ~0, (char *)es, offset);
160
161         return cpu_to_le32(csum);
162 }
163
164 static int ext4_superblock_csum_verify(struct super_block *sb,
165                                        struct ext4_super_block *es)
166 {
167         if (!ext4_has_metadata_csum(sb))
168                 return 1;
169
170         return es->s_checksum == ext4_superblock_csum(sb, es);
171 }
172
173 void ext4_superblock_csum_set(struct super_block *sb)
174 {
175         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
176
177         if (!ext4_has_metadata_csum(sb))
178                 return;
179
180         es->s_checksum = ext4_superblock_csum(sb, es);
181 }
182
183 void *ext4_kvmalloc(size_t size, gfp_t flags)
184 {
185         void *ret;
186
187         ret = kmalloc(size, flags | __GFP_NOWARN);
188         if (!ret)
189                 ret = __vmalloc(size, flags, PAGE_KERNEL);
190         return ret;
191 }
192
193 void *ext4_kvzalloc(size_t size, gfp_t flags)
194 {
195         void *ret;
196
197         ret = kzalloc(size, flags | __GFP_NOWARN);
198         if (!ret)
199                 ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
200         return ret;
201 }
202
203 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
204                                struct ext4_group_desc *bg)
205 {
206         return le32_to_cpu(bg->bg_block_bitmap_lo) |
207                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
208                  (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
209 }
210
211 ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
212                                struct ext4_group_desc *bg)
213 {
214         return le32_to_cpu(bg->bg_inode_bitmap_lo) |
215                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
216                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
217 }
218
219 ext4_fsblk_t ext4_inode_table(struct super_block *sb,
220                               struct ext4_group_desc *bg)
221 {
222         return le32_to_cpu(bg->bg_inode_table_lo) |
223                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
224                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
225 }
226
227 __u32 ext4_free_group_clusters(struct super_block *sb,
228                                struct ext4_group_desc *bg)
229 {
230         return le16_to_cpu(bg->bg_free_blocks_count_lo) |
231                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
232                  (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
233 }
234
235 __u32 ext4_free_inodes_count(struct super_block *sb,
236                               struct ext4_group_desc *bg)
237 {
238         return le16_to_cpu(bg->bg_free_inodes_count_lo) |
239                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
240                  (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
241 }
242
243 __u32 ext4_used_dirs_count(struct super_block *sb,
244                               struct ext4_group_desc *bg)
245 {
246         return le16_to_cpu(bg->bg_used_dirs_count_lo) |
247                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
248                  (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
249 }
250
251 __u32 ext4_itable_unused_count(struct super_block *sb,
252                               struct ext4_group_desc *bg)
253 {
254         return le16_to_cpu(bg->bg_itable_unused_lo) |
255                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
256                  (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
257 }
258
259 void ext4_block_bitmap_set(struct super_block *sb,
260                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
261 {
262         bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
263         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
264                 bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
265 }
266
267 void ext4_inode_bitmap_set(struct super_block *sb,
268                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
269 {
270         bg->bg_inode_bitmap_lo  = cpu_to_le32((u32)blk);
271         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
272                 bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
273 }
274
275 void ext4_inode_table_set(struct super_block *sb,
276                           struct ext4_group_desc *bg, ext4_fsblk_t blk)
277 {
278         bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
279         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
280                 bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
281 }
282
283 void ext4_free_group_clusters_set(struct super_block *sb,
284                                   struct ext4_group_desc *bg, __u32 count)
285 {
286         bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
287         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
288                 bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
289 }
290
291 void ext4_free_inodes_set(struct super_block *sb,
292                           struct ext4_group_desc *bg, __u32 count)
293 {
294         bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
295         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
296                 bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
297 }
298
299 void ext4_used_dirs_set(struct super_block *sb,
300                           struct ext4_group_desc *bg, __u32 count)
301 {
302         bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
303         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
304                 bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
305 }
306
307 void ext4_itable_unused_set(struct super_block *sb,
308                           struct ext4_group_desc *bg, __u32 count)
309 {
310         bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
311         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
312                 bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
313 }
314
315
316 static void __save_error_info(struct super_block *sb, const char *func,
317                             unsigned int line)
318 {
319         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
320
321         EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
322         if (bdev_read_only(sb->s_bdev))
323                 return;
324         es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
325         es->s_last_error_time = cpu_to_le32(get_seconds());
326         strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
327         es->s_last_error_line = cpu_to_le32(line);
328         if (!es->s_first_error_time) {
329                 es->s_first_error_time = es->s_last_error_time;
330                 strncpy(es->s_first_error_func, func,
331                         sizeof(es->s_first_error_func));
332                 es->s_first_error_line = cpu_to_le32(line);
333                 es->s_first_error_ino = es->s_last_error_ino;
334                 es->s_first_error_block = es->s_last_error_block;
335         }
336         /*
337          * Start the daily error reporting function if it hasn't been
338          * started already
339          */
340         if (!es->s_error_count)
341                 mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
342         le32_add_cpu(&es->s_error_count, 1);
343 }
344
345 static void save_error_info(struct super_block *sb, const char *func,
346                             unsigned int line)
347 {
348         __save_error_info(sb, func, line);
349         ext4_commit_super(sb, 1);
350 }
351
352 /*
353  * The del_gendisk() function uninitializes the disk-specific data
354  * structures, including the bdi structure, without telling anyone
355  * else.  Once this happens, any attempt to call mark_buffer_dirty()
356  * (for example, by ext4_commit_super), will cause a kernel OOPS.
357  * This is a kludge to prevent these oops until we can put in a proper
358  * hook in del_gendisk() to inform the VFS and file system layers.
359  */
360 static int block_device_ejected(struct super_block *sb)
361 {
362         struct inode *bd_inode = sb->s_bdev->bd_inode;
363         struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
364
365         return bdi->dev == NULL;
366 }
367
368 static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
369 {
370         struct super_block              *sb = journal->j_private;
371         struct ext4_sb_info             *sbi = EXT4_SB(sb);
372         int                             error = is_journal_aborted(journal);
373         struct ext4_journal_cb_entry    *jce;
374
375         BUG_ON(txn->t_state == T_FINISHED);
376         spin_lock(&sbi->s_md_lock);
377         while (!list_empty(&txn->t_private_list)) {
378                 jce = list_entry(txn->t_private_list.next,
379                                  struct ext4_journal_cb_entry, jce_list);
380                 list_del_init(&jce->jce_list);
381                 spin_unlock(&sbi->s_md_lock);
382                 jce->jce_func(sb, jce, error);
383                 spin_lock(&sbi->s_md_lock);
384         }
385         spin_unlock(&sbi->s_md_lock);
386 }
387
388 /* Deal with the reporting of failure conditions on a filesystem such as
389  * inconsistencies detected or read IO failures.
390  *
391  * On ext2, we can store the error state of the filesystem in the
392  * superblock.  That is not possible on ext4, because we may have other
393  * write ordering constraints on the superblock which prevent us from
394  * writing it out straight away; and given that the journal is about to
395  * be aborted, we can't rely on the current, or future, transactions to
396  * write out the superblock safely.
397  *
398  * We'll just use the jbd2_journal_abort() error code to record an error in
399  * the journal instead.  On recovery, the journal will complain about
400  * that error until we've noted it down and cleared it.
401  */
402
403 static void ext4_handle_error(struct super_block *sb)
404 {
405         if (sb->s_flags & MS_RDONLY)
406                 return;
407
408         if (!test_opt(sb, ERRORS_CONT)) {
409                 journal_t *journal = EXT4_SB(sb)->s_journal;
410
411                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
412                 if (journal)
413                         jbd2_journal_abort(journal, -EIO);
414         }
415         if (test_opt(sb, ERRORS_RO)) {
416                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
417                 /*
418                  * Make sure updated value of ->s_mount_flags will be visible
419                  * before ->s_flags update
420                  */
421                 smp_wmb();
422                 sb->s_flags |= MS_RDONLY;
423         }
424         if (test_opt(sb, ERRORS_PANIC)) {
425                 if (EXT4_SB(sb)->s_journal &&
426                   !(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
427                         return;
428                 panic("EXT4-fs (device %s): panic forced after error\n",
429                         sb->s_id);
430         }
431 }
432
433 #define ext4_error_ratelimit(sb)                                        \
434                 ___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state),     \
435                              "EXT4-fs error")
436
437 void __ext4_error(struct super_block *sb, const char *function,
438                   unsigned int line, const char *fmt, ...)
439 {
440         struct va_format vaf;
441         va_list args;
442
443         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
444                 return;
445
446         if (ext4_error_ratelimit(sb)) {
447                 va_start(args, fmt);
448                 vaf.fmt = fmt;
449                 vaf.va = &args;
450                 printk(KERN_CRIT
451                        "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
452                        sb->s_id, function, line, current->comm, &vaf);
453                 va_end(args);
454         }
455         save_error_info(sb, function, line);
456         ext4_handle_error(sb);
457 }
458
459 void __ext4_error_inode(struct inode *inode, 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 = EXT4_SB(inode->i_sb)->s_es;
466
467         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
468                 return;
469
470         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
471         es->s_last_error_block = cpu_to_le64(block);
472         if (ext4_error_ratelimit(inode->i_sb)) {
473                 va_start(args, fmt);
474                 vaf.fmt = fmt;
475                 vaf.va = &args;
476                 if (block)
477                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
478                                "inode #%lu: block %llu: comm %s: %pV\n",
479                                inode->i_sb->s_id, function, line, inode->i_ino,
480                                block, current->comm, &vaf);
481                 else
482                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
483                                "inode #%lu: comm %s: %pV\n",
484                                inode->i_sb->s_id, function, line, inode->i_ino,
485                                current->comm, &vaf);
486                 va_end(args);
487         }
488         save_error_info(inode->i_sb, function, line);
489         ext4_handle_error(inode->i_sb);
490 }
491
492 void __ext4_error_file(struct file *file, const char *function,
493                        unsigned int line, ext4_fsblk_t block,
494                        const char *fmt, ...)
495 {
496         va_list args;
497         struct va_format vaf;
498         struct ext4_super_block *es;
499         struct inode *inode = file_inode(file);
500         char pathname[80], *path;
501
502         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
503                 return;
504
505         es = EXT4_SB(inode->i_sb)->s_es;
506         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
507         if (ext4_error_ratelimit(inode->i_sb)) {
508                 path = file_path(file, pathname, sizeof(pathname));
509                 if (IS_ERR(path))
510                         path = "(unknown)";
511                 va_start(args, fmt);
512                 vaf.fmt = fmt;
513                 vaf.va = &args;
514                 if (block)
515                         printk(KERN_CRIT
516                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
517                                "block %llu: comm %s: path %s: %pV\n",
518                                inode->i_sb->s_id, function, line, inode->i_ino,
519                                block, current->comm, path, &vaf);
520                 else
521                         printk(KERN_CRIT
522                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
523                                "comm %s: path %s: %pV\n",
524                                inode->i_sb->s_id, function, line, inode->i_ino,
525                                current->comm, path, &vaf);
526                 va_end(args);
527         }
528         save_error_info(inode->i_sb, function, line);
529         ext4_handle_error(inode->i_sb);
530 }
531
532 const char *ext4_decode_error(struct super_block *sb, int errno,
533                               char nbuf[16])
534 {
535         char *errstr = NULL;
536
537         switch (errno) {
538         case -EFSCORRUPTED:
539                 errstr = "Corrupt filesystem";
540                 break;
541         case -EFSBADCRC:
542                 errstr = "Filesystem failed CRC";
543                 break;
544         case -EIO:
545                 errstr = "IO failure";
546                 break;
547         case -ENOMEM:
548                 errstr = "Out of memory";
549                 break;
550         case -EROFS:
551                 if (!sb || (EXT4_SB(sb)->s_journal &&
552                             EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
553                         errstr = "Journal has aborted";
554                 else
555                         errstr = "Readonly filesystem";
556                 break;
557         default:
558                 /* If the caller passed in an extra buffer for unknown
559                  * errors, textualise them now.  Else we just return
560                  * NULL. */
561                 if (nbuf) {
562                         /* Check for truncated error codes... */
563                         if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
564                                 errstr = nbuf;
565                 }
566                 break;
567         }
568
569         return errstr;
570 }
571
572 /* __ext4_std_error decodes expected errors from journaling functions
573  * automatically and invokes the appropriate error response.  */
574
575 void __ext4_std_error(struct super_block *sb, const char *function,
576                       unsigned int line, int errno)
577 {
578         char nbuf[16];
579         const char *errstr;
580
581         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
582                 return;
583
584         /* Special case: if the error is EROFS, and we're not already
585          * inside a transaction, then there's really no point in logging
586          * an error. */
587         if (errno == -EROFS && journal_current_handle() == NULL &&
588             (sb->s_flags & MS_RDONLY))
589                 return;
590
591         if (ext4_error_ratelimit(sb)) {
592                 errstr = ext4_decode_error(sb, errno, nbuf);
593                 printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
594                        sb->s_id, function, line, errstr);
595         }
596
597         save_error_info(sb, function, line);
598         ext4_handle_error(sb);
599 }
600
601 /*
602  * ext4_abort is a much stronger failure handler than ext4_error.  The
603  * abort function may be used to deal with unrecoverable failures such
604  * as journal IO errors or ENOMEM at a critical moment in log management.
605  *
606  * We unconditionally force the filesystem into an ABORT|READONLY state,
607  * unless the error response on the fs has been set to panic in which
608  * case we take the easy way out and panic immediately.
609  */
610
611 void __ext4_abort(struct super_block *sb, const char *function,
612                 unsigned int line, const char *fmt, ...)
613 {
614         struct va_format vaf;
615         va_list args;
616
617         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
618                 return;
619
620         save_error_info(sb, function, line);
621         va_start(args, fmt);
622         vaf.fmt = fmt;
623         vaf.va = &args;
624         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: %pV\n",
625                sb->s_id, function, line, &vaf);
626         va_end(args);
627
628         if ((sb->s_flags & MS_RDONLY) == 0) {
629                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
630                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
631                 /*
632                  * Make sure updated value of ->s_mount_flags will be visible
633                  * before ->s_flags update
634                  */
635                 smp_wmb();
636                 sb->s_flags |= MS_RDONLY;
637                 if (EXT4_SB(sb)->s_journal)
638                         jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
639                 save_error_info(sb, function, line);
640         }
641         if (test_opt(sb, ERRORS_PANIC)) {
642                 if (EXT4_SB(sb)->s_journal &&
643                   !(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
644                         return;
645                 panic("EXT4-fs panic from previous error\n");
646         }
647 }
648
649 void __ext4_msg(struct super_block *sb,
650                 const char *prefix, const char *fmt, ...)
651 {
652         struct va_format vaf;
653         va_list args;
654
655         if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
656                 return;
657
658         va_start(args, fmt);
659         vaf.fmt = fmt;
660         vaf.va = &args;
661         printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
662         va_end(args);
663 }
664
665 #define ext4_warning_ratelimit(sb)                                      \
666                 ___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state), \
667                              "EXT4-fs warning")
668
669 void __ext4_warning(struct super_block *sb, const char *function,
670                     unsigned int line, const char *fmt, ...)
671 {
672         struct va_format vaf;
673         va_list args;
674
675         if (!ext4_warning_ratelimit(sb))
676                 return;
677
678         va_start(args, fmt);
679         vaf.fmt = fmt;
680         vaf.va = &args;
681         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
682                sb->s_id, function, line, &vaf);
683         va_end(args);
684 }
685
686 void __ext4_warning_inode(const struct inode *inode, const char *function,
687                           unsigned int line, const char *fmt, ...)
688 {
689         struct va_format vaf;
690         va_list args;
691
692         if (!ext4_warning_ratelimit(inode->i_sb))
693                 return;
694
695         va_start(args, fmt);
696         vaf.fmt = fmt;
697         vaf.va = &args;
698         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
699                "inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
700                function, line, inode->i_ino, current->comm, &vaf);
701         va_end(args);
702 }
703
704 void __ext4_grp_locked_error(const char *function, unsigned int line,
705                              struct super_block *sb, ext4_group_t grp,
706                              unsigned long ino, ext4_fsblk_t block,
707                              const char *fmt, ...)
708 __releases(bitlock)
709 __acquires(bitlock)
710 {
711         struct va_format vaf;
712         va_list args;
713         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
714
715         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
716                 return;
717
718         es->s_last_error_ino = cpu_to_le32(ino);
719         es->s_last_error_block = cpu_to_le64(block);
720         __save_error_info(sb, function, line);
721
722         if (ext4_error_ratelimit(sb)) {
723                 va_start(args, fmt);
724                 vaf.fmt = fmt;
725                 vaf.va = &args;
726                 printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
727                        sb->s_id, function, line, grp);
728                 if (ino)
729                         printk(KERN_CONT "inode %lu: ", ino);
730                 if (block)
731                         printk(KERN_CONT "block %llu:",
732                                (unsigned long long) block);
733                 printk(KERN_CONT "%pV\n", &vaf);
734                 va_end(args);
735         }
736
737         if (test_opt(sb, ERRORS_CONT)) {
738                 ext4_commit_super(sb, 0);
739                 return;
740         }
741
742         ext4_unlock_group(sb, grp);
743         ext4_handle_error(sb);
744         /*
745          * We only get here in the ERRORS_RO case; relocking the group
746          * may be dangerous, but nothing bad will happen since the
747          * filesystem will have already been marked read/only and the
748          * journal has been aborted.  We return 1 as a hint to callers
749          * who might what to use the return value from
750          * ext4_grp_locked_error() to distinguish between the
751          * ERRORS_CONT and ERRORS_RO case, and perhaps return more
752          * aggressively from the ext4 function in question, with a
753          * more appropriate error code.
754          */
755         ext4_lock_group(sb, grp);
756         return;
757 }
758
759 void ext4_update_dynamic_rev(struct super_block *sb)
760 {
761         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
762
763         if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
764                 return;
765
766         ext4_warning(sb,
767                      "updating to rev %d because of new feature flag, "
768                      "running e2fsck is recommended",
769                      EXT4_DYNAMIC_REV);
770
771         es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
772         es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
773         es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
774         /* leave es->s_feature_*compat flags alone */
775         /* es->s_uuid will be set by e2fsck if empty */
776
777         /*
778          * The rest of the superblock fields should be zero, and if not it
779          * means they are likely already in use, so leave them alone.  We
780          * can leave it up to e2fsck to clean up any inconsistencies there.
781          */
782 }
783
784 /*
785  * Open the external journal device
786  */
787 static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
788 {
789         struct block_device *bdev;
790         char b[BDEVNAME_SIZE];
791
792         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
793         if (IS_ERR(bdev))
794                 goto fail;
795         return bdev;
796
797 fail:
798         ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
799                         __bdevname(dev, b), PTR_ERR(bdev));
800         return NULL;
801 }
802
803 /*
804  * Release the journal device
805  */
806 static void ext4_blkdev_put(struct block_device *bdev)
807 {
808         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
809 }
810
811 static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
812 {
813         struct block_device *bdev;
814         bdev = sbi->journal_bdev;
815         if (bdev) {
816                 ext4_blkdev_put(bdev);
817                 sbi->journal_bdev = NULL;
818         }
819 }
820
821 static inline struct inode *orphan_list_entry(struct list_head *l)
822 {
823         return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
824 }
825
826 static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
827 {
828         struct list_head *l;
829
830         ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
831                  le32_to_cpu(sbi->s_es->s_last_orphan));
832
833         printk(KERN_ERR "sb_info orphan list:\n");
834         list_for_each(l, &sbi->s_orphan) {
835                 struct inode *inode = orphan_list_entry(l);
836                 printk(KERN_ERR "  "
837                        "inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
838                        inode->i_sb->s_id, inode->i_ino, inode,
839                        inode->i_mode, inode->i_nlink,
840                        NEXT_ORPHAN(inode));
841         }
842 }
843
844 #ifdef CONFIG_QUOTA
845 static int ext4_quota_off(struct super_block *sb, int type);
846
847 static inline void ext4_quota_off_umount(struct super_block *sb)
848 {
849         int type;
850
851         /* Use our quota_off function to clear inode flags etc. */
852         for (type = 0; type < EXT4_MAXQUOTAS; type++)
853                 ext4_quota_off(sb, type);
854 }
855 #else
856 static inline void ext4_quota_off_umount(struct super_block *sb)
857 {
858 }
859 #endif
860
861 static void ext4_put_super(struct super_block *sb)
862 {
863         struct ext4_sb_info *sbi = EXT4_SB(sb);
864         struct ext4_super_block *es = sbi->s_es;
865         int aborted = 0;
866         int i, err;
867
868         ext4_unregister_li_request(sb);
869         ext4_quota_off_umount(sb);
870
871         flush_workqueue(sbi->rsv_conversion_wq);
872         destroy_workqueue(sbi->rsv_conversion_wq);
873
874         if (sbi->s_journal) {
875                 aborted = is_journal_aborted(sbi->s_journal);
876                 err = jbd2_journal_destroy(sbi->s_journal);
877                 sbi->s_journal = NULL;
878                 if ((err < 0) && !aborted)
879                         ext4_abort(sb, "Couldn't clean up the journal");
880         }
881
882         ext4_unregister_sysfs(sb);
883         ext4_es_unregister_shrinker(sbi);
884         del_timer_sync(&sbi->s_err_report);
885         ext4_release_system_zone(sb);
886         ext4_mb_release(sb);
887         ext4_ext_release(sb);
888
889         if (!(sb->s_flags & MS_RDONLY) && !aborted) {
890                 ext4_clear_feature_journal_needs_recovery(sb);
891                 es->s_state = cpu_to_le16(sbi->s_mount_state);
892         }
893         if (!(sb->s_flags & MS_RDONLY))
894                 ext4_commit_super(sb, 1);
895
896         for (i = 0; i < sbi->s_gdb_count; i++)
897                 brelse(sbi->s_group_desc[i]);
898         kvfree(sbi->s_group_desc);
899         kvfree(sbi->s_flex_groups);
900         percpu_counter_destroy(&sbi->s_freeclusters_counter);
901         percpu_counter_destroy(&sbi->s_freeinodes_counter);
902         percpu_counter_destroy(&sbi->s_dirs_counter);
903         percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
904         percpu_free_rwsem(&sbi->s_journal_flag_rwsem);
905 #ifdef CONFIG_QUOTA
906         for (i = 0; i < EXT4_MAXQUOTAS; i++)
907                 kfree(sbi->s_qf_names[i]);
908 #endif
909
910         /* Debugging code just in case the in-memory inode orphan list
911          * isn't empty.  The on-disk one can be non-empty if we've
912          * detected an error and taken the fs readonly, but the
913          * in-memory list had better be clean by this point. */
914         if (!list_empty(&sbi->s_orphan))
915                 dump_orphan_list(sb, sbi);
916         J_ASSERT(list_empty(&sbi->s_orphan));
917
918         sync_blockdev(sb->s_bdev);
919         invalidate_bdev(sb->s_bdev);
920         if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
921                 /*
922                  * Invalidate the journal device's buffers.  We don't want them
923                  * floating about in memory - the physical journal device may
924                  * hotswapped, and it breaks the `ro-after' testing code.
925                  */
926                 sync_blockdev(sbi->journal_bdev);
927                 invalidate_bdev(sbi->journal_bdev);
928                 ext4_blkdev_remove(sbi);
929         }
930         if (sbi->s_mb_cache) {
931                 ext4_xattr_destroy_cache(sbi->s_mb_cache);
932                 sbi->s_mb_cache = NULL;
933         }
934         if (sbi->s_mmp_tsk)
935                 kthread_stop(sbi->s_mmp_tsk);
936         brelse(sbi->s_sbh);
937         sb->s_fs_info = NULL;
938         /*
939          * Now that we are completely done shutting down the
940          * superblock, we need to actually destroy the kobject.
941          */
942         kobject_put(&sbi->s_kobj);
943         wait_for_completion(&sbi->s_kobj_unregister);
944         if (sbi->s_chksum_driver)
945                 crypto_free_shash(sbi->s_chksum_driver);
946         kfree(sbi->s_blockgroup_lock);
947         kfree(sbi);
948 }
949
950 static struct kmem_cache *ext4_inode_cachep;
951
952 /*
953  * Called inside transaction, so use GFP_NOFS
954  */
955 static struct inode *ext4_alloc_inode(struct super_block *sb)
956 {
957         struct ext4_inode_info *ei;
958
959         ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
960         if (!ei)
961                 return NULL;
962
963         ei->vfs_inode.i_version = 1;
964         spin_lock_init(&ei->i_raw_lock);
965         INIT_LIST_HEAD(&ei->i_prealloc_list);
966         spin_lock_init(&ei->i_prealloc_lock);
967         ext4_es_init_tree(&ei->i_es_tree);
968         rwlock_init(&ei->i_es_lock);
969         INIT_LIST_HEAD(&ei->i_es_list);
970         ei->i_es_all_nr = 0;
971         ei->i_es_shk_nr = 0;
972         ei->i_es_shrink_lblk = 0;
973         ei->i_reserved_data_blocks = 0;
974         ei->i_reserved_meta_blocks = 0;
975         ei->i_allocated_meta_blocks = 0;
976         ei->i_da_metadata_calc_len = 0;
977         ei->i_da_metadata_calc_last_lblock = 0;
978         spin_lock_init(&(ei->i_block_reservation_lock));
979 #ifdef CONFIG_QUOTA
980         ei->i_reserved_quota = 0;
981         memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
982 #endif
983         ei->jinode = NULL;
984         INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
985         spin_lock_init(&ei->i_completed_io_lock);
986         ei->i_sync_tid = 0;
987         ei->i_datasync_tid = 0;
988         atomic_set(&ei->i_unwritten, 0);
989         INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
990         return &ei->vfs_inode;
991 }
992
993 static int ext4_drop_inode(struct inode *inode)
994 {
995         int drop = generic_drop_inode(inode);
996
997         trace_ext4_drop_inode(inode, drop);
998         return drop;
999 }
1000
1001 static void ext4_i_callback(struct rcu_head *head)
1002 {
1003         struct inode *inode = container_of(head, struct inode, i_rcu);
1004         kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
1005 }
1006
1007 static void ext4_destroy_inode(struct inode *inode)
1008 {
1009         if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
1010                 ext4_msg(inode->i_sb, KERN_ERR,
1011                          "Inode %lu (%p): orphan list check failed!",
1012                          inode->i_ino, EXT4_I(inode));
1013                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
1014                                 EXT4_I(inode), sizeof(struct ext4_inode_info),
1015                                 true);
1016                 dump_stack();
1017         }
1018         call_rcu(&inode->i_rcu, ext4_i_callback);
1019 }
1020
1021 static void init_once(void *foo)
1022 {
1023         struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
1024
1025         INIT_LIST_HEAD(&ei->i_orphan);
1026         init_rwsem(&ei->xattr_sem);
1027         init_rwsem(&ei->i_data_sem);
1028         init_rwsem(&ei->i_mmap_sem);
1029         inode_init_once(&ei->vfs_inode);
1030 }
1031
1032 static int __init init_inodecache(void)
1033 {
1034         ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
1035                                              sizeof(struct ext4_inode_info),
1036                                              0, (SLAB_RECLAIM_ACCOUNT|
1037                                                 SLAB_MEM_SPREAD|SLAB_ACCOUNT),
1038                                              init_once);
1039         if (ext4_inode_cachep == NULL)
1040                 return -ENOMEM;
1041         return 0;
1042 }
1043
1044 static void destroy_inodecache(void)
1045 {
1046         /*
1047          * Make sure all delayed rcu free inodes are flushed before we
1048          * destroy cache.
1049          */
1050         rcu_barrier();
1051         kmem_cache_destroy(ext4_inode_cachep);
1052 }
1053
1054 void ext4_clear_inode(struct inode *inode)
1055 {
1056         invalidate_inode_buffers(inode);
1057         clear_inode(inode);
1058         dquot_drop(inode);
1059         ext4_discard_preallocations(inode);
1060         ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
1061         if (EXT4_I(inode)->jinode) {
1062                 jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
1063                                                EXT4_I(inode)->jinode);
1064                 jbd2_free_inode(EXT4_I(inode)->jinode);
1065                 EXT4_I(inode)->jinode = NULL;
1066         }
1067 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1068         fscrypt_put_encryption_info(inode, NULL);
1069 #endif
1070 }
1071
1072 static struct inode *ext4_nfs_get_inode(struct super_block *sb,
1073                                         u64 ino, u32 generation)
1074 {
1075         struct inode *inode;
1076
1077         if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
1078                 return ERR_PTR(-ESTALE);
1079         if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
1080                 return ERR_PTR(-ESTALE);
1081
1082         /* iget isn't really right if the inode is currently unallocated!!
1083          *
1084          * ext4_read_inode will return a bad_inode if the inode had been
1085          * deleted, so we should be safe.
1086          *
1087          * Currently we don't know the generation for parent directory, so
1088          * a generation of 0 means "accept any"
1089          */
1090         inode = ext4_iget_normal(sb, ino);
1091         if (IS_ERR(inode))
1092                 return ERR_CAST(inode);
1093         if (generation && inode->i_generation != generation) {
1094                 iput(inode);
1095                 return ERR_PTR(-ESTALE);
1096         }
1097
1098         return inode;
1099 }
1100
1101 static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
1102                                         int fh_len, int fh_type)
1103 {
1104         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1105                                     ext4_nfs_get_inode);
1106 }
1107
1108 static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
1109                                         int fh_len, int fh_type)
1110 {
1111         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1112                                     ext4_nfs_get_inode);
1113 }
1114
1115 /*
1116  * Try to release metadata pages (indirect blocks, directories) which are
1117  * mapped via the block device.  Since these pages could have journal heads
1118  * which would prevent try_to_free_buffers() from freeing them, we must use
1119  * jbd2 layer's try_to_free_buffers() function to release them.
1120  */
1121 static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
1122                                  gfp_t wait)
1123 {
1124         journal_t *journal = EXT4_SB(sb)->s_journal;
1125
1126         WARN_ON(PageChecked(page));
1127         if (!page_has_buffers(page))
1128                 return 0;
1129         if (journal)
1130                 return jbd2_journal_try_to_free_buffers(journal, page,
1131                                                 wait & ~__GFP_DIRECT_RECLAIM);
1132         return try_to_free_buffers(page);
1133 }
1134
1135 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1136 static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
1137 {
1138         return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
1139                                  EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
1140 }
1141
1142 static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
1143                                                         void *fs_data)
1144 {
1145         handle_t *handle = fs_data;
1146         int res, res2, retries = 0;
1147
1148         res = ext4_convert_inline_data(inode);
1149         if (res)
1150                 return res;
1151
1152         /*
1153          * If a journal handle was specified, then the encryption context is
1154          * being set on a new inode via inheritance and is part of a larger
1155          * transaction to create the inode.  Otherwise the encryption context is
1156          * being set on an existing inode in its own transaction.  Only in the
1157          * latter case should the "retry on ENOSPC" logic be used.
1158          */
1159
1160         if (handle) {
1161                 res = ext4_xattr_set_handle(handle, inode,
1162                                             EXT4_XATTR_INDEX_ENCRYPTION,
1163                                             EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1164                                             ctx, len, 0);
1165                 if (!res) {
1166                         ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1167                         ext4_clear_inode_state(inode,
1168                                         EXT4_STATE_MAY_INLINE_DATA);
1169                         /*
1170                          * Update inode->i_flags - e.g. S_DAX may get disabled
1171                          */
1172                         ext4_set_inode_flags(inode);
1173                 }
1174                 return res;
1175         }
1176
1177 retry:
1178         handle = ext4_journal_start(inode, EXT4_HT_MISC,
1179                         ext4_jbd2_credits_xattr(inode));
1180         if (IS_ERR(handle))
1181                 return PTR_ERR(handle);
1182
1183         res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
1184                                     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1185                                     ctx, len, 0);
1186         if (!res) {
1187                 ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1188                 /* Update inode->i_flags - e.g. S_DAX may get disabled */
1189                 ext4_set_inode_flags(inode);
1190                 res = ext4_mark_inode_dirty(handle, inode);
1191                 if (res)
1192                         EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
1193         }
1194         res2 = ext4_journal_stop(handle);
1195
1196         if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1197                 goto retry;
1198         if (!res)
1199                 res = res2;
1200         return res;
1201 }
1202
1203 static int ext4_dummy_context(struct inode *inode)
1204 {
1205         return DUMMY_ENCRYPTION_ENABLED(EXT4_SB(inode->i_sb));
1206 }
1207
1208 static unsigned ext4_max_namelen(struct inode *inode)
1209 {
1210         return S_ISLNK(inode->i_mode) ? inode->i_sb->s_blocksize :
1211                 EXT4_NAME_LEN;
1212 }
1213
1214 static const struct fscrypt_operations ext4_cryptops = {
1215         .key_prefix             = "ext4:",
1216         .get_context            = ext4_get_context,
1217         .set_context            = ext4_set_context,
1218         .dummy_context          = ext4_dummy_context,
1219         .is_encrypted           = ext4_encrypted_inode,
1220         .empty_dir              = ext4_empty_dir,
1221         .max_namelen            = ext4_max_namelen,
1222 };
1223 #else
1224 static const struct fscrypt_operations ext4_cryptops = {
1225         .is_encrypted           = ext4_encrypted_inode,
1226 };
1227 #endif
1228
1229 #ifdef CONFIG_QUOTA
1230 static const char * const quotatypes[] = INITQFNAMES;
1231 #define QTYPE2NAME(t) (quotatypes[t])
1232
1233 static int ext4_write_dquot(struct dquot *dquot);
1234 static int ext4_acquire_dquot(struct dquot *dquot);
1235 static int ext4_release_dquot(struct dquot *dquot);
1236 static int ext4_mark_dquot_dirty(struct dquot *dquot);
1237 static int ext4_write_info(struct super_block *sb, int type);
1238 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
1239                          const struct path *path);
1240 static int ext4_quota_on_mount(struct super_block *sb, int type);
1241 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
1242                                size_t len, loff_t off);
1243 static ssize_t ext4_quota_write(struct super_block *sb, int type,
1244                                 const char *data, size_t len, loff_t off);
1245 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
1246                              unsigned int flags);
1247 static int ext4_enable_quotas(struct super_block *sb);
1248 static int ext4_get_next_id(struct super_block *sb, struct kqid *qid);
1249
1250 static struct dquot **ext4_get_dquots(struct inode *inode)
1251 {
1252         return EXT4_I(inode)->i_dquot;
1253 }
1254
1255 static const struct dquot_operations ext4_quota_operations = {
1256         .get_reserved_space = ext4_get_reserved_space,
1257         .write_dquot    = ext4_write_dquot,
1258         .acquire_dquot  = ext4_acquire_dquot,
1259         .release_dquot  = ext4_release_dquot,
1260         .mark_dirty     = ext4_mark_dquot_dirty,
1261         .write_info     = ext4_write_info,
1262         .alloc_dquot    = dquot_alloc,
1263         .destroy_dquot  = dquot_destroy,
1264         .get_projid     = ext4_get_projid,
1265         .get_next_id    = ext4_get_next_id,
1266 };
1267
1268 static const struct quotactl_ops ext4_qctl_operations = {
1269         .quota_on       = ext4_quota_on,
1270         .quota_off      = ext4_quota_off,
1271         .quota_sync     = dquot_quota_sync,
1272         .get_state      = dquot_get_state,
1273         .set_info       = dquot_set_dqinfo,
1274         .get_dqblk      = dquot_get_dqblk,
1275         .set_dqblk      = dquot_set_dqblk,
1276         .get_nextdqblk  = dquot_get_next_dqblk,
1277 };
1278 #endif
1279
1280 static const struct super_operations ext4_sops = {
1281         .alloc_inode    = ext4_alloc_inode,
1282         .destroy_inode  = ext4_destroy_inode,
1283         .write_inode    = ext4_write_inode,
1284         .dirty_inode    = ext4_dirty_inode,
1285         .drop_inode     = ext4_drop_inode,
1286         .evict_inode    = ext4_evict_inode,
1287         .put_super      = ext4_put_super,
1288         .sync_fs        = ext4_sync_fs,
1289         .freeze_fs      = ext4_freeze,
1290         .unfreeze_fs    = ext4_unfreeze,
1291         .statfs         = ext4_statfs,
1292         .remount_fs     = ext4_remount,
1293         .show_options   = ext4_show_options,
1294 #ifdef CONFIG_QUOTA
1295         .quota_read     = ext4_quota_read,
1296         .quota_write    = ext4_quota_write,
1297         .get_dquots     = ext4_get_dquots,
1298 #endif
1299         .bdev_try_to_free_page = bdev_try_to_free_page,
1300 };
1301
1302 static const struct export_operations ext4_export_ops = {
1303         .fh_to_dentry = ext4_fh_to_dentry,
1304         .fh_to_parent = ext4_fh_to_parent,
1305         .get_parent = ext4_get_parent,
1306 };
1307
1308 enum {
1309         Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
1310         Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
1311         Opt_nouid32, Opt_debug, Opt_removed,
1312         Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
1313         Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
1314         Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
1315         Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
1316         Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
1317         Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
1318         Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
1319         Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
1320         Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
1321         Opt_usrquota, Opt_grpquota, Opt_prjquota, Opt_i_version, Opt_dax,
1322         Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
1323         Opt_lazytime, Opt_nolazytime, Opt_debug_want_extra_isize,
1324         Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
1325         Opt_inode_readahead_blks, Opt_journal_ioprio,
1326         Opt_dioread_nolock, Opt_dioread_lock,
1327         Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
1328         Opt_max_dir_size_kb, Opt_nojournal_checksum,
1329 };
1330
1331 static const match_table_t tokens = {
1332         {Opt_bsd_df, "bsddf"},
1333         {Opt_minix_df, "minixdf"},
1334         {Opt_grpid, "grpid"},
1335         {Opt_grpid, "bsdgroups"},
1336         {Opt_nogrpid, "nogrpid"},
1337         {Opt_nogrpid, "sysvgroups"},
1338         {Opt_resgid, "resgid=%u"},
1339         {Opt_resuid, "resuid=%u"},
1340         {Opt_sb, "sb=%u"},
1341         {Opt_err_cont, "errors=continue"},
1342         {Opt_err_panic, "errors=panic"},
1343         {Opt_err_ro, "errors=remount-ro"},
1344         {Opt_nouid32, "nouid32"},
1345         {Opt_debug, "debug"},
1346         {Opt_removed, "oldalloc"},
1347         {Opt_removed, "orlov"},
1348         {Opt_user_xattr, "user_xattr"},
1349         {Opt_nouser_xattr, "nouser_xattr"},
1350         {Opt_acl, "acl"},
1351         {Opt_noacl, "noacl"},
1352         {Opt_noload, "norecovery"},
1353         {Opt_noload, "noload"},
1354         {Opt_removed, "nobh"},
1355         {Opt_removed, "bh"},
1356         {Opt_commit, "commit=%u"},
1357         {Opt_min_batch_time, "min_batch_time=%u"},
1358         {Opt_max_batch_time, "max_batch_time=%u"},
1359         {Opt_journal_dev, "journal_dev=%u"},
1360         {Opt_journal_path, "journal_path=%s"},
1361         {Opt_journal_checksum, "journal_checksum"},
1362         {Opt_nojournal_checksum, "nojournal_checksum"},
1363         {Opt_journal_async_commit, "journal_async_commit"},
1364         {Opt_abort, "abort"},
1365         {Opt_data_journal, "data=journal"},
1366         {Opt_data_ordered, "data=ordered"},
1367         {Opt_data_writeback, "data=writeback"},
1368         {Opt_data_err_abort, "data_err=abort"},
1369         {Opt_data_err_ignore, "data_err=ignore"},
1370         {Opt_offusrjquota, "usrjquota="},
1371         {Opt_usrjquota, "usrjquota=%s"},
1372         {Opt_offgrpjquota, "grpjquota="},
1373         {Opt_grpjquota, "grpjquota=%s"},
1374         {Opt_jqfmt_vfsold, "jqfmt=vfsold"},
1375         {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
1376         {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
1377         {Opt_grpquota, "grpquota"},
1378         {Opt_noquota, "noquota"},
1379         {Opt_quota, "quota"},
1380         {Opt_usrquota, "usrquota"},
1381         {Opt_prjquota, "prjquota"},
1382         {Opt_barrier, "barrier=%u"},
1383         {Opt_barrier, "barrier"},
1384         {Opt_nobarrier, "nobarrier"},
1385         {Opt_i_version, "i_version"},
1386         {Opt_dax, "dax"},
1387         {Opt_stripe, "stripe=%u"},
1388         {Opt_delalloc, "delalloc"},
1389         {Opt_lazytime, "lazytime"},
1390         {Opt_nolazytime, "nolazytime"},
1391         {Opt_debug_want_extra_isize, "debug_want_extra_isize=%u"},
1392         {Opt_nodelalloc, "nodelalloc"},
1393         {Opt_removed, "mblk_io_submit"},
1394         {Opt_removed, "nomblk_io_submit"},
1395         {Opt_block_validity, "block_validity"},
1396         {Opt_noblock_validity, "noblock_validity"},
1397         {Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
1398         {Opt_journal_ioprio, "journal_ioprio=%u"},
1399         {Opt_auto_da_alloc, "auto_da_alloc=%u"},
1400         {Opt_auto_da_alloc, "auto_da_alloc"},
1401         {Opt_noauto_da_alloc, "noauto_da_alloc"},
1402         {Opt_dioread_nolock, "dioread_nolock"},
1403         {Opt_dioread_lock, "dioread_lock"},
1404         {Opt_discard, "discard"},
1405         {Opt_nodiscard, "nodiscard"},
1406         {Opt_init_itable, "init_itable=%u"},
1407         {Opt_init_itable, "init_itable"},
1408         {Opt_noinit_itable, "noinit_itable"},
1409         {Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
1410         {Opt_test_dummy_encryption, "test_dummy_encryption"},
1411         {Opt_removed, "check=none"},    /* mount option from ext2/3 */
1412         {Opt_removed, "nocheck"},       /* mount option from ext2/3 */
1413         {Opt_removed, "reservation"},   /* mount option from ext2/3 */
1414         {Opt_removed, "noreservation"}, /* mount option from ext2/3 */
1415         {Opt_removed, "journal=%u"},    /* mount option from ext2/3 */
1416         {Opt_err, NULL},
1417 };
1418
1419 static ext4_fsblk_t get_sb_block(void **data)
1420 {
1421         ext4_fsblk_t    sb_block;
1422         char            *options = (char *) *data;
1423
1424         if (!options || strncmp(options, "sb=", 3) != 0)
1425                 return 1;       /* Default location */
1426
1427         options += 3;
1428         /* TODO: use simple_strtoll with >32bit ext4 */
1429         sb_block = simple_strtoul(options, &options, 0);
1430         if (*options && *options != ',') {
1431                 printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
1432                        (char *) *data);
1433                 return 1;
1434         }
1435         if (*options == ',')
1436                 options++;
1437         *data = (void *) options;
1438
1439         return sb_block;
1440 }
1441
1442 #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
1443 static const char deprecated_msg[] =
1444         "Mount option \"%s\" will be removed by %s\n"
1445         "Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
1446
1447 #ifdef CONFIG_QUOTA
1448 static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
1449 {
1450         struct ext4_sb_info *sbi = EXT4_SB(sb);
1451         char *qname;
1452         int ret = -1;
1453
1454         if (sb_any_quota_loaded(sb) &&
1455                 !sbi->s_qf_names[qtype]) {
1456                 ext4_msg(sb, KERN_ERR,
1457                         "Cannot change journaled "
1458                         "quota options when quota turned on");
1459                 return -1;
1460         }
1461         if (ext4_has_feature_quota(sb)) {
1462                 ext4_msg(sb, KERN_INFO, "Journaled quota options "
1463                          "ignored when QUOTA feature is enabled");
1464                 return 1;
1465         }
1466         qname = match_strdup(args);
1467         if (!qname) {
1468                 ext4_msg(sb, KERN_ERR,
1469                         "Not enough memory for storing quotafile name");
1470                 return -1;
1471         }
1472         if (sbi->s_qf_names[qtype]) {
1473                 if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
1474                         ret = 1;
1475                 else
1476                         ext4_msg(sb, KERN_ERR,
1477                                  "%s quota file already specified",
1478                                  QTYPE2NAME(qtype));
1479                 goto errout;
1480         }
1481         if (strchr(qname, '/')) {
1482                 ext4_msg(sb, KERN_ERR,
1483                         "quotafile must be on filesystem root");
1484                 goto errout;
1485         }
1486         sbi->s_qf_names[qtype] = qname;
1487         set_opt(sb, QUOTA);
1488         return 1;
1489 errout:
1490         kfree(qname);
1491         return ret;
1492 }
1493
1494 static int clear_qf_name(struct super_block *sb, int qtype)
1495 {
1496
1497         struct ext4_sb_info *sbi = EXT4_SB(sb);
1498
1499         if (sb_any_quota_loaded(sb) &&
1500                 sbi->s_qf_names[qtype]) {
1501                 ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
1502                         " when quota turned on");
1503                 return -1;
1504         }
1505         kfree(sbi->s_qf_names[qtype]);
1506         sbi->s_qf_names[qtype] = NULL;
1507         return 1;
1508 }
1509 #endif
1510
1511 #define MOPT_SET        0x0001
1512 #define MOPT_CLEAR      0x0002
1513 #define MOPT_NOSUPPORT  0x0004
1514 #define MOPT_EXPLICIT   0x0008
1515 #define MOPT_CLEAR_ERR  0x0010
1516 #define MOPT_GTE0       0x0020
1517 #ifdef CONFIG_QUOTA
1518 #define MOPT_Q          0
1519 #define MOPT_QFMT       0x0040
1520 #else
1521 #define MOPT_Q          MOPT_NOSUPPORT
1522 #define MOPT_QFMT       MOPT_NOSUPPORT
1523 #endif
1524 #define MOPT_DATAJ      0x0080
1525 #define MOPT_NO_EXT2    0x0100
1526 #define MOPT_NO_EXT3    0x0200
1527 #define MOPT_EXT4_ONLY  (MOPT_NO_EXT2 | MOPT_NO_EXT3)
1528 #define MOPT_STRING     0x0400
1529
1530 static const struct mount_opts {
1531         int     token;
1532         int     mount_opt;
1533         int     flags;
1534 } ext4_mount_opts[] = {
1535         {Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
1536         {Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
1537         {Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
1538         {Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
1539         {Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
1540         {Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
1541         {Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
1542          MOPT_EXT4_ONLY | MOPT_SET},
1543         {Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
1544          MOPT_EXT4_ONLY | MOPT_CLEAR},
1545         {Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
1546         {Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
1547         {Opt_delalloc, EXT4_MOUNT_DELALLOC,
1548          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1549         {Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
1550          MOPT_EXT4_ONLY | MOPT_CLEAR},
1551         {Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1552          MOPT_EXT4_ONLY | MOPT_CLEAR},
1553         {Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1554          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1555         {Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
1556                                     EXT4_MOUNT_JOURNAL_CHECKSUM),
1557          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1558         {Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
1559         {Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
1560         {Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
1561         {Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
1562         {Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
1563          MOPT_NO_EXT2},
1564         {Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
1565          MOPT_NO_EXT2},
1566         {Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
1567         {Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
1568         {Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
1569         {Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
1570         {Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
1571         {Opt_commit, 0, MOPT_GTE0},
1572         {Opt_max_batch_time, 0, MOPT_GTE0},
1573         {Opt_min_batch_time, 0, MOPT_GTE0},
1574         {Opt_inode_readahead_blks, 0, MOPT_GTE0},
1575         {Opt_init_itable, 0, MOPT_GTE0},
1576         {Opt_dax, EXT4_MOUNT_DAX, MOPT_SET},
1577         {Opt_stripe, 0, MOPT_GTE0},
1578         {Opt_resuid, 0, MOPT_GTE0},
1579         {Opt_resgid, 0, MOPT_GTE0},
1580         {Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1581         {Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
1582         {Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1583         {Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1584         {Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1585         {Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
1586          MOPT_NO_EXT2 | MOPT_DATAJ},
1587         {Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
1588         {Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
1589 #ifdef CONFIG_EXT4_FS_POSIX_ACL
1590         {Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
1591         {Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
1592 #else
1593         {Opt_acl, 0, MOPT_NOSUPPORT},
1594         {Opt_noacl, 0, MOPT_NOSUPPORT},
1595 #endif
1596         {Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
1597         {Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
1598         {Opt_debug_want_extra_isize, 0, MOPT_GTE0},
1599         {Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
1600         {Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
1601                                                         MOPT_SET | MOPT_Q},
1602         {Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
1603                                                         MOPT_SET | MOPT_Q},
1604         {Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
1605                                                         MOPT_SET | MOPT_Q},
1606         {Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
1607                        EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
1608                                                         MOPT_CLEAR | MOPT_Q},
1609         {Opt_usrjquota, 0, MOPT_Q},
1610         {Opt_grpjquota, 0, MOPT_Q},
1611         {Opt_offusrjquota, 0, MOPT_Q},
1612         {Opt_offgrpjquota, 0, MOPT_Q},
1613         {Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
1614         {Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
1615         {Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
1616         {Opt_max_dir_size_kb, 0, MOPT_GTE0},
1617         {Opt_test_dummy_encryption, 0, MOPT_GTE0},
1618         {Opt_err, 0, 0}
1619 };
1620
1621 static int handle_mount_opt(struct super_block *sb, char *opt, int token,
1622                             substring_t *args, unsigned long *journal_devnum,
1623                             unsigned int *journal_ioprio, int is_remount)
1624 {
1625         struct ext4_sb_info *sbi = EXT4_SB(sb);
1626         const struct mount_opts *m;
1627         kuid_t uid;
1628         kgid_t gid;
1629         int arg = 0;
1630
1631 #ifdef CONFIG_QUOTA
1632         if (token == Opt_usrjquota)
1633                 return set_qf_name(sb, USRQUOTA, &args[0]);
1634         else if (token == Opt_grpjquota)
1635                 return set_qf_name(sb, GRPQUOTA, &args[0]);
1636         else if (token == Opt_offusrjquota)
1637                 return clear_qf_name(sb, USRQUOTA);
1638         else if (token == Opt_offgrpjquota)
1639                 return clear_qf_name(sb, GRPQUOTA);
1640 #endif
1641         switch (token) {
1642         case Opt_noacl:
1643         case Opt_nouser_xattr:
1644                 ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
1645                 break;
1646         case Opt_sb:
1647                 return 1;       /* handled by get_sb_block() */
1648         case Opt_removed:
1649                 ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
1650                 return 1;
1651         case Opt_abort:
1652                 sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
1653                 return 1;
1654         case Opt_i_version:
1655                 sb->s_flags |= MS_I_VERSION;
1656                 return 1;
1657         case Opt_lazytime:
1658                 sb->s_flags |= MS_LAZYTIME;
1659                 return 1;
1660         case Opt_nolazytime:
1661                 sb->s_flags &= ~MS_LAZYTIME;
1662                 return 1;
1663         }
1664
1665         for (m = ext4_mount_opts; m->token != Opt_err; m++)
1666                 if (token == m->token)
1667                         break;
1668
1669         if (m->token == Opt_err) {
1670                 ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
1671                          "or missing value", opt);
1672                 return -1;
1673         }
1674
1675         if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
1676                 ext4_msg(sb, KERN_ERR,
1677                          "Mount option \"%s\" incompatible with ext2", opt);
1678                 return -1;
1679         }
1680         if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
1681                 ext4_msg(sb, KERN_ERR,
1682                          "Mount option \"%s\" incompatible with ext3", opt);
1683                 return -1;
1684         }
1685
1686         if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
1687                 return -1;
1688         if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
1689                 return -1;
1690         if (m->flags & MOPT_EXPLICIT) {
1691                 if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
1692                         set_opt2(sb, EXPLICIT_DELALLOC);
1693                 } else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
1694                         set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
1695                 } else
1696                         return -1;
1697         }
1698         if (m->flags & MOPT_CLEAR_ERR)
1699                 clear_opt(sb, ERRORS_MASK);
1700         if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
1701                 ext4_msg(sb, KERN_ERR, "Cannot change quota "
1702                          "options when quota turned on");
1703                 return -1;
1704         }
1705
1706         if (m->flags & MOPT_NOSUPPORT) {
1707                 ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
1708         } else if (token == Opt_commit) {
1709                 if (arg == 0)
1710                         arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
1711                 sbi->s_commit_interval = HZ * arg;
1712         } else if (token == Opt_debug_want_extra_isize) {
1713                 sbi->s_want_extra_isize = arg;
1714         } else if (token == Opt_max_batch_time) {
1715                 sbi->s_max_batch_time = arg;
1716         } else if (token == Opt_min_batch_time) {
1717                 sbi->s_min_batch_time = arg;
1718         } else if (token == Opt_inode_readahead_blks) {
1719                 if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
1720                         ext4_msg(sb, KERN_ERR,
1721                                  "EXT4-fs: inode_readahead_blks must be "
1722                                  "0 or a power of 2 smaller than 2^31");
1723                         return -1;
1724                 }
1725                 sbi->s_inode_readahead_blks = arg;
1726         } else if (token == Opt_init_itable) {
1727                 set_opt(sb, INIT_INODE_TABLE);
1728                 if (!args->from)
1729                         arg = EXT4_DEF_LI_WAIT_MULT;
1730                 sbi->s_li_wait_mult = arg;
1731         } else if (token == Opt_max_dir_size_kb) {
1732                 sbi->s_max_dir_size_kb = arg;
1733         } else if (token == Opt_stripe) {
1734                 sbi->s_stripe = arg;
1735         } else if (token == Opt_resuid) {
1736                 uid = make_kuid(current_user_ns(), arg);
1737                 if (!uid_valid(uid)) {
1738                         ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
1739                         return -1;
1740                 }
1741                 sbi->s_resuid = uid;
1742         } else if (token == Opt_resgid) {
1743                 gid = make_kgid(current_user_ns(), arg);
1744                 if (!gid_valid(gid)) {
1745                         ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
1746                         return -1;
1747                 }
1748                 sbi->s_resgid = gid;
1749         } else if (token == Opt_journal_dev) {
1750                 if (is_remount) {
1751                         ext4_msg(sb, KERN_ERR,
1752                                  "Cannot specify journal on remount");
1753                         return -1;
1754                 }
1755                 *journal_devnum = arg;
1756         } else if (token == Opt_journal_path) {
1757                 char *journal_path;
1758                 struct inode *journal_inode;
1759                 struct path path;
1760                 int error;
1761
1762                 if (is_remount) {
1763                         ext4_msg(sb, KERN_ERR,
1764                                  "Cannot specify journal on remount");
1765                         return -1;
1766                 }
1767                 journal_path = match_strdup(&args[0]);
1768                 if (!journal_path) {
1769                         ext4_msg(sb, KERN_ERR, "error: could not dup "
1770                                 "journal device string");
1771                         return -1;
1772                 }
1773
1774                 error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
1775                 if (error) {
1776                         ext4_msg(sb, KERN_ERR, "error: could not find "
1777                                 "journal device path: error %d", error);
1778                         kfree(journal_path);
1779                         return -1;
1780                 }
1781
1782                 journal_inode = d_inode(path.dentry);
1783                 if (!S_ISBLK(journal_inode->i_mode)) {
1784                         ext4_msg(sb, KERN_ERR, "error: journal path %s "
1785                                 "is not a block device", journal_path);
1786                         path_put(&path);
1787                         kfree(journal_path);
1788                         return -1;
1789                 }
1790
1791                 *journal_devnum = new_encode_dev(journal_inode->i_rdev);
1792                 path_put(&path);
1793                 kfree(journal_path);
1794         } else if (token == Opt_journal_ioprio) {
1795                 if (arg > 7) {
1796                         ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
1797                                  " (must be 0-7)");
1798                         return -1;
1799                 }
1800                 *journal_ioprio =
1801                         IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
1802         } else if (token == Opt_test_dummy_encryption) {
1803 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1804                 sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
1805                 ext4_msg(sb, KERN_WARNING,
1806                          "Test dummy encryption mode enabled");
1807 #else
1808                 ext4_msg(sb, KERN_WARNING,
1809                          "Test dummy encryption mount option ignored");
1810 #endif
1811         } else if (m->flags & MOPT_DATAJ) {
1812                 if (is_remount) {
1813                         if (!sbi->s_journal)
1814                                 ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
1815                         else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
1816                                 ext4_msg(sb, KERN_ERR,
1817                                          "Cannot change data mode on remount");
1818                                 return -1;
1819                         }
1820                 } else {
1821                         clear_opt(sb, DATA_FLAGS);
1822                         sbi->s_mount_opt |= m->mount_opt;
1823                 }
1824 #ifdef CONFIG_QUOTA
1825         } else if (m->flags & MOPT_QFMT) {
1826                 if (sb_any_quota_loaded(sb) &&
1827                     sbi->s_jquota_fmt != m->mount_opt) {
1828                         ext4_msg(sb, KERN_ERR, "Cannot change journaled "
1829                                  "quota options when quota turned on");
1830                         return -1;
1831                 }
1832                 if (ext4_has_feature_quota(sb)) {
1833                         ext4_msg(sb, KERN_INFO,
1834                                  "Quota format mount options ignored "
1835                                  "when QUOTA feature is enabled");
1836                         return 1;
1837                 }
1838                 sbi->s_jquota_fmt = m->mount_opt;
1839 #endif
1840         } else if (token == Opt_dax) {
1841 #ifdef CONFIG_FS_DAX
1842                 ext4_msg(sb, KERN_WARNING,
1843                 "DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
1844                         sbi->s_mount_opt |= m->mount_opt;
1845 #else
1846                 ext4_msg(sb, KERN_INFO, "dax option not supported");
1847                 return -1;
1848 #endif
1849         } else if (token == Opt_data_err_abort) {
1850                 sbi->s_mount_opt |= m->mount_opt;
1851         } else if (token == Opt_data_err_ignore) {
1852                 sbi->s_mount_opt &= ~m->mount_opt;
1853         } else {
1854                 if (!args->from)
1855                         arg = 1;
1856                 if (m->flags & MOPT_CLEAR)
1857                         arg = !arg;
1858                 else if (unlikely(!(m->flags & MOPT_SET))) {
1859                         ext4_msg(sb, KERN_WARNING,
1860                                  "buggy handling of option %s", opt);
1861                         WARN_ON(1);
1862                         return -1;
1863                 }
1864                 if (arg != 0)
1865                         sbi->s_mount_opt |= m->mount_opt;
1866                 else
1867                         sbi->s_mount_opt &= ~m->mount_opt;
1868         }
1869         return 1;
1870 }
1871
1872 static int parse_options(char *options, struct super_block *sb,
1873                          unsigned long *journal_devnum,
1874                          unsigned int *journal_ioprio,
1875                          int is_remount)
1876 {
1877         struct ext4_sb_info *sbi = EXT4_SB(sb);
1878         char *p;
1879         substring_t args[MAX_OPT_ARGS];
1880         int token;
1881
1882         if (!options)
1883                 return 1;
1884
1885         while ((p = strsep(&options, ",")) != NULL) {
1886                 if (!*p)
1887                         continue;
1888                 /*
1889                  * Initialize args struct so we know whether arg was
1890                  * found; some options take optional arguments.
1891                  */
1892                 args[0].to = args[0].from = NULL;
1893                 token = match_token(p, tokens, args);
1894                 if (handle_mount_opt(sb, p, token, args, journal_devnum,
1895                                      journal_ioprio, is_remount) < 0)
1896                         return 0;
1897         }
1898 #ifdef CONFIG_QUOTA
1899         /*
1900          * We do the test below only for project quotas. 'usrquota' and
1901          * 'grpquota' mount options are allowed even without quota feature
1902          * to support legacy quotas in quota files.
1903          */
1904         if (test_opt(sb, PRJQUOTA) && !ext4_has_feature_project(sb)) {
1905                 ext4_msg(sb, KERN_ERR, "Project quota feature not enabled. "
1906                          "Cannot enable project quota enforcement.");
1907                 return 0;
1908         }
1909         if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
1910                 if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
1911                         clear_opt(sb, USRQUOTA);
1912
1913                 if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
1914                         clear_opt(sb, GRPQUOTA);
1915
1916                 if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
1917                         ext4_msg(sb, KERN_ERR, "old and new quota "
1918                                         "format mixing");
1919                         return 0;
1920                 }
1921
1922                 if (!sbi->s_jquota_fmt) {
1923                         ext4_msg(sb, KERN_ERR, "journaled quota format "
1924                                         "not specified");
1925                         return 0;
1926                 }
1927         }
1928 #endif
1929         if (test_opt(sb, DIOREAD_NOLOCK)) {
1930                 int blocksize =
1931                         BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
1932
1933                 if (blocksize < PAGE_SIZE) {
1934                         ext4_msg(sb, KERN_ERR, "can't mount with "
1935                                  "dioread_nolock if block size != PAGE_SIZE");
1936                         return 0;
1937                 }
1938         }
1939         return 1;
1940 }
1941
1942 static inline void ext4_show_quota_options(struct seq_file *seq,
1943                                            struct super_block *sb)
1944 {
1945 #if defined(CONFIG_QUOTA)
1946         struct ext4_sb_info *sbi = EXT4_SB(sb);
1947
1948         if (sbi->s_jquota_fmt) {
1949                 char *fmtname = "";
1950
1951                 switch (sbi->s_jquota_fmt) {
1952                 case QFMT_VFS_OLD:
1953                         fmtname = "vfsold";
1954                         break;
1955                 case QFMT_VFS_V0:
1956                         fmtname = "vfsv0";
1957                         break;
1958                 case QFMT_VFS_V1:
1959                         fmtname = "vfsv1";
1960                         break;
1961                 }
1962                 seq_printf(seq, ",jqfmt=%s", fmtname);
1963         }
1964
1965         if (sbi->s_qf_names[USRQUOTA])
1966                 seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]);
1967
1968         if (sbi->s_qf_names[GRPQUOTA])
1969                 seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]);
1970 #endif
1971 }
1972
1973 static const char *token2str(int token)
1974 {
1975         const struct match_token *t;
1976
1977         for (t = tokens; t->token != Opt_err; t++)
1978                 if (t->token == token && !strchr(t->pattern, '='))
1979                         break;
1980         return t->pattern;
1981 }
1982
1983 /*
1984  * Show an option if
1985  *  - it's set to a non-default value OR
1986  *  - if the per-sb default is different from the global default
1987  */
1988 static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
1989                               int nodefs)
1990 {
1991         struct ext4_sb_info *sbi = EXT4_SB(sb);
1992         struct ext4_super_block *es = sbi->s_es;
1993         int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
1994         const struct mount_opts *m;
1995         char sep = nodefs ? '\n' : ',';
1996
1997 #define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
1998 #define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
1999
2000         if (sbi->s_sb_block != 1)
2001                 SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
2002
2003         for (m = ext4_mount_opts; m->token != Opt_err; m++) {
2004                 int want_set = m->flags & MOPT_SET;
2005                 if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
2006                     (m->flags & MOPT_CLEAR_ERR))
2007                         continue;
2008                 if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
2009                         continue; /* skip if same as the default */
2010                 if ((want_set &&
2011                      (sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
2012                     (!want_set && (sbi->s_mount_opt & m->mount_opt)))
2013                         continue; /* select Opt_noFoo vs Opt_Foo */
2014                 SEQ_OPTS_PRINT("%s", token2str(m->token));
2015         }
2016
2017         if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
2018             le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
2019                 SEQ_OPTS_PRINT("resuid=%u",
2020                                 from_kuid_munged(&init_user_ns, sbi->s_resuid));
2021         if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
2022             le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
2023                 SEQ_OPTS_PRINT("resgid=%u",
2024                                 from_kgid_munged(&init_user_ns, sbi->s_resgid));
2025         def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
2026         if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
2027                 SEQ_OPTS_PUTS("errors=remount-ro");
2028         if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
2029                 SEQ_OPTS_PUTS("errors=continue");
2030         if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
2031                 SEQ_OPTS_PUTS("errors=panic");
2032         if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
2033                 SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
2034         if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
2035                 SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
2036         if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
2037                 SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
2038         if (sb->s_flags & MS_I_VERSION)
2039                 SEQ_OPTS_PUTS("i_version");
2040         if (nodefs || sbi->s_stripe)
2041                 SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
2042         if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
2043                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
2044                         SEQ_OPTS_PUTS("data=journal");
2045                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
2046                         SEQ_OPTS_PUTS("data=ordered");
2047                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
2048                         SEQ_OPTS_PUTS("data=writeback");
2049         }
2050         if (nodefs ||
2051             sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
2052                 SEQ_OPTS_PRINT("inode_readahead_blks=%u",
2053                                sbi->s_inode_readahead_blks);
2054
2055         if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
2056                        (sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
2057                 SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
2058         if (nodefs || sbi->s_max_dir_size_kb)
2059                 SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
2060         if (test_opt(sb, DATA_ERR_ABORT))
2061                 SEQ_OPTS_PUTS("data_err=abort");
2062
2063         ext4_show_quota_options(seq, sb);
2064         return 0;
2065 }
2066
2067 static int ext4_show_options(struct seq_file *seq, struct dentry *root)
2068 {
2069         return _ext4_show_options(seq, root->d_sb, 0);
2070 }
2071
2072 int ext4_seq_options_show(struct seq_file *seq, void *offset)
2073 {
2074         struct super_block *sb = seq->private;
2075         int rc;
2076
2077         seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
2078         rc = _ext4_show_options(seq, sb, 1);
2079         seq_puts(seq, "\n");
2080         return rc;
2081 }
2082
2083 static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
2084                             int read_only)
2085 {
2086         struct ext4_sb_info *sbi = EXT4_SB(sb);
2087         int res = 0;
2088
2089         if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
2090                 ext4_msg(sb, KERN_ERR, "revision level too high, "
2091                          "forcing read-only mode");
2092                 res = MS_RDONLY;
2093         }
2094         if (read_only)
2095                 goto done;
2096         if (!(sbi->s_mount_state & EXT4_VALID_FS))
2097                 ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
2098                          "running e2fsck is recommended");
2099         else if (sbi->s_mount_state & EXT4_ERROR_FS)
2100                 ext4_msg(sb, KERN_WARNING,
2101                          "warning: mounting fs with errors, "
2102                          "running e2fsck is recommended");
2103         else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
2104                  le16_to_cpu(es->s_mnt_count) >=
2105                  (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
2106                 ext4_msg(sb, KERN_WARNING,
2107                          "warning: maximal mount count reached, "
2108                          "running e2fsck is recommended");
2109         else if (le32_to_cpu(es->s_checkinterval) &&
2110                 (le32_to_cpu(es->s_lastcheck) +
2111                         le32_to_cpu(es->s_checkinterval) <= get_seconds()))
2112                 ext4_msg(sb, KERN_WARNING,
2113                          "warning: checktime reached, "
2114                          "running e2fsck is recommended");
2115         if (!sbi->s_journal)
2116                 es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
2117         if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
2118                 es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
2119         le16_add_cpu(&es->s_mnt_count, 1);
2120         es->s_mtime = cpu_to_le32(get_seconds());
2121         ext4_update_dynamic_rev(sb);
2122         if (sbi->s_journal)
2123                 ext4_set_feature_journal_needs_recovery(sb);
2124
2125         ext4_commit_super(sb, 1);
2126 done:
2127         if (test_opt(sb, DEBUG))
2128                 printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
2129                                 "bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
2130                         sb->s_blocksize,
2131                         sbi->s_groups_count,
2132                         EXT4_BLOCKS_PER_GROUP(sb),
2133                         EXT4_INODES_PER_GROUP(sb),
2134                         sbi->s_mount_opt, sbi->s_mount_opt2);
2135
2136         cleancache_init_fs(sb);
2137         return res;
2138 }
2139
2140 int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
2141 {
2142         struct ext4_sb_info *sbi = EXT4_SB(sb);
2143         struct flex_groups *new_groups;
2144         int size;
2145
2146         if (!sbi->s_log_groups_per_flex)
2147                 return 0;
2148
2149         size = ext4_flex_group(sbi, ngroup - 1) + 1;
2150         if (size <= sbi->s_flex_groups_allocated)
2151                 return 0;
2152
2153         size = roundup_pow_of_two(size * sizeof(struct flex_groups));
2154         new_groups = kvzalloc(size, GFP_KERNEL);
2155         if (!new_groups) {
2156                 ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
2157                          size / (int) sizeof(struct flex_groups));
2158                 return -ENOMEM;
2159         }
2160
2161         if (sbi->s_flex_groups) {
2162                 memcpy(new_groups, sbi->s_flex_groups,
2163                        (sbi->s_flex_groups_allocated *
2164                         sizeof(struct flex_groups)));
2165                 kvfree(sbi->s_flex_groups);
2166         }
2167         sbi->s_flex_groups = new_groups;
2168         sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
2169         return 0;
2170 }
2171
2172 static int ext4_fill_flex_info(struct super_block *sb)
2173 {
2174         struct ext4_sb_info *sbi = EXT4_SB(sb);
2175         struct ext4_group_desc *gdp = NULL;
2176         ext4_group_t flex_group;
2177         int i, err;
2178
2179         sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
2180         if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
2181                 sbi->s_log_groups_per_flex = 0;
2182                 return 1;
2183         }
2184
2185         err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
2186         if (err)
2187                 goto failed;
2188
2189         for (i = 0; i < sbi->s_groups_count; i++) {
2190                 gdp = ext4_get_group_desc(sb, i, NULL);
2191
2192                 flex_group = ext4_flex_group(sbi, i);
2193                 atomic_add(ext4_free_inodes_count(sb, gdp),
2194                            &sbi->s_flex_groups[flex_group].free_inodes);
2195                 atomic64_add(ext4_free_group_clusters(sb, gdp),
2196                              &sbi->s_flex_groups[flex_group].free_clusters);
2197                 atomic_add(ext4_used_dirs_count(sb, gdp),
2198                            &sbi->s_flex_groups[flex_group].used_dirs);
2199         }
2200
2201         return 1;
2202 failed:
2203         return 0;
2204 }
2205
2206 static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
2207                                    struct ext4_group_desc *gdp)
2208 {
2209         int offset = offsetof(struct ext4_group_desc, bg_checksum);
2210         __u16 crc = 0;
2211         __le32 le_group = cpu_to_le32(block_group);
2212         struct ext4_sb_info *sbi = EXT4_SB(sb);
2213
2214         if (ext4_has_metadata_csum(sbi->s_sb)) {
2215                 /* Use new metadata_csum algorithm */
2216                 __u32 csum32;
2217                 __u16 dummy_csum = 0;
2218
2219                 csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
2220                                      sizeof(le_group));
2221                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
2222                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
2223                                      sizeof(dummy_csum));
2224                 offset += sizeof(dummy_csum);
2225                 if (offset < sbi->s_desc_size)
2226                         csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
2227                                              sbi->s_desc_size - offset);
2228
2229                 crc = csum32 & 0xFFFF;
2230                 goto out;
2231         }
2232
2233         /* old crc16 code */
2234         if (!ext4_has_feature_gdt_csum(sb))
2235                 return 0;
2236
2237         crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
2238         crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
2239         crc = crc16(crc, (__u8 *)gdp, offset);
2240         offset += sizeof(gdp->bg_checksum); /* skip checksum */
2241         /* for checksum of struct ext4_group_desc do the rest...*/
2242         if (ext4_has_feature_64bit(sb) &&
2243             offset < le16_to_cpu(sbi->s_es->s_desc_size))
2244                 crc = crc16(crc, (__u8 *)gdp + offset,
2245                             le16_to_cpu(sbi->s_es->s_desc_size) -
2246                                 offset);
2247
2248 out:
2249         return cpu_to_le16(crc);
2250 }
2251
2252 int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
2253                                 struct ext4_group_desc *gdp)
2254 {
2255         if (ext4_has_group_desc_csum(sb) &&
2256             (gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
2257                 return 0;
2258
2259         return 1;
2260 }
2261
2262 void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
2263                               struct ext4_group_desc *gdp)
2264 {
2265         if (!ext4_has_group_desc_csum(sb))
2266                 return;
2267         gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
2268 }
2269
2270 /* Called at mount-time, super-block is locked */
2271 static int ext4_check_descriptors(struct super_block *sb,
2272                                   ext4_fsblk_t sb_block,
2273                                   ext4_group_t *first_not_zeroed)
2274 {
2275         struct ext4_sb_info *sbi = EXT4_SB(sb);
2276         ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
2277         ext4_fsblk_t last_block;
2278         ext4_fsblk_t block_bitmap;
2279         ext4_fsblk_t inode_bitmap;
2280         ext4_fsblk_t inode_table;
2281         int flexbg_flag = 0;
2282         ext4_group_t i, grp = sbi->s_groups_count;
2283
2284         if (ext4_has_feature_flex_bg(sb))
2285                 flexbg_flag = 1;
2286
2287         ext4_debug("Checking group descriptors");
2288
2289         for (i = 0; i < sbi->s_groups_count; i++) {
2290                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
2291
2292                 if (i == sbi->s_groups_count - 1 || flexbg_flag)
2293                         last_block = ext4_blocks_count(sbi->s_es) - 1;
2294                 else
2295                         last_block = first_block +
2296                                 (EXT4_BLOCKS_PER_GROUP(sb) - 1);
2297
2298                 if ((grp == sbi->s_groups_count) &&
2299                    !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
2300                         grp = i;
2301
2302                 block_bitmap = ext4_block_bitmap(sb, gdp);
2303                 if (block_bitmap == sb_block) {
2304                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2305                                  "Block bitmap for group %u overlaps "
2306                                  "superblock", i);
2307                 }
2308                 if (block_bitmap < first_block || block_bitmap > last_block) {
2309                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2310                                "Block bitmap for group %u not in group "
2311                                "(block %llu)!", i, block_bitmap);
2312                         return 0;
2313                 }
2314                 inode_bitmap = ext4_inode_bitmap(sb, gdp);
2315                 if (inode_bitmap == sb_block) {
2316                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2317                                  "Inode bitmap for group %u overlaps "
2318                                  "superblock", i);
2319                 }
2320                 if (inode_bitmap < first_block || inode_bitmap > last_block) {
2321                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2322                                "Inode bitmap for group %u not in group "
2323                                "(block %llu)!", i, inode_bitmap);
2324                         return 0;
2325                 }
2326                 inode_table = ext4_inode_table(sb, gdp);
2327                 if (inode_table == sb_block) {
2328                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2329                                  "Inode table for group %u overlaps "
2330                                  "superblock", i);
2331                 }
2332                 if (inode_table < first_block ||
2333                     inode_table + sbi->s_itb_per_group - 1 > last_block) {
2334                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2335                                "Inode table for group %u not in group "
2336                                "(block %llu)!", i, inode_table);
2337                         return 0;
2338                 }
2339                 ext4_lock_group(sb, i);
2340                 if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
2341                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2342                                  "Checksum for group %u failed (%u!=%u)",
2343                                  i, le16_to_cpu(ext4_group_desc_csum(sb, i,
2344                                      gdp)), le16_to_cpu(gdp->bg_checksum));
2345                         if (!(sb->s_flags & MS_RDONLY)) {
2346                                 ext4_unlock_group(sb, i);
2347                                 return 0;
2348                         }
2349                 }
2350                 ext4_unlock_group(sb, i);
2351                 if (!flexbg_flag)
2352                         first_block += EXT4_BLOCKS_PER_GROUP(sb);
2353         }
2354         if (NULL != first_not_zeroed)
2355                 *first_not_zeroed = grp;
2356         return 1;
2357 }
2358
2359 /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
2360  * the superblock) which were deleted from all directories, but held open by
2361  * a process at the time of a crash.  We walk the list and try to delete these
2362  * inodes at recovery time (only with a read-write filesystem).
2363  *
2364  * In order to keep the orphan inode chain consistent during traversal (in
2365  * case of crash during recovery), we link each inode into the superblock
2366  * orphan list_head and handle it the same way as an inode deletion during
2367  * normal operation (which journals the operations for us).
2368  *
2369  * We only do an iget() and an iput() on each inode, which is very safe if we
2370  * accidentally point at an in-use or already deleted inode.  The worst that
2371  * can happen in this case is that we get a "bit already cleared" message from
2372  * ext4_free_inode().  The only reason we would point at a wrong inode is if
2373  * e2fsck was run on this filesystem, and it must have already done the orphan
2374  * inode cleanup for us, so we can safely abort without any further action.
2375  */
2376 static void ext4_orphan_cleanup(struct super_block *sb,
2377                                 struct ext4_super_block *es)
2378 {
2379         unsigned int s_flags = sb->s_flags;
2380         int ret, nr_orphans = 0, nr_truncates = 0;
2381 #ifdef CONFIG_QUOTA
2382         int i;
2383 #endif
2384         if (!es->s_last_orphan) {
2385                 jbd_debug(4, "no orphan inodes to clean up\n");
2386                 return;
2387         }
2388
2389         if (bdev_read_only(sb->s_bdev)) {
2390                 ext4_msg(sb, KERN_ERR, "write access "
2391                         "unavailable, skipping orphan cleanup");
2392                 return;
2393         }
2394
2395         /* Check if feature set would not allow a r/w mount */
2396         if (!ext4_feature_set_ok(sb, 0)) {
2397                 ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
2398                          "unknown ROCOMPAT features");
2399                 return;
2400         }
2401
2402         if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2403                 /* don't clear list on RO mount w/ errors */
2404                 if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
2405                         ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
2406                                   "clearing orphan list.\n");
2407                         es->s_last_orphan = 0;
2408                 }
2409                 jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2410                 return;
2411         }
2412
2413         if (s_flags & MS_RDONLY) {
2414                 ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
2415                 sb->s_flags &= ~MS_RDONLY;
2416         }
2417 #ifdef CONFIG_QUOTA
2418         /* Needed for iput() to work correctly and not trash data */
2419         sb->s_flags |= MS_ACTIVE;
2420         /* Turn on quotas so that they are updated correctly */
2421         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2422                 if (EXT4_SB(sb)->s_qf_names[i]) {
2423                         int ret = ext4_quota_on_mount(sb, i);
2424                         if (ret < 0)
2425                                 ext4_msg(sb, KERN_ERR,
2426                                         "Cannot turn on journaled "
2427                                         "quota: error %d", ret);
2428                 }
2429         }
2430 #endif
2431
2432         while (es->s_last_orphan) {
2433                 struct inode *inode;
2434
2435                 /*
2436                  * We may have encountered an error during cleanup; if
2437                  * so, skip the rest.
2438                  */
2439                 if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2440                         jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2441                         es->s_last_orphan = 0;
2442                         break;
2443                 }
2444
2445                 inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
2446                 if (IS_ERR(inode)) {
2447                         es->s_last_orphan = 0;
2448                         break;
2449                 }
2450
2451                 list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
2452                 dquot_initialize(inode);
2453                 if (inode->i_nlink) {
2454                         if (test_opt(sb, DEBUG))
2455                                 ext4_msg(sb, KERN_DEBUG,
2456                                         "%s: truncating inode %lu to %lld bytes",
2457                                         __func__, inode->i_ino, inode->i_size);
2458                         jbd_debug(2, "truncating inode %lu to %lld bytes\n",
2459                                   inode->i_ino, inode->i_size);
2460                         inode_lock(inode);
2461                         truncate_inode_pages(inode->i_mapping, inode->i_size);
2462                         ret = ext4_truncate(inode);
2463                         if (ret)
2464                                 ext4_std_error(inode->i_sb, ret);
2465                         inode_unlock(inode);
2466                         nr_truncates++;
2467                 } else {
2468                         if (test_opt(sb, DEBUG))
2469                                 ext4_msg(sb, KERN_DEBUG,
2470                                         "%s: deleting unreferenced inode %lu",
2471                                         __func__, inode->i_ino);
2472                         jbd_debug(2, "deleting unreferenced inode %lu\n",
2473                                   inode->i_ino);
2474                         nr_orphans++;
2475                 }
2476                 iput(inode);  /* The delete magic happens here! */
2477         }
2478
2479 #define PLURAL(x) (x), ((x) == 1) ? "" : "s"
2480
2481         if (nr_orphans)
2482                 ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
2483                        PLURAL(nr_orphans));
2484         if (nr_truncates)
2485                 ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
2486                        PLURAL(nr_truncates));
2487 #ifdef CONFIG_QUOTA
2488         /* Turn quotas off */
2489         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2490                 if (sb_dqopt(sb)->files[i])
2491                         dquot_quota_off(sb, i);
2492         }
2493 #endif
2494         sb->s_flags = s_flags; /* Restore MS_RDONLY status */
2495 }
2496
2497 /*
2498  * Maximal extent format file size.
2499  * Resulting logical blkno at s_maxbytes must fit in our on-disk
2500  * extent format containers, within a sector_t, and within i_blocks
2501  * in the vfs.  ext4 inode has 48 bits of i_block in fsblock units,
2502  * so that won't be a limiting factor.
2503  *
2504  * However there is other limiting factor. We do store extents in the form
2505  * of starting block and length, hence the resulting length of the extent
2506  * covering maximum file size must fit into on-disk format containers as
2507  * well. Given that length is always by 1 unit bigger than max unit (because
2508  * we count 0 as well) we have to lower the s_maxbytes by one fs block.
2509  *
2510  * Note, this does *not* consider any metadata overhead for vfs i_blocks.
2511  */
2512 static loff_t ext4_max_size(int blkbits, int has_huge_files)
2513 {
2514         loff_t res;
2515         loff_t upper_limit = MAX_LFS_FILESIZE;
2516
2517         /* small i_blocks in vfs inode? */
2518         if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
2519                 /*
2520                  * CONFIG_LBDAF is not enabled implies the inode
2521                  * i_block represent total blocks in 512 bytes
2522                  * 32 == size of vfs inode i_blocks * 8
2523                  */
2524                 upper_limit = (1LL << 32) - 1;
2525
2526                 /* total blocks in file system block size */
2527                 upper_limit >>= (blkbits - 9);
2528                 upper_limit <<= blkbits;
2529         }
2530
2531         /*
2532          * 32-bit extent-start container, ee_block. We lower the maxbytes
2533          * by one fs block, so ee_len can cover the extent of maximum file
2534          * size
2535          */
2536         res = (1LL << 32) - 1;
2537         res <<= blkbits;
2538
2539         /* Sanity check against vm- & vfs- imposed limits */
2540         if (res > upper_limit)
2541                 res = upper_limit;
2542
2543         return res;
2544 }
2545
2546 /*
2547  * Maximal bitmap file size.  There is a direct, and {,double-,triple-}indirect
2548  * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
2549  * We need to be 1 filesystem block less than the 2^48 sector limit.
2550  */
2551 static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
2552 {
2553         loff_t res = EXT4_NDIR_BLOCKS;
2554         int meta_blocks;
2555         loff_t upper_limit;
2556         /* This is calculated to be the largest file size for a dense, block
2557          * mapped file such that the file's total number of 512-byte sectors,
2558          * including data and all indirect blocks, does not exceed (2^48 - 1).
2559          *
2560          * __u32 i_blocks_lo and _u16 i_blocks_high represent the total
2561          * number of 512-byte sectors of the file.
2562          */
2563
2564         if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
2565                 /*
2566                  * !has_huge_files or CONFIG_LBDAF not enabled implies that
2567                  * the inode i_block field represents total file blocks in
2568                  * 2^32 512-byte sectors == size of vfs inode i_blocks * 8
2569                  */
2570                 upper_limit = (1LL << 32) - 1;
2571
2572                 /* total blocks in file system block size */
2573                 upper_limit >>= (bits - 9);
2574
2575         } else {
2576                 /*
2577                  * We use 48 bit ext4_inode i_blocks
2578                  * With EXT4_HUGE_FILE_FL set the i_blocks
2579                  * represent total number of blocks in
2580                  * file system block size
2581                  */
2582                 upper_limit = (1LL << 48) - 1;
2583
2584         }
2585
2586         /* indirect blocks */
2587         meta_blocks = 1;
2588         /* double indirect blocks */
2589         meta_blocks += 1 + (1LL << (bits-2));
2590         /* tripple indirect blocks */
2591         meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
2592
2593         upper_limit -= meta_blocks;
2594         upper_limit <<= bits;
2595
2596         res += 1LL << (bits-2);
2597         res += 1LL << (2*(bits-2));
2598         res += 1LL << (3*(bits-2));
2599         res <<= bits;
2600         if (res > upper_limit)
2601                 res = upper_limit;
2602
2603         if (res > MAX_LFS_FILESIZE)
2604                 res = MAX_LFS_FILESIZE;
2605
2606         return res;
2607 }
2608
2609 static ext4_fsblk_t descriptor_loc(struct super_block *sb,
2610                                    ext4_fsblk_t logical_sb_block, int nr)
2611 {
2612         struct ext4_sb_info *sbi = EXT4_SB(sb);
2613         ext4_group_t bg, first_meta_bg;
2614         int has_super = 0;
2615
2616         first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
2617
2618         if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
2619                 return logical_sb_block + nr + 1;
2620         bg = sbi->s_desc_per_block * nr;
2621         if (ext4_bg_has_super(sb, bg))
2622                 has_super = 1;
2623
2624         /*
2625          * If we have a meta_bg fs with 1k blocks, group 0's GDT is at
2626          * block 2, not 1.  If s_first_data_block == 0 (bigalloc is enabled
2627          * on modern mke2fs or blksize > 1k on older mke2fs) then we must
2628          * compensate.
2629          */
2630         if (sb->s_blocksize == 1024 && nr == 0 &&
2631             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) == 0)
2632                 has_super++;
2633
2634         return (has_super + ext4_group_first_block_no(sb, bg));
2635 }
2636
2637 /**
2638  * ext4_get_stripe_size: Get the stripe size.
2639  * @sbi: In memory super block info
2640  *
2641  * If we have specified it via mount option, then
2642  * use the mount option value. If the value specified at mount time is
2643  * greater than the blocks per group use the super block value.
2644  * If the super block value is greater than blocks per group return 0.
2645  * Allocator needs it be less than blocks per group.
2646  *
2647  */
2648 static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
2649 {
2650         unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
2651         unsigned long stripe_width =
2652                         le32_to_cpu(sbi->s_es->s_raid_stripe_width);
2653         int ret;
2654
2655         if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
2656                 ret = sbi->s_stripe;
2657         else if (stripe_width && stripe_width <= sbi->s_blocks_per_group)
2658                 ret = stripe_width;
2659         else if (stride && stride <= sbi->s_blocks_per_group)
2660                 ret = stride;
2661         else
2662                 ret = 0;
2663
2664         /*
2665          * If the stripe width is 1, this makes no sense and
2666          * we set it to 0 to turn off stripe handling code.
2667          */
2668         if (ret <= 1)
2669                 ret = 0;
2670
2671         return ret;
2672 }
2673
2674 /*
2675  * Check whether this filesystem can be mounted based on
2676  * the features present and the RDONLY/RDWR mount requested.
2677  * Returns 1 if this filesystem can be mounted as requested,
2678  * 0 if it cannot be.
2679  */
2680 static int ext4_feature_set_ok(struct super_block *sb, int readonly)
2681 {
2682         if (ext4_has_unknown_ext4_incompat_features(sb)) {
2683                 ext4_msg(sb, KERN_ERR,
2684                         "Couldn't mount because of "
2685                         "unsupported optional features (%x)",
2686                         (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
2687                         ~EXT4_FEATURE_INCOMPAT_SUPP));
2688                 return 0;
2689         }
2690
2691         if (readonly)
2692                 return 1;
2693
2694         if (ext4_has_feature_readonly(sb)) {
2695                 ext4_msg(sb, KERN_INFO, "filesystem is read-only");
2696                 sb->s_flags |= MS_RDONLY;
2697                 return 1;
2698         }
2699
2700         /* Check that feature set is OK for a read-write mount */
2701         if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
2702                 ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
2703                          "unsupported optional features (%x)",
2704                          (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
2705                                 ~EXT4_FEATURE_RO_COMPAT_SUPP));
2706                 return 0;
2707         }
2708         /*
2709          * Large file size enabled file system can only be mounted
2710          * read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
2711          */
2712         if (ext4_has_feature_huge_file(sb)) {
2713                 if (sizeof(blkcnt_t) < sizeof(u64)) {
2714                         ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
2715                                  "cannot be mounted RDWR without "
2716                                  "CONFIG_LBDAF");
2717                         return 0;
2718                 }
2719         }
2720         if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
2721                 ext4_msg(sb, KERN_ERR,
2722                          "Can't support bigalloc feature without "
2723                          "extents feature\n");
2724                 return 0;
2725         }
2726
2727 #ifndef CONFIG_QUOTA
2728         if (ext4_has_feature_quota(sb) && !readonly) {
2729                 ext4_msg(sb, KERN_ERR,
2730                          "Filesystem with quota feature cannot be mounted RDWR "
2731                          "without CONFIG_QUOTA");
2732                 return 0;
2733         }
2734         if (ext4_has_feature_project(sb) && !readonly) {
2735                 ext4_msg(sb, KERN_ERR,
2736                          "Filesystem with project quota feature cannot be mounted RDWR "
2737                          "without CONFIG_QUOTA");
2738                 return 0;
2739         }
2740 #endif  /* CONFIG_QUOTA */
2741         return 1;
2742 }
2743
2744 /*
2745  * This function is called once a day if we have errors logged
2746  * on the file system
2747  */
2748 static void print_daily_error_info(unsigned long arg)
2749 {
2750         struct super_block *sb = (struct super_block *) arg;
2751         struct ext4_sb_info *sbi;
2752         struct ext4_super_block *es;
2753
2754         sbi = EXT4_SB(sb);
2755         es = sbi->s_es;
2756
2757         if (es->s_error_count)
2758                 /* fsck newer than v1.41.13 is needed to clean this condition. */
2759                 ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
2760                          le32_to_cpu(es->s_error_count));
2761         if (es->s_first_error_time) {
2762                 printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %u: %.*s:%d",
2763                        sb->s_id, le32_to_cpu(es->s_first_error_time),
2764                        (int) sizeof(es->s_first_error_func),
2765                        es->s_first_error_func,
2766                        le32_to_cpu(es->s_first_error_line));
2767                 if (es->s_first_error_ino)
2768                         printk(KERN_CONT ": inode %u",
2769                                le32_to_cpu(es->s_first_error_ino));
2770                 if (es->s_first_error_block)
2771                         printk(KERN_CONT ": block %llu", (unsigned long long)
2772                                le64_to_cpu(es->s_first_error_block));
2773                 printk(KERN_CONT "\n");
2774         }
2775         if (es->s_last_error_time) {
2776                 printk(KERN_NOTICE "EXT4-fs (%s): last error at time %u: %.*s:%d",
2777                        sb->s_id, le32_to_cpu(es->s_last_error_time),
2778                        (int) sizeof(es->s_last_error_func),
2779                        es->s_last_error_func,
2780                        le32_to_cpu(es->s_last_error_line));
2781                 if (es->s_last_error_ino)
2782                         printk(KERN_CONT ": inode %u",
2783                                le32_to_cpu(es->s_last_error_ino));
2784                 if (es->s_last_error_block)
2785                         printk(KERN_CONT ": block %llu", (unsigned long long)
2786                                le64_to_cpu(es->s_last_error_block));
2787                 printk(KERN_CONT "\n");
2788         }
2789         mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);  /* Once a day */
2790 }
2791
2792 /* Find next suitable group and run ext4_init_inode_table */
2793 static int ext4_run_li_request(struct ext4_li_request *elr)
2794 {
2795         struct ext4_group_desc *gdp = NULL;
2796         ext4_group_t group, ngroups;
2797         struct super_block *sb;
2798         unsigned long timeout = 0;
2799         int ret = 0;
2800
2801         sb = elr->lr_super;
2802         ngroups = EXT4_SB(sb)->s_groups_count;
2803
2804         for (group = elr->lr_next_group; group < ngroups; group++) {
2805                 gdp = ext4_get_group_desc(sb, group, NULL);
2806                 if (!gdp) {
2807                         ret = 1;
2808                         break;
2809                 }
2810
2811                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
2812                         break;
2813         }
2814
2815         if (group >= ngroups)
2816                 ret = 1;
2817
2818         if (!ret) {
2819                 timeout = jiffies;
2820                 ret = ext4_init_inode_table(sb, group,
2821                                             elr->lr_timeout ? 0 : 1);
2822                 if (elr->lr_timeout == 0) {
2823                         timeout = (jiffies - timeout) *
2824                                   elr->lr_sbi->s_li_wait_mult;
2825                         elr->lr_timeout = timeout;
2826                 }
2827                 elr->lr_next_sched = jiffies + elr->lr_timeout;
2828                 elr->lr_next_group = group + 1;
2829         }
2830         return ret;
2831 }
2832
2833 /*
2834  * Remove lr_request from the list_request and free the
2835  * request structure. Should be called with li_list_mtx held
2836  */
2837 static void ext4_remove_li_request(struct ext4_li_request *elr)
2838 {
2839         struct ext4_sb_info *sbi;
2840
2841         if (!elr)
2842                 return;
2843
2844         sbi = elr->lr_sbi;
2845
2846         list_del(&elr->lr_request);
2847         sbi->s_li_request = NULL;
2848         kfree(elr);
2849 }
2850
2851 static void ext4_unregister_li_request(struct super_block *sb)
2852 {
2853         mutex_lock(&ext4_li_mtx);
2854         if (!ext4_li_info) {
2855                 mutex_unlock(&ext4_li_mtx);
2856                 return;
2857         }
2858
2859         mutex_lock(&ext4_li_info->li_list_mtx);
2860         ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
2861         mutex_unlock(&ext4_li_info->li_list_mtx);
2862         mutex_unlock(&ext4_li_mtx);
2863 }
2864
2865 static struct task_struct *ext4_lazyinit_task;
2866
2867 /*
2868  * This is the function where ext4lazyinit thread lives. It walks
2869  * through the request list searching for next scheduled filesystem.
2870  * When such a fs is found, run the lazy initialization request
2871  * (ext4_rn_li_request) and keep track of the time spend in this
2872  * function. Based on that time we compute next schedule time of
2873  * the request. When walking through the list is complete, compute
2874  * next waking time and put itself into sleep.
2875  */
2876 static int ext4_lazyinit_thread(void *arg)
2877 {
2878         struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
2879         struct list_head *pos, *n;
2880         struct ext4_li_request *elr;
2881         unsigned long next_wakeup, cur;
2882
2883         BUG_ON(NULL == eli);
2884
2885 cont_thread:
2886         while (true) {
2887                 next_wakeup = MAX_JIFFY_OFFSET;
2888
2889                 mutex_lock(&eli->li_list_mtx);
2890                 if (list_empty(&eli->li_request_list)) {
2891                         mutex_unlock(&eli->li_list_mtx);
2892                         goto exit_thread;
2893                 }
2894                 list_for_each_safe(pos, n, &eli->li_request_list) {
2895                         int err = 0;
2896                         int progress = 0;
2897                         elr = list_entry(pos, struct ext4_li_request,
2898                                          lr_request);
2899
2900                         if (time_before(jiffies, elr->lr_next_sched)) {
2901                                 if (time_before(elr->lr_next_sched, next_wakeup))
2902                                         next_wakeup = elr->lr_next_sched;
2903                                 continue;
2904                         }
2905                         if (down_read_trylock(&elr->lr_super->s_umount)) {
2906                                 if (sb_start_write_trylock(elr->lr_super)) {
2907                                         progress = 1;
2908                                         /*
2909                                          * We hold sb->s_umount, sb can not
2910                                          * be removed from the list, it is
2911                                          * now safe to drop li_list_mtx
2912                                          */
2913                                         mutex_unlock(&eli->li_list_mtx);
2914                                         err = ext4_run_li_request(elr);
2915                                         sb_end_write(elr->lr_super);
2916                                         mutex_lock(&eli->li_list_mtx);
2917                                         n = pos->next;
2918                                 }
2919                                 up_read((&elr->lr_super->s_umount));
2920                         }
2921                         /* error, remove the lazy_init job */
2922                         if (err) {
2923                                 ext4_remove_li_request(elr);
2924                                 continue;
2925                         }
2926                         if (!progress) {
2927                                 elr->lr_next_sched = jiffies +
2928                                         (prandom_u32()
2929                                          % (EXT4_DEF_LI_MAX_START_DELAY * HZ));
2930                         }
2931                         if (time_before(elr->lr_next_sched, next_wakeup))
2932                                 next_wakeup = elr->lr_next_sched;
2933                 }
2934                 mutex_unlock(&eli->li_list_mtx);
2935
2936                 try_to_freeze();
2937
2938                 cur = jiffies;
2939                 if ((time_after_eq(cur, next_wakeup)) ||
2940                     (MAX_JIFFY_OFFSET == next_wakeup)) {
2941                         cond_resched();
2942                         continue;
2943                 }
2944
2945                 schedule_timeout_interruptible(next_wakeup - cur);
2946
2947                 if (kthread_should_stop()) {
2948                         ext4_clear_request_list();
2949                         goto exit_thread;
2950                 }
2951         }
2952
2953 exit_thread:
2954         /*
2955          * It looks like the request list is empty, but we need
2956          * to check it under the li_list_mtx lock, to prevent any
2957          * additions into it, and of course we should lock ext4_li_mtx
2958          * to atomically free the list and ext4_li_info, because at
2959          * this point another ext4 filesystem could be registering
2960          * new one.
2961          */
2962         mutex_lock(&ext4_li_mtx);
2963         mutex_lock(&eli->li_list_mtx);
2964         if (!list_empty(&eli->li_request_list)) {
2965                 mutex_unlock(&eli->li_list_mtx);
2966                 mutex_unlock(&ext4_li_mtx);
2967                 goto cont_thread;
2968         }
2969         mutex_unlock(&eli->li_list_mtx);
2970         kfree(ext4_li_info);
2971         ext4_li_info = NULL;
2972         mutex_unlock(&ext4_li_mtx);
2973
2974         return 0;
2975 }
2976
2977 static void ext4_clear_request_list(void)
2978 {
2979         struct list_head *pos, *n;
2980         struct ext4_li_request *elr;
2981
2982         mutex_lock(&ext4_li_info->li_list_mtx);
2983         list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
2984                 elr = list_entry(pos, struct ext4_li_request,
2985                                  lr_request);
2986                 ext4_remove_li_request(elr);
2987         }
2988         mutex_unlock(&ext4_li_info->li_list_mtx);
2989 }
2990
2991 static int ext4_run_lazyinit_thread(void)
2992 {
2993         ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
2994                                          ext4_li_info, "ext4lazyinit");
2995         if (IS_ERR(ext4_lazyinit_task)) {
2996                 int err = PTR_ERR(ext4_lazyinit_task);
2997                 ext4_clear_request_list();
2998                 kfree(ext4_li_info);
2999                 ext4_li_info = NULL;
3000                 printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
3001                                  "initialization thread\n",
3002                                  err);
3003                 return err;
3004         }
3005         ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
3006         return 0;
3007 }
3008
3009 /*
3010  * Check whether it make sense to run itable init. thread or not.
3011  * If there is at least one uninitialized inode table, return
3012  * corresponding group number, else the loop goes through all
3013  * groups and return total number of groups.
3014  */
3015 static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
3016 {
3017         ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
3018         struct ext4_group_desc *gdp = NULL;
3019
3020         for (group = 0; group < ngroups; group++) {
3021                 gdp = ext4_get_group_desc(sb, group, NULL);
3022                 if (!gdp)
3023                         continue;
3024
3025                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3026                         break;
3027         }
3028
3029         return group;
3030 }
3031
3032 static int ext4_li_info_new(void)
3033 {
3034         struct ext4_lazy_init *eli = NULL;
3035
3036         eli = kzalloc(sizeof(*eli), GFP_KERNEL);
3037         if (!eli)
3038                 return -ENOMEM;
3039
3040         INIT_LIST_HEAD(&eli->li_request_list);
3041         mutex_init(&eli->li_list_mtx);
3042
3043         eli->li_state |= EXT4_LAZYINIT_QUIT;
3044
3045         ext4_li_info = eli;
3046
3047         return 0;
3048 }
3049
3050 static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
3051                                             ext4_group_t start)
3052 {
3053         struct ext4_sb_info *sbi = EXT4_SB(sb);
3054         struct ext4_li_request *elr;
3055
3056         elr = kzalloc(sizeof(*elr), GFP_KERNEL);
3057         if (!elr)
3058                 return NULL;
3059
3060         elr->lr_super = sb;
3061         elr->lr_sbi = sbi;
3062         elr->lr_next_group = start;
3063
3064         /*
3065          * Randomize first schedule time of the request to
3066          * spread the inode table initialization requests
3067          * better.
3068          */
3069         elr->lr_next_sched = jiffies + (prandom_u32() %
3070                                 (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3071         return elr;
3072 }
3073
3074 int ext4_register_li_request(struct super_block *sb,
3075                              ext4_group_t first_not_zeroed)
3076 {
3077         struct ext4_sb_info *sbi = EXT4_SB(sb);
3078         struct ext4_li_request *elr = NULL;
3079         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
3080         int ret = 0;
3081
3082         mutex_lock(&ext4_li_mtx);
3083         if (sbi->s_li_request != NULL) {
3084                 /*
3085                  * Reset timeout so it can be computed again, because
3086                  * s_li_wait_mult might have changed.
3087                  */
3088                 sbi->s_li_request->lr_timeout = 0;
3089                 goto out;
3090         }
3091
3092         if (first_not_zeroed == ngroups ||
3093             (sb->s_flags & MS_RDONLY) ||
3094             !test_opt(sb, INIT_INODE_TABLE))
3095                 goto out;
3096
3097         elr = ext4_li_request_new(sb, first_not_zeroed);
3098         if (!elr) {
3099                 ret = -ENOMEM;
3100                 goto out;
3101         }
3102
3103         if (NULL == ext4_li_info) {
3104                 ret = ext4_li_info_new();
3105                 if (ret)
3106                         goto out;
3107         }
3108
3109         mutex_lock(&ext4_li_info->li_list_mtx);
3110         list_add(&elr->lr_request, &ext4_li_info->li_request_list);
3111         mutex_unlock(&ext4_li_info->li_list_mtx);
3112
3113         sbi->s_li_request = elr;
3114         /*
3115          * set elr to NULL here since it has been inserted to
3116          * the request_list and the removal and free of it is
3117          * handled by ext4_clear_request_list from now on.
3118          */
3119         elr = NULL;
3120
3121         if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
3122                 ret = ext4_run_lazyinit_thread();
3123                 if (ret)
3124                         goto out;
3125         }
3126 out:
3127         mutex_unlock(&ext4_li_mtx);
3128         if (ret)
3129                 kfree(elr);
3130         return ret;
3131 }
3132
3133 /*
3134  * We do not need to lock anything since this is called on
3135  * module unload.
3136  */
3137 static void ext4_destroy_lazyinit_thread(void)
3138 {
3139         /*
3140          * If thread exited earlier
3141          * there's nothing to be done.
3142          */
3143         if (!ext4_li_info || !ext4_lazyinit_task)
3144                 return;
3145
3146         kthread_stop(ext4_lazyinit_task);
3147 }
3148
3149 static int set_journal_csum_feature_set(struct super_block *sb)
3150 {
3151         int ret = 1;
3152         int compat, incompat;
3153         struct ext4_sb_info *sbi = EXT4_SB(sb);
3154
3155         if (ext4_has_metadata_csum(sb)) {
3156                 /* journal checksum v3 */
3157                 compat = 0;
3158                 incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
3159         } else {
3160                 /* journal checksum v1 */
3161                 compat = JBD2_FEATURE_COMPAT_CHECKSUM;
3162                 incompat = 0;
3163         }
3164
3165         jbd2_journal_clear_features(sbi->s_journal,
3166                         JBD2_FEATURE_COMPAT_CHECKSUM, 0,
3167                         JBD2_FEATURE_INCOMPAT_CSUM_V3 |
3168                         JBD2_FEATURE_INCOMPAT_CSUM_V2);
3169         if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
3170                 ret = jbd2_journal_set_features(sbi->s_journal,
3171                                 compat, 0,
3172                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
3173                                 incompat);
3174         } else if (test_opt(sb, JOURNAL_CHECKSUM)) {
3175                 ret = jbd2_journal_set_features(sbi->s_journal,
3176                                 compat, 0,
3177                                 incompat);
3178                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3179                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3180         } else {
3181                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3182                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3183         }
3184
3185         return ret;
3186 }
3187
3188 /*
3189  * Note: calculating the overhead so we can be compatible with
3190  * historical BSD practice is quite difficult in the face of
3191  * clusters/bigalloc.  This is because multiple metadata blocks from
3192  * different block group can end up in the same allocation cluster.
3193  * Calculating the exact overhead in the face of clustered allocation
3194  * requires either O(all block bitmaps) in memory or O(number of block
3195  * groups**2) in time.  We will still calculate the superblock for
3196  * older file systems --- and if we come across with a bigalloc file
3197  * system with zero in s_overhead_clusters the estimate will be close to
3198  * correct especially for very large cluster sizes --- but for newer
3199  * file systems, it's better to calculate this figure once at mkfs
3200  * time, and store it in the superblock.  If the superblock value is
3201  * present (even for non-bigalloc file systems), we will use it.
3202  */
3203 static int count_overhead(struct super_block *sb, ext4_group_t grp,
3204                           char *buf)
3205 {
3206         struct ext4_sb_info     *sbi = EXT4_SB(sb);
3207         struct ext4_group_desc  *gdp;
3208         ext4_fsblk_t            first_block, last_block, b;
3209         ext4_group_t            i, ngroups = ext4_get_groups_count(sb);
3210         int                     s, j, count = 0;
3211
3212         if (!ext4_has_feature_bigalloc(sb))
3213                 return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
3214                         sbi->s_itb_per_group + 2);
3215
3216         first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
3217                 (grp * EXT4_BLOCKS_PER_GROUP(sb));
3218         last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
3219         for (i = 0; i < ngroups; i++) {
3220                 gdp = ext4_get_group_desc(sb, i, NULL);
3221                 b = ext4_block_bitmap(sb, gdp);
3222                 if (b >= first_block && b <= last_block) {
3223                         ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3224                         count++;
3225                 }
3226                 b = ext4_inode_bitmap(sb, gdp);
3227                 if (b >= first_block && b <= last_block) {
3228                         ext4_set_bit(EXT4_B2C(sbi, b - first_block),&nbs