]> bbs.cooldavid.org Git - net-next-2.6.git/blob - fs/ext4/super.c
a94d3f56898fca3a47f44fbe009170b0acd203b4
[net-next-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/jbd2.h>
25 #include <linux/slab.h>
26 #include <linux/init.h>
27 #include <linux/blkdev.h>
28 #include <linux/parser.h>
29 #include <linux/smp_lock.h>
30 #include <linux/buffer_head.h>
31 #include <linux/exportfs.h>
32 #include <linux/vfs.h>
33 #include <linux/random.h>
34 #include <linux/mount.h>
35 #include <linux/namei.h>
36 #include <linux/quotaops.h>
37 #include <linux/seq_file.h>
38 #include <linux/proc_fs.h>
39 #include <linux/ctype.h>
40 #include <linux/log2.h>
41 #include <linux/crc16.h>
42 #include <asm/uaccess.h>
43
44 #include "ext4.h"
45 #include "ext4_jbd2.h"
46 #include "xattr.h"
47 #include "acl.h"
48 #include "mballoc.h"
49
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/ext4.h>
52
53 struct proc_dir_entry *ext4_proc_root;
54 static struct kset *ext4_kset;
55
56 static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
57                              unsigned long journal_devnum);
58 static int ext4_commit_super(struct super_block *sb, int sync);
59 static void ext4_mark_recovery_complete(struct super_block *sb,
60                                         struct ext4_super_block *es);
61 static void ext4_clear_journal_err(struct super_block *sb,
62                                    struct ext4_super_block *es);
63 static int ext4_sync_fs(struct super_block *sb, int wait);
64 static const char *ext4_decode_error(struct super_block *sb, int errno,
65                                      char nbuf[16]);
66 static int ext4_remount(struct super_block *sb, int *flags, char *data);
67 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
68 static int ext4_unfreeze(struct super_block *sb);
69 static void ext4_write_super(struct super_block *sb);
70 static int ext4_freeze(struct super_block *sb);
71 static int ext4_get_sb(struct file_system_type *fs_type, int flags,
72                        const char *dev_name, void *data, struct vfsmount *mnt);
73
74 #if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
75 static struct file_system_type ext3_fs_type = {
76         .owner          = THIS_MODULE,
77         .name           = "ext3",
78         .get_sb         = ext4_get_sb,
79         .kill_sb        = kill_block_super,
80         .fs_flags       = FS_REQUIRES_DEV,
81 };
82 #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
83 #else
84 #define IS_EXT3_SB(sb) (0)
85 #endif
86
87 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
88                                struct ext4_group_desc *bg)
89 {
90         return le32_to_cpu(bg->bg_block_bitmap_lo) |
91                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
92                  (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
93 }
94
95 ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
96                                struct ext4_group_desc *bg)
97 {
98         return le32_to_cpu(bg->bg_inode_bitmap_lo) |
99                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
100                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
101 }
102
103 ext4_fsblk_t ext4_inode_table(struct super_block *sb,
104                               struct ext4_group_desc *bg)
105 {
106         return le32_to_cpu(bg->bg_inode_table_lo) |
107                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
108                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
109 }
110
111 __u32 ext4_free_blks_count(struct super_block *sb,
112                               struct ext4_group_desc *bg)
113 {
114         return le16_to_cpu(bg->bg_free_blocks_count_lo) |
115                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
116                  (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
117 }
118
119 __u32 ext4_free_inodes_count(struct super_block *sb,
120                               struct ext4_group_desc *bg)
121 {
122         return le16_to_cpu(bg->bg_free_inodes_count_lo) |
123                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
124                  (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
125 }
126
127 __u32 ext4_used_dirs_count(struct super_block *sb,
128                               struct ext4_group_desc *bg)
129 {
130         return le16_to_cpu(bg->bg_used_dirs_count_lo) |
131                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
132                  (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
133 }
134
135 __u32 ext4_itable_unused_count(struct super_block *sb,
136                               struct ext4_group_desc *bg)
137 {
138         return le16_to_cpu(bg->bg_itable_unused_lo) |
139                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
140                  (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
141 }
142
143 void ext4_block_bitmap_set(struct super_block *sb,
144                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
145 {
146         bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
147         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
148                 bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
149 }
150
151 void ext4_inode_bitmap_set(struct super_block *sb,
152                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
153 {
154         bg->bg_inode_bitmap_lo  = cpu_to_le32((u32)blk);
155         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
156                 bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
157 }
158
159 void ext4_inode_table_set(struct super_block *sb,
160                           struct ext4_group_desc *bg, ext4_fsblk_t blk)
161 {
162         bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
163         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
164                 bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
165 }
166
167 void ext4_free_blks_set(struct super_block *sb,
168                           struct ext4_group_desc *bg, __u32 count)
169 {
170         bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
171         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
172                 bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
173 }
174
175 void ext4_free_inodes_set(struct super_block *sb,
176                           struct ext4_group_desc *bg, __u32 count)
177 {
178         bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
179         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
180                 bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
181 }
182
183 void ext4_used_dirs_set(struct super_block *sb,
184                           struct ext4_group_desc *bg, __u32 count)
185 {
186         bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
187         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
188                 bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
189 }
190
191 void ext4_itable_unused_set(struct super_block *sb,
192                           struct ext4_group_desc *bg, __u32 count)
193 {
194         bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
195         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
196                 bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
197 }
198
199
200 /* Just increment the non-pointer handle value */
201 static handle_t *ext4_get_nojournal(void)
202 {
203         handle_t *handle = current->journal_info;
204         unsigned long ref_cnt = (unsigned long)handle;
205
206         BUG_ON(ref_cnt >= EXT4_NOJOURNAL_MAX_REF_COUNT);
207
208         ref_cnt++;
209         handle = (handle_t *)ref_cnt;
210
211         current->journal_info = handle;
212         return handle;
213 }
214
215
216 /* Decrement the non-pointer handle value */
217 static void ext4_put_nojournal(handle_t *handle)
218 {
219         unsigned long ref_cnt = (unsigned long)handle;
220
221         BUG_ON(ref_cnt == 0);
222
223         ref_cnt--;
224         handle = (handle_t *)ref_cnt;
225
226         current->journal_info = handle;
227 }
228
229 /*
230  * Wrappers for jbd2_journal_start/end.
231  *
232  * The only special thing we need to do here is to make sure that all
233  * journal_end calls result in the superblock being marked dirty, so
234  * that sync() will call the filesystem's write_super callback if
235  * appropriate.
236  */
237 handle_t *ext4_journal_start_sb(struct super_block *sb, int nblocks)
238 {
239         journal_t *journal;
240
241         if (sb->s_flags & MS_RDONLY)
242                 return ERR_PTR(-EROFS);
243
244         vfs_check_frozen(sb, SB_FREEZE_WRITE);
245         /* Special case here: if the journal has aborted behind our
246          * backs (eg. EIO in the commit thread), then we still need to
247          * take the FS itself readonly cleanly. */
248         journal = EXT4_SB(sb)->s_journal;
249         if (journal) {
250                 if (is_journal_aborted(journal)) {
251                         ext4_abort(sb, "Detected aborted journal");
252                         return ERR_PTR(-EROFS);
253                 }
254                 return jbd2_journal_start(journal, nblocks);
255         }
256         return ext4_get_nojournal();
257 }
258
259 /*
260  * The only special thing we need to do here is to make sure that all
261  * jbd2_journal_stop calls result in the superblock being marked dirty, so
262  * that sync() will call the filesystem's write_super callback if
263  * appropriate.
264  */
265 int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
266 {
267         struct super_block *sb;
268         int err;
269         int rc;
270
271         if (!ext4_handle_valid(handle)) {
272                 ext4_put_nojournal(handle);
273                 return 0;
274         }
275         sb = handle->h_transaction->t_journal->j_private;
276         err = handle->h_err;
277         rc = jbd2_journal_stop(handle);
278
279         if (!err)
280                 err = rc;
281         if (err)
282                 __ext4_std_error(sb, where, line, err);
283         return err;
284 }
285
286 void ext4_journal_abort_handle(const char *caller, unsigned int line,
287                                const char *err_fn, struct buffer_head *bh,
288                                handle_t *handle, int err)
289 {
290         char nbuf[16];
291         const char *errstr = ext4_decode_error(NULL, err, nbuf);
292
293         BUG_ON(!ext4_handle_valid(handle));
294
295         if (bh)
296                 BUFFER_TRACE(bh, "abort");
297
298         if (!handle->h_err)
299                 handle->h_err = err;
300
301         if (is_handle_aborted(handle))
302                 return;
303
304         printk(KERN_ERR "%s:%d: aborting transaction: %s in %s\n",
305                caller, line, errstr, err_fn);
306
307         jbd2_journal_abort_handle(handle);
308 }
309
310 static void __save_error_info(struct super_block *sb, const char *func,
311                             unsigned int line)
312 {
313         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
314
315         EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
316         es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
317         es->s_last_error_time = cpu_to_le32(get_seconds());
318         strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
319         es->s_last_error_line = cpu_to_le32(line);
320         if (!es->s_first_error_time) {
321                 es->s_first_error_time = es->s_last_error_time;
322                 strncpy(es->s_first_error_func, func,
323                         sizeof(es->s_first_error_func));
324                 es->s_first_error_line = cpu_to_le32(line);
325                 es->s_first_error_ino = es->s_last_error_ino;
326                 es->s_first_error_block = es->s_last_error_block;
327         }
328         es->s_error_count = cpu_to_le32(le32_to_cpu(es->s_error_count) + 1);
329 }
330
331 static void save_error_info(struct super_block *sb, const char *func,
332                             unsigned int line)
333 {
334         __save_error_info(sb, func, line);
335         ext4_commit_super(sb, 1);
336 }
337
338
339 /* Deal with the reporting of failure conditions on a filesystem such as
340  * inconsistencies detected or read IO failures.
341  *
342  * On ext2, we can store the error state of the filesystem in the
343  * superblock.  That is not possible on ext4, because we may have other
344  * write ordering constraints on the superblock which prevent us from
345  * writing it out straight away; and given that the journal is about to
346  * be aborted, we can't rely on the current, or future, transactions to
347  * write out the superblock safely.
348  *
349  * We'll just use the jbd2_journal_abort() error code to record an error in
350  * the journal instead.  On recovery, the journal will complain about
351  * that error until we've noted it down and cleared it.
352  */
353
354 static void ext4_handle_error(struct super_block *sb)
355 {
356         if (sb->s_flags & MS_RDONLY)
357                 return;
358
359         if (!test_opt(sb, ERRORS_CONT)) {
360                 journal_t *journal = EXT4_SB(sb)->s_journal;
361
362                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
363                 if (journal)
364                         jbd2_journal_abort(journal, -EIO);
365         }
366         if (test_opt(sb, ERRORS_RO)) {
367                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
368                 sb->s_flags |= MS_RDONLY;
369         }
370         if (test_opt(sb, ERRORS_PANIC))
371                 panic("EXT4-fs (device %s): panic forced after error\n",
372                         sb->s_id);
373 }
374
375 void __ext4_error(struct super_block *sb, const char *function,
376                   unsigned int line, const char *fmt, ...)
377 {
378         va_list args;
379
380         va_start(args, fmt);
381         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: comm %s: ",
382                sb->s_id, function, line, current->comm);
383         vprintk(fmt, args);
384         printk("\n");
385         va_end(args);
386
387         ext4_handle_error(sb);
388 }
389
390 void ext4_error_inode(struct inode *inode, const char *function,
391                       unsigned int line, ext4_fsblk_t block,
392                       const char *fmt, ...)
393 {
394         va_list args;
395         struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
396
397         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
398         es->s_last_error_block = cpu_to_le64(block);
399         save_error_info(inode->i_sb, function, line);
400         va_start(args, fmt);
401         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: inode #%lu: ",
402                inode->i_sb->s_id, function, line, inode->i_ino);
403         if (block)
404                 printk("block %llu: ", block);
405         printk("comm %s: ", current->comm);
406         vprintk(fmt, args);
407         printk("\n");
408         va_end(args);
409
410         ext4_handle_error(inode->i_sb);
411 }
412
413 void ext4_error_file(struct file *file, const char *function,
414                      unsigned int line, const char *fmt, ...)
415 {
416         va_list args;
417         struct ext4_super_block *es;
418         struct inode *inode = file->f_dentry->d_inode;
419         char pathname[80], *path;
420
421         es = EXT4_SB(inode->i_sb)->s_es;
422         es->s_last_error_ino = cpu_to_le32(inode->i_ino);
423         save_error_info(inode->i_sb, function, line);
424         va_start(args, fmt);
425         path = d_path(&(file->f_path), pathname, sizeof(pathname));
426         if (!path)
427                 path = "(unknown)";
428         printk(KERN_CRIT
429                "EXT4-fs error (device %s): %s:%d: inode #%lu "
430                "(comm %s path %s): ",
431                inode->i_sb->s_id, function, line, inode->i_ino,
432                current->comm, path);
433         vprintk(fmt, args);
434         printk("\n");
435         va_end(args);
436
437         ext4_handle_error(inode->i_sb);
438 }
439
440 static const char *ext4_decode_error(struct super_block *sb, int errno,
441                                      char nbuf[16])
442 {
443         char *errstr = NULL;
444
445         switch (errno) {
446         case -EIO:
447                 errstr = "IO failure";
448                 break;
449         case -ENOMEM:
450                 errstr = "Out of memory";
451                 break;
452         case -EROFS:
453                 if (!sb || (EXT4_SB(sb)->s_journal &&
454                             EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
455                         errstr = "Journal has aborted";
456                 else
457                         errstr = "Readonly filesystem";
458                 break;
459         default:
460                 /* If the caller passed in an extra buffer for unknown
461                  * errors, textualise them now.  Else we just return
462                  * NULL. */
463                 if (nbuf) {
464                         /* Check for truncated error codes... */
465                         if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
466                                 errstr = nbuf;
467                 }
468                 break;
469         }
470
471         return errstr;
472 }
473
474 /* __ext4_std_error decodes expected errors from journaling functions
475  * automatically and invokes the appropriate error response.  */
476
477 void __ext4_std_error(struct super_block *sb, const char *function,
478                       unsigned int line, int errno)
479 {
480         char nbuf[16];
481         const char *errstr;
482
483         /* Special case: if the error is EROFS, and we're not already
484          * inside a transaction, then there's really no point in logging
485          * an error. */
486         if (errno == -EROFS && journal_current_handle() == NULL &&
487             (sb->s_flags & MS_RDONLY))
488                 return;
489
490         errstr = ext4_decode_error(sb, errno, nbuf);
491         printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
492                sb->s_id, function, line, errstr);
493         save_error_info(sb, function, line);
494
495         ext4_handle_error(sb);
496 }
497
498 /*
499  * ext4_abort is a much stronger failure handler than ext4_error.  The
500  * abort function may be used to deal with unrecoverable failures such
501  * as journal IO errors or ENOMEM at a critical moment in log management.
502  *
503  * We unconditionally force the filesystem into an ABORT|READONLY state,
504  * unless the error response on the fs has been set to panic in which
505  * case we take the easy way out and panic immediately.
506  */
507
508 void __ext4_abort(struct super_block *sb, const char *function,
509                 unsigned int line, const char *fmt, ...)
510 {
511         va_list args;
512
513         save_error_info(sb, function, line);
514         va_start(args, fmt);
515         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id,
516                function, line);
517         vprintk(fmt, args);
518         printk("\n");
519         va_end(args);
520
521         if ((sb->s_flags & MS_RDONLY) == 0) {
522                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
523                 sb->s_flags |= MS_RDONLY;
524                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
525                 if (EXT4_SB(sb)->s_journal)
526                         jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
527                 save_error_info(sb, function, line);
528         }
529         if (test_opt(sb, ERRORS_PANIC))
530                 panic("EXT4-fs panic from previous error\n");
531 }
532
533 void ext4_msg (struct super_block * sb, const char *prefix,
534                    const char *fmt, ...)
535 {
536         va_list args;
537
538         va_start(args, fmt);
539         printk("%sEXT4-fs (%s): ", prefix, sb->s_id);
540         vprintk(fmt, args);
541         printk("\n");
542         va_end(args);
543 }
544
545 void __ext4_warning(struct super_block *sb, const char *function,
546                     unsigned int line, const char *fmt, ...)
547 {
548         va_list args;
549
550         va_start(args, fmt);
551         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: ",
552                sb->s_id, function, line);
553         vprintk(fmt, args);
554         printk("\n");
555         va_end(args);
556 }
557
558 void __ext4_grp_locked_error(const char *function, unsigned int line,
559                              struct super_block *sb, ext4_group_t grp,
560                              unsigned long ino, ext4_fsblk_t block,
561                              const char *fmt, ...)
562 __releases(bitlock)
563 __acquires(bitlock)
564 {
565         va_list args;
566         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
567
568         es->s_last_error_ino = cpu_to_le32(ino);
569         es->s_last_error_block = cpu_to_le64(block);
570         __save_error_info(sb, function, line);
571         va_start(args, fmt);
572         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u",
573                sb->s_id, function, line, grp);
574         if (ino)
575                 printk("inode %lu: ", ino);
576         if (block)
577                 printk("block %llu:", (unsigned long long) block);
578         vprintk(fmt, args);
579         printk("\n");
580         va_end(args);
581
582         if (test_opt(sb, ERRORS_CONT)) {
583                 ext4_commit_super(sb, 0);
584                 return;
585         }
586
587         ext4_unlock_group(sb, grp);
588         ext4_handle_error(sb);
589         /*
590          * We only get here in the ERRORS_RO case; relocking the group
591          * may be dangerous, but nothing bad will happen since the
592          * filesystem will have already been marked read/only and the
593          * journal has been aborted.  We return 1 as a hint to callers
594          * who might what to use the return value from
595          * ext4_grp_locked_error() to distinguish beween the
596          * ERRORS_CONT and ERRORS_RO case, and perhaps return more
597          * aggressively from the ext4 function in question, with a
598          * more appropriate error code.
599          */
600         ext4_lock_group(sb, grp);
601         return;
602 }
603
604 void ext4_update_dynamic_rev(struct super_block *sb)
605 {
606         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
607
608         if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
609                 return;
610
611         ext4_warning(sb,
612                      "updating to rev %d because of new feature flag, "
613                      "running e2fsck is recommended",
614                      EXT4_DYNAMIC_REV);
615
616         es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
617         es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
618         es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
619         /* leave es->s_feature_*compat flags alone */
620         /* es->s_uuid will be set by e2fsck if empty */
621
622         /*
623          * The rest of the superblock fields should be zero, and if not it
624          * means they are likely already in use, so leave them alone.  We
625          * can leave it up to e2fsck to clean up any inconsistencies there.
626          */
627 }
628
629 /*
630  * Open the external journal device
631  */
632 static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
633 {
634         struct block_device *bdev;
635         char b[BDEVNAME_SIZE];
636
637         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
638         if (IS_ERR(bdev))
639                 goto fail;
640         return bdev;
641
642 fail:
643         ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
644                         __bdevname(dev, b), PTR_ERR(bdev));
645         return NULL;
646 }
647
648 /*
649  * Release the journal device
650  */
651 static int ext4_blkdev_put(struct block_device *bdev)
652 {
653         bd_release(bdev);
654         return blkdev_put(bdev, FMODE_READ|FMODE_WRITE);
655 }
656
657 static int ext4_blkdev_remove(struct ext4_sb_info *sbi)
658 {
659         struct block_device *bdev;
660         int ret = -ENODEV;
661
662         bdev = sbi->journal_bdev;
663         if (bdev) {
664                 ret = ext4_blkdev_put(bdev);
665                 sbi->journal_bdev = NULL;
666         }
667         return ret;
668 }
669
670 static inline struct inode *orphan_list_entry(struct list_head *l)
671 {
672         return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
673 }
674
675 static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
676 {
677         struct list_head *l;
678
679         ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
680                  le32_to_cpu(sbi->s_es->s_last_orphan));
681
682         printk(KERN_ERR "sb_info orphan list:\n");
683         list_for_each(l, &sbi->s_orphan) {
684                 struct inode *inode = orphan_list_entry(l);
685                 printk(KERN_ERR "  "
686                        "inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
687                        inode->i_sb->s_id, inode->i_ino, inode,
688                        inode->i_mode, inode->i_nlink,
689                        NEXT_ORPHAN(inode));
690         }
691 }
692
693 static void ext4_put_super(struct super_block *sb)
694 {
695         struct ext4_sb_info *sbi = EXT4_SB(sb);
696         struct ext4_super_block *es = sbi->s_es;
697         int i, err;
698
699         dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
700
701         flush_workqueue(sbi->dio_unwritten_wq);
702         destroy_workqueue(sbi->dio_unwritten_wq);
703
704         lock_super(sb);
705         lock_kernel();
706         if (sb->s_dirt)
707                 ext4_commit_super(sb, 1);
708
709         if (sbi->s_journal) {
710                 err = jbd2_journal_destroy(sbi->s_journal);
711                 sbi->s_journal = NULL;
712                 if (err < 0)
713                         ext4_abort(sb, "Couldn't clean up the journal");
714         }
715
716         ext4_release_system_zone(sb);
717         ext4_mb_release(sb);
718         ext4_ext_release(sb);
719         ext4_xattr_put_super(sb);
720
721         if (!(sb->s_flags & MS_RDONLY)) {
722                 EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
723                 es->s_state = cpu_to_le16(sbi->s_mount_state);
724                 ext4_commit_super(sb, 1);
725         }
726         if (sbi->s_proc) {
727                 remove_proc_entry(sb->s_id, ext4_proc_root);
728         }
729         kobject_del(&sbi->s_kobj);
730
731         for (i = 0; i < sbi->s_gdb_count; i++)
732                 brelse(sbi->s_group_desc[i]);
733         kfree(sbi->s_group_desc);
734         if (is_vmalloc_addr(sbi->s_flex_groups))
735                 vfree(sbi->s_flex_groups);
736         else
737                 kfree(sbi->s_flex_groups);
738         percpu_counter_destroy(&sbi->s_freeblocks_counter);
739         percpu_counter_destroy(&sbi->s_freeinodes_counter);
740         percpu_counter_destroy(&sbi->s_dirs_counter);
741         percpu_counter_destroy(&sbi->s_dirtyblocks_counter);
742         brelse(sbi->s_sbh);
743 #ifdef CONFIG_QUOTA
744         for (i = 0; i < MAXQUOTAS; i++)
745                 kfree(sbi->s_qf_names[i]);
746 #endif
747
748         /* Debugging code just in case the in-memory inode orphan list
749          * isn't empty.  The on-disk one can be non-empty if we've
750          * detected an error and taken the fs readonly, but the
751          * in-memory list had better be clean by this point. */
752         if (!list_empty(&sbi->s_orphan))
753                 dump_orphan_list(sb, sbi);
754         J_ASSERT(list_empty(&sbi->s_orphan));
755
756         invalidate_bdev(sb->s_bdev);
757         if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
758                 /*
759                  * Invalidate the journal device's buffers.  We don't want them
760                  * floating about in memory - the physical journal device may
761                  * hotswapped, and it breaks the `ro-after' testing code.
762                  */
763                 sync_blockdev(sbi->journal_bdev);
764                 invalidate_bdev(sbi->journal_bdev);
765                 ext4_blkdev_remove(sbi);
766         }
767         sb->s_fs_info = NULL;
768         /*
769          * Now that we are completely done shutting down the
770          * superblock, we need to actually destroy the kobject.
771          */
772         unlock_kernel();
773         unlock_super(sb);
774         kobject_put(&sbi->s_kobj);
775         wait_for_completion(&sbi->s_kobj_unregister);
776         kfree(sbi->s_blockgroup_lock);
777         kfree(sbi);
778 }
779
780 static struct kmem_cache *ext4_inode_cachep;
781
782 /*
783  * Called inside transaction, so use GFP_NOFS
784  */
785 static struct inode *ext4_alloc_inode(struct super_block *sb)
786 {
787         struct ext4_inode_info *ei;
788
789         ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
790         if (!ei)
791                 return NULL;
792
793         ei->vfs_inode.i_version = 1;
794         ei->vfs_inode.i_data.writeback_index = 0;
795         memset(&ei->i_cached_extent, 0, sizeof(struct ext4_ext_cache));
796         INIT_LIST_HEAD(&ei->i_prealloc_list);
797         spin_lock_init(&ei->i_prealloc_lock);
798         /*
799          * Note:  We can be called before EXT4_SB(sb)->s_journal is set,
800          * therefore it can be null here.  Don't check it, just initialize
801          * jinode.
802          */
803         jbd2_journal_init_jbd_inode(&ei->jinode, &ei->vfs_inode);
804         ei->i_reserved_data_blocks = 0;
805         ei->i_reserved_meta_blocks = 0;
806         ei->i_allocated_meta_blocks = 0;
807         ei->i_da_metadata_calc_len = 0;
808         ei->i_delalloc_reserved_flag = 0;
809         spin_lock_init(&(ei->i_block_reservation_lock));
810 #ifdef CONFIG_QUOTA
811         ei->i_reserved_quota = 0;
812 #endif
813         INIT_LIST_HEAD(&ei->i_completed_io_list);
814         spin_lock_init(&ei->i_completed_io_lock);
815         ei->cur_aio_dio = NULL;
816         ei->i_sync_tid = 0;
817         ei->i_datasync_tid = 0;
818
819         return &ei->vfs_inode;
820 }
821
822 static void ext4_destroy_inode(struct inode *inode)
823 {
824         if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
825                 ext4_msg(inode->i_sb, KERN_ERR,
826                          "Inode %lu (%p): orphan list check failed!",
827                          inode->i_ino, EXT4_I(inode));
828                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
829                                 EXT4_I(inode), sizeof(struct ext4_inode_info),
830                                 true);
831                 dump_stack();
832         }
833         kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
834 }
835
836 static void init_once(void *foo)
837 {
838         struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
839
840         INIT_LIST_HEAD(&ei->i_orphan);
841 #ifdef CONFIG_EXT4_FS_XATTR
842         init_rwsem(&ei->xattr_sem);
843 #endif
844         init_rwsem(&ei->i_data_sem);
845         inode_init_once(&ei->vfs_inode);
846 }
847
848 static int init_inodecache(void)
849 {
850         ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
851                                              sizeof(struct ext4_inode_info),
852                                              0, (SLAB_RECLAIM_ACCOUNT|
853                                                 SLAB_MEM_SPREAD),
854                                              init_once);
855         if (ext4_inode_cachep == NULL)
856                 return -ENOMEM;
857         return 0;
858 }
859
860 static void destroy_inodecache(void)
861 {
862         kmem_cache_destroy(ext4_inode_cachep);
863 }
864
865 static void ext4_clear_inode(struct inode *inode)
866 {
867         dquot_drop(inode);
868         ext4_discard_preallocations(inode);
869         if (EXT4_JOURNAL(inode))
870                 jbd2_journal_release_jbd_inode(EXT4_SB(inode->i_sb)->s_journal,
871                                        &EXT4_I(inode)->jinode);
872 }
873
874 static inline void ext4_show_quota_options(struct seq_file *seq,
875                                            struct super_block *sb)
876 {
877 #if defined(CONFIG_QUOTA)
878         struct ext4_sb_info *sbi = EXT4_SB(sb);
879
880         if (sbi->s_jquota_fmt) {
881                 char *fmtname = "";
882
883                 switch (sbi->s_jquota_fmt) {
884                 case QFMT_VFS_OLD:
885                         fmtname = "vfsold";
886                         break;
887                 case QFMT_VFS_V0:
888                         fmtname = "vfsv0";
889                         break;
890                 case QFMT_VFS_V1:
891                         fmtname = "vfsv1";
892                         break;
893                 }
894                 seq_printf(seq, ",jqfmt=%s", fmtname);
895         }
896
897         if (sbi->s_qf_names[USRQUOTA])
898                 seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]);
899
900         if (sbi->s_qf_names[GRPQUOTA])
901                 seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]);
902
903         if (test_opt(sb, USRQUOTA))
904                 seq_puts(seq, ",usrquota");
905
906         if (test_opt(sb, GRPQUOTA))
907                 seq_puts(seq, ",grpquota");
908 #endif
909 }
910
911 /*
912  * Show an option if
913  *  - it's set to a non-default value OR
914  *  - if the per-sb default is different from the global default
915  */
916 static int ext4_show_options(struct seq_file *seq, struct vfsmount *vfs)
917 {
918         int def_errors;
919         unsigned long def_mount_opts;
920         struct super_block *sb = vfs->mnt_sb;
921         struct ext4_sb_info *sbi = EXT4_SB(sb);
922         struct ext4_super_block *es = sbi->s_es;
923
924         def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
925         def_errors     = le16_to_cpu(es->s_errors);
926
927         if (sbi->s_sb_block != 1)
928                 seq_printf(seq, ",sb=%llu", sbi->s_sb_block);
929         if (test_opt(sb, MINIX_DF))
930                 seq_puts(seq, ",minixdf");
931         if (test_opt(sb, GRPID) && !(def_mount_opts & EXT4_DEFM_BSDGROUPS))
932                 seq_puts(seq, ",grpid");
933         if (!test_opt(sb, GRPID) && (def_mount_opts & EXT4_DEFM_BSDGROUPS))
934                 seq_puts(seq, ",nogrpid");
935         if (sbi->s_resuid != EXT4_DEF_RESUID ||
936             le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID) {
937                 seq_printf(seq, ",resuid=%u", sbi->s_resuid);
938         }
939         if (sbi->s_resgid != EXT4_DEF_RESGID ||
940             le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID) {
941                 seq_printf(seq, ",resgid=%u", sbi->s_resgid);
942         }
943         if (test_opt(sb, ERRORS_RO)) {
944                 if (def_errors == EXT4_ERRORS_PANIC ||
945                     def_errors == EXT4_ERRORS_CONTINUE) {
946                         seq_puts(seq, ",errors=remount-ro");
947                 }
948         }
949         if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
950                 seq_puts(seq, ",errors=continue");
951         if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
952                 seq_puts(seq, ",errors=panic");
953         if (test_opt(sb, NO_UID32) && !(def_mount_opts & EXT4_DEFM_UID16))
954                 seq_puts(seq, ",nouid32");
955         if (test_opt(sb, DEBUG) && !(def_mount_opts & EXT4_DEFM_DEBUG))
956                 seq_puts(seq, ",debug");
957         if (test_opt(sb, OLDALLOC))
958                 seq_puts(seq, ",oldalloc");
959 #ifdef CONFIG_EXT4_FS_XATTR
960         if (test_opt(sb, XATTR_USER) &&
961                 !(def_mount_opts & EXT4_DEFM_XATTR_USER))
962                 seq_puts(seq, ",user_xattr");
963         if (!test_opt(sb, XATTR_USER) &&
964             (def_mount_opts & EXT4_DEFM_XATTR_USER)) {
965                 seq_puts(seq, ",nouser_xattr");
966         }
967 #endif
968 #ifdef CONFIG_EXT4_FS_POSIX_ACL
969         if (test_opt(sb, POSIX_ACL) && !(def_mount_opts & EXT4_DEFM_ACL))
970                 seq_puts(seq, ",acl");
971         if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT4_DEFM_ACL))
972                 seq_puts(seq, ",noacl");
973 #endif
974         if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
975                 seq_printf(seq, ",commit=%u",
976                            (unsigned) (sbi->s_commit_interval / HZ));
977         }
978         if (sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME) {
979                 seq_printf(seq, ",min_batch_time=%u",
980                            (unsigned) sbi->s_min_batch_time);
981         }
982         if (sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME) {
983                 seq_printf(seq, ",max_batch_time=%u",
984                            (unsigned) sbi->s_min_batch_time);
985         }
986
987         /*
988          * We're changing the default of barrier mount option, so
989          * let's always display its mount state so it's clear what its
990          * status is.
991          */
992         seq_puts(seq, ",barrier=");
993         seq_puts(seq, test_opt(sb, BARRIER) ? "1" : "0");
994         if (test_opt(sb, JOURNAL_ASYNC_COMMIT))
995                 seq_puts(seq, ",journal_async_commit");
996         else if (test_opt(sb, JOURNAL_CHECKSUM))
997                 seq_puts(seq, ",journal_checksum");
998         if (test_opt(sb, I_VERSION))
999                 seq_puts(seq, ",i_version");
1000         if (!test_opt(sb, DELALLOC))
1001                 seq_puts(seq, ",nodelalloc");
1002
1003
1004         if (sbi->s_stripe)
1005                 seq_printf(seq, ",stripe=%lu", sbi->s_stripe);
1006         /*
1007          * journal mode get enabled in different ways
1008          * So just print the value even if we didn't specify it
1009          */
1010         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
1011                 seq_puts(seq, ",data=journal");
1012         else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
1013                 seq_puts(seq, ",data=ordered");
1014         else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
1015                 seq_puts(seq, ",data=writeback");
1016
1017         if (sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
1018                 seq_printf(seq, ",inode_readahead_blks=%u",
1019                            sbi->s_inode_readahead_blks);
1020
1021         if (test_opt(sb, DATA_ERR_ABORT))
1022                 seq_puts(seq, ",data_err=abort");
1023
1024         if (test_opt(sb, NO_AUTO_DA_ALLOC))
1025                 seq_puts(seq, ",noauto_da_alloc");
1026
1027         if (test_opt(sb, DISCARD))
1028                 seq_puts(seq, ",discard");
1029
1030         if (test_opt(sb, NOLOAD))
1031                 seq_puts(seq, ",norecovery");
1032
1033         if (test_opt(sb, DIOREAD_NOLOCK))
1034                 seq_puts(seq, ",dioread_nolock");
1035
1036         ext4_show_quota_options(seq, sb);
1037
1038         return 0;
1039 }
1040
1041 static struct inode *ext4_nfs_get_inode(struct super_block *sb,
1042                                         u64 ino, u32 generation)
1043 {
1044         struct inode *inode;
1045
1046         if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
1047                 return ERR_PTR(-ESTALE);
1048         if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
1049                 return ERR_PTR(-ESTALE);
1050
1051         /* iget isn't really right if the inode is currently unallocated!!
1052          *
1053          * ext4_read_inode will return a bad_inode if the inode had been
1054          * deleted, so we should be safe.
1055          *
1056          * Currently we don't know the generation for parent directory, so
1057          * a generation of 0 means "accept any"
1058          */
1059         inode = ext4_iget(sb, ino);
1060         if (IS_ERR(inode))
1061                 return ERR_CAST(inode);
1062         if (generation && inode->i_generation != generation) {
1063                 iput(inode);
1064                 return ERR_PTR(-ESTALE);
1065         }
1066
1067         return inode;
1068 }
1069
1070 static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
1071                                         int fh_len, int fh_type)
1072 {
1073         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1074                                     ext4_nfs_get_inode);
1075 }
1076
1077 static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
1078                                         int fh_len, int fh_type)
1079 {
1080         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1081                                     ext4_nfs_get_inode);
1082 }
1083
1084 /*
1085  * Try to release metadata pages (indirect blocks, directories) which are
1086  * mapped via the block device.  Since these pages could have journal heads
1087  * which would prevent try_to_free_buffers() from freeing them, we must use
1088  * jbd2 layer's try_to_free_buffers() function to release them.
1089  */
1090 static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
1091                                  gfp_t wait)
1092 {
1093         journal_t *journal = EXT4_SB(sb)->s_journal;
1094
1095         WARN_ON(PageChecked(page));
1096         if (!page_has_buffers(page))
1097                 return 0;
1098         if (journal)
1099                 return jbd2_journal_try_to_free_buffers(journal, page,
1100                                                         wait & ~__GFP_WAIT);
1101         return try_to_free_buffers(page);
1102 }
1103
1104 #ifdef CONFIG_QUOTA
1105 #define QTYPE2NAME(t) ((t) == USRQUOTA ? "user" : "group")
1106 #define QTYPE2MOPT(on, t) ((t) == USRQUOTA?((on)##USRJQUOTA):((on)##GRPJQUOTA))
1107
1108 static int ext4_write_dquot(struct dquot *dquot);
1109 static int ext4_acquire_dquot(struct dquot *dquot);
1110 static int ext4_release_dquot(struct dquot *dquot);
1111 static int ext4_mark_dquot_dirty(struct dquot *dquot);
1112 static int ext4_write_info(struct super_block *sb, int type);
1113 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
1114                                 char *path);
1115 static int ext4_quota_on_mount(struct super_block *sb, int type);
1116 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
1117                                size_t len, loff_t off);
1118 static ssize_t ext4_quota_write(struct super_block *sb, int type,
1119                                 const char *data, size_t len, loff_t off);
1120
1121 static const struct dquot_operations ext4_quota_operations = {
1122 #ifdef CONFIG_QUOTA
1123         .get_reserved_space = ext4_get_reserved_space,
1124 #endif
1125         .write_dquot    = ext4_write_dquot,
1126         .acquire_dquot  = ext4_acquire_dquot,
1127         .release_dquot  = ext4_release_dquot,
1128         .mark_dirty     = ext4_mark_dquot_dirty,
1129         .write_info     = ext4_write_info,
1130         .alloc_dquot    = dquot_alloc,
1131         .destroy_dquot  = dquot_destroy,
1132 };
1133
1134 static const struct quotactl_ops ext4_qctl_operations = {
1135         .quota_on       = ext4_quota_on,
1136         .quota_off      = dquot_quota_off,
1137         .quota_sync     = dquot_quota_sync,
1138         .get_info       = dquot_get_dqinfo,
1139         .set_info       = dquot_set_dqinfo,
1140         .get_dqblk      = dquot_get_dqblk,
1141         .set_dqblk      = dquot_set_dqblk
1142 };
1143 #endif
1144
1145 static const struct super_operations ext4_sops = {
1146         .alloc_inode    = ext4_alloc_inode,
1147         .destroy_inode  = ext4_destroy_inode,
1148         .write_inode    = ext4_write_inode,
1149         .dirty_inode    = ext4_dirty_inode,
1150         .delete_inode   = ext4_delete_inode,
1151         .put_super      = ext4_put_super,
1152         .sync_fs        = ext4_sync_fs,
1153         .freeze_fs      = ext4_freeze,
1154         .unfreeze_fs    = ext4_unfreeze,
1155         .statfs         = ext4_statfs,
1156         .remount_fs     = ext4_remount,
1157         .clear_inode    = ext4_clear_inode,
1158         .show_options   = ext4_show_options,
1159 #ifdef CONFIG_QUOTA
1160         .quota_read     = ext4_quota_read,
1161         .quota_write    = ext4_quota_write,
1162 #endif
1163         .bdev_try_to_free_page = bdev_try_to_free_page,
1164 };
1165
1166 static const struct super_operations ext4_nojournal_sops = {
1167         .alloc_inode    = ext4_alloc_inode,
1168         .destroy_inode  = ext4_destroy_inode,
1169         .write_inode    = ext4_write_inode,
1170         .dirty_inode    = ext4_dirty_inode,
1171         .delete_inode   = ext4_delete_inode,
1172         .write_super    = ext4_write_super,
1173         .put_super      = ext4_put_super,
1174         .statfs         = ext4_statfs,
1175         .remount_fs     = ext4_remount,
1176         .clear_inode    = ext4_clear_inode,
1177         .show_options   = ext4_show_options,
1178 #ifdef CONFIG_QUOTA
1179         .quota_read     = ext4_quota_read,
1180         .quota_write    = ext4_quota_write,
1181 #endif
1182         .bdev_try_to_free_page = bdev_try_to_free_page,
1183 };
1184
1185 static const struct export_operations ext4_export_ops = {
1186         .fh_to_dentry = ext4_fh_to_dentry,
1187         .fh_to_parent = ext4_fh_to_parent,
1188         .get_parent = ext4_get_parent,
1189 };
1190
1191 enum {
1192         Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
1193         Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
1194         Opt_nouid32, Opt_debug, Opt_oldalloc, Opt_orlov,
1195         Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
1196         Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload, Opt_nobh, Opt_bh,
1197         Opt_commit, Opt_min_batch_time, Opt_max_batch_time,
1198         Opt_journal_update, Opt_journal_dev,
1199         Opt_journal_checksum, Opt_journal_async_commit,
1200         Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
1201         Opt_data_err_abort, Opt_data_err_ignore,
1202         Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
1203         Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
1204         Opt_noquota, Opt_ignore, Opt_barrier, Opt_nobarrier, Opt_err,
1205         Opt_resize, Opt_usrquota, Opt_grpquota, Opt_i_version,
1206         Opt_stripe, Opt_delalloc, Opt_nodelalloc,
1207         Opt_block_validity, Opt_noblock_validity,
1208         Opt_inode_readahead_blks, Opt_journal_ioprio,
1209         Opt_dioread_nolock, Opt_dioread_lock,
1210         Opt_discard, Opt_nodiscard,
1211 };
1212
1213 static const match_table_t tokens = {
1214         {Opt_bsd_df, "bsddf"},
1215         {Opt_minix_df, "minixdf"},
1216         {Opt_grpid, "grpid"},
1217         {Opt_grpid, "bsdgroups"},
1218         {Opt_nogrpid, "nogrpid"},
1219         {Opt_nogrpid, "sysvgroups"},
1220         {Opt_resgid, "resgid=%u"},
1221         {Opt_resuid, "resuid=%u"},
1222         {Opt_sb, "sb=%u"},
1223         {Opt_err_cont, "errors=continue"},
1224         {Opt_err_panic, "errors=panic"},
1225         {Opt_err_ro, "errors=remount-ro"},
1226         {Opt_nouid32, "nouid32"},
1227         {Opt_debug, "debug"},
1228         {Opt_oldalloc, "oldalloc"},
1229         {Opt_orlov, "orlov"},
1230         {Opt_user_xattr, "user_xattr"},
1231         {Opt_nouser_xattr, "nouser_xattr"},
1232         {Opt_acl, "acl"},
1233         {Opt_noacl, "noacl"},
1234         {Opt_noload, "noload"},
1235         {Opt_noload, "norecovery"},
1236         {Opt_nobh, "nobh"},
1237         {Opt_bh, "bh"},
1238         {Opt_commit, "commit=%u"},
1239         {Opt_min_batch_time, "min_batch_time=%u"},
1240         {Opt_max_batch_time, "max_batch_time=%u"},
1241         {Opt_journal_update, "journal=update"},
1242         {Opt_journal_dev, "journal_dev=%u"},
1243         {Opt_journal_checksum, "journal_checksum"},
1244         {Opt_journal_async_commit, "journal_async_commit"},
1245         {Opt_abort, "abort"},
1246         {Opt_data_journal, "data=journal"},
1247         {Opt_data_ordered, "data=ordered"},
1248         {Opt_data_writeback, "data=writeback"},
1249         {Opt_data_err_abort, "data_err=abort"},
1250         {Opt_data_err_ignore, "data_err=ignore"},
1251         {Opt_offusrjquota, "usrjquota="},
1252         {Opt_usrjquota, "usrjquota=%s"},
1253         {Opt_offgrpjquota, "grpjquota="},
1254         {Opt_grpjquota, "grpjquota=%s"},
1255         {Opt_jqfmt_vfsold, "jqfmt=vfsold"},
1256         {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
1257         {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
1258         {Opt_grpquota, "grpquota"},
1259         {Opt_noquota, "noquota"},
1260         {Opt_quota, "quota"},
1261         {Opt_usrquota, "usrquota"},
1262         {Opt_barrier, "barrier=%u"},
1263         {Opt_barrier, "barrier"},
1264         {Opt_nobarrier, "nobarrier"},
1265         {Opt_i_version, "i_version"},
1266         {Opt_stripe, "stripe=%u"},
1267         {Opt_resize, "resize"},
1268         {Opt_delalloc, "delalloc"},
1269         {Opt_nodelalloc, "nodelalloc"},
1270         {Opt_block_validity, "block_validity"},
1271         {Opt_noblock_validity, "noblock_validity"},
1272         {Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
1273         {Opt_journal_ioprio, "journal_ioprio=%u"},
1274         {Opt_auto_da_alloc, "auto_da_alloc=%u"},
1275         {Opt_auto_da_alloc, "auto_da_alloc"},
1276         {Opt_noauto_da_alloc, "noauto_da_alloc"},
1277         {Opt_dioread_nolock, "dioread_nolock"},
1278         {Opt_dioread_lock, "dioread_lock"},
1279         {Opt_discard, "discard"},
1280         {Opt_nodiscard, "nodiscard"},
1281         {Opt_err, NULL},
1282 };
1283
1284 static ext4_fsblk_t get_sb_block(void **data)
1285 {
1286         ext4_fsblk_t    sb_block;
1287         char            *options = (char *) *data;
1288
1289         if (!options || strncmp(options, "sb=", 3) != 0)
1290                 return 1;       /* Default location */
1291
1292         options += 3;
1293         /* TODO: use simple_strtoll with >32bit ext4 */
1294         sb_block = simple_strtoul(options, &options, 0);
1295         if (*options && *options != ',') {
1296                 printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
1297                        (char *) *data);
1298                 return 1;
1299         }
1300         if (*options == ',')
1301                 options++;
1302         *data = (void *) options;
1303
1304         return sb_block;
1305 }
1306
1307 #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
1308 static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
1309         "Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
1310
1311 #ifdef CONFIG_QUOTA
1312 static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
1313 {
1314         struct ext4_sb_info *sbi = EXT4_SB(sb);
1315         char *qname;
1316
1317         if (sb_any_quota_loaded(sb) &&
1318                 !sbi->s_qf_names[qtype]) {
1319                 ext4_msg(sb, KERN_ERR,
1320                         "Cannot change journaled "
1321                         "quota options when quota turned on");
1322                 return 0;
1323         }
1324         qname = match_strdup(args);
1325         if (!qname) {
1326                 ext4_msg(sb, KERN_ERR,
1327                         "Not enough memory for storing quotafile name");
1328                 return 0;
1329         }
1330         if (sbi->s_qf_names[qtype] &&
1331                 strcmp(sbi->s_qf_names[qtype], qname)) {
1332                 ext4_msg(sb, KERN_ERR,
1333                         "%s quota file already specified", QTYPE2NAME(qtype));
1334                 kfree(qname);
1335                 return 0;
1336         }
1337         sbi->s_qf_names[qtype] = qname;
1338         if (strchr(sbi->s_qf_names[qtype], '/')) {
1339                 ext4_msg(sb, KERN_ERR,
1340                         "quotafile must be on filesystem root");
1341                 kfree(sbi->s_qf_names[qtype]);
1342                 sbi->s_qf_names[qtype] = NULL;
1343                 return 0;
1344         }
1345         set_opt(sbi->s_mount_opt, QUOTA);
1346         return 1;
1347 }
1348
1349 static int clear_qf_name(struct super_block *sb, int qtype)
1350 {
1351
1352         struct ext4_sb_info *sbi = EXT4_SB(sb);
1353
1354         if (sb_any_quota_loaded(sb) &&
1355                 sbi->s_qf_names[qtype]) {
1356                 ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
1357                         " when quota turned on");
1358                 return 0;
1359         }
1360         /*
1361          * The space will be released later when all options are confirmed
1362          * to be correct
1363          */
1364         sbi->s_qf_names[qtype] = NULL;
1365         return 1;
1366 }
1367 #endif
1368
1369 static int parse_options(char *options, struct super_block *sb,
1370                          unsigned long *journal_devnum,
1371                          unsigned int *journal_ioprio,
1372                          ext4_fsblk_t *n_blocks_count, int is_remount)
1373 {
1374         struct ext4_sb_info *sbi = EXT4_SB(sb);
1375         char *p;
1376         substring_t args[MAX_OPT_ARGS];
1377         int data_opt = 0;
1378         int option;
1379 #ifdef CONFIG_QUOTA
1380         int qfmt;
1381 #endif
1382
1383         if (!options)
1384                 return 1;
1385
1386         while ((p = strsep(&options, ",")) != NULL) {
1387                 int token;
1388                 if (!*p)
1389                         continue;
1390
1391                 /*
1392                  * Initialize args struct so we know whether arg was
1393                  * found; some options take optional arguments.
1394                  */
1395                 args[0].to = args[0].from = 0;
1396                 token = match_token(p, tokens, args);
1397                 switch (token) {
1398                 case Opt_bsd_df:
1399                         ext4_msg(sb, KERN_WARNING, deprecated_msg, p, "2.6.38");
1400                         clear_opt(sbi->s_mount_opt, MINIX_DF);
1401                         break;
1402                 case Opt_minix_df:
1403                         ext4_msg(sb, KERN_WARNING, deprecated_msg, p, "2.6.38");
1404                         set_opt(sbi->s_mount_opt, MINIX_DF);
1405
1406                         break;
1407                 case Opt_grpid:
1408                         ext4_msg(sb, KERN_WARNING, deprecated_msg, p, "2.6.38");
1409                         set_opt(sbi->s_mount_opt, GRPID);
1410
1411                         break;
1412                 case Opt_nogrpid:
1413                         ext4_msg(sb, KERN_WARNING, deprecated_msg, p, "2.6.38");
1414                         clear_opt(sbi->s_mount_opt, GRPID);
1415
1416                         break;
1417                 case Opt_resuid:
1418                         if (match_int(&args[0], &option))
1419                                 return 0;
1420                         sbi->s_resuid = option;
1421                         break;
1422                 case Opt_resgid:
1423                         if (match_int(&args[0], &option))
1424                                 return 0;
1425                         sbi->s_resgid = option;
1426                         break;
1427                 case Opt_sb:
1428                         /* handled by get_sb_block() instead of here */
1429                         /* *sb_block = match_int(&args[0]); */
1430                         break;
1431                 case Opt_err_panic:
1432                         clear_opt(sbi->s_mount_opt, ERRORS_CONT);
1433                         clear_opt(sbi->s_mount_opt, ERRORS_RO);
1434                         set_opt(sbi->s_mount_opt, ERRORS_PANIC);
1435                         break;
1436                 case Opt_err_ro:
1437                         clear_opt(sbi->s_mount_opt, ERRORS_CONT);
1438                         clear_opt(sbi->s_mount_opt, ERRORS_PANIC);
1439                         set_opt(sbi->s_mount_opt, ERRORS_RO);
1440                         break;
1441                 case Opt_err_cont:
1442                         clear_opt(sbi->s_mount_opt, ERRORS_RO);
1443                         clear_opt(sbi->s_mount_opt, ERRORS_PANIC);
1444                         set_opt(sbi->s_mount_opt, ERRORS_CONT);
1445                         break;
1446                 case Opt_nouid32:
1447                         set_opt(sbi->s_mount_opt, NO_UID32);
1448                         break;
1449                 case Opt_debug:
1450                         set_opt(sbi->s_mount_opt, DEBUG);
1451                         break;
1452                 case Opt_oldalloc:
1453                         set_opt(sbi->s_mount_opt, OLDALLOC);
1454                         break;
1455                 case Opt_orlov:
1456                         clear_opt(sbi->s_mount_opt, OLDALLOC);
1457                         break;
1458 #ifdef CONFIG_EXT4_FS_XATTR
1459                 case Opt_user_xattr:
1460                         set_opt(sbi->s_mount_opt, XATTR_USER);
1461                         break;
1462                 case Opt_nouser_xattr:
1463                         clear_opt(sbi->s_mount_opt, XATTR_USER);
1464                         break;
1465 #else
1466                 case Opt_user_xattr:
1467                 case Opt_nouser_xattr:
1468                         ext4_msg(sb, KERN_ERR, "(no)user_xattr options not supported");
1469                         break;
1470 #endif
1471 #ifdef CONFIG_EXT4_FS_POSIX_ACL
1472                 case Opt_acl:
1473                         set_opt(sbi->s_mount_opt, POSIX_ACL);
1474                         break;
1475                 case Opt_noacl:
1476                         clear_opt(sbi->s_mount_opt, POSIX_ACL);
1477                         break;
1478 #else
1479                 case Opt_acl:
1480                 case Opt_noacl:
1481                         ext4_msg(sb, KERN_ERR, "(no)acl options not supported");
1482                         break;
1483 #endif
1484                 case Opt_journal_update:
1485                         /* @@@ FIXME */
1486                         /* Eventually we will want to be able to create
1487                            a journal file here.  For now, only allow the
1488                            user to specify an existing inode to be the
1489                            journal file. */
1490                         if (is_remount) {
1491                                 ext4_msg(sb, KERN_ERR,
1492                                          "Cannot specify journal on remount");
1493                                 return 0;
1494                         }
1495                         set_opt(sbi->s_mount_opt, UPDATE_JOURNAL);
1496                         break;
1497                 case Opt_journal_dev:
1498                         if (is_remount) {
1499                                 ext4_msg(sb, KERN_ERR,
1500                                         "Cannot specify journal on remount");
1501                                 return 0;
1502                         }
1503                         if (match_int(&args[0], &option))
1504                                 return 0;
1505                         *journal_devnum = option;
1506                         break;
1507                 case Opt_journal_checksum:
1508                         set_opt(sbi->s_mount_opt, JOURNAL_CHECKSUM);
1509                         break;
1510                 case Opt_journal_async_commit:
1511                         set_opt(sbi->s_mount_opt, JOURNAL_ASYNC_COMMIT);
1512                         set_opt(sbi->s_mount_opt, JOURNAL_CHECKSUM);
1513                         break;
1514                 case Opt_noload:
1515                         set_opt(sbi->s_mount_opt, NOLOAD);
1516                         break;
1517                 case Opt_commit:
1518                         if (match_int(&args[0], &option))
1519                                 return 0;
1520                         if (option < 0)
1521                                 return 0;
1522                         if (option == 0)
1523                                 option = JBD2_DEFAULT_MAX_COMMIT_AGE;
1524                         sbi->s_commit_interval = HZ * option;
1525                         break;
1526                 case Opt_max_batch_time:
1527                         if (match_int(&args[0], &option))
1528                                 return 0;
1529                         if (option < 0)
1530                                 return 0;
1531                         if (option == 0)
1532                                 option = EXT4_DEF_MAX_BATCH_TIME;
1533                         sbi->s_max_batch_time = option;
1534                         break;
1535                 case Opt_min_batch_time:
1536                         if (match_int(&args[0], &option))
1537                                 return 0;
1538                         if (option < 0)
1539                                 return 0;
1540                         sbi->s_min_batch_time = option;
1541                         break;
1542                 case Opt_data_journal:
1543                         data_opt = EXT4_MOUNT_JOURNAL_DATA;
1544                         goto datacheck;
1545                 case Opt_data_ordered:
1546                         data_opt = EXT4_MOUNT_ORDERED_DATA;
1547                         goto datacheck;
1548                 case Opt_data_writeback:
1549                         data_opt = EXT4_MOUNT_WRITEBACK_DATA;
1550                 datacheck:
1551                         if (is_remount) {
1552                                 if (test_opt(sb, DATA_FLAGS) != data_opt) {
1553                                         ext4_msg(sb, KERN_ERR,
1554                                                 "Cannot change data mode on remount");
1555                                         return 0;
1556                                 }
1557                         } else {
1558                                 clear_opt(sbi->s_mount_opt, DATA_FLAGS);
1559                                 sbi->s_mount_opt |= data_opt;
1560                         }
1561                         break;
1562                 case Opt_data_err_abort:
1563                         set_opt(sbi->s_mount_opt, DATA_ERR_ABORT);
1564                         break;
1565                 case Opt_data_err_ignore:
1566                         clear_opt(sbi->s_mount_opt, DATA_ERR_ABORT);
1567                         break;
1568 #ifdef CONFIG_QUOTA
1569                 case Opt_usrjquota:
1570                         if (!set_qf_name(sb, USRQUOTA, &args[0]))
1571                                 return 0;
1572                         break;
1573                 case Opt_grpjquota:
1574                         if (!set_qf_name(sb, GRPQUOTA, &args[0]))
1575                                 return 0;
1576                         break;
1577                 case Opt_offusrjquota:
1578                         if (!clear_qf_name(sb, USRQUOTA))
1579                                 return 0;
1580                         break;
1581                 case Opt_offgrpjquota:
1582                         if (!clear_qf_name(sb, GRPQUOTA))
1583                                 return 0;
1584                         break;
1585
1586                 case Opt_jqfmt_vfsold:
1587                         qfmt = QFMT_VFS_OLD;
1588                         goto set_qf_format;
1589                 case Opt_jqfmt_vfsv0:
1590                         qfmt = QFMT_VFS_V0;
1591                         goto set_qf_format;
1592                 case Opt_jqfmt_vfsv1:
1593                         qfmt = QFMT_VFS_V1;
1594 set_qf_format:
1595                         if (sb_any_quota_loaded(sb) &&
1596                             sbi->s_jquota_fmt != qfmt) {
1597                                 ext4_msg(sb, KERN_ERR, "Cannot change "
1598                                         "journaled quota options when "
1599                                         "quota turned on");
1600                                 return 0;
1601                         }
1602                         sbi->s_jquota_fmt = qfmt;
1603                         break;
1604                 case Opt_quota:
1605                 case Opt_usrquota:
1606                         set_opt(sbi->s_mount_opt, QUOTA);
1607                         set_opt(sbi->s_mount_opt, USRQUOTA);
1608                         break;
1609                 case Opt_grpquota:
1610                         set_opt(sbi->s_mount_opt, QUOTA);
1611                         set_opt(sbi->s_mount_opt, GRPQUOTA);
1612                         break;
1613                 case Opt_noquota:
1614                         if (sb_any_quota_loaded(sb)) {
1615                                 ext4_msg(sb, KERN_ERR, "Cannot change quota "
1616                                         "options when quota turned on");
1617                                 return 0;
1618                         }
1619                         clear_opt(sbi->s_mount_opt, QUOTA);
1620                         clear_opt(sbi->s_mount_opt, USRQUOTA);
1621                         clear_opt(sbi->s_mount_opt, GRPQUOTA);
1622                         break;
1623 #else
1624                 case Opt_quota:
1625                 case Opt_usrquota:
1626                 case Opt_grpquota:
1627                         ext4_msg(sb, KERN_ERR,
1628                                 "quota options not supported");
1629                         break;
1630                 case Opt_usrjquota:
1631                 case Opt_grpjquota:
1632                 case Opt_offusrjquota:
1633                 case Opt_offgrpjquota:
1634                 case Opt_jqfmt_vfsold:
1635                 case Opt_jqfmt_vfsv0:
1636                 case Opt_jqfmt_vfsv1:
1637                         ext4_msg(sb, KERN_ERR,
1638                                 "journaled quota options not supported");
1639                         break;
1640                 case Opt_noquota:
1641                         break;
1642 #endif
1643                 case Opt_abort:
1644                         sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
1645                         break;
1646                 case Opt_nobarrier:
1647                         clear_opt(sbi->s_mount_opt, BARRIER);
1648                         break;
1649                 case Opt_barrier:
1650                         if (args[0].from) {
1651                                 if (match_int(&args[0], &option))
1652                                         return 0;
1653                         } else
1654                                 option = 1;     /* No argument, default to 1 */
1655                         if (option)
1656                                 set_opt(sbi->s_mount_opt, BARRIER);
1657                         else
1658                                 clear_opt(sbi->s_mount_opt, BARRIER);
1659                         break;
1660                 case Opt_ignore:
1661                         break;
1662                 case Opt_resize:
1663                         if (!is_remount) {
1664                                 ext4_msg(sb, KERN_ERR,
1665                                         "resize option only available "
1666                                         "for remount");
1667                                 return 0;
1668                         }
1669                         if (match_int(&args[0], &option) != 0)
1670                                 return 0;
1671                         *n_blocks_count = option;
1672                         break;
1673                 case Opt_nobh:
1674                         ext4_msg(sb, KERN_WARNING,
1675                                  "Ignoring deprecated nobh option");
1676                         break;
1677                 case Opt_bh:
1678                         ext4_msg(sb, KERN_WARNING,
1679                                  "Ignoring deprecated bh option");
1680                         break;
1681                 case Opt_i_version:
1682                         set_opt(sbi->s_mount_opt, I_VERSION);
1683                         sb->s_flags |= MS_I_VERSION;
1684                         break;
1685                 case Opt_nodelalloc:
1686                         clear_opt(sbi->s_mount_opt, DELALLOC);
1687                         break;
1688                 case Opt_stripe:
1689                         if (match_int(&args[0], &option))
1690                                 return 0;
1691                         if (option < 0)
1692                                 return 0;
1693                         sbi->s_stripe = option;
1694                         break;
1695                 case Opt_delalloc:
1696                         set_opt(sbi->s_mount_opt, DELALLOC);
1697                         break;
1698                 case Opt_block_validity:
1699                         set_opt(sbi->s_mount_opt, BLOCK_VALIDITY);
1700                         break;
1701                 case Opt_noblock_validity:
1702                         clear_opt(sbi->s_mount_opt, BLOCK_VALIDITY);
1703                         break;
1704                 case Opt_inode_readahead_blks:
1705                         if (match_int(&args[0], &option))
1706                                 return 0;
1707                         if (option < 0 || option > (1 << 30))
1708                                 return 0;
1709                         if (!is_power_of_2(option)) {
1710                                 ext4_msg(sb, KERN_ERR,
1711                                          "EXT4-fs: inode_readahead_blks"
1712                                          " must be a power of 2");
1713                                 return 0;
1714                         }
1715                         sbi->s_inode_readahead_blks = option;
1716                         break;
1717                 case Opt_journal_ioprio:
1718                         if (match_int(&args[0], &option))
1719                                 return 0;
1720                         if (option < 0 || option > 7)
1721                                 break;
1722                         *journal_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE,
1723                                                             option);
1724                         break;
1725                 case Opt_noauto_da_alloc:
1726                         set_opt(sbi->s_mount_opt,NO_AUTO_DA_ALLOC);
1727                         break;
1728                 case Opt_auto_da_alloc:
1729                         if (args[0].from) {
1730                                 if (match_int(&args[0], &option))
1731                                         return 0;
1732                         } else
1733                                 option = 1;     /* No argument, default to 1 */
1734                         if (option)
1735                                 clear_opt(sbi->s_mount_opt, NO_AUTO_DA_ALLOC);
1736                         else
1737                                 set_opt(sbi->s_mount_opt,NO_AUTO_DA_ALLOC);
1738                         break;
1739                 case Opt_discard:
1740                         set_opt(sbi->s_mount_opt, DISCARD);
1741                         break;
1742                 case Opt_nodiscard:
1743                         clear_opt(sbi->s_mount_opt, DISCARD);
1744                         break;
1745                 case Opt_dioread_nolock:
1746                         set_opt(sbi->s_mount_opt, DIOREAD_NOLOCK);
1747                         break;
1748                 case Opt_dioread_lock:
1749                         clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK);
1750                         break;
1751                 default:
1752                         ext4_msg(sb, KERN_ERR,
1753                                "Unrecognized mount option \"%s\" "
1754                                "or missing value", p);
1755                         return 0;
1756                 }
1757         }
1758 #ifdef CONFIG_QUOTA
1759         if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
1760                 if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
1761                         clear_opt(sbi->s_mount_opt, USRQUOTA);
1762
1763                 if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
1764                         clear_opt(sbi->s_mount_opt, GRPQUOTA);
1765
1766                 if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
1767                         ext4_msg(sb, KERN_ERR, "old and new quota "
1768                                         "format mixing");
1769                         return 0;
1770                 }
1771
1772                 if (!sbi->s_jquota_fmt) {
1773                         ext4_msg(sb, KERN_ERR, "journaled quota format "
1774                                         "not specified");
1775                         return 0;
1776                 }
1777         } else {
1778                 if (sbi->s_jquota_fmt) {
1779                         ext4_msg(sb, KERN_ERR, "journaled quota format "
1780                                         "specified with no journaling "
1781                                         "enabled");
1782                         return 0;
1783                 }
1784         }
1785 #endif
1786         return 1;
1787 }
1788
1789 static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
1790                             int read_only)
1791 {
1792         struct ext4_sb_info *sbi = EXT4_SB(sb);
1793         int res = 0;
1794
1795         if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
1796                 ext4_msg(sb, KERN_ERR, "revision level too high, "
1797                          "forcing read-only mode");
1798                 res = MS_RDONLY;
1799         }
1800         if (read_only)
1801                 return res;
1802         if (!(sbi->s_mount_state & EXT4_VALID_FS))
1803                 ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
1804                          "running e2fsck is recommended");
1805         else if ((sbi->s_mount_state & EXT4_ERROR_FS))
1806                 ext4_msg(sb, KERN_WARNING,
1807                          "warning: mounting fs with errors, "
1808                          "running e2fsck is recommended");
1809         else if ((__s16) le16_to_cpu(es->s_max_mnt_count) >= 0 &&
1810                  le16_to_cpu(es->s_mnt_count) >=
1811                  (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
1812                 ext4_msg(sb, KERN_WARNING,
1813                          "warning: maximal mount count reached, "
1814                          "running e2fsck is recommended");
1815         else if (le32_to_cpu(es->s_checkinterval) &&
1816                 (le32_to_cpu(es->s_lastcheck) +
1817                         le32_to_cpu(es->s_checkinterval) <= get_seconds()))
1818                 ext4_msg(sb, KERN_WARNING,
1819                          "warning: checktime reached, "
1820                          "running e2fsck is recommended");
1821         if (!sbi->s_journal)
1822                 es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
1823         if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
1824                 es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
1825         le16_add_cpu(&es->s_mnt_count, 1);
1826         es->s_mtime = cpu_to_le32(get_seconds());
1827         ext4_update_dynamic_rev(sb);
1828         if (sbi->s_journal)
1829                 EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
1830
1831         ext4_commit_super(sb, 1);
1832         if (test_opt(sb, DEBUG))
1833                 printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
1834                                 "bpg=%lu, ipg=%lu, mo=%04x]\n",
1835                         sb->s_blocksize,
1836                         sbi->s_groups_count,
1837                         EXT4_BLOCKS_PER_GROUP(sb),
1838                         EXT4_INODES_PER_GROUP(sb),
1839                         sbi->s_mount_opt);
1840
1841         return res;
1842 }
1843
1844 static int ext4_fill_flex_info(struct super_block *sb)
1845 {
1846         struct ext4_sb_info *sbi = EXT4_SB(sb);
1847         struct ext4_group_desc *gdp = NULL;
1848         ext4_group_t flex_group_count;
1849         ext4_group_t flex_group;
1850         int groups_per_flex = 0;
1851         size_t size;
1852         int i;
1853
1854         sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
1855         groups_per_flex = 1 << sbi->s_log_groups_per_flex;
1856
1857         if (groups_per_flex < 2) {
1858                 sbi->s_log_groups_per_flex = 0;
1859                 return 1;
1860         }
1861
1862         /* We allocate both existing and potentially added groups */
1863         flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +
1864                         ((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) <<
1865                               EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex;
1866         size = flex_group_count * sizeof(struct flex_groups);
1867         sbi->s_flex_groups = kzalloc(size, GFP_KERNEL);
1868         if (sbi->s_flex_groups == NULL) {
1869                 sbi->s_flex_groups = vmalloc(size);
1870                 if (sbi->s_flex_groups)
1871                         memset(sbi->s_flex_groups, 0, size);
1872         }
1873         if (sbi->s_flex_groups == NULL) {
1874                 ext4_msg(sb, KERN_ERR, "not enough memory for "
1875                                 "%u flex groups", flex_group_count);
1876                 goto failed;
1877         }
1878
1879         for (i = 0; i < sbi->s_groups_count; i++) {
1880                 gdp = ext4_get_group_desc(sb, i, NULL);
1881
1882                 flex_group = ext4_flex_group(sbi, i);
1883                 atomic_add(ext4_free_inodes_count(sb, gdp),
1884                            &sbi->s_flex_groups[flex_group].free_inodes);
1885                 atomic_add(ext4_free_blks_count(sb, gdp),
1886                            &sbi->s_flex_groups[flex_group].free_blocks);
1887                 atomic_add(ext4_used_dirs_count(sb, gdp),
1888                            &sbi->s_flex_groups[flex_group].used_dirs);
1889         }
1890
1891         return 1;
1892 failed:
1893         return 0;
1894 }
1895
1896 __le16 ext4_group_desc_csum(struct ext4_sb_info *sbi, __u32 block_group,
1897                             struct ext4_group_desc *gdp)
1898 {
1899         __u16 crc = 0;
1900
1901         if (sbi->s_es->s_feature_ro_compat &
1902             cpu_to_le32(EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1903                 int offset = offsetof(struct ext4_group_desc, bg_checksum);
1904                 __le32 le_group = cpu_to_le32(block_group);
1905
1906                 crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
1907                 crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
1908                 crc = crc16(crc, (__u8 *)gdp, offset);
1909                 offset += sizeof(gdp->bg_checksum); /* skip checksum */
1910                 /* for checksum of struct ext4_group_desc do the rest...*/
1911                 if ((sbi->s_es->s_feature_incompat &
1912                      cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT)) &&
1913                     offset < le16_to_cpu(sbi->s_es->s_desc_size))
1914                         crc = crc16(crc, (__u8 *)gdp + offset,
1915                                     le16_to_cpu(sbi->s_es->s_desc_size) -
1916                                         offset);
1917         }
1918
1919         return cpu_to_le16(crc);
1920 }
1921
1922 int ext4_group_desc_csum_verify(struct ext4_sb_info *sbi, __u32 block_group,
1923                                 struct ext4_group_desc *gdp)
1924 {
1925         if ((sbi->s_es->s_feature_ro_compat &
1926              cpu_to_le32(EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) &&
1927             (gdp->bg_checksum != ext4_group_desc_csum(sbi, block_group, gdp)))
1928                 return 0;
1929
1930         return 1;
1931 }
1932
1933 /* Called at mount-time, super-block is locked */
1934 static int ext4_check_descriptors(struct super_block *sb)
1935 {
1936         struct ext4_sb_info *sbi = EXT4_SB(sb);
1937         ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
1938         ext4_fsblk_t last_block;
1939         ext4_fsblk_t block_bitmap;
1940         ext4_fsblk_t inode_bitmap;
1941         ext4_fsblk_t inode_table;
1942         int flexbg_flag = 0;
1943         ext4_group_t i;
1944
1945         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
1946                 flexbg_flag = 1;
1947
1948         ext4_debug("Checking group descriptors");
1949
1950         for (i = 0; i < sbi->s_groups_count; i++) {
1951                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1952
1953                 if (i == sbi->s_groups_count - 1 || flexbg_flag)
1954                         last_block = ext4_blocks_count(sbi->s_es) - 1;
1955                 else
1956                         last_block = first_block +
1957                                 (EXT4_BLOCKS_PER_GROUP(sb) - 1);
1958
1959                 block_bitmap = ext4_block_bitmap(sb, gdp);
1960                 if (block_bitmap < first_block || block_bitmap > last_block) {
1961                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
1962                                "Block bitmap for group %u not in group "
1963                                "(block %llu)!", i, block_bitmap);
1964                         return 0;
1965                 }
1966                 inode_bitmap = ext4_inode_bitmap(sb, gdp);
1967                 if (inode_bitmap < first_block || inode_bitmap > last_block) {
1968                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
1969                                "Inode bitmap for group %u not in group "
1970                                "(block %llu)!", i, inode_bitmap);
1971                         return 0;
1972                 }
1973                 inode_table = ext4_inode_table(sb, gdp);
1974                 if (inode_table < first_block ||
1975                     inode_table + sbi->s_itb_per_group - 1 > last_block) {
1976                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
1977                                "Inode table for group %u not in group "
1978                                "(block %llu)!", i, inode_table);
1979                         return 0;
1980                 }
1981                 ext4_lock_group(sb, i);
1982                 if (!ext4_group_desc_csum_verify(sbi, i, gdp)) {
1983                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
1984                                  "Checksum for group %u failed (%u!=%u)",
1985                                  i, le16_to_cpu(ext4_group_desc_csum(sbi, i,
1986                                      gdp)), le16_to_cpu(gdp->bg_checksum));
1987                         if (!(sb->s_flags & MS_RDONLY)) {
1988                                 ext4_unlock_group(sb, i);
1989                                 return 0;
1990                         }
1991                 }
1992                 ext4_unlock_group(sb, i);
1993                 if (!flexbg_flag)
1994                         first_block += EXT4_BLOCKS_PER_GROUP(sb);
1995         }
1996
1997         ext4_free_blocks_count_set(sbi->s_es, ext4_count_free_blocks(sb));
1998         sbi->s_es->s_free_inodes_count =cpu_to_le32(ext4_count_free_inodes(sb));
1999         return 1;
2000 }
2001
2002 /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
2003  * the superblock) which were deleted from all directories, but held open by
2004  * a process at the time of a crash.  We walk the list and try to delete these
2005  * inodes at recovery time (only with a read-write filesystem).
2006  *
2007  * In order to keep the orphan inode chain consistent during traversal (in
2008  * case of crash during recovery), we link each inode into the superblock
2009  * orphan list_head and handle it the same way as an inode deletion during
2010  * normal operation (which journals the operations for us).
2011  *
2012  * We only do an iget() and an iput() on each inode, which is very safe if we
2013  * accidentally point at an in-use or already deleted inode.  The worst that
2014  * can happen in this case is that we get a "bit already cleared" message from
2015  * ext4_free_inode().  The only reason we would point at a wrong inode is if
2016  * e2fsck was run on this filesystem, and it must have already done the orphan
2017  * inode cleanup for us, so we can safely abort without any further action.
2018  */
2019 static void ext4_orphan_cleanup(struct super_block *sb,
2020                                 struct ext4_super_block *es)
2021 {
2022         unsigned int s_flags = sb->s_flags;
2023         int nr_orphans = 0, nr_truncates = 0;
2024 #ifdef CONFIG_QUOTA
2025         int i;
2026 #endif
2027         if (!es->s_last_orphan) {
2028                 jbd_debug(4, "no orphan inodes to clean up\n");
2029                 return;
2030         }
2031
2032         if (bdev_read_only(sb->s_bdev)) {
2033                 ext4_msg(sb, KERN_ERR, "write access "
2034                         "unavailable, skipping orphan cleanup");
2035                 return;
2036         }
2037
2038         if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2039                 if (es->s_last_orphan)
2040                         jbd_debug(1, "Errors on filesystem, "
2041                                   "clearing orphan list.\n");
2042                 es->s_last_orphan = 0;
2043                 jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2044                 return;
2045         }
2046
2047         if (s_flags & MS_RDONLY) {
2048                 ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
2049                 sb->s_flags &= ~MS_RDONLY;
2050         }
2051 #ifdef CONFIG_QUOTA
2052         /* Needed for iput() to work correctly and not trash data */
2053         sb->s_flags |= MS_ACTIVE;
2054         /* Turn on quotas so that they are updated correctly */
2055         for (i = 0; i < MAXQUOTAS; i++) {
2056                 if (EXT4_SB(sb)->s_qf_names[i]) {
2057                         int ret = ext4_quota_on_mount(sb, i);
2058                         if (ret < 0)
2059                                 ext4_msg(sb, KERN_ERR,
2060                                         "Cannot turn on journaled "
2061                                         "quota: error %d", ret);
2062                 }
2063         }
2064 #endif
2065
2066         while (es->s_last_orphan) {
2067                 struct inode *inode;
2068
2069                 inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
2070                 if (IS_ERR(inode)) {
2071                         es->s_last_orphan = 0;
2072                         break;
2073                 }
2074
2075                 list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
2076                 dquot_initialize(inode);
2077                 if (inode->i_nlink) {
2078                         ext4_msg(sb, KERN_DEBUG,
2079                                 "%s: truncating inode %lu to %lld bytes",
2080                                 __func__, inode->i_ino, inode->i_size);
2081                         jbd_debug(2, "truncating inode %lu to %lld bytes\n",
2082                                   inode->i_ino, inode->i_size);
2083                         ext4_truncate(inode);
2084                         nr_truncates++;
2085                 } else {
2086                         ext4_msg(sb, KERN_DEBUG,
2087                                 "%s: deleting unreferenced inode %lu",
2088                                 __func__, inode->i_ino);
2089                         jbd_debug(2, "deleting unreferenced inode %lu\n",
2090                                   inode->i_ino);
2091                         nr_orphans++;
2092                 }
2093                 iput(inode);  /* The delete magic happens here! */
2094         }
2095
2096 #define PLURAL(x) (x), ((x) == 1) ? "" : "s"
2097
2098         if (nr_orphans)
2099                 ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
2100                        PLURAL(nr_orphans));
2101         if (nr_truncates)
2102                 ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
2103                        PLURAL(nr_truncates));
2104 #ifdef CONFIG_QUOTA
2105         /* Turn quotas off */
2106         for (i = 0; i < MAXQUOTAS; i++) {
2107                 if (sb_dqopt(sb)->files[i])
2108                         dquot_quota_off(sb, i);
2109         }
2110 #endif
2111         sb->s_flags = s_flags; /* Restore MS_RDONLY status */
2112 }
2113
2114 /*
2115  * Maximal extent format file size.
2116  * Resulting logical blkno at s_maxbytes must fit in our on-disk
2117  * extent format containers, within a sector_t, and within i_blocks
2118  * in the vfs.  ext4 inode has 48 bits of i_block in fsblock units,
2119  * so that won't be a limiting factor.
2120  *
2121  * Note, this does *not* consider any metadata overhead for vfs i_blocks.
2122  */
2123 static loff_t ext4_max_size(int blkbits, int has_huge_files)
2124 {
2125         loff_t res;
2126         loff_t upper_limit = MAX_LFS_FILESIZE;
2127
2128         /* small i_blocks in vfs inode? */
2129         if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
2130                 /*
2131                  * CONFIG_LBDAF is not enabled implies the inode
2132                  * i_block represent total blocks in 512 bytes
2133                  * 32 == size of vfs inode i_blocks * 8
2134                  */
2135                 upper_limit = (1LL << 32) - 1;
2136
2137                 /* total blocks in file system block size */
2138                 upper_limit >>= (blkbits - 9);
2139                 upper_limit <<= blkbits;
2140         }
2141
2142         /* 32-bit extent-start container, ee_block */
2143         res = 1LL << 32;
2144         res <<= blkbits;
2145         res -= 1;
2146
2147         /* Sanity check against vm- & vfs- imposed limits */
2148         if (res > upper_limit)
2149                 res = upper_limit;
2150
2151         return res;
2152 }
2153
2154 /*
2155  * Maximal bitmap file size.  There is a direct, and {,double-,triple-}indirect
2156  * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
2157  * We need to be 1 filesystem block less than the 2^48 sector limit.
2158  */
2159 static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
2160 {
2161         loff_t res = EXT4_NDIR_BLOCKS;
2162         int meta_blocks;
2163         loff_t upper_limit;
2164         /* This is calculated to be the largest file size for a dense, block
2165          * mapped file such that the file's total number of 512-byte sectors,
2166          * including data and all indirect blocks, does not exceed (2^48 - 1).
2167          *
2168          * __u32 i_blocks_lo and _u16 i_blocks_high represent the total
2169          * number of 512-byte sectors of the file.
2170          */
2171
2172         if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
2173                 /*
2174                  * !has_huge_files or CONFIG_LBDAF not enabled implies that
2175                  * the inode i_block field represents total file blocks in
2176                  * 2^32 512-byte sectors == size of vfs inode i_blocks * 8
2177                  */
2178                 upper_limit = (1LL << 32) - 1;
2179
2180                 /* total blocks in file system block size */
2181                 upper_limit >>= (bits - 9);
2182
2183         } else {
2184                 /*
2185                  * We use 48 bit ext4_inode i_blocks
2186                  * With EXT4_HUGE_FILE_FL set the i_blocks
2187                  * represent total number of blocks in
2188                  * file system block size
2189                  */
2190                 upper_limit = (1LL << 48) - 1;
2191
2192         }
2193
2194         /* indirect blocks */
2195         meta_blocks = 1;
2196         /* double indirect blocks */
2197         meta_blocks += 1 + (1LL << (bits-2));
2198         /* tripple indirect blocks */
2199         meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
2200
2201         upper_limit -= meta_blocks;
2202         upper_limit <<= bits;
2203
2204         res += 1LL << (bits-2);
2205         res += 1LL << (2*(bits-2));
2206         res += 1LL << (3*(bits-2));
2207         res <<= bits;
2208         if (res > upper_limit)
2209                 res = upper_limit;
2210
2211         if (res > MAX_LFS_FILESIZE)
2212                 res = MAX_LFS_FILESIZE;
2213
2214         return res;
2215 }
2216
2217 static ext4_fsblk_t descriptor_loc(struct super_block *sb,
2218                                    ext4_fsblk_t logical_sb_block, int nr)
2219 {
2220         struct ext4_sb_info *sbi = EXT4_SB(sb);
2221         ext4_group_t bg, first_meta_bg;
2222         int has_super = 0;
2223
2224         first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
2225
2226         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_META_BG) ||
2227             nr < first_meta_bg)
2228                 return logical_sb_block + nr + 1;
2229         bg = sbi->s_desc_per_block * nr;
2230         if (ext4_bg_has_super(sb, bg))
2231                 has_super = 1;
2232
2233         return (has_super + ext4_group_first_block_no(sb, bg));
2234 }
2235
2236 /**
2237  * ext4_get_stripe_size: Get the stripe size.
2238  * @sbi: In memory super block info
2239  *
2240  * If we have specified it via mount option, then
2241  * use the mount option value. If the value specified at mount time is
2242  * greater than the blocks per group use the super block value.
2243  * If the super block value is greater than blocks per group return 0.
2244  * Allocator needs it be less than blocks per group.
2245  *
2246  */
2247 static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
2248 {
2249         unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
2250         unsigned long stripe_width =
2251                         le32_to_cpu(sbi->s_es->s_raid_stripe_width);
2252
2253         if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
2254                 return sbi->s_stripe;
2255
2256         if (stripe_width <= sbi->s_blocks_per_group)
2257                 return stripe_width;
2258
2259         if (stride <= sbi->s_blocks_per_group)
2260                 return stride;
2261
2262         return 0;
2263 }
2264
2265 /* sysfs supprt */
2266
2267 struct ext4_attr {
2268         struct attribute attr;
2269         ssize_t (*show)(struct ext4_attr *, struct ext4_sb_info *, char *);
2270         ssize_t (*store)(struct ext4_attr *, struct ext4_sb_info *,
2271                          const char *, size_t);
2272         int offset;
2273 };
2274
2275 static int parse_strtoul(const char *buf,
2276                 unsigned long max, unsigned long *value)
2277 {
2278         char *endp;
2279
2280         *value = simple_strtoul(skip_spaces(buf), &endp, 0);
2281         endp = skip_spaces(endp);
2282         if (*endp || *value > max)
2283                 return -EINVAL;
2284
2285         return 0;
2286 }
2287
2288 static ssize_t delayed_allocation_blocks_show(struct ext4_attr *a,
2289                                               struct ext4_sb_info *sbi,
2290                                               char *buf)
2291 {
2292         return snprintf(buf, PAGE_SIZE, "%llu\n",
2293                         (s64) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2294 }
2295
2296 static ssize_t session_write_kbytes_show(struct ext4_attr *a,
2297                                          struct ext4_sb_info *sbi, char *buf)
2298 {
2299         struct super_block *sb = sbi->s_buddy_cache->i_sb;
2300
2301         return snprintf(buf, PAGE_SIZE, "%lu\n",
2302                         (part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
2303                          sbi->s_sectors_written_start) >> 1);
2304 }
2305
2306 static ssize_t lifetime_write_kbytes_show(struct ext4_attr *a,
2307                                           struct ext4_sb_info *sbi, char *buf)
2308 {
2309         struct super_block *sb = sbi->s_buddy_cache->i_sb;
2310
2311         return snprintf(buf, PAGE_SIZE, "%llu\n",
2312                         (unsigned long long)(sbi->s_kbytes_written +
2313                         ((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
2314                           EXT4_SB(sb)->s_sectors_written_start) >> 1)));
2315 }
2316
2317 static ssize_t inode_readahead_blks_store(struct ext4_attr *a,
2318                                           struct ext4_sb_info *sbi,
2319                                           const char *buf, size_t count)
2320 {
2321         unsigned long t;
2322
2323         if (parse_strtoul(buf, 0x40000000, &t))
2324                 return -EINVAL;
2325
2326         if (!is_power_of_2(t))
2327                 return -EINVAL;
2328
2329         sbi->s_inode_readahead_blks = t;
2330         return count;
2331 }
2332
2333 static ssize_t sbi_ui_show(struct ext4_attr *a,
2334                            struct ext4_sb_info *sbi, char *buf)
2335 {
2336         unsigned int *ui = (unsigned int *) (((char *) sbi) + a->offset);
2337
2338         return snprintf(buf, PAGE_SIZE, "%u\n", *ui);
2339 }
2340
2341 static ssize_t sbi_ui_store(struct ext4_attr *a,
2342                             struct ext4_sb_info *sbi,
2343                             const char *buf, size_t count)
2344 {
2345         unsigned int *ui = (unsigned int *) (((char *) sbi) + a->offset);
2346         unsigned long t;
2347
2348         if (parse_strtoul(buf, 0xffffffff, &t))
2349                 return -EINVAL;
2350         *ui = t;
2351         return count;
2352 }
2353
2354 #define EXT4_ATTR_OFFSET(_name,_mode,_show,_store,_elname) \
2355 static struct ext4_attr ext4_attr_##_name = {                   \
2356         .attr = {.name = __stringify(_name), .mode = _mode },   \
2357         .show   = _show,                                        \
2358         .store  = _store,                                       \
2359         .offset = offsetof(struct ext4_sb_info, _elname),       \
2360 }
2361 #define EXT4_ATTR(name, mode, show, store) \
2362 static struct ext4_attr ext4_attr_##name = __ATTR(name, mode, show, store)
2363
2364 #define EXT4_RO_ATTR(name) EXT4_ATTR(name, 0444, name##_show, NULL)
2365 #define EXT4_RW_ATTR(name) EXT4_ATTR(name, 0644, name##_show, name##_store)
2366 #define EXT4_RW_ATTR_SBI_UI(name, elname)       \
2367         EXT4_ATTR_OFFSET(name, 0644, sbi_ui_show, sbi_ui_store, elname)
2368 #define ATTR_LIST(name) &ext4_attr_##name.attr
2369
2370 EXT4_RO_ATTR(delayed_allocation_blocks);
2371 EXT4_RO_ATTR(session_write_kbytes);
2372 EXT4_RO_ATTR(lifetime_write_kbytes);
2373 EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, sbi_ui_show,
2374                  inode_readahead_blks_store, s_inode_readahead_blks);
2375 EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
2376 EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
2377 EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
2378 EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
2379 EXT4_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs);
2380 EXT4_RW_ATTR_SBI_UI(mb_stream_req, s_mb_stream_request);
2381 EXT4_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc);
2382 EXT4_RW_ATTR_SBI_UI(max_writeback_mb_bump, s_max_writeback_mb_bump);
2383
2384 static struct attribute *ext4_attrs[] = {
2385         ATTR_LIST(delayed_allocation_blocks),
2386         ATTR_LIST(session_write_kbytes),
2387         ATTR_LIST(lifetime_write_kbytes),
2388         ATTR_LIST(inode_readahead_blks),
2389         ATTR_LIST(inode_goal),
2390         ATTR_LIST(mb_stats),
2391         ATTR_LIST(mb_max_to_scan),
2392         ATTR_LIST(mb_min_to_scan),
2393         ATTR_LIST(mb_order2_req),
2394         ATTR_LIST(mb_stream_req),
2395         ATTR_LIST(mb_group_prealloc),
2396         ATTR_LIST(max_writeback_mb_bump),
2397         NULL,
2398 };
2399
2400 static ssize_t ext4_attr_show(struct kobject *kobj,
2401                               struct attribute *attr, char *buf)
2402 {
2403         struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
2404                                                 s_kobj);
2405         struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
2406
2407         return a->show ? a->show(a, sbi, buf) : 0;
2408 }
2409
2410 static ssize_t ext4_attr_store(struct kobject *kobj,
2411                                struct attribute *attr,
2412                                const char *buf, size_t len)
2413 {
2414         struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
2415                                                 s_kobj);
2416         struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
2417
2418         return a->store ? a->store(a, sbi, buf, len) : 0;
2419 }
2420
2421 static void ext4_sb_release(struct kobject *kobj)
2422 {
2423         struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
2424                                                 s_kobj);
2425         complete(&sbi->s_kobj_unregister);
2426 }
2427
2428
2429 static const struct sysfs_ops ext4_attr_ops = {
2430         .show   = ext4_attr_show,
2431         .store  = ext4_attr_store,
2432 };
2433
2434 static struct kobj_type ext4_ktype = {
2435         .default_attrs  = ext4_attrs,
2436         .sysfs_ops      = &ext4_attr_ops,
2437         .release        = ext4_sb_release,
2438 };
2439
2440 /*
2441  * Check whether this filesystem can be mounted based on
2442  * the features present and the RDONLY/RDWR mount requested.
2443  * Returns 1 if this filesystem can be mounted as requested,
2444  * 0 if it cannot be.
2445  */
2446 static int ext4_feature_set_ok(struct super_block *sb, int readonly)
2447 {
2448         if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP)) {
2449                 ext4_msg(sb, KERN_ERR,
2450                         "Couldn't mount because of "
2451                         "unsupported optional features (%x)",
2452                         (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
2453                         ~EXT4_FEATURE_INCOMPAT_SUPP));
2454                 return 0;
2455         }
2456
2457         if (readonly)
2458                 return 1;
2459
2460         /* Check that feature set is OK for a read-write mount */
2461         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP)) {
2462                 ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
2463                          "unsupported optional features (%x)",
2464                          (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
2465                                 ~EXT4_FEATURE_RO_COMPAT_SUPP));
2466                 return 0;
2467         }
2468         /*
2469          * Large file size enabled file system can only be mounted
2470          * read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
2471          */
2472         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
2473                 if (sizeof(blkcnt_t) < sizeof(u64)) {
2474                         ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
2475                                  "cannot be mounted RDWR without "
2476                                  "CONFIG_LBDAF");
2477                         return 0;
2478                 }
2479         }
2480         return 1;
2481 }
2482
2483 static int ext4_fill_super(struct super_block *sb, void *data, int silent)
2484                                 __releases(kernel_lock)
2485                                 __acquires(kernel_lock)
2486 {
2487         char *orig_data = kstrdup(data, GFP_KERNEL);
2488         struct buffer_head *bh;
2489         struct ext4_super_block *es = NULL;
2490         struct ext4_sb_info *sbi;
2491         ext4_fsblk_t block;
2492         ext4_fsblk_t sb_block = get_sb_block(&data);
2493         ext4_fsblk_t logical_sb_block;
2494         unsigned long offset = 0;
2495         unsigned long journal_devnum = 0;
2496         unsigned long def_mount_opts;
2497         struct inode *root;
2498         char *cp;
2499         const char *descr;
2500         int ret = -EINVAL;
2501         int blocksize;
2502         unsigned int db_count;
2503         unsigned int i;
2504         int needs_recovery, has_huge_files;
2505         __u64 blocks_count;
2506         int err;
2507         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
2508
2509         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2510         if (!sbi)
2511                 return -ENOMEM;
2512
2513         sbi->s_blockgroup_lock =
2514                 kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
2515         if (!sbi->s_blockgroup_lock) {
2516                 kfree(sbi);
2517                 return -ENOMEM;
2518         }
2519         sb->s_fs_info = sbi;
2520         sbi->s_mount_opt = 0;
2521         sbi->s_resuid = EXT4_DEF_RESUID;
2522         sbi->s_resgid = EXT4_DEF_RESGID;
2523         sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
2524         sbi->s_sb_block = sb_block;
2525         sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part,
2526                                                       sectors[1]);
2527
2528         unlock_kernel();
2529
2530         /* Cleanup superblock name */
2531         for (cp = sb->s_id; (cp = strchr(cp, '/'));)
2532                 *cp = '!';
2533
2534         blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
2535         if (!blocksize) {
2536                 ext4_msg(sb, KERN_ERR, "unable to set blocksize");
2537                 goto out_fail;
2538         }
2539
2540         /*
2541          * The ext4 superblock will not be buffer aligned for other than 1kB
2542          * block sizes.  We need to calculate the offset from buffer start.
2543          */
2544         if (blocksize != EXT4_MIN_BLOCK_SIZE) {
2545                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
2546                 offset = do_div(logical_sb_block, blocksize);
2547         } else {
2548                 logical_sb_block = sb_block;
2549         }
2550
2551         if (!(bh = sb_bread(sb, logical_sb_block))) {
2552                 ext4_msg(sb, KERN_ERR, "unable to read superblock");
2553                 goto out_fail;
2554         }
2555         /*
2556          * Note: s_es must be initialized as soon as possible because
2557          *       some ext4 macro-instructions depend on its value
2558          */
2559         es = (struct ext4_super_block *) (((char *)bh->b_data) + offset);
2560         sbi->s_es = es;
2561         sb->s_magic = le16_to_cpu(es->s_magic);
2562         if (sb->s_magic != EXT4_SUPER_MAGIC)
2563                 goto cantfind_ext4;
2564         sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
2565
2566         /* Set defaults before we parse the mount options */
2567         def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
2568         if (def_mount_opts & EXT4_DEFM_DEBUG)
2569                 set_opt(sbi->s_mount_opt, DEBUG);
2570         if (def_mount_opts & EXT4_DEFM_BSDGROUPS) {
2571                 ext4_msg(sb, KERN_WARNING, deprecated_msg, "bsdgroups",
2572                         "2.6.38");
2573                 set_opt(sbi->s_mount_opt, GRPID);
2574         }
2575         if (def_mount_opts & EXT4_DEFM_UID16)
2576                 set_opt(sbi->s_mount_opt, NO_UID32);
2577 #ifdef CONFIG_EXT4_FS_XATTR
2578         if (def_mount_opts & EXT4_DEFM_XATTR_USER)
2579                 set_opt(sbi->s_mount_opt, XATTR_USER);
2580 #endif
2581 #ifdef CONFIG_EXT4_FS_POSIX_ACL
2582         if (def_mount_opts & EXT4_DEFM_ACL)
2583                 set_opt(sbi->s_mount_opt, POSIX_ACL);
2584 #endif
2585         if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
2586                 set_opt(sbi->s_mount_opt, JOURNAL_DATA);
2587         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
2588                 set_opt(sbi->s_mount_opt, ORDERED_DATA);
2589         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
2590                 set_opt(sbi->s_mount_opt, WRITEBACK_DATA);
2591
2592         if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
2593                 set_opt(sbi->s_mount_opt, ERRORS_PANIC);
2594         else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
2595                 set_opt(sbi->s_mount_opt, ERRORS_CONT);
2596         else
2597                 set_opt(sbi->s_mount_opt, ERRORS_RO);
2598
2599         sbi->s_resuid = le16_to_cpu(es->s_def_resuid);
2600         sbi->s_resgid = le16_to_cpu(es->s_def_resgid);
2601         sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
2602         sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
2603         sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
2604
2605         set_opt(sbi->s_mount_opt, BARRIER);
2606
2607         /*
2608          * enable delayed allocation by default
2609          * Use -o nodelalloc to turn it off
2610          */
2611         if (!IS_EXT3_SB(sb))
2612                 set_opt(sbi->s_mount_opt, DELALLOC);
2613
2614         if (!parse_options((char *) data, sb, &journal_devnum,
2615                            &journal_ioprio, NULL, 0))
2616                 goto failed_mount;
2617
2618         sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
2619                 (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
2620
2621         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
2622             (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) ||
2623              EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
2624              EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U)))
2625                 ext4_msg(sb, KERN_WARNING,
2626                        "feature flags set on rev 0 fs, "
2627                        "running e2fsck is recommended");
2628
2629         /*
2630          * Check feature flags regardless of the revision level, since we
2631          * previously didn't change the revision level when setting the flags,
2632          * so there is a chance incompat flags are set on a rev 0 filesystem.
2633          */
2634         if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
2635                 goto failed_mount;
2636
2637         blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
2638
2639         if (blocksize < EXT4_MIN_BLOCK_SIZE ||
2640             blocksize > EXT4_MAX_BLOCK_SIZE) {
2641                 ext4_msg(sb, KERN_ERR,
2642                        "Unsupported filesystem blocksize %d", blocksize);
2643                 goto failed_mount;
2644         }
2645
2646         if (sb->s_blocksize != blocksize) {
2647                 /* Validate the filesystem blocksize */
2648                 if (!sb_set_blocksize(sb, blocksize)) {
2649                         ext4_msg(sb, KERN_ERR, "bad block size %d",
2650                                         blocksize);
2651                         goto failed_mount;
2652                 }
2653
2654                 brelse(bh);
2655                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
2656                 offset = do_div(logical_sb_block, blocksize);
2657                 bh = sb_bread(sb, logical_sb_block);
2658                 if (!bh) {
2659                         ext4_msg(sb, KERN_ERR,
2660                                "Can't read superblock on 2nd try");
2661                         goto failed_mount;
2662                 }
2663                 es = (struct ext4_super_block *)(((char *)bh->b_data) + offset);
2664                 sbi->s_es = es;
2665                 if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
2666                         ext4_msg(sb, KERN_ERR,
2667                                "Magic mismatch, very weird!");
2668                         goto failed_mount;
2669                 }
2670         }
2671
2672         has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb,
2673                                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
2674         sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
2675                                                       has_huge_files);
2676         sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
2677
2678         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
2679                 sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
2680                 sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
2681         } else {
2682                 sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
2683                 sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
2684                 if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
2685                     (!is_power_of_2(sbi->s_inode_size)) ||
2686                     (sbi->s_inode_size > blocksize)) {
2687                         ext4_msg(sb, KERN_ERR,
2688                                "unsupported inode size: %d",
2689                                sbi->s_inode_size);
2690                         goto failed_mount;
2691                 }
2692                 if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
2693                         sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
2694         }
2695
2696         sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
2697         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) {
2698                 if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
2699                     sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
2700                     !is_power_of_2(sbi->s_desc_size)) {
2701                         ext4_msg(sb, KERN_ERR,
2702                                "unsupported descriptor size %lu",
2703                                sbi->s_desc_size);
2704                         goto failed_mount;
2705                 }
2706         } else
2707                 sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
2708
2709         sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
2710         sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
2711         if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)
2712                 goto cantfind_ext4;
2713
2714         sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
2715         if (sbi->s_inodes_per_block == 0)
2716                 goto cantfind_ext4;
2717         sbi->s_itb_per_group = sbi->s_inodes_per_group /
2718                                         sbi->s_inodes_per_block;
2719         sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
2720         sbi->s_sbh = bh;
2721         sbi->s_mount_state = le16_to_cpu(es->s_state);
2722         sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
2723         sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
2724
2725         for (i = 0; i < 4; i++)
2726                 sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
2727         sbi->s_def_hash_version = es->s_def_hash_version;
2728         i = le32_to_cpu(es->s_flags);
2729         if (i & EXT2_FLAGS_UNSIGNED_HASH)
2730                 sbi->s_hash_unsigned = 3;
2731         else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
2732 #ifdef __CHAR_UNSIGNED__
2733                 es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
2734                 sbi->s_hash_unsigned = 3;
2735 #else
2736                 es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
2737 #endif
2738                 sb->s_dirt = 1;
2739         }
2740
2741         if (sbi->s_blocks_per_group > blocksize * 8) {
2742                 ext4_msg(sb, KERN_ERR,
2743                        "#blocks per group too big: %lu",
2744                        sbi->s_blocks_per_group);
2745                 goto failed_mount;
2746         }
2747         if (sbi->s_inodes_per_group > blocksize * 8) {
2748                 ext4_msg(sb, KERN_ERR,
2749                        "#inodes per group too big: %lu",
2750                        sbi->s_inodes_per_group);
2751                 goto failed_mount;
2752         }
2753
2754         /*
2755          * Test whether we have more sectors than will fit in sector_t,
2756          * and whether the max offset is addressable by the page cache.
2757          */
2758         if ((ext4_blocks_count(es) >
2759              (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) ||
2760             (ext4_blocks_count(es) >
2761              (pgoff_t)(~0ULL) >> (PAGE_CACHE_SHIFT - sb->s_blocksize_bits))) {
2762                 ext4_msg(sb, KERN_ERR, "filesystem"
2763                          " too large to mount safely on this system");
2764                 if (sizeof(sector_t) < 8)
2765                         ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
2766                 ret = -EFBIG;
2767                 goto failed_mount;
2768         }
2769
2770         if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
2771                 goto cantfind_ext4;
2772
2773         /* check blocks count against device size */
2774         blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
2775         if (blocks_count && ext4_blocks_count(es) > blocks_count) {
2776                 ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
2777                        "exceeds size of device (%llu blocks)",
2778                        ext4_blocks_count(es), blocks_count);
2779                 goto failed_mount;
2780         }
2781
2782         /*
2783          * It makes no sense for the first data block to be beyond the end
2784          * of the filesystem.
2785          */
2786         if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
2787                 ext4_msg(sb, KERN_WARNING, "bad geometry: first data"
2788                          "block %u is beyond end of filesystem (%llu)",
2789                          le32_to_cpu(es->s_first_data_block),
2790                          ext4_blocks_count(es));
2791                 goto failed_mount;
2792         }
2793         blocks_count = (ext4_blocks_count(es) -
2794                         le32_to_cpu(es->s_first_data_block) +
2795                         EXT4_BLOCKS_PER_GROUP(sb) - 1);
2796         do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
2797         if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
2798                 ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
2799                        "(block count %llu, first data block %u, "
2800                        "blocks per group %lu)", sbi->s_groups_count,
2801                        ext4_blocks_count(es),
2802                        le32_to_cpu(es->s_first_data_block),
2803                        EXT4_BLOCKS_PER_GROUP(sb));
2804                 goto failed_mount;
2805         }
2806         sbi->s_groups_count = blocks_count;
2807         sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
2808                         (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
2809         db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
2810                    EXT4_DESC_PER_BLOCK(sb);
2811         sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *),
2812                                     GFP_KERNEL);
2813         if (sbi->s_group_desc == NULL) {
2814                 ext4_msg(sb, KERN_ERR, "not enough memory");
2815                 goto failed_mount;
2816         }
2817
2818 #ifdef CONFIG_PROC_FS
2819         if (ext4_proc_root)
2820                 sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root);
2821 #endif
2822
2823         bgl_lock_init(sbi->s_blockgroup_lock);
2824
2825         for (i = 0; i < db_count; i++) {
2826                 block = descriptor_loc(sb, logical_sb_block, i);
2827                 sbi->s_group_desc[i] = sb_bread(sb, block);
2828                 if (!sbi->s_group_desc[i]) {
2829                         ext4_msg(sb, KERN_ERR,
2830                                "can't read group descriptor %d", i);
2831                         db_count = i;
2832                         goto failed_mount2;
2833                 }
2834         }
2835         if (!ext4_check_descriptors(sb)) {
2836                 ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
2837                 goto failed_mount2;
2838         }
2839         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
2840                 if (!ext4_fill_flex_info(sb)) {
2841                         ext4_msg(sb, KERN_ERR,
2842                                "unable to initialize "
2843                                "flex_bg meta info!");
2844                         goto failed_mount2;
2845                 }
2846
2847         sbi->s_gdb_count = db_count;
2848         get_random_bytes(&sbi->s_next_generation, sizeof(u32));
2849         spin_lock_init(&sbi->s_next_gen_lock);
2850
2851         sbi->s_stripe = ext4_get_stripe_size(sbi);
2852         sbi->s_max_writeback_mb_bump = 128;
2853
2854         /*
2855          * set up enough so that it can read an inode
2856          */
2857         if (!test_opt(sb, NOLOAD) &&
2858             EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL))
2859                 sb->s_op = &ext4_sops;
2860         else
2861                 sb->s_op = &ext4_nojournal_sops;
2862         sb->s_export_op = &ext4_export_ops;
2863         sb->s_xattr = ext4_xattr_handlers;
2864 #ifdef CONFIG_QUOTA
2865         sb->s_qcop = &ext4_qctl_operations;
2866         sb->dq_op = &ext4_quota_operations;
2867 #endif
2868         INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
2869         mutex_init(&sbi->s_orphan_lock);
2870         mutex_init(&sbi->s_resize_lock);
2871
2872         sb->s_root = NULL;
2873
2874         needs_recovery = (es->s_last_orphan != 0 ||
2875                           EXT4_HAS_INCOMPAT_FEATURE(sb,
2876                                     EXT4_FEATURE_INCOMPAT_RECOVER));
2877
2878         /*
2879          * The first inode we look at is the journal inode.  Don't try
2880          * root first: it may be modified in the journal!
2881          */
2882         if (!test_opt(sb, NOLOAD) &&
2883             EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
2884                 if (ext4_load_journal(sb, es, journal_devnum))
2885                         goto failed_mount3;
2886         } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
2887               EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
2888                 ext4_msg(sb, KERN_ERR, "required journal recovery "
2889                        "suppressed and not mounted read-only");
2890                 goto failed_mount_wq;
2891         } else {
2892                 clear_opt(sbi->s_mount_opt, DATA_FLAGS);
2893                 set_opt(sbi->s_mount_opt, WRITEBACK_DATA);
2894                 sbi->s_journal = NULL;
2895                 needs_recovery = 0;
2896                 goto no_journal;
2897         }
2898
2899         if (ext4_blocks_count(es) > 0xffffffffULL &&
2900             !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
2901                                        JBD2_FEATURE_INCOMPAT_64BIT)) {
2902                 ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
2903                 goto failed_mount_wq;
2904         }
2905
2906         if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
2907                 jbd2_journal_set_features(sbi->s_journal,
2908                                 JBD2_FEATURE_COMPAT_CHECKSUM, 0,
2909                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
2910         } else if (test_opt(sb, JOURNAL_CHECKSUM)) {
2911                 jbd2_journal_set_features(sbi->s_journal,
2912                                 JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0);
2913                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
2914                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
2915         } else {
2916                 jbd2_journal_clear_features(sbi->s_journal,
2917                                 JBD2_FEATURE_COMPAT_CHECKSUM, 0,
2918                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
2919         }
2920
2921         /* We have now updated the journal if required, so we can
2922          * validate the data journaling mode. */
2923         switch (test_opt(sb, DATA_FLAGS)) {
2924         case 0:
2925                 /* No mode set, assume a default based on the journal
2926                  * capabilities: ORDERED_DATA if the journal can
2927                  * cope, else JOURNAL_DATA
2928                  */
2929                 if (jbd2_journal_check_available_features
2930                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
2931                         set_opt(sbi->s_mount_opt, ORDERED_DATA);
2932                 else
2933                         set_opt(sbi->s_mount_opt, JOURNAL_DATA);
2934                 break;
2935
2936         case EXT4_MOUNT_ORDERED_DATA:
2937         case EXT4_MOUNT_WRITEBACK_DATA:
2938                 if (!jbd2_journal_check_available_features
2939                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
2940                         ext4_msg(sb, KERN_ERR, "Journal does not support "
2941                                "requested data journaling mode");
2942                         goto failed_mount_wq;
2943                 }
2944         default:
2945                 break;
2946         }
2947         set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
2948
2949 no_journal:
2950         err = percpu_counter_init(&sbi->s_freeblocks_counter,
2951                                   ext4_count_free_blocks(sb));
2952         if (!err)
2953                 err = percpu_counter_init(&sbi->s_freeinodes_counter,
2954                                           ext4_count_free_inodes(sb));
2955         if (!err)
2956                 err = percpu_counter_init(&sbi->s_dirs_counter,
2957                                           ext4_count_dirs(sb));
2958         if (!err)
2959                 err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0);
2960         if (err) {
2961                 ext4_msg(sb, KERN_ERR, "insufficient memory");
2962                 goto failed_mount_wq;
2963         }
2964
2965         EXT4_SB(sb)->dio_unwritten_wq = create_workqueue("ext4-dio-unwritten");
2966         if (!EXT4_SB(sb)->dio_unwritten_wq) {
2967                 printk(KERN_ERR "EXT4-fs: failed to create DIO workqueue\n");
2968                 goto failed_mount_wq;
2969         }
2970
2971         /*
2972          * The jbd2_journal_load will have done any necessary log recovery,
2973          * so we can safely mount the rest of the filesystem now.
2974          */
2975
2976         root = ext4_iget(sb, EXT4_ROOT_INO);
2977         if (IS_ERR(root)) {
2978                 ext4_msg(sb, KERN_ERR, "get root inode failed");
2979                 ret = PTR_ERR(root);
2980                 goto failed_mount4;
2981         }
2982         if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
2983                 iput(root);
2984                 ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
2985                 goto failed_mount4;
2986         }
2987         sb->s_root = d_alloc_root(root);
2988         if (!sb->s_root) {
2989                 ext4_msg(sb, KERN_ERR, "get root dentry failed");
2990                 iput(root);
2991                 ret = -ENOMEM;
2992                 goto failed_mount4;
2993         }
2994
2995         ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY);
2996
2997         /* determine the minimum size of new large inodes, if present */
2998         if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
2999                 sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
3000                                                      EXT4_GOOD_OLD_INODE_SIZE;
3001                 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3002                                        EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) {
3003                         if (sbi->s_want_extra_isize <
3004                             le16_to_cpu(es->s_want_extra_isize))
3005                                 sbi->s_want_extra_isize =
3006                                         le16_to_cpu(es->s_want_extra_isize);
3007                         if (sbi->s_want_extra_isize <
3008                             le16_to_cpu(es->s_min_extra_isize))
3009                                 sbi->s_want_extra_isize =
3010                                         le16_to_cpu(es->s_min_extra_isize);
3011                 }
3012         }
3013         /* Check if enough inode space is available */
3014         if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
3015                                                         sbi->s_inode_size) {
3016                 sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
3017                                                        EXT4_GOOD_OLD_INODE_SIZE;
3018                 ext4_msg(sb, KERN_INFO, "required extra inode space not"
3019                          "available");
3020         }
3021
3022         if (test_opt(sb, DELALLOC) &&
3023             (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) {
3024                 ext4_msg(sb, KERN_WARNING, "Ignoring delalloc option - "
3025                          "requested data journaling mode");
3026                 clear_opt(sbi->s_mount_opt, DELALLOC);
3027         }
3028         if (test_opt(sb, DIOREAD_NOLOCK)) {
3029                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
3030                         ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock "
3031                                 "option - requested data journaling mode");
3032                         clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK);
3033                 }
3034                 if (sb->s_blocksize < PAGE_SIZE) {
3035                         ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock "
3036                                 "option - block size is too small");
3037                         clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK);
3038                 }
3039         }
3040
3041         err = ext4_setup_system_zone(sb);
3042         if (err) {
3043                 ext4_msg(sb, KERN_ERR, "failed to initialize system "
3044                          "zone (%d)", err);
3045                 goto failed_mount4;
3046         }
3047
3048         ext4_ext_init(sb);
3049         err = ext4_mb_init(sb, needs_recovery);
3050         if (err) {
3051                 ext4_msg(sb, KERN_ERR, "failed to initalize mballoc (%d)",
3052                          err);
3053                 goto failed_mount4;
3054         }
3055
3056         sbi->s_kobj.kset = ext4_kset;
3057         init_completion(&sbi->s_kobj_unregister);
3058         err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL,
3059                                    "%s", sb->s_id);
3060         if (err) {
3061                 ext4_mb_release(sb);
3062                 ext4_ext_release(sb);
3063                 goto failed_mount4;
3064         };
3065
3066         EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
3067         ext4_orphan_cleanup(sb, es);
3068         EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
3069         if (needs_recovery) {
3070                 ext4_msg(sb, KERN_INFO, "recovery complete");
3071                 ext4_mark_recovery_complete(sb, es);
3072         }
3073         if (EXT4_SB(sb)->s_journal) {
3074                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
3075                         descr = " journalled data mode";
3076                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
3077                         descr = " ordered data mode";
3078                 else
3079                         descr = " writeback data mode";
3080         } else
3081                 descr = "out journal";
3082
3083         ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
3084                 "Opts: %s", descr, orig_data);
3085
3086         lock_kernel();
3087         kfree(orig_data);
3088         return 0;
3089
3090 cantfind_ext4:
3091         if (!silent)
3092                 ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
3093         goto failed_mount;
3094
3095 failed_mount4:
3096         ext4_msg(sb, KERN_ERR, "mount failed");
3097         destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq);
3098 failed_mount_wq:
3099         ext4_release_system_zone(sb);
3100         if (sbi->s_journal) {
3101                 jbd2_journal_destroy(sbi->s_journal);
3102                 sbi->s_journal = NULL;
3103         }
3104         percpu_counter_destroy(&sbi->s_freeblocks_counter);
3105         percpu_counter_destroy(&sbi->s_freeinodes_counter);
3106         percpu_counter_destroy(&sbi->s_dirs_counter);
3107         percpu_counter_destroy(&sbi->s_dirtyblocks_counter);
3108 failed_mount3:
3109         if (sbi->s_flex_groups) {
3110                 if (is_vmalloc_addr(sbi->s_flex_groups))
3111                         vfree(sbi->s_flex_groups);
3112                 else
3113                         kfree(sbi->s_flex_groups);
3114         }
3115 failed_mount2:
3116         for (i = 0; i < db_count; i++)
3117                 brelse(sbi->s_group_desc[i]);
3118         kfree(sbi->s_group_desc);
3119 failed_mount:
3120         if (sbi->s_proc) {
3121                 remove_proc_entry(sb->s_id, ext4_proc_root);
3122         }
3123 #ifdef CONFIG_QUOTA
3124         for (i = 0; i < MAXQUOTAS; i++)
3125                 kfree(sbi->s_qf_names[i]);
3126 #endif
3127         ext4_blkdev_remove(sbi);
3128         brelse(bh);
3129 out_fail:
3130         sb->s_fs_info = NULL;
3131         kfree(sbi->s_blockgroup_lock);
3132         kfree(sbi);
3133         lock_kernel();
3134         kfree(orig_data);
3135         return ret;
3136 }
3137
3138 /*
3139  * Setup any per-fs journal parameters now.  We'll do this both on
3140  * initial mount, once the journal has been initialised but before we've
3141  * done any recovery; and again on any subsequent remount.
3142  */
3143 static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
3144 {
3145         struct ext4_sb_info *sbi = EXT4_SB(sb);
3146
3147         journal->j_commit_interval = sbi->s_commit_interval;
3148         journal->j_min_batch_time = sbi->s_min_batch_time;
3149         journal->j_max_batch_time = sbi->s_max_batch_time;
3150
3151         spin_lock(&journal->j_state_lock);
3152         if (test_opt(sb, BARRIER))
3153                 journal->j_flags |= JBD2_BARRIER;
3154         else
3155                 journal->j_flags &= ~JBD2_BARRIER;
3156         if (test_opt(sb, DATA_ERR_ABORT))
3157                 journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
3158         else
3159                 journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
3160         spin_unlock(&journal->j_state_lock);
3161 }
3162
3163 static journal_t *ext4_get_journal(struct super_block *sb,
3164                                    unsigned int journal_inum)
3165 {
3166         struct inode *journal_inode;
3167         journal_t *journal;
3168
3169         BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
3170
3171         /* First, test for the existence of a valid inode on disk.  Bad
3172          * things happen if we iget() an unused inode, as the subsequent
3173          * iput() will try to delete it. */
3174
3175         journal_inode = ext4_iget(sb, journal_inum);
3176         if (IS_ERR(journal_inode)) {
3177                 ext4_msg(sb, KERN_ERR, "no journal found");
3178                 return NULL;
3179         }
3180         if (!journal_inode->i_nlink) {
3181                 make_bad_inode(journal_inode);
3182                 iput(journal_inode);
3183                 ext4_msg(sb, KERN_ERR, "journal inode is deleted");
3184                 return NULL;
3185         }
3186
3187         jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
3188                   journal_inode, journal_inode->i_size);
3189         if (!S_ISREG(journal_inode->i_mode)) {
3190                 ext4_msg(sb, KERN_ERR, "invalid journal inode");
3191                 iput(journal_inode);
3192                 return NULL;
3193         }
3194
3195         journal = jbd2_journal_init_inode(journal_inode);
3196         if (!journal) {
3197                 ext4_msg(sb, KERN_ERR, "Could not load journal inode");
3198                 iput(journal_inode);
3199                 return NULL;
3200         }
3201         journal->j_private = sb;
3202         ext4_init_journal_params(sb, journal);
3203         return journal;
3204 }
3205
3206 static journal_t *ext4_get_dev_journal(struct super_block *sb,
3207                                        dev_t j_dev)
3208 {
3209         struct buffer_head *bh;
3210         journal_t *journal;
3211         ext4_fsblk_t start;
3212         ext4_fsblk_t len;
3213         int hblock, blocksize;
3214         ext4_fsblk_t sb_block;
3215         unsigned long offset;
3216         struct ext4_super_block *es;
3217         struct block_device *bdev;
3218
3219         BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
3220
3221         bdev = ext4_blkdev_get(j_dev, sb);
3222         if (bdev == NULL)
3223                 return NULL;
3224
3225         if (bd_claim(bdev, sb)) {
3226                 ext4_msg(sb, KERN_ERR,
3227                         "failed to claim external journal device");
3228                 blkdev_put(bdev, FMODE_READ|FMODE_WRITE);
3229                 return NULL;
3230         }
3231
3232         blocksize = sb->s_blocksize;
3233         hblock = bdev_logical_block_size(bdev);
3234         if (blocksize < hblock) {
3235                 ext4_msg(sb, KERN_ERR,
3236                         "blocksize too small for journal device");
3237                 goto out_bdev;
3238         }
3239
3240         sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
3241         offset = EXT4_MIN_BLOCK_SIZE % blocksize;
3242         set_blocksize(bdev, blocksize);
3243         if (!(bh = __bread(bdev, sb_block, blocksize))) {
3244                 ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
3245                        "external journal");
3246                 goto out_bdev;
3247         }
3248
3249         es = (struct ext4_super_block *) (((char *)bh->b_data) + offset);
3250         if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
3251             !(le32_to_cpu(es->s_feature_incompat) &
3252               EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
3253                 ext4_msg(sb, KERN_ERR, "external journal has "
3254                                         "bad superblock");
3255                 brelse(bh);
3256                 goto out_bdev;
3257         }
3258
3259         if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
3260                 ext4_msg(sb, KERN_ERR, "journal UUID does not match");
3261                 brelse(bh);
3262                 goto out_bdev;
3263         }
3264
3265         len = ext4_blocks_count(es);
3266         start = sb_block + 1;
3267         brelse(bh);     /* we're done with the superblock */
3268
3269         journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
3270                                         start, len, blocksize);
3271         if (!journal) {
3272                 ext4_msg(sb, KERN_ERR, "failed to create device journal");
3273                 goto out_bdev;
3274         }
3275         journal->j_private = sb;
3276         ll_rw_block(READ, 1, &journal->j_sb_buffer);
3277         wait_on_buffer(journal->j_sb_buffer);
3278         if (!buffer_uptodate(journal->j_sb_buffer)) {
3279                 ext4_msg(sb, KERN_ERR, "I/O error on journal device");
3280                 goto out_journal;
3281         }
3282         if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
3283                 ext4_msg(sb, KERN_ERR, "External journal has more than one "
3284                                         "user (unsupported) - %d",
3285                         be32_to_cpu(journal->j_superblock->s_nr_users));
3286                 goto out_journal;
3287         }
3288         EXT4_SB(sb)->journal_bdev = bdev;
3289         ext4_init_journal_params(sb, journal);
3290         return journal;
3291
3292 out_journal:
3293         jbd2_journal_destroy(journal);
3294 out_bdev:
3295         ext4_blkdev_put(bdev);
3296         return NULL;
3297 }
3298
3299 static int ext4_load_journal(struct super_block *sb,
3300                              struct ext4_super_block *es,
3301                              unsigned long journal_devnum)
3302 {
3303         journal_t *journal;
3304         unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
3305         dev_t journal_dev;
3306         int err = 0;
3307         int really_read_only;
3308
3309         BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
3310
3311         if (journal_devnum &&
3312             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
3313                 ext4_msg(sb, KERN_INFO, "external journal device major/minor "
3314                         "numbers have changed");
3315                 journal_dev = new_decode_dev(journal_devnum);
3316         } else
3317                 journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
3318
3319         really_read_only = bdev_read_only(sb->s_bdev);
3320
3321         /*
3322          * Are we loading a blank journal or performing recovery after a
3323          * crash?  For recovery, we need to check in advance whether we
3324          * can get read-write access to the device.
3325          */
3326         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
3327                 if (sb->s_flags & MS_RDONLY) {
3328                         ext4_msg(sb, KERN_INFO, "INFO: recovery "
3329                                         "required on readonly filesystem");
3330                         if (really_read_only) {
3331                                 ext4_msg(sb, KERN_ERR, "write access "
3332                                         "unavailable, cannot proceed");
3333                                 return -EROFS;
3334                         }
3335                         ext4_msg(sb, KERN_INFO, "write access will "
3336                                "be enabled during recovery");
3337                 }
3338         }
3339
3340         if (journal_inum && journal_dev) {
3341                 ext4_msg(sb, KERN_ERR, "filesystem has both journal "
3342                        "and inode journals!");
3343                 return -EINVAL;
3344         }
3345
3346         if (journal_inum) {
3347                 if (!(journal = ext4_get_journal(sb, journal_inum)))
3348                         return -EINVAL;
3349         } else {
3350                 if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
3351                         return -EINVAL;
3352         }
3353
3354         if (!(journal->j_flags & JBD2_BARRIER))
3355                 ext4_msg(sb, KERN_INFO, "barriers disabled");
3356
3357         if (!really_read_only && test_opt(sb, UPDATE_JOURNAL)) {
3358                 err = jbd2_journal_update_format(journal);
3359                 if (err)  {
3360                         ext4_msg(sb, KERN_ERR, "error updating journal");
3361                         jbd2_journal_destroy(journal);
3362                         return err;
3363                 }
3364         }
3365
3366         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER))
3367                 err = jbd2_journal_wipe(journal, !really_read_only);
3368         if (!err) {
3369                 char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
3370                 if (save)
3371                         memcpy(save, ((char *) es) +
3372                                EXT4_S_ERR_START, EXT4_S_ERR_LEN);
3373                 err = jbd2_journal_load(journal);
3374                 if (save)
3375                         memcpy(((char *) es) + EXT4_S_ERR_START,
3376                                save, EXT4_S_ERR_LEN);
3377                 kfree(save);
3378         }
3379
3380         if (err) {
3381                 ext4_msg(sb, KERN_ERR, "error loading journal");
3382                 jbd2_journal_destroy(journal);
3383                 return err;
3384         }
3385
3386         EXT4_SB(sb)->s_journal = journal;
3387         ext4_clear_journal_err(sb, es);
3388
3389         if (journal_devnum &&
3390             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
3391                 es->s_journal_dev = cpu_to_le32(journal_devnum);
3392
3393                 /* Make sure we flush the recovery flag to disk. */
3394                 ext4_commit_super(sb, 1);
3395         }
3396
3397         return 0;
3398 }
3399
3400 static int ext4_commit_super(struct super_block *sb, int sync)
3401 {
3402         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
3403         struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
3404         int error = 0;
3405
3406         if (!sbh)
3407                 return error;
3408         if (buffer_write_io_error(sbh)) {
3409                 /*
3410                  * Oh, dear.  A previous attempt to write the
3411                  * superblock failed.  This could happen because the
3412                  * USB device was yanked out.  Or it could happen to
3413                  * be a transient write error and maybe the block will
3414                  * be remapped.  Nothing we can do but to retry the
3415                  * write and hope for the best.
3416                  */
3417                 ext4_msg(sb, KERN_ERR, "previous I/O error to "
3418                        "superblock detected");
3419                 clear_buffer_write_io_error(sbh);
3420                 set_buffer_uptodate(sbh);
3421         }
3422         /*
3423          * If the file system is mounted read-only, don't update the
3424          * superblock write time.  This avoids updating the superblock
3425          * write time when we are mounting the root file system
3426          * read/only but we need to replay the journal; at that point,
3427          * for people who are east of GMT and who make their clock
3428          * tick in localtime for Windows bug-for-bug compatibility,
3429          * the clock is set in the future, and this will cause e2fsck
3430          * to complain and force a full file system check.
3431          */
3432         if (!(sb->s_flags & MS_RDONLY))
3433                 es->s_wtime = cpu_to_le32(get_seconds());
3434         es->s_kbytes_written =
3435                 cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
3436                             ((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
3437                               EXT4_SB(sb)->s_sectors_written_start) >> 1));
3438         ext4_free_blocks_count_set(es, percpu_counter_sum_positive(
3439                                         &EXT4_SB(sb)->s_freeblocks_counter));
3440         es->s_free_inodes_count = cpu_to_le32(percpu_counter_sum_positive(
3441                                         &EXT4_SB(sb)->s_freeinodes_counter));
3442         sb->s_dirt = 0;
3443         BUFFER_TRACE(sbh, "marking dirty");
3444         mark_buffer_dirty(sbh);
3445         if (sync) {
3446                 error = sync_dirty_buffer(sbh);
3447                 if (error)
3448                         return error;
3449
3450                 error = buffer_write_io_error(sbh);
3451                 if (error) {
3452                         ext4_msg(sb, KERN_ERR, "I/O error while writing "
3453                                "superblock");
3454                         clear_buffer_write_io_error(sbh);
3455                         set_buffer_uptodate(sbh);
3456                 }
3457         }
3458         return error;
3459 }
3460
3461 /*
3462  * Have we just finished recovery?  If so, and if we are mounting (or
3463  * remounting) the filesystem readonly, then we will end up with a
3464  * consistent fs on disk.  Record that fact.
3465  */
3466 static void ext4_mark_recovery_complete(struct super_block *sb,
3467                                         struct ext4_super_block *es)
3468 {
3469         journal_t *journal = EXT4_SB(sb)->s_journal;
3470
3471         if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
3472                 BUG_ON(journal != NULL);
3473                 return;
3474         }
3475         jbd2_journal_lock_updates(journal);
3476         if (jbd2_journal_flush(journal) < 0)
3477                 goto out;
3478
3479         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER) &&
3480             sb->s_flags & MS_RDONLY) {
3481                 EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
3482                 ext4_commit_super(sb, 1);
3483         }
3484
3485 out:
3486         jbd2_journal_unlock_updates(journal);
3487 }
3488
3489 /*
3490  * If we are mounting (or read-write remounting) a filesystem whose journal
3491  * has recorded an error from a previous lifetime, move that error to the
3492  * main filesystem now.
3493  */
3494 static void ext4_clear_journal_err(struct super_block *sb,
3495                                    struct ext4_super_block *es)
3496 {
3497         journal_t *journal;
3498         int j_errno;
3499         const char *errstr;
3500
3501         BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
3502
3503         journal = EXT4_SB(sb)->s_journal;
3504
3505         /*
3506          * Now check for any error status which may have been recorded in the
3507          * journal by a prior ext4_error() or ext4_abort()
3508          */
3509
3510         j_errno = jbd2_journal_errno(journal);
3511         if (j_errno) {
3512                 char nbuf[16];
3513
3514                 errstr = ext4_decode_error(sb, j_errno, nbuf);
3515                 ext4_warning(sb, "Filesystem error recorded "
3516                              "from previous mount: %s", errstr);
3517                 ext4_warning(sb, "Marking fs in need of filesystem check.");
3518
3519                 EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
3520                 es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
3521                 ext4_commit_super(sb, 1);
3522
3523                 jbd2_journal_clear_err(journal);
3524         }
3525 }
3526
3527 /*
3528  * Force the running and committing transactions to commit,
3529  * and wait on the commit.
3530  */
3531 int ext4_force_commit(struct super_block *sb)
3532 {
3533         journal_t *journal;
3534         int ret = 0;
3535
3536         if (sb->s_flags & MS_RDONLY)
3537                 return 0;
3538
3539         journal = EXT4_SB(sb)->s_journal;
3540         if (journal) {
3541                 vfs_check_frozen(sb, SB_FREEZE_WRITE);
3542                 ret = ext4_journal_force_commit(journal);
3543         }
3544
3545         return ret;
3546 }
3547
3548 static void ext4_write_super(struct super_block *sb)
3549 {
3550         lock_super(sb);
3551         ext4_commit_super(sb, 1);
3552         unlock_super(sb);
3553 }
3554
3555 static int ext4_sync_fs(struct super_block *sb, int wait)
3556 {
3557         int ret = 0;
3558         tid_t target;
3559         struct ext4_sb_info *sbi = EXT4_SB(sb);
3560
3561         trace_ext4_sync_fs(sb, wait);
3562         flush_workqueue(sbi->dio_unwritten_wq);
3563         if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
3564                 if (wait)
3565                         jbd2_log_wait_commit(sbi->s_journal, target);
3566         }
3567         return ret;
3568 }
3569
3570 /*
3571  * LVM calls this function before a (read-only) snapshot is created.  This
3572  * gives us a chance to flush the journal completely and mark the fs clean.
3573  */
3574 static int ext4_freeze(struct super_block *sb)
3575 {
3576         int error = 0;
3577         journal_t *journal;
3578
3579         if (sb->s_flags & MS_RDONLY)
3580                 return 0;
3581
3582         journal = EXT4_SB(sb)->s_journal;
3583
3584         /* Now we set up the journal barrier. */
3585         jbd2_journal_lock_updates(journal);
3586
3587         /*
3588          * Don't clear the needs_recovery flag if we failed to flush
3589          * the journal.
3590          */
3591         error = jbd2_journal_flush(journal);
3592         if (error < 0)
3593                 goto out;
3594
3595         /* Journal blocked and flushed, clear needs_recovery flag. */
3596         EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
3597         error = ext4_commit_super(sb, 1);
3598 out:
3599         /* we rely on s_frozen to stop further updates */
3600         jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
3601         return error;
3602 }
3603
3604 /*
3605  * Called by LVM after the snapshot is done.  We need to reset the RECOVER
3606  * flag here, even though the filesystem is not technically dirty yet.
3607  */
3608 static int ext4_unfreeze(struct super_block *sb)
3609 {
3610         if (sb->s_flags & MS_RDONLY)
3611                 return 0;
3612
3613         lock_super(sb);
3614         /* Reset the needs_recovery flag before the fs is unlocked. */
3615         EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
3616         ext4_commit_super(sb, 1);
3617         unlock_super(sb);
3618         return 0;
3619 }
3620
3621 static int ext4_remount(struct super_block *sb, int *flags, char *data)
3622 {
3623         struct ext4_super_block *es;
3624         struct ext4_sb_info *sbi = EXT4_SB(sb);
3625         ext4_fsblk_t n_blocks_count = 0;
3626         unsigned long old_sb_flags;
3627         struct ext4_mount_options old_opts;
3628         int enable_quota = 0;
3629         ext4_group_t g;
3630         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
3631         int err;
3632 #ifdef CONFIG_QUOTA
3633         int i;
3634 #endif
3635         char *orig_data = kstrdup(data, GFP_KERNEL);
3636
3637         lock_kernel();
3638
3639         /* Store the original options */
3640         lock_super(sb);
3641         old_sb_flags = sb->s_flags;
3642         old_opts.s_mount_opt = sbi->s_mount_opt;
3643         old_opts.s_resuid = sbi->s_resuid;
3644         old_opts.s_resgid = sbi->s_resgid;
3645         old_opts.s_commit_interval = sbi->s_commit_interval;
3646         old_opts.s_min_batch_time = sbi->s_min_batch_time;
3647         old_opts.s_max_batch_time = sbi->s_max_batch_time;
3648 #ifdef CONFIG_QUOTA
3649         old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
3650         for (i = 0; i < MAXQUOTAS; i++)
3651                 old_opts.s_qf_names[i] = sbi->s_qf_names[i];
3652 #endif
3653         if (sbi->s_journal && sbi->s_journal->j_task->io_context)
3654                 journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
3655
3656         /*
3657          * Allow the "check" option to be passed as a remount option.
3658          */
3659         if (!parse_options(data, sb, NULL, &journal_ioprio,
3660                            &n_blocks_count, 1)) {
3661                 err = -EINVAL;
3662                 goto restore_opts;
3663         }
3664
3665         if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
3666                 ext4_abort(sb, "Abort forced by user");
3667
3668         sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
3669                 (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
3670
3671         es = sbi->s_es;
3672
3673         if (sbi->s_journal) {
3674                 ext4_init_journal_params(sb, sbi->s_journal);
3675                 set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
3676         }
3677
3678         if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY) ||
3679                 n_blocks_count > ext4_blocks_count(es)) {
3680                 if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
3681                         err = -EROFS;
3682                         goto restore_opts;
3683                 }
3684
3685                 if (*flags & MS_RDONLY) {
3686                         err = dquot_suspend(sb, -1);
3687                         if (err < 0)
3688                                 goto restore_opts;
3689
3690                         /*
3691                          * First of all, the unconditional stuff we have to do
3692                          * to disable replay of the journal when we next remount
3693                          */
3694                         sb->s_flags |= MS_RDONLY;
3695
3696                         /*
3697                          * OK, test if we are remounting a valid rw partition
3698                          * readonly, and if so set the rdonly flag and then
3699                          * mark the partition as valid again.
3700                          */
3701                         if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
3702                             (sbi->s_mount_state & EXT4_VALID_FS))
3703                                 es->s_state = cpu_to_le16(sbi->s_mount_state);
3704
3705                         if (sbi->s_journal)
3706                                 ext4_mark_recovery_complete(sb, es);
3707                 } else {
3708                         /* Make sure we can mount this feature set readwrite */
3709                         if (!ext4_feature_set_ok(sb, 0)) {
3710                                 err = -EROFS;
3711                                 goto restore_opts;
3712                         }
3713                         /*
3714                          * Make sure the group descriptor checksums
3715                          * are sane.  If they aren't, refuse to remount r/w.
3716                          */
3717                         for (g = 0; g < sbi->s_groups_count; g++) {
3718                                 struct ext4_group_desc *gdp =
3719                                         ext4_get_group_desc(sb, g, NULL);
3720
3721                                 if (!ext4_group_desc_csum_verify(sbi, g, gdp)) {
3722                                         ext4_msg(sb, KERN_ERR,
3723                "ext4_remount: Checksum for group %u failed (%u!=%u)",
3724                 g, le16_to_cpu(ext4_group_desc_csum(sbi, g, gdp)),
3725                                                le16_to_cpu(gdp->bg_checksum));
3726                                         err = -EINVAL;
3727                                         goto restore_opts;
3728                                 }
3729                         }
3730
3731                         /*
3732                          * If we have an unprocessed orphan list hanging
3733                          * around from a previously readonly bdev mount,
3734                          * require a full umount/remount for now.
3735                          */
3736                         if (es->s_last_orphan) {
3737                                 ext4_msg(sb, KERN_WARNING, "Couldn't "
3738                                        "remount RDWR because of unprocessed "
3739                                        "orphan inode list.  Please "
3740                                        "umount/remount instead");
3741                                 err = -EINVAL;
3742                                 goto restore_opts;
3743                         }
3744
3745                         /*
3746                          * Mounting a RDONLY partition read-write, so reread
3747                          * and store the current valid flag.  (It may have
3748                          * been changed by e2fsck since we originally mounted
3749                          * the partition.)
3750                          */
3751                         if (sbi->s_journal)
3752                                 ext4_clear_journal_err(sb, es);
3753                         sbi->s_mount_state = le16_to_cpu(es->s_state);
3754                         if ((err = ext4_group_extend(sb, es, n_blocks_count)))
3755                                 goto restore_opts;
3756                         if (!ext4_setup_super(sb, es, 0))
3757                                 sb->s_flags &= ~MS_RDONLY;
3758                         enable_quota = 1;
3759                 }
3760         }
3761         ext4_setup_system_zone(sb);
3762         if (sbi->s_journal == NULL)
3763                 ext4_commit_super(sb, 1);
3764
3765 #ifdef CONFIG_QUOTA
3766         /* Release old quota file names */
3767         for (i = 0; i < MAXQUOTAS; i++)
3768                 if (old_opts.s_qf_names[i] &&
3769                     old_opts.s_qf_names[i] != sbi->s_qf_names[i])
3770                         kfree(old_opts.s_qf_names[i]);
3771 #endif
3772         unlock_super(sb);
3773         unlock_kernel();
3774         if (enable_quota)
3775                 dquot_resume(sb, -1);
3776
3777         ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
3778         kfree(orig_data);
3779         return 0;
3780
3781 restore_opts:
3782         sb->s_flags = old_sb_flags;
3783         sbi->s_mount_opt = old_opts.s_mount_opt;
3784         sbi->s_resuid = old_opts.s_resuid;
3785         sbi->s_resgid = old_opts.s_resgid;
3786         sbi->s_commit_interval = old_opts.s_commit_interval;
3787         sbi->s_min_batch_time = old_opts.s_min_batch_time;
3788         sbi->s_max_batch_time = old_opts.s_max_batch_time;
3789 #ifdef CONFIG_QUOTA
3790         sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
3791         for (i = 0; i < MAXQUOTAS; i++) {
3792                 if (sbi->s_qf_names[i] &&
3793                     old_opts.s_qf_names[i] != sbi->s_qf_names[i])
3794                         kfree(sbi->s_qf_names[i]);
3795                 sbi->s_qf_names[i] = old_opts.s_qf_names[i];
3796         }
3797 #endif
3798         unlock_super(sb);
3799         unlock_kernel();
3800         kfree(orig_data);
3801         return err;
3802 }
3803
3804 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
3805 {
3806         struct super_block *sb = dentry->d_sb;
3807         struct ext4_sb_info *sbi = EXT4_SB(sb);
3808         struct ext4_super_block *es = sbi->s_es;
3809         u64 fsid;
3810
3811         if (test_opt(sb, MINIX_DF)) {
3812                 sbi->s_overhead_last = 0;
3813         } else if (sbi->s_blocks_last != ext4_blocks_count(es)) {
3814                 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
3815                 ext4_fsblk_t overhead = 0;
3816
3817                 /*
3818                  * Compute the overhead (FS structures).  This is constant
3819                  * for a given filesystem unless the number of block groups
3820                  * changes so we cache the previous value until it does.
3821                  */
3822
3823                 /*
3824                  * All of the blocks before first_data_block are
3825                  * overhead
3826                  */
3827                 overhead = le32_to_cpu(es->s_first_data_block);
3828
3829                 /*
3830                  * Add the overhead attributed to the superblock and
3831                  * block group descriptors.  If the sparse superblocks
3832                  * feature is turned on, then not all groups have this.
3833                  */
3834                 for (i = 0; i < ngroups; i++) {
3835                         overhead += ext4_bg_has_super(sb, i) +
3836                                 ext4_bg_num_gdb(sb, i);
3837                         cond_resched();
3838                 }
3839
3840                 /*
3841                  * Every block group has an inode bitmap, a block
3842                  * bitmap, and an inode table.
3843                  */
3844                 overhead += ngroups * (2 + sbi->s_itb_per_group);
3845                 sbi->s_overhead_last = overhead;
3846                 smp_wmb();
3847                 sbi->s_blocks_last = ext4_blocks_count(es);
3848         }
3849
3850         buf->f_type = EXT4_SUPER_MAGIC;
3851         buf->f_bsize = sb->s_blocksize;
3852         buf->f_blocks = ext4_blocks_count(es) - sbi->s_overhead_last;
3853         buf->f_bfree = percpu_counter_sum_positive(&sbi->s_freeblocks_counter) -
3854                        percpu_counter_sum_positive(&sbi->s_dirtyblocks_counter);
3855         buf->f_bavail = buf->f_bfree - ext4_r_blocks_count(es);
3856         if (buf->f_bfree < ext4_r_blocks_count(es))
3857                 buf->f_bavail = 0;
3858         buf->f_files = le32_to_cpu(es->s_inodes_count);
3859         buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
3860         buf->f_namelen = EXT4_NAME_LEN;
3861         fsid = le64_to_cpup((void *)es->s_uuid) ^
3862                le64_to_cpup((void *)es->s_uuid + sizeof(u64));
3863         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
3864         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
3865
3866         return 0;
3867 }
3868
3869 /* Helper function for writing quotas on sync - we need to start transaction
3870  * before quota file is locked for write. Otherwise the are possible deadlocks:
3871  * Process 1                         Process 2
3872  * ext4_create()                     quota_sync()
3873  *   jbd2_journal_start()                  write_dquot()
3874  *   dquot_initialize()                         down(dqio_mutex)
3875  *     down(dqio_mutex)                    jbd2_journal_start()
3876  *
3877  */
3878
3879 #ifdef CONFIG_QUOTA
3880
3881 static inline struct inode *dquot_to_inode(struct dquot *dquot)
3882 {
3883         return sb_dqopt(dquot->dq_sb)->files[dquot->dq_type];
3884 }
3885
3886 static int ext4_write_dquot(struct dquot *dquot)
3887 {
3888         int ret, err;
3889         handle_t *handle;
3890         struct inode *inode;
3891
3892         inode = dquot_to_inode(dquot);
3893         handle = ext4_journal_start(inode,
3894                                     EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
3895         if (IS_ERR(handle))
3896                 return PTR_ERR(handle);
3897         ret = dquot_commit(dquot);
3898         err = ext4_journal_stop(handle);
3899         if (!ret)
3900                 ret = err;
3901         return ret;
3902 }
3903
3904 static int ext4_acquire_dquot(struct dquot *dquot)
3905 {
3906         int ret, err;
3907         handle_t *handle;
3908
3909         handle = ext4_journal_start(dquot_to_inode(dquot),
3910                                     EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
3911         if (IS_ERR(handle))
3912                 return PTR_ERR(handle);
3913         ret = dquot_acquire(dquot);
3914         err = ext4_journal_stop(handle);
3915         if (!ret)
3916                 ret = err;
3917         return ret;
3918 }
3919
3920 static int ext4_release_dquot(struct dquot *dquot)
3921 {
3922         int ret, err;
3923         handle_t *handle;
3924
3925         handle = ext4_journal_start(dquot_to_inode(dquot),
3926                                     EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
3927         if (IS_ERR(handle)) {
3928                 /* Release dquot anyway to avoid endless cycle in dqput() */
3929                 dquot_release(dquot);
3930                 return PTR_ERR(handle);
3931         }
3932         ret = dquot_release(dquot);
3933         err = ext4_journal_stop(handle);
3934         if (!ret)
3935                 ret = err;
3936         return ret;
3937 }
3938
3939 static int ext4_mark_dquot_dirty(struct dquot *dquot)
3940 {
3941         /* Are we journaling quotas? */
3942         if (EXT4_SB(dquot->dq_sb)->s_qf_names[USRQUOTA] ||
3943             EXT4_SB(dquot->dq_sb)->s_qf_names[GRPQUOTA]) {
3944                 dquot_mark_dquot_dirty(dquot);
3945                 return ext4_write_dquot(dquot);
3946         } else {
3947                 return dquot_mark_dquot_dirty(dquot);
3948         }
3949 }
3950
3951 static int ext4_write_info(struct super_block *sb, int type)
3952 {
3953         int ret, err;
3954         handle_t *handle;
3955
3956         /* Data block + inode block */
3957         handle = ext4_journal_start(sb->s_root->d_inode, 2);
3958         if (IS_ERR(handle))
3959                 return PTR_ERR(handle);
3960         ret = dquot_commit_info(sb, type);
3961         err = ext4_journal_stop(handle);
3962         if (!ret)
3963                 ret = err;
3964         return ret;
3965 }
3966
3967 /*
3968  * Turn on quotas during mount time - we need to find
3969  * the quota file and such...
3970  */
3971 static int ext4_quota_on_mount(struct super_block *sb, int type)
3972 {
3973         return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
3974                                         EXT4_SB(sb)->s_jquota_fmt, type);
3975 }
3976
3977 /*
3978  * Standard function to be called on quota_on
3979  */
3980 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
3981                          char *name)
3982 {
3983         int err;
3984         struct path path;
3985
3986         if (!test_opt(sb, QUOTA))
3987                 return -EINVAL;
3988
3989         err = kern_path(name, LOOKUP_FOLLOW, &path);
3990         if (err)
3991                 return err;
3992
3993         /* Quotafile not on the same filesystem? */
3994         if (path.mnt->mnt_sb != sb) {
3995                 path_put(&path);
3996                 return -EXDEV;
3997         }
3998         /* Journaling quota? */
3999         if (EXT4_SB(sb)->s_qf_names[type]) {
4000                 /* Quotafile not in fs root? */
4001                 if (path.dentry->d_parent != sb->s_root)
4002                         ext4_msg(sb, KERN_WARNING,
4003                                 "Quota file not on filesystem root. "
4004                                 "Journaled quota will not work");
4005         }
4006
4007         /*
4008          * When we journal data on quota file, we have to flush journal to see
4009          * all updates to the file when we bypass pagecache...
4010          */
4011         if (EXT4_SB(sb)->s_journal &&
4012             ext4_should_journal_data(path.dentry->d_inode)) {
4013                 /*
4014                  * We don't need to lock updates but journal_flush() could
4015                  * otherwise be livelocked...
4016                  */
4017                 jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
4018                 err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
4019                 jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
4020                 if (err) {
4021                         path_put(&path);
4022                         return err;
4023                 }
4024         }
4025
4026         err = dquot_quota_on_path(sb, type, format_id, &path);
4027         path_put(&path);
4028         return err;
4029 }
4030
4031 /* Read data from quotafile - avoid pagecache and such because we cannot afford
4032  * acquiring the locks... As quota files are never truncated and quota code
4033  * itself serializes the operations (and noone else should touch the files)
4034  * we don't have to be afraid of races */
4035 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
4036                                size_t len, loff_t off)
4037 {
4038         struct inode *inode = sb_dqopt(sb)->files[type];
4039         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
4040         int err = 0;
4041         int offset = off & (sb->s_blocksize - 1);
4042         int tocopy;
4043         size_t toread;
4044         struct buffer_head *bh;
4045         loff_t i_size = i_size_read(inode);
4046
4047         if (off > i_size)
4048                 return 0;
4049         if (off+len > i_size)
4050                 len = i_size-off;
4051         toread = len;
4052         while (toread > 0) {
4053                 tocopy = sb->s_blocksize - offset < toread ?
4054                                 sb->s_blocksize - offset : toread;
4055                 bh = ext4_bread(NULL, inode, blk, 0, &err);
4056                 if (err)
4057                         return err;
4058                 if (!bh)        /* A hole? */
4059                         memset(data, 0, tocopy);
4060                 else
4061                         memcpy(data, bh->b_data+offset, tocopy);
4062                 brelse(bh);
4063                 offset = 0;
4064                 toread -= tocopy;
4065                 data += tocopy;
4066                 blk++;
4067         }
4068         return len;
4069 }
4070
4071 /* Write to quotafile (we know the transaction is already started and has
4072  * enough credits) */
4073 static ssize_t ext4_quota_write(struct super_block *sb, int type,
4074                                 const char *data, size_t len, loff_t off)
4075 {
4076         struct inode *inode = sb_dqopt(sb)->files[type];
4077         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
4078         int err = 0;
4079         int offset = off & (sb->s_blocksize - 1);
4080         int journal_quota = EXT4_SB(sb)->s_qf_names[type] != NULL;
4081         struct buffer_head *bh;
4082         handle_t *handle = journal_current_handle();
4083
4084         if (EXT4_SB(sb)->s_journal && !handle) {
4085                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
4086                         " cancelled because transaction is not started",
4087                         (unsigned long long)off, (unsigned long long)len);
4088                 return -EIO;
4089         }
4090         /*
4091          * Since we account only one data block in transaction credits,
4092          * then it is impossible to cross a block boundary.
4093          */
4094         if (sb->s_blocksize - offset < len) {
4095                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
4096                         " cancelled because not block aligned",
4097                         (unsigned long long)off, (unsigned long long)len);
4098                 return -EIO;
4099         }
4100
4101         mutex_lock_nested(&inode->i_mutex, I_MUTEX_QUOTA);
4102         bh = ext4_bread(handle, inode, blk, 1, &err);
4103         if (!bh)
4104                 goto out;
4105         if (journal_quota) {
4106                 err = ext4_journal_get_write_access(handle, bh);
4107                 if (err) {
4108                         brelse(bh);
4109                         goto out;
4110                 }
4111         }
4112         lock_buffer(bh);
4113         memcpy(bh->b_data+offset, data, len);
4114         flush_dcache_page(bh->b_page);
4115         unlock_buffer(bh);
4116         if (journal_quota)
4117                 err = ext4_handle_dirty_metadata(handle, NULL, bh);
4118         else {
4119                 /* Always do at least ordered writes for quotas */
4120                 err = ext4_jbd2_file_inode(handle, inode);
4121                 mark_buffer_dirty(bh);
4122         }
4123         brelse(bh);
4124 out:
4125         if (err) {
4126                 mutex_unlock(&inode->i_mutex);
4127                 return err;
4128         }
4129         if (inode->i_size < off + len) {
4130                 i_size_write(inode, off + len);
4131                 EXT4_I(inode)->i_disksize = inode->i_size;
4132         }
4133         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
4134         ext4_mark_inode_dirty(handle, inode);
4135         mutex_unlock(&inode->i_mutex);
4136         return len;
4137 }
4138
4139 #endif
4140
4141 static int ext4_get_sb(struct file_system_type *fs_type, int flags,
4142                        const char *dev_name, void *data, struct vfsmount *mnt)
4143 {
4144         return get_sb_bdev(fs_type, flags, dev_name, data, ext4_fill_super,mnt);
4145 }
4146
4147 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
4148 static struct file_system_type ext2_fs_type = {
4149         .owner          = THIS_MODULE,
4150         .name           = "ext2",
4151         .get_sb         = ext4_get_sb,
4152         .kill_sb        = kill_block_super,
4153         .fs_flags       = FS_REQUIRES_DEV,
4154 };
4155
4156 static inline void register_as_ext2(void)
4157 {
4158         int err = register_filesystem(&ext2_fs_type);
4159         if (err)
4160                 printk(KERN_WARNING
4161                        "EXT4-fs: Unable to register as ext2 (%d)\n", err);
4162 }
4163
4164 static inline void unregister_as_ext2(void)
4165 {
4166         unregister_filesystem(&ext2_fs_type);
4167 }
4168 MODULE_ALIAS("ext2");
4169 #else
4170 static inline void register_as_ext2(void) { }
4171 static inline void unregister_as_ext2(void) { }
4172 #endif
4173
4174 #if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
4175 static inline void register_as_ext3(void)
4176 {
4177         int err = register_filesystem(&ext3_fs_type);
4178         if (err)
4179                 printk(KERN_WARNING
4180                        "EXT4-fs: Unable to register as ext3 (%d)\n", err);
4181 }
4182
4183 static inline void unregister_as_ext3(void)
4184 {
4185         unregister_filesystem(&ext3_fs_type);
4186 }
4187 MODULE_ALIAS("ext3");
4188 #else
4189 static inline void register_as_ext3(void) { }
4190 static inline void unregister_as_ext3(void) { }
4191 #endif
4192
4193 static struct file_system_type ext4_fs_type = {
4194         .owner          = THIS_MODULE,
4195         .name           = "ext4",
4196         .get_sb         = ext4_get_sb,
4197         .kill_sb        = kill_block_super,
4198         .fs_flags       = FS_REQUIRES_DEV,
4199 };
4200
4201 static int __init init_ext4_fs(void)
4202 {
4203         int err;
4204
4205         ext4_check_flag_values();
4206         err = init_ext4_system_zone();
4207         if (err)
4208                 return err;
4209         ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj);
4210         if (!ext4_kset)
4211                 goto out4;
4212         ext4_proc_root = proc_mkdir("fs/ext4", NULL);
4213         err = init_ext4_mballoc();
4214         if (err)
4215                 goto out3;
4216
4217         err = init_ext4_xattr();
4218         if (err)
4219                 goto out2;
4220         err = init_inodecache();
4221         if (err)
4222                 goto out1;
4223         register_as_ext2();
4224         register_as_ext3();
4225         err = register_filesystem(&ext4_fs_type);
4226         if (err)
4227                 goto out;
4228         return 0;
4229 out:
4230         unregister_as_ext2();
4231         unregister_as_ext3();
4232         destroy_inodecache();
4233 out1:
4234         exit_ext4_xattr();
4235 out2:
4236         exit_ext4_mballoc();
4237 out3:
4238         remove_proc_entry("fs/ext4", NULL);
4239         kset_unregister(ext4_kset);
4240 out4:
4241         exit_ext4_system_zone();
4242         return err;
4243 }
4244
4245 static void __exit exit_ext4_fs(void)
4246 {
4247         unregister_as_ext2();
4248         unregister_as_ext3();
4249         unregister_filesystem(&ext4_fs_type);
4250         destroy_inodecache();
4251         exit_ext4_xattr();
4252         exit_ext4_mballoc();
4253         remove_proc_entry("fs/ext4", NULL);
4254         kset_unregister(ext4_kset);
4255         exit_ext4_system_zone();
4256 }
4257
4258 MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
4259 MODULE_DESCRIPTION("Fourth Extended Filesystem");
4260 MODULE_LICENSE("GPL");
4261 module_init(init_ext4_fs)
4262 module_exit(exit_ext4_fs)