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