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