• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/super.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/inode.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  Big-endian to little-endian byte-swapping/bitmaps by
17  *        David S. Miller (davem@caip.rutgers.edu), 1995
18  */
19 
20 #include <linux/module.h>
21 #include <linux/string.h>
22 #include <linux/fs.h>
23 #include <linux/time.h>
24 #include <linux/vmalloc.h>
25 #include <linux/slab.h>
26 #include <linux/init.h>
27 #include <linux/blkdev.h>
28 #include <linux/backing-dev.h>
29 #include <linux/parser.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/ctype.h>
39 #include <linux/log2.h>
40 #include <linux/crc16.h>
41 #include <linux/dax.h>
42 #include <linux/cleancache.h>
43 #include <linux/uaccess.h>
44 #include <linux/iversion.h>
45 #include <linux/unicode.h>
46 #include <linux/part_stat.h>
47 #include <linux/kthread.h>
48 #include <linux/freezer.h>
49 
50 #include "ext4.h"
51 #include "ext4_extents.h"	/* Needed for trace points definition */
52 #include "ext4_jbd2.h"
53 #include "xattr.h"
54 #include "acl.h"
55 #include "mballoc.h"
56 #include "fsmap.h"
57 
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/ext4.h>
60 
61 static struct ext4_lazy_init *ext4_li_info;
62 static struct mutex ext4_li_mtx;
63 static struct ratelimit_state ext4_mount_msg_ratelimit;
64 
65 static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
66 			     unsigned long journal_devnum);
67 static int ext4_show_options(struct seq_file *seq, struct dentry *root);
68 static void ext4_update_super(struct super_block *sb);
69 static int ext4_commit_super(struct super_block *sb);
70 static int ext4_mark_recovery_complete(struct super_block *sb,
71 					struct ext4_super_block *es);
72 static int ext4_clear_journal_err(struct super_block *sb,
73 				  struct ext4_super_block *es);
74 static int ext4_sync_fs(struct super_block *sb, int wait);
75 static int ext4_remount(struct super_block *sb, int *flags, char *data);
76 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
77 static int ext4_unfreeze(struct super_block *sb);
78 static int ext4_freeze(struct super_block *sb);
79 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
80 		       const char *dev_name, void *data);
81 static inline int ext2_feature_set_ok(struct super_block *sb);
82 static inline int ext3_feature_set_ok(struct super_block *sb);
83 static int ext4_feature_set_ok(struct super_block *sb, int readonly);
84 static void ext4_destroy_lazyinit_thread(void);
85 static void ext4_unregister_li_request(struct super_block *sb);
86 static void ext4_clear_request_list(void);
87 static struct inode *ext4_get_journal_inode(struct super_block *sb,
88 					    unsigned int journal_inum);
89 
90 /*
91  * Lock ordering
92  *
93  * Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
94  * i_mmap_rwsem (inode->i_mmap_rwsem)!
95  *
96  * page fault path:
97  * mmap_lock -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
98  *   page lock -> i_data_sem (rw)
99  *
100  * buffered write path:
101  * sb_start_write -> i_mutex -> mmap_lock
102  * sb_start_write -> i_mutex -> transaction start -> page lock ->
103  *   i_data_sem (rw)
104  *
105  * truncate:
106  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> i_mmap_rwsem (w) -> page lock
107  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> transaction start ->
108  *   i_data_sem (rw)
109  *
110  * direct IO:
111  * sb_start_write -> i_mutex -> mmap_lock
112  * sb_start_write -> i_mutex -> transaction start -> i_data_sem (rw)
113  *
114  * writepages:
115  * transaction start -> page lock(s) -> i_data_sem (rw)
116  */
117 
118 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
119 static struct file_system_type ext2_fs_type = {
120 	.owner		= THIS_MODULE,
121 	.name		= "ext2",
122 	.mount		= ext4_mount,
123 	.kill_sb	= kill_block_super,
124 	.fs_flags	= FS_REQUIRES_DEV,
125 };
126 MODULE_ALIAS_FS("ext2");
127 MODULE_ALIAS("ext2");
128 #define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
129 #else
130 #define IS_EXT2_SB(sb) (0)
131 #endif
132 
133 
134 static struct file_system_type ext3_fs_type = {
135 	.owner		= THIS_MODULE,
136 	.name		= "ext3",
137 	.mount		= ext4_mount,
138 	.kill_sb	= kill_block_super,
139 	.fs_flags	= FS_REQUIRES_DEV,
140 };
141 MODULE_ALIAS_FS("ext3");
142 MODULE_ALIAS("ext3");
143 #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
144 
145 
__ext4_read_bh(struct buffer_head * bh,int op_flags,bh_end_io_t * end_io)146 static inline void __ext4_read_bh(struct buffer_head *bh, int op_flags,
147 				  bh_end_io_t *end_io)
148 {
149 	/*
150 	 * buffer's verified bit is no longer valid after reading from
151 	 * disk again due to write out error, clear it to make sure we
152 	 * recheck the buffer contents.
153 	 */
154 	clear_buffer_verified(bh);
155 
156 	bh->b_end_io = end_io ? end_io : end_buffer_read_sync;
157 	get_bh(bh);
158 	submit_bh(REQ_OP_READ, op_flags, bh);
159 }
160 
ext4_read_bh_nowait(struct buffer_head * bh,int op_flags,bh_end_io_t * end_io)161 void ext4_read_bh_nowait(struct buffer_head *bh, int op_flags,
162 			 bh_end_io_t *end_io)
163 {
164 	BUG_ON(!buffer_locked(bh));
165 
166 	if (ext4_buffer_uptodate(bh)) {
167 		unlock_buffer(bh);
168 		return;
169 	}
170 	__ext4_read_bh(bh, op_flags, end_io);
171 }
172 
ext4_read_bh(struct buffer_head * bh,int op_flags,bh_end_io_t * end_io)173 int ext4_read_bh(struct buffer_head *bh, int op_flags, bh_end_io_t *end_io)
174 {
175 	BUG_ON(!buffer_locked(bh));
176 
177 	if (ext4_buffer_uptodate(bh)) {
178 		unlock_buffer(bh);
179 		return 0;
180 	}
181 
182 	__ext4_read_bh(bh, op_flags, end_io);
183 
184 	wait_on_buffer(bh);
185 	if (buffer_uptodate(bh))
186 		return 0;
187 	return -EIO;
188 }
189 
ext4_read_bh_lock(struct buffer_head * bh,int op_flags,bool wait)190 int ext4_read_bh_lock(struct buffer_head *bh, int op_flags, bool wait)
191 {
192 	if (trylock_buffer(bh)) {
193 		if (wait)
194 			return ext4_read_bh(bh, op_flags, NULL);
195 		ext4_read_bh_nowait(bh, op_flags, NULL);
196 		return 0;
197 	}
198 	if (wait) {
199 		wait_on_buffer(bh);
200 		if (buffer_uptodate(bh))
201 			return 0;
202 		return -EIO;
203 	}
204 	return 0;
205 }
206 
207 /*
208  * This works like __bread_gfp() except it uses ERR_PTR for error
209  * returns.  Currently with sb_bread it's impossible to distinguish
210  * between ENOMEM and EIO situations (since both result in a NULL
211  * return.
212  */
__ext4_sb_bread_gfp(struct super_block * sb,sector_t block,int op_flags,gfp_t gfp)213 static struct buffer_head *__ext4_sb_bread_gfp(struct super_block *sb,
214 					       sector_t block, int op_flags,
215 					       gfp_t gfp)
216 {
217 	struct buffer_head *bh;
218 	int ret;
219 
220 	bh = sb_getblk_gfp(sb, block, gfp);
221 	if (bh == NULL)
222 		return ERR_PTR(-ENOMEM);
223 	if (ext4_buffer_uptodate(bh))
224 		return bh;
225 
226 	ret = ext4_read_bh_lock(bh, REQ_META | op_flags, true);
227 	if (ret) {
228 		put_bh(bh);
229 		return ERR_PTR(ret);
230 	}
231 	return bh;
232 }
233 
ext4_sb_bread(struct super_block * sb,sector_t block,int op_flags)234 struct buffer_head *ext4_sb_bread(struct super_block *sb, sector_t block,
235 				   int op_flags)
236 {
237 	return __ext4_sb_bread_gfp(sb, block, op_flags, __GFP_MOVABLE);
238 }
239 
ext4_sb_bread_unmovable(struct super_block * sb,sector_t block)240 struct buffer_head *ext4_sb_bread_unmovable(struct super_block *sb,
241 					    sector_t block)
242 {
243 	return __ext4_sb_bread_gfp(sb, block, 0, 0);
244 }
245 
ext4_sb_breadahead_unmovable(struct super_block * sb,sector_t block)246 void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block)
247 {
248 	struct buffer_head *bh = sb_getblk_gfp(sb, block, 0);
249 
250 	if (likely(bh)) {
251 		ext4_read_bh_lock(bh, REQ_RAHEAD, false);
252 		brelse(bh);
253 	}
254 }
255 
ext4_verify_csum_type(struct super_block * sb,struct ext4_super_block * es)256 static int ext4_verify_csum_type(struct super_block *sb,
257 				 struct ext4_super_block *es)
258 {
259 	if (!ext4_has_feature_metadata_csum(sb))
260 		return 1;
261 
262 	return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
263 }
264 
ext4_superblock_csum(struct super_block * sb,struct ext4_super_block * es)265 static __le32 ext4_superblock_csum(struct super_block *sb,
266 				   struct ext4_super_block *es)
267 {
268 	struct ext4_sb_info *sbi = EXT4_SB(sb);
269 	int offset = offsetof(struct ext4_super_block, s_checksum);
270 	__u32 csum;
271 
272 	csum = ext4_chksum(sbi, ~0, (char *)es, offset);
273 
274 	return cpu_to_le32(csum);
275 }
276 
ext4_superblock_csum_verify(struct super_block * sb,struct ext4_super_block * es)277 static int ext4_superblock_csum_verify(struct super_block *sb,
278 				       struct ext4_super_block *es)
279 {
280 	if (!ext4_has_metadata_csum(sb))
281 		return 1;
282 
283 	return es->s_checksum == ext4_superblock_csum(sb, es);
284 }
285 
ext4_superblock_csum_set(struct super_block * sb)286 void ext4_superblock_csum_set(struct super_block *sb)
287 {
288 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
289 
290 	if (!ext4_has_metadata_csum(sb))
291 		return;
292 
293 	es->s_checksum = ext4_superblock_csum(sb, es);
294 }
295 
ext4_block_bitmap(struct super_block * sb,struct ext4_group_desc * bg)296 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
297 			       struct ext4_group_desc *bg)
298 {
299 	return le32_to_cpu(bg->bg_block_bitmap_lo) |
300 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
301 		 (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
302 }
303 
ext4_inode_bitmap(struct super_block * sb,struct ext4_group_desc * bg)304 ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
305 			       struct ext4_group_desc *bg)
306 {
307 	return le32_to_cpu(bg->bg_inode_bitmap_lo) |
308 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
309 		 (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
310 }
311 
ext4_inode_table(struct super_block * sb,struct ext4_group_desc * bg)312 ext4_fsblk_t ext4_inode_table(struct super_block *sb,
313 			      struct ext4_group_desc *bg)
314 {
315 	return le32_to_cpu(bg->bg_inode_table_lo) |
316 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
317 		 (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
318 }
319 
ext4_free_group_clusters(struct super_block * sb,struct ext4_group_desc * bg)320 __u32 ext4_free_group_clusters(struct super_block *sb,
321 			       struct ext4_group_desc *bg)
322 {
323 	return le16_to_cpu(bg->bg_free_blocks_count_lo) |
324 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
325 		 (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
326 }
327 
ext4_free_inodes_count(struct super_block * sb,struct ext4_group_desc * bg)328 __u32 ext4_free_inodes_count(struct super_block *sb,
329 			      struct ext4_group_desc *bg)
330 {
331 	return le16_to_cpu(bg->bg_free_inodes_count_lo) |
332 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
333 		 (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
334 }
335 
ext4_used_dirs_count(struct super_block * sb,struct ext4_group_desc * bg)336 __u32 ext4_used_dirs_count(struct super_block *sb,
337 			      struct ext4_group_desc *bg)
338 {
339 	return le16_to_cpu(bg->bg_used_dirs_count_lo) |
340 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
341 		 (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
342 }
343 
ext4_itable_unused_count(struct super_block * sb,struct ext4_group_desc * bg)344 __u32 ext4_itable_unused_count(struct super_block *sb,
345 			      struct ext4_group_desc *bg)
346 {
347 	return le16_to_cpu(bg->bg_itable_unused_lo) |
348 		(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
349 		 (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
350 }
351 
ext4_block_bitmap_set(struct super_block * sb,struct ext4_group_desc * bg,ext4_fsblk_t blk)352 void ext4_block_bitmap_set(struct super_block *sb,
353 			   struct ext4_group_desc *bg, ext4_fsblk_t blk)
354 {
355 	bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
356 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
357 		bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
358 }
359 
ext4_inode_bitmap_set(struct super_block * sb,struct ext4_group_desc * bg,ext4_fsblk_t blk)360 void ext4_inode_bitmap_set(struct super_block *sb,
361 			   struct ext4_group_desc *bg, ext4_fsblk_t blk)
362 {
363 	bg->bg_inode_bitmap_lo  = cpu_to_le32((u32)blk);
364 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
365 		bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
366 }
367 
ext4_inode_table_set(struct super_block * sb,struct ext4_group_desc * bg,ext4_fsblk_t blk)368 void ext4_inode_table_set(struct super_block *sb,
369 			  struct ext4_group_desc *bg, ext4_fsblk_t blk)
370 {
371 	bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
372 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
373 		bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
374 }
375 
ext4_free_group_clusters_set(struct super_block * sb,struct ext4_group_desc * bg,__u32 count)376 void ext4_free_group_clusters_set(struct super_block *sb,
377 				  struct ext4_group_desc *bg, __u32 count)
378 {
379 	bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
380 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
381 		bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
382 }
383 
ext4_free_inodes_set(struct super_block * sb,struct ext4_group_desc * bg,__u32 count)384 void ext4_free_inodes_set(struct super_block *sb,
385 			  struct ext4_group_desc *bg, __u32 count)
386 {
387 	bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
388 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
389 		bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
390 }
391 
ext4_used_dirs_set(struct super_block * sb,struct ext4_group_desc * bg,__u32 count)392 void ext4_used_dirs_set(struct super_block *sb,
393 			  struct ext4_group_desc *bg, __u32 count)
394 {
395 	bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
396 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
397 		bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
398 }
399 
ext4_itable_unused_set(struct super_block * sb,struct ext4_group_desc * bg,__u32 count)400 void ext4_itable_unused_set(struct super_block *sb,
401 			  struct ext4_group_desc *bg, __u32 count)
402 {
403 	bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
404 	if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
405 		bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
406 }
407 
__ext4_update_tstamp(__le32 * lo,__u8 * hi,time64_t now)408 static void __ext4_update_tstamp(__le32 *lo, __u8 *hi, time64_t now)
409 {
410 	now = clamp_val(now, 0, (1ull << 40) - 1);
411 
412 	*lo = cpu_to_le32(lower_32_bits(now));
413 	*hi = upper_32_bits(now);
414 }
415 
__ext4_get_tstamp(__le32 * lo,__u8 * hi)416 static time64_t __ext4_get_tstamp(__le32 *lo, __u8 *hi)
417 {
418 	return ((time64_t)(*hi) << 32) + le32_to_cpu(*lo);
419 }
420 #define ext4_update_tstamp(es, tstamp) \
421 	__ext4_update_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi, \
422 			     ktime_get_real_seconds())
423 #define ext4_get_tstamp(es, tstamp) \
424 	__ext4_get_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
425 
426 /*
427  * The del_gendisk() function uninitializes the disk-specific data
428  * structures, including the bdi structure, without telling anyone
429  * else.  Once this happens, any attempt to call mark_buffer_dirty()
430  * (for example, by ext4_commit_super), will cause a kernel OOPS.
431  * This is a kludge to prevent these oops until we can put in a proper
432  * hook in del_gendisk() to inform the VFS and file system layers.
433  */
block_device_ejected(struct super_block * sb)434 static int block_device_ejected(struct super_block *sb)
435 {
436 	struct inode *bd_inode = sb->s_bdev->bd_inode;
437 	struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
438 
439 	return bdi->dev == NULL;
440 }
441 
ext4_journal_commit_callback(journal_t * journal,transaction_t * txn)442 static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
443 {
444 	struct super_block		*sb = journal->j_private;
445 	struct ext4_sb_info		*sbi = EXT4_SB(sb);
446 	int				error = is_journal_aborted(journal);
447 	struct ext4_journal_cb_entry	*jce;
448 
449 	BUG_ON(txn->t_state == T_FINISHED);
450 
451 	ext4_process_freed_data(sb, txn->t_tid);
452 
453 	spin_lock(&sbi->s_md_lock);
454 	while (!list_empty(&txn->t_private_list)) {
455 		jce = list_entry(txn->t_private_list.next,
456 				 struct ext4_journal_cb_entry, jce_list);
457 		list_del_init(&jce->jce_list);
458 		spin_unlock(&sbi->s_md_lock);
459 		jce->jce_func(sb, jce, error);
460 		spin_lock(&sbi->s_md_lock);
461 	}
462 	spin_unlock(&sbi->s_md_lock);
463 }
464 
465 /*
466  * This writepage callback for write_cache_pages()
467  * takes care of a few cases after page cleaning.
468  *
469  * write_cache_pages() already checks for dirty pages
470  * and calls clear_page_dirty_for_io(), which we want,
471  * to write protect the pages.
472  *
473  * However, we may have to redirty a page (see below.)
474  */
ext4_journalled_writepage_callback(struct page * page,struct writeback_control * wbc,void * data)475 static int ext4_journalled_writepage_callback(struct page *page,
476 					      struct writeback_control *wbc,
477 					      void *data)
478 {
479 	transaction_t *transaction = (transaction_t *) data;
480 	struct buffer_head *bh, *head;
481 	struct journal_head *jh;
482 
483 	bh = head = page_buffers(page);
484 	do {
485 		/*
486 		 * We have to redirty a page in these cases:
487 		 * 1) If buffer is dirty, it means the page was dirty because it
488 		 * contains a buffer that needs checkpointing. So the dirty bit
489 		 * needs to be preserved so that checkpointing writes the buffer
490 		 * properly.
491 		 * 2) If buffer is not part of the committing transaction
492 		 * (we may have just accidentally come across this buffer because
493 		 * inode range tracking is not exact) or if the currently running
494 		 * transaction already contains this buffer as well, dirty bit
495 		 * needs to be preserved so that the buffer gets writeprotected
496 		 * properly on running transaction's commit.
497 		 */
498 		jh = bh2jh(bh);
499 		if (buffer_dirty(bh) ||
500 		    (jh && (jh->b_transaction != transaction ||
501 			    jh->b_next_transaction))) {
502 			redirty_page_for_writepage(wbc, page);
503 			goto out;
504 		}
505 	} while ((bh = bh->b_this_page) != head);
506 
507 out:
508 	return AOP_WRITEPAGE_ACTIVATE;
509 }
510 
ext4_journalled_submit_inode_data_buffers(struct jbd2_inode * jinode)511 static int ext4_journalled_submit_inode_data_buffers(struct jbd2_inode *jinode)
512 {
513 	struct address_space *mapping = jinode->i_vfs_inode->i_mapping;
514 	struct writeback_control wbc = {
515 		.sync_mode =  WB_SYNC_ALL,
516 		.nr_to_write = LONG_MAX,
517 		.range_start = jinode->i_dirty_start,
518 		.range_end = jinode->i_dirty_end,
519         };
520 
521 	return write_cache_pages(mapping, &wbc,
522 				 ext4_journalled_writepage_callback,
523 				 jinode->i_transaction);
524 }
525 
ext4_journal_submit_inode_data_buffers(struct jbd2_inode * jinode)526 static int ext4_journal_submit_inode_data_buffers(struct jbd2_inode *jinode)
527 {
528 	int ret;
529 
530 	if (ext4_should_journal_data(jinode->i_vfs_inode))
531 		ret = ext4_journalled_submit_inode_data_buffers(jinode);
532 	else
533 		ret = jbd2_journal_submit_inode_data_buffers(jinode);
534 
535 	return ret;
536 }
537 
ext4_journal_finish_inode_data_buffers(struct jbd2_inode * jinode)538 static int ext4_journal_finish_inode_data_buffers(struct jbd2_inode *jinode)
539 {
540 	int ret = 0;
541 
542 	if (!ext4_should_journal_data(jinode->i_vfs_inode))
543 		ret = jbd2_journal_finish_inode_data_buffers(jinode);
544 
545 	return ret;
546 }
547 
system_going_down(void)548 static bool system_going_down(void)
549 {
550 	return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
551 		|| system_state == SYSTEM_RESTART;
552 }
553 
554 struct ext4_err_translation {
555 	int code;
556 	int errno;
557 };
558 
559 #define EXT4_ERR_TRANSLATE(err) { .code = EXT4_ERR_##err, .errno = err }
560 
561 static struct ext4_err_translation err_translation[] = {
562 	EXT4_ERR_TRANSLATE(EIO),
563 	EXT4_ERR_TRANSLATE(ENOMEM),
564 	EXT4_ERR_TRANSLATE(EFSBADCRC),
565 	EXT4_ERR_TRANSLATE(EFSCORRUPTED),
566 	EXT4_ERR_TRANSLATE(ENOSPC),
567 	EXT4_ERR_TRANSLATE(ENOKEY),
568 	EXT4_ERR_TRANSLATE(EROFS),
569 	EXT4_ERR_TRANSLATE(EFBIG),
570 	EXT4_ERR_TRANSLATE(EEXIST),
571 	EXT4_ERR_TRANSLATE(ERANGE),
572 	EXT4_ERR_TRANSLATE(EOVERFLOW),
573 	EXT4_ERR_TRANSLATE(EBUSY),
574 	EXT4_ERR_TRANSLATE(ENOTDIR),
575 	EXT4_ERR_TRANSLATE(ENOTEMPTY),
576 	EXT4_ERR_TRANSLATE(ESHUTDOWN),
577 	EXT4_ERR_TRANSLATE(EFAULT),
578 };
579 
ext4_errno_to_code(int errno)580 static int ext4_errno_to_code(int errno)
581 {
582 	int i;
583 
584 	for (i = 0; i < ARRAY_SIZE(err_translation); i++)
585 		if (err_translation[i].errno == errno)
586 			return err_translation[i].code;
587 	return EXT4_ERR_UNKNOWN;
588 }
589 
save_error_info(struct super_block * sb,int error,__u32 ino,__u64 block,const char * func,unsigned int line)590 static void save_error_info(struct super_block *sb, int error,
591 			    __u32 ino, __u64 block,
592 			    const char *func, unsigned int line)
593 {
594 	struct ext4_sb_info *sbi = EXT4_SB(sb);
595 
596 	/* We default to EFSCORRUPTED error... */
597 	if (error == 0)
598 		error = EFSCORRUPTED;
599 
600 	spin_lock(&sbi->s_error_lock);
601 	sbi->s_add_error_count++;
602 	sbi->s_last_error_code = error;
603 	sbi->s_last_error_line = line;
604 	sbi->s_last_error_ino = ino;
605 	sbi->s_last_error_block = block;
606 	sbi->s_last_error_func = func;
607 	sbi->s_last_error_time = ktime_get_real_seconds();
608 	if (!sbi->s_first_error_time) {
609 		sbi->s_first_error_code = error;
610 		sbi->s_first_error_line = line;
611 		sbi->s_first_error_ino = ino;
612 		sbi->s_first_error_block = block;
613 		sbi->s_first_error_func = func;
614 		sbi->s_first_error_time = sbi->s_last_error_time;
615 	}
616 	spin_unlock(&sbi->s_error_lock);
617 }
618 
619 /* Deal with the reporting of failure conditions on a filesystem such as
620  * inconsistencies detected or read IO failures.
621  *
622  * On ext2, we can store the error state of the filesystem in the
623  * superblock.  That is not possible on ext4, because we may have other
624  * write ordering constraints on the superblock which prevent us from
625  * writing it out straight away; and given that the journal is about to
626  * be aborted, we can't rely on the current, or future, transactions to
627  * write out the superblock safely.
628  *
629  * We'll just use the jbd2_journal_abort() error code to record an error in
630  * the journal instead.  On recovery, the journal will complain about
631  * that error until we've noted it down and cleared it.
632  *
633  * If force_ro is set, we unconditionally force the filesystem into an
634  * ABORT|READONLY state, unless the error response on the fs has been set to
635  * panic in which case we take the easy way out and panic immediately. This is
636  * used to deal with unrecoverable failures such as journal IO errors or ENOMEM
637  * at a critical moment in log management.
638  */
ext4_handle_error(struct super_block * sb,bool force_ro,int error,__u32 ino,__u64 block,const char * func,unsigned int line)639 static void ext4_handle_error(struct super_block *sb, bool force_ro, int error,
640 			      __u32 ino, __u64 block,
641 			      const char *func, unsigned int line)
642 {
643 	journal_t *journal = EXT4_SB(sb)->s_journal;
644 	bool continue_fs = !force_ro && test_opt(sb, ERRORS_CONT);
645 
646 	EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
647 	if (test_opt(sb, WARN_ON_ERROR))
648 		WARN_ON_ONCE(1);
649 
650 	if (!continue_fs && !sb_rdonly(sb)) {
651 		ext4_set_mount_flag(sb, EXT4_MF_FS_ABORTED);
652 		if (journal)
653 			jbd2_journal_abort(journal, -EIO);
654 	}
655 
656 	if (!bdev_read_only(sb->s_bdev)) {
657 		save_error_info(sb, error, ino, block, func, line);
658 		/*
659 		 * In case the fs should keep running, we need to writeout
660 		 * superblock through the journal. Due to lock ordering
661 		 * constraints, it may not be safe to do it right here so we
662 		 * defer superblock flushing to a workqueue.
663 		 */
664 		if (continue_fs && journal)
665 			schedule_work(&EXT4_SB(sb)->s_error_work);
666 		else
667 			ext4_commit_super(sb);
668 	}
669 
670 	if (sb_rdonly(sb) || continue_fs)
671 		return;
672 
673 	/*
674 	 * We force ERRORS_RO behavior when system is rebooting. Otherwise we
675 	 * could panic during 'reboot -f' as the underlying device got already
676 	 * disabled.
677 	 */
678 	if (test_opt(sb, ERRORS_PANIC) && !system_going_down()) {
679 		panic("EXT4-fs (device %s): panic forced after error\n",
680 			sb->s_id);
681 	}
682 	ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
683 	/*
684 	 * Make sure updated value of ->s_mount_flags will be visible before
685 	 * ->s_flags update
686 	 */
687 	smp_wmb();
688 	sb->s_flags |= SB_RDONLY;
689 }
690 
flush_stashed_error_work(struct work_struct * work)691 static void flush_stashed_error_work(struct work_struct *work)
692 {
693 	struct ext4_sb_info *sbi = container_of(work, struct ext4_sb_info,
694 						s_error_work);
695 	journal_t *journal = sbi->s_journal;
696 	handle_t *handle;
697 
698 	/*
699 	 * If the journal is still running, we have to write out superblock
700 	 * through the journal to avoid collisions of other journalled sb
701 	 * updates.
702 	 *
703 	 * We use directly jbd2 functions here to avoid recursing back into
704 	 * ext4 error handling code during handling of previous errors.
705 	 */
706 	if (!sb_rdonly(sbi->s_sb) && journal) {
707 		struct buffer_head *sbh = sbi->s_sbh;
708 		handle = jbd2_journal_start(journal, 1);
709 		if (IS_ERR(handle))
710 			goto write_directly;
711 		if (jbd2_journal_get_write_access(handle, sbh)) {
712 			jbd2_journal_stop(handle);
713 			goto write_directly;
714 		}
715 		ext4_update_super(sbi->s_sb);
716 		if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
717 			ext4_msg(sbi->s_sb, KERN_ERR, "previous I/O error to "
718 				 "superblock detected");
719 			clear_buffer_write_io_error(sbh);
720 			set_buffer_uptodate(sbh);
721 		}
722 
723 		if (jbd2_journal_dirty_metadata(handle, sbh)) {
724 			jbd2_journal_stop(handle);
725 			goto write_directly;
726 		}
727 		jbd2_journal_stop(handle);
728 		return;
729 	}
730 write_directly:
731 	/*
732 	 * Write through journal failed. Write sb directly to get error info
733 	 * out and hope for the best.
734 	 */
735 	ext4_commit_super(sbi->s_sb);
736 }
737 
738 #define ext4_error_ratelimit(sb)					\
739 		___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state),	\
740 			     "EXT4-fs error")
741 
__ext4_error(struct super_block * sb,const char * function,unsigned int line,bool force_ro,int error,__u64 block,const char * fmt,...)742 void __ext4_error(struct super_block *sb, const char *function,
743 		  unsigned int line, bool force_ro, int error, __u64 block,
744 		  const char *fmt, ...)
745 {
746 	struct va_format vaf;
747 	va_list args;
748 
749 	if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
750 		return;
751 
752 	trace_ext4_error(sb, function, line);
753 	if (ext4_error_ratelimit(sb)) {
754 		va_start(args, fmt);
755 		vaf.fmt = fmt;
756 		vaf.va = &args;
757 		printk(KERN_CRIT
758 		       "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
759 		       sb->s_id, function, line, current->comm, &vaf);
760 		va_end(args);
761 	}
762 	ext4_handle_error(sb, force_ro, error, 0, block, function, line);
763 }
764 
__ext4_error_inode(struct inode * inode,const char * function,unsigned int line,ext4_fsblk_t block,int error,const char * fmt,...)765 void __ext4_error_inode(struct inode *inode, const char *function,
766 			unsigned int line, ext4_fsblk_t block, int error,
767 			const char *fmt, ...)
768 {
769 	va_list args;
770 	struct va_format vaf;
771 
772 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
773 		return;
774 
775 	trace_ext4_error(inode->i_sb, function, line);
776 	if (ext4_error_ratelimit(inode->i_sb)) {
777 		va_start(args, fmt);
778 		vaf.fmt = fmt;
779 		vaf.va = &args;
780 		if (block)
781 			printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
782 			       "inode #%lu: block %llu: comm %s: %pV\n",
783 			       inode->i_sb->s_id, function, line, inode->i_ino,
784 			       block, current->comm, &vaf);
785 		else
786 			printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
787 			       "inode #%lu: comm %s: %pV\n",
788 			       inode->i_sb->s_id, function, line, inode->i_ino,
789 			       current->comm, &vaf);
790 		va_end(args);
791 	}
792 	ext4_handle_error(inode->i_sb, false, error, inode->i_ino, block,
793 			  function, line);
794 }
795 
__ext4_error_file(struct file * file,const char * function,unsigned int line,ext4_fsblk_t block,const char * fmt,...)796 void __ext4_error_file(struct file *file, const char *function,
797 		       unsigned int line, ext4_fsblk_t block,
798 		       const char *fmt, ...)
799 {
800 	va_list args;
801 	struct va_format vaf;
802 	struct inode *inode = file_inode(file);
803 	char pathname[80], *path;
804 
805 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
806 		return;
807 
808 	trace_ext4_error(inode->i_sb, function, line);
809 	if (ext4_error_ratelimit(inode->i_sb)) {
810 		path = file_path(file, pathname, sizeof(pathname));
811 		if (IS_ERR(path))
812 			path = "(unknown)";
813 		va_start(args, fmt);
814 		vaf.fmt = fmt;
815 		vaf.va = &args;
816 		if (block)
817 			printk(KERN_CRIT
818 			       "EXT4-fs error (device %s): %s:%d: inode #%lu: "
819 			       "block %llu: comm %s: path %s: %pV\n",
820 			       inode->i_sb->s_id, function, line, inode->i_ino,
821 			       block, current->comm, path, &vaf);
822 		else
823 			printk(KERN_CRIT
824 			       "EXT4-fs error (device %s): %s:%d: inode #%lu: "
825 			       "comm %s: path %s: %pV\n",
826 			       inode->i_sb->s_id, function, line, inode->i_ino,
827 			       current->comm, path, &vaf);
828 		va_end(args);
829 	}
830 	ext4_handle_error(inode->i_sb, false, EFSCORRUPTED, inode->i_ino, block,
831 			  function, line);
832 }
833 
ext4_decode_error(struct super_block * sb,int errno,char nbuf[16])834 const char *ext4_decode_error(struct super_block *sb, int errno,
835 			      char nbuf[16])
836 {
837 	char *errstr = NULL;
838 
839 	switch (errno) {
840 	case -EFSCORRUPTED:
841 		errstr = "Corrupt filesystem";
842 		break;
843 	case -EFSBADCRC:
844 		errstr = "Filesystem failed CRC";
845 		break;
846 	case -EIO:
847 		errstr = "IO failure";
848 		break;
849 	case -ENOMEM:
850 		errstr = "Out of memory";
851 		break;
852 	case -EROFS:
853 		if (!sb || (EXT4_SB(sb)->s_journal &&
854 			    EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
855 			errstr = "Journal has aborted";
856 		else
857 			errstr = "Readonly filesystem";
858 		break;
859 	default:
860 		/* If the caller passed in an extra buffer for unknown
861 		 * errors, textualise them now.  Else we just return
862 		 * NULL. */
863 		if (nbuf) {
864 			/* Check for truncated error codes... */
865 			if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
866 				errstr = nbuf;
867 		}
868 		break;
869 	}
870 
871 	return errstr;
872 }
873 
874 /* __ext4_std_error decodes expected errors from journaling functions
875  * automatically and invokes the appropriate error response.  */
876 
__ext4_std_error(struct super_block * sb,const char * function,unsigned int line,int errno)877 void __ext4_std_error(struct super_block *sb, const char *function,
878 		      unsigned int line, int errno)
879 {
880 	char nbuf[16];
881 	const char *errstr;
882 
883 	if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
884 		return;
885 
886 	/* Special case: if the error is EROFS, and we're not already
887 	 * inside a transaction, then there's really no point in logging
888 	 * an error. */
889 	if (errno == -EROFS && journal_current_handle() == NULL && sb_rdonly(sb))
890 		return;
891 
892 	if (ext4_error_ratelimit(sb)) {
893 		errstr = ext4_decode_error(sb, errno, nbuf);
894 		printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
895 		       sb->s_id, function, line, errstr);
896 	}
897 
898 	ext4_handle_error(sb, false, -errno, 0, 0, function, line);
899 }
900 
__ext4_msg(struct super_block * sb,const char * prefix,const char * fmt,...)901 void __ext4_msg(struct super_block *sb,
902 		const char *prefix, const char *fmt, ...)
903 {
904 	struct va_format vaf;
905 	va_list args;
906 
907 	atomic_inc(&EXT4_SB(sb)->s_msg_count);
908 	if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
909 		return;
910 
911 	va_start(args, fmt);
912 	vaf.fmt = fmt;
913 	vaf.va = &args;
914 	printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
915 	va_end(args);
916 }
917 
ext4_warning_ratelimit(struct super_block * sb)918 static int ext4_warning_ratelimit(struct super_block *sb)
919 {
920 	atomic_inc(&EXT4_SB(sb)->s_warning_count);
921 	return ___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state),
922 			    "EXT4-fs warning");
923 }
924 
__ext4_warning(struct super_block * sb,const char * function,unsigned int line,const char * fmt,...)925 void __ext4_warning(struct super_block *sb, const char *function,
926 		    unsigned int line, const char *fmt, ...)
927 {
928 	struct va_format vaf;
929 	va_list args;
930 
931 	if (!ext4_warning_ratelimit(sb))
932 		return;
933 
934 	va_start(args, fmt);
935 	vaf.fmt = fmt;
936 	vaf.va = &args;
937 	printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
938 	       sb->s_id, function, line, &vaf);
939 	va_end(args);
940 }
941 
__ext4_warning_inode(const struct inode * inode,const char * function,unsigned int line,const char * fmt,...)942 void __ext4_warning_inode(const struct inode *inode, const char *function,
943 			  unsigned int line, const char *fmt, ...)
944 {
945 	struct va_format vaf;
946 	va_list args;
947 
948 	if (!ext4_warning_ratelimit(inode->i_sb))
949 		return;
950 
951 	va_start(args, fmt);
952 	vaf.fmt = fmt;
953 	vaf.va = &args;
954 	printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
955 	       "inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
956 	       function, line, inode->i_ino, current->comm, &vaf);
957 	va_end(args);
958 }
959 
__ext4_grp_locked_error(const char * function,unsigned int line,struct super_block * sb,ext4_group_t grp,unsigned long ino,ext4_fsblk_t block,const char * fmt,...)960 void __ext4_grp_locked_error(const char *function, unsigned int line,
961 			     struct super_block *sb, ext4_group_t grp,
962 			     unsigned long ino, ext4_fsblk_t block,
963 			     const char *fmt, ...)
964 __releases(bitlock)
965 __acquires(bitlock)
966 {
967 	struct va_format vaf;
968 	va_list args;
969 
970 	if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
971 		return;
972 
973 	trace_ext4_error(sb, function, line);
974 	if (ext4_error_ratelimit(sb)) {
975 		va_start(args, fmt);
976 		vaf.fmt = fmt;
977 		vaf.va = &args;
978 		printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
979 		       sb->s_id, function, line, grp);
980 		if (ino)
981 			printk(KERN_CONT "inode %lu: ", ino);
982 		if (block)
983 			printk(KERN_CONT "block %llu:",
984 			       (unsigned long long) block);
985 		printk(KERN_CONT "%pV\n", &vaf);
986 		va_end(args);
987 	}
988 
989 	if (test_opt(sb, ERRORS_CONT)) {
990 		if (test_opt(sb, WARN_ON_ERROR))
991 			WARN_ON_ONCE(1);
992 		EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
993 		if (!bdev_read_only(sb->s_bdev)) {
994 			save_error_info(sb, EFSCORRUPTED, ino, block, function,
995 					line);
996 			schedule_work(&EXT4_SB(sb)->s_error_work);
997 		}
998 		return;
999 	}
1000 	ext4_unlock_group(sb, grp);
1001 	ext4_handle_error(sb, false, EFSCORRUPTED, ino, block, function, line);
1002 	/*
1003 	 * We only get here in the ERRORS_RO case; relocking the group
1004 	 * may be dangerous, but nothing bad will happen since the
1005 	 * filesystem will have already been marked read/only and the
1006 	 * journal has been aborted.  We return 1 as a hint to callers
1007 	 * who might what to use the return value from
1008 	 * ext4_grp_locked_error() to distinguish between the
1009 	 * ERRORS_CONT and ERRORS_RO case, and perhaps return more
1010 	 * aggressively from the ext4 function in question, with a
1011 	 * more appropriate error code.
1012 	 */
1013 	ext4_lock_group(sb, grp);
1014 	return;
1015 }
1016 
ext4_mark_group_bitmap_corrupted(struct super_block * sb,ext4_group_t group,unsigned int flags)1017 void ext4_mark_group_bitmap_corrupted(struct super_block *sb,
1018 				     ext4_group_t group,
1019 				     unsigned int flags)
1020 {
1021 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1022 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1023 	struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
1024 	int ret;
1025 
1026 	if (flags & EXT4_GROUP_INFO_BBITMAP_CORRUPT) {
1027 		ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1028 					    &grp->bb_state);
1029 		if (!ret)
1030 			percpu_counter_sub(&sbi->s_freeclusters_counter,
1031 					   grp->bb_free);
1032 	}
1033 
1034 	if (flags & EXT4_GROUP_INFO_IBITMAP_CORRUPT) {
1035 		ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT,
1036 					    &grp->bb_state);
1037 		if (!ret && gdp) {
1038 			int count;
1039 
1040 			count = ext4_free_inodes_count(sb, gdp);
1041 			percpu_counter_sub(&sbi->s_freeinodes_counter,
1042 					   count);
1043 		}
1044 	}
1045 }
1046 
ext4_update_dynamic_rev(struct super_block * sb)1047 void ext4_update_dynamic_rev(struct super_block *sb)
1048 {
1049 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
1050 
1051 	if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
1052 		return;
1053 
1054 	ext4_warning(sb,
1055 		     "updating to rev %d because of new feature flag, "
1056 		     "running e2fsck is recommended",
1057 		     EXT4_DYNAMIC_REV);
1058 
1059 	es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
1060 	es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
1061 	es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
1062 	/* leave es->s_feature_*compat flags alone */
1063 	/* es->s_uuid will be set by e2fsck if empty */
1064 
1065 	/*
1066 	 * The rest of the superblock fields should be zero, and if not it
1067 	 * means they are likely already in use, so leave them alone.  We
1068 	 * can leave it up to e2fsck to clean up any inconsistencies there.
1069 	 */
1070 }
1071 
1072 /*
1073  * Open the external journal device
1074  */
ext4_blkdev_get(dev_t dev,struct super_block * sb)1075 static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
1076 {
1077 	struct block_device *bdev;
1078 
1079 	bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
1080 	if (IS_ERR(bdev))
1081 		goto fail;
1082 	return bdev;
1083 
1084 fail:
1085 	ext4_msg(sb, KERN_ERR,
1086 		 "failed to open journal device unknown-block(%u,%u) %ld",
1087 		 MAJOR(dev), MINOR(dev), PTR_ERR(bdev));
1088 	return NULL;
1089 }
1090 
1091 /*
1092  * Release the journal device
1093  */
ext4_blkdev_put(struct block_device * bdev)1094 static void ext4_blkdev_put(struct block_device *bdev)
1095 {
1096 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1097 }
1098 
ext4_blkdev_remove(struct ext4_sb_info * sbi)1099 static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
1100 {
1101 	struct block_device *bdev;
1102 	bdev = sbi->s_journal_bdev;
1103 	if (bdev) {
1104 		ext4_blkdev_put(bdev);
1105 		sbi->s_journal_bdev = NULL;
1106 	}
1107 }
1108 
orphan_list_entry(struct list_head * l)1109 static inline struct inode *orphan_list_entry(struct list_head *l)
1110 {
1111 	return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
1112 }
1113 
dump_orphan_list(struct super_block * sb,struct ext4_sb_info * sbi)1114 static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
1115 {
1116 	struct list_head *l;
1117 
1118 	ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
1119 		 le32_to_cpu(sbi->s_es->s_last_orphan));
1120 
1121 	printk(KERN_ERR "sb_info orphan list:\n");
1122 	list_for_each(l, &sbi->s_orphan) {
1123 		struct inode *inode = orphan_list_entry(l);
1124 		printk(KERN_ERR "  "
1125 		       "inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
1126 		       inode->i_sb->s_id, inode->i_ino, inode,
1127 		       inode->i_mode, inode->i_nlink,
1128 		       NEXT_ORPHAN(inode));
1129 	}
1130 }
1131 
1132 #ifdef CONFIG_QUOTA
1133 static int ext4_quota_off(struct super_block *sb, int type);
1134 
ext4_quota_off_umount(struct super_block * sb)1135 static inline void ext4_quota_off_umount(struct super_block *sb)
1136 {
1137 	int type;
1138 
1139 	/* Use our quota_off function to clear inode flags etc. */
1140 	for (type = 0; type < EXT4_MAXQUOTAS; type++)
1141 		ext4_quota_off(sb, type);
1142 }
1143 
1144 /*
1145  * This is a helper function which is used in the mount/remount
1146  * codepaths (which holds s_umount) to fetch the quota file name.
1147  */
get_qf_name(struct super_block * sb,struct ext4_sb_info * sbi,int type)1148 static inline char *get_qf_name(struct super_block *sb,
1149 				struct ext4_sb_info *sbi,
1150 				int type)
1151 {
1152 	return rcu_dereference_protected(sbi->s_qf_names[type],
1153 					 lockdep_is_held(&sb->s_umount));
1154 }
1155 #else
ext4_quota_off_umount(struct super_block * sb)1156 static inline void ext4_quota_off_umount(struct super_block *sb)
1157 {
1158 }
1159 #endif
1160 
ext4_put_super(struct super_block * sb)1161 static void ext4_put_super(struct super_block *sb)
1162 {
1163 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1164 	struct ext4_super_block *es = sbi->s_es;
1165 	struct buffer_head **group_desc;
1166 	struct flex_groups **flex_groups;
1167 	int aborted = 0;
1168 	int i, err;
1169 
1170 	ext4_unregister_li_request(sb);
1171 	ext4_quota_off_umount(sb);
1172 
1173 	flush_work(&sbi->s_error_work);
1174 	destroy_workqueue(sbi->rsv_conversion_wq);
1175 
1176 	/*
1177 	 * Unregister sysfs before destroying jbd2 journal.
1178 	 * Since we could still access attr_journal_task attribute via sysfs
1179 	 * path which could have sbi->s_journal->j_task as NULL
1180 	 */
1181 	ext4_unregister_sysfs(sb);
1182 
1183 	if (sbi->s_journal) {
1184 		aborted = is_journal_aborted(sbi->s_journal);
1185 		err = jbd2_journal_destroy(sbi->s_journal);
1186 		sbi->s_journal = NULL;
1187 		if ((err < 0) && !aborted) {
1188 			ext4_abort(sb, -err, "Couldn't clean up the journal");
1189 		}
1190 	}
1191 
1192 	ext4_es_unregister_shrinker(sbi);
1193 	del_timer_sync(&sbi->s_err_report);
1194 	ext4_release_system_zone(sb);
1195 	ext4_mb_release(sb);
1196 	ext4_ext_release(sb);
1197 
1198 	if (!sb_rdonly(sb) && !aborted) {
1199 		ext4_clear_feature_journal_needs_recovery(sb);
1200 		es->s_state = cpu_to_le16(sbi->s_mount_state);
1201 	}
1202 	if (!sb_rdonly(sb))
1203 		ext4_commit_super(sb);
1204 
1205 	rcu_read_lock();
1206 	group_desc = rcu_dereference(sbi->s_group_desc);
1207 	for (i = 0; i < sbi->s_gdb_count; i++)
1208 		brelse(group_desc[i]);
1209 	kvfree(group_desc);
1210 	flex_groups = rcu_dereference(sbi->s_flex_groups);
1211 	if (flex_groups) {
1212 		for (i = 0; i < sbi->s_flex_groups_allocated; i++)
1213 			kvfree(flex_groups[i]);
1214 		kvfree(flex_groups);
1215 	}
1216 	rcu_read_unlock();
1217 	percpu_counter_destroy(&sbi->s_freeclusters_counter);
1218 	percpu_counter_destroy(&sbi->s_freeinodes_counter);
1219 	percpu_counter_destroy(&sbi->s_dirs_counter);
1220 	percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
1221 	percpu_counter_destroy(&sbi->s_sra_exceeded_retry_limit);
1222 	percpu_free_rwsem(&sbi->s_writepages_rwsem);
1223 #ifdef CONFIG_QUOTA
1224 	for (i = 0; i < EXT4_MAXQUOTAS; i++)
1225 		kfree(get_qf_name(sb, sbi, i));
1226 #endif
1227 
1228 	/* Debugging code just in case the in-memory inode orphan list
1229 	 * isn't empty.  The on-disk one can be non-empty if we've
1230 	 * detected an error and taken the fs readonly, but the
1231 	 * in-memory list had better be clean by this point. */
1232 	if (!list_empty(&sbi->s_orphan))
1233 		dump_orphan_list(sb, sbi);
1234 	J_ASSERT(list_empty(&sbi->s_orphan));
1235 
1236 	sync_blockdev(sb->s_bdev);
1237 	invalidate_bdev(sb->s_bdev);
1238 	if (sbi->s_journal_bdev && sbi->s_journal_bdev != sb->s_bdev) {
1239 		/*
1240 		 * Invalidate the journal device's buffers.  We don't want them
1241 		 * floating about in memory - the physical journal device may
1242 		 * hotswapped, and it breaks the `ro-after' testing code.
1243 		 */
1244 		sync_blockdev(sbi->s_journal_bdev);
1245 		invalidate_bdev(sbi->s_journal_bdev);
1246 		ext4_blkdev_remove(sbi);
1247 	}
1248 
1249 	ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
1250 	sbi->s_ea_inode_cache = NULL;
1251 
1252 	ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
1253 	sbi->s_ea_block_cache = NULL;
1254 
1255 	ext4_stop_mmpd(sbi);
1256 
1257 	brelse(sbi->s_sbh);
1258 	sb->s_fs_info = NULL;
1259 	/*
1260 	 * Now that we are completely done shutting down the
1261 	 * superblock, we need to actually destroy the kobject.
1262 	 */
1263 	kobject_put(&sbi->s_kobj);
1264 	wait_for_completion(&sbi->s_kobj_unregister);
1265 	if (sbi->s_chksum_driver)
1266 		crypto_free_shash(sbi->s_chksum_driver);
1267 	kfree(sbi->s_blockgroup_lock);
1268 	fs_put_dax(sbi->s_daxdev);
1269 	fscrypt_free_dummy_policy(&sbi->s_dummy_enc_policy);
1270 #ifdef CONFIG_UNICODE
1271 	utf8_unload(sb->s_encoding);
1272 #endif
1273 	kfree(sbi);
1274 }
1275 
1276 static struct kmem_cache *ext4_inode_cachep;
1277 
1278 /*
1279  * Called inside transaction, so use GFP_NOFS
1280  */
ext4_alloc_inode(struct super_block * sb)1281 static struct inode *ext4_alloc_inode(struct super_block *sb)
1282 {
1283 	struct ext4_inode_info *ei;
1284 
1285 	ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
1286 	if (!ei)
1287 		return NULL;
1288 
1289 	inode_set_iversion(&ei->vfs_inode, 1);
1290 	spin_lock_init(&ei->i_raw_lock);
1291 	INIT_LIST_HEAD(&ei->i_prealloc_list);
1292 	atomic_set(&ei->i_prealloc_active, 0);
1293 	spin_lock_init(&ei->i_prealloc_lock);
1294 	ext4_es_init_tree(&ei->i_es_tree);
1295 	rwlock_init(&ei->i_es_lock);
1296 	INIT_LIST_HEAD(&ei->i_es_list);
1297 	ei->i_es_all_nr = 0;
1298 	ei->i_es_shk_nr = 0;
1299 	ei->i_es_shrink_lblk = 0;
1300 	ei->i_reserved_data_blocks = 0;
1301 	spin_lock_init(&(ei->i_block_reservation_lock));
1302 	ext4_init_pending_tree(&ei->i_pending_tree);
1303 #ifdef CONFIG_QUOTA
1304 	ei->i_reserved_quota = 0;
1305 	memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
1306 #endif
1307 	ei->jinode = NULL;
1308 	INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
1309 	spin_lock_init(&ei->i_completed_io_lock);
1310 	ei->i_sync_tid = 0;
1311 	ei->i_datasync_tid = 0;
1312 	atomic_set(&ei->i_unwritten, 0);
1313 	INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
1314 	ext4_fc_init_inode(&ei->vfs_inode);
1315 	mutex_init(&ei->i_fc_lock);
1316 	return &ei->vfs_inode;
1317 }
1318 
ext4_drop_inode(struct inode * inode)1319 static int ext4_drop_inode(struct inode *inode)
1320 {
1321 	int drop = generic_drop_inode(inode);
1322 
1323 	if (!drop)
1324 		drop = fscrypt_drop_inode(inode);
1325 
1326 	trace_ext4_drop_inode(inode, drop);
1327 	return drop;
1328 }
1329 
ext4_free_in_core_inode(struct inode * inode)1330 static void ext4_free_in_core_inode(struct inode *inode)
1331 {
1332 	fscrypt_free_inode(inode);
1333 	if (!list_empty(&(EXT4_I(inode)->i_fc_list))) {
1334 		pr_warn("%s: inode %ld still in fc list",
1335 			__func__, inode->i_ino);
1336 	}
1337 	kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
1338 }
1339 
ext4_destroy_inode(struct inode * inode)1340 static void ext4_destroy_inode(struct inode *inode)
1341 {
1342 	if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
1343 		ext4_msg(inode->i_sb, KERN_ERR,
1344 			 "Inode %lu (%p): orphan list check failed!",
1345 			 inode->i_ino, EXT4_I(inode));
1346 		print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
1347 				EXT4_I(inode), sizeof(struct ext4_inode_info),
1348 				true);
1349 		dump_stack();
1350 	}
1351 
1352 	if (EXT4_I(inode)->i_reserved_data_blocks)
1353 		ext4_msg(inode->i_sb, KERN_ERR,
1354 			 "Inode %lu (%p): i_reserved_data_blocks (%u) not cleared!",
1355 			 inode->i_ino, EXT4_I(inode),
1356 			 EXT4_I(inode)->i_reserved_data_blocks);
1357 }
1358 
init_once(void * foo)1359 static void init_once(void *foo)
1360 {
1361 	struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
1362 
1363 	INIT_LIST_HEAD(&ei->i_orphan);
1364 	init_rwsem(&ei->xattr_sem);
1365 	init_rwsem(&ei->i_data_sem);
1366 	init_rwsem(&ei->i_mmap_sem);
1367 	inode_init_once(&ei->vfs_inode);
1368 	ext4_fc_init_inode(&ei->vfs_inode);
1369 }
1370 
init_inodecache(void)1371 static int __init init_inodecache(void)
1372 {
1373 	ext4_inode_cachep = kmem_cache_create_usercopy("ext4_inode_cache",
1374 				sizeof(struct ext4_inode_info), 0,
1375 				(SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
1376 					SLAB_ACCOUNT),
1377 				offsetof(struct ext4_inode_info, i_data),
1378 				sizeof_field(struct ext4_inode_info, i_data),
1379 				init_once);
1380 	if (ext4_inode_cachep == NULL)
1381 		return -ENOMEM;
1382 	return 0;
1383 }
1384 
destroy_inodecache(void)1385 static void destroy_inodecache(void)
1386 {
1387 	/*
1388 	 * Make sure all delayed rcu free inodes are flushed before we
1389 	 * destroy cache.
1390 	 */
1391 	rcu_barrier();
1392 	kmem_cache_destroy(ext4_inode_cachep);
1393 }
1394 
ext4_clear_inode(struct inode * inode)1395 void ext4_clear_inode(struct inode *inode)
1396 {
1397 	ext4_fc_del(inode);
1398 	invalidate_inode_buffers(inode);
1399 	clear_inode(inode);
1400 	ext4_discard_preallocations(inode, 0);
1401 	ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
1402 	dquot_drop(inode);
1403 	if (EXT4_I(inode)->jinode) {
1404 		jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
1405 					       EXT4_I(inode)->jinode);
1406 		jbd2_free_inode(EXT4_I(inode)->jinode);
1407 		EXT4_I(inode)->jinode = NULL;
1408 	}
1409 	fscrypt_put_encryption_info(inode);
1410 	fsverity_cleanup_inode(inode);
1411 }
1412 
ext4_nfs_get_inode(struct super_block * sb,u64 ino,u32 generation)1413 static struct inode *ext4_nfs_get_inode(struct super_block *sb,
1414 					u64 ino, u32 generation)
1415 {
1416 	struct inode *inode;
1417 
1418 	/*
1419 	 * Currently we don't know the generation for parent directory, so
1420 	 * a generation of 0 means "accept any"
1421 	 */
1422 	inode = ext4_iget(sb, ino, EXT4_IGET_HANDLE);
1423 	if (IS_ERR(inode))
1424 		return ERR_CAST(inode);
1425 	if (generation && inode->i_generation != generation) {
1426 		iput(inode);
1427 		return ERR_PTR(-ESTALE);
1428 	}
1429 
1430 	return inode;
1431 }
1432 
ext4_fh_to_dentry(struct super_block * sb,struct fid * fid,int fh_len,int fh_type)1433 static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
1434 					int fh_len, int fh_type)
1435 {
1436 	return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1437 				    ext4_nfs_get_inode);
1438 }
1439 
ext4_fh_to_parent(struct super_block * sb,struct fid * fid,int fh_len,int fh_type)1440 static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
1441 					int fh_len, int fh_type)
1442 {
1443 	return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1444 				    ext4_nfs_get_inode);
1445 }
1446 
ext4_nfs_commit_metadata(struct inode * inode)1447 static int ext4_nfs_commit_metadata(struct inode *inode)
1448 {
1449 	struct writeback_control wbc = {
1450 		.sync_mode = WB_SYNC_ALL
1451 	};
1452 
1453 	trace_ext4_nfs_commit_metadata(inode);
1454 	return ext4_write_inode(inode, &wbc);
1455 }
1456 
1457 #ifdef CONFIG_FS_ENCRYPTION
ext4_get_context(struct inode * inode,void * ctx,size_t len)1458 static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
1459 {
1460 	return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
1461 				 EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
1462 }
1463 
ext4_set_context(struct inode * inode,const void * ctx,size_t len,void * fs_data)1464 static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
1465 							void *fs_data)
1466 {
1467 	handle_t *handle = fs_data;
1468 	int res, res2, credits, retries = 0;
1469 
1470 	/*
1471 	 * Encrypting the root directory is not allowed because e2fsck expects
1472 	 * lost+found to exist and be unencrypted, and encrypting the root
1473 	 * directory would imply encrypting the lost+found directory as well as
1474 	 * the filename "lost+found" itself.
1475 	 */
1476 	if (inode->i_ino == EXT4_ROOT_INO)
1477 		return -EPERM;
1478 
1479 	if (WARN_ON_ONCE(IS_DAX(inode) && i_size_read(inode)))
1480 		return -EINVAL;
1481 
1482 	if (ext4_test_inode_flag(inode, EXT4_INODE_DAX))
1483 		return -EOPNOTSUPP;
1484 
1485 	res = ext4_convert_inline_data(inode);
1486 	if (res)
1487 		return res;
1488 
1489 	/*
1490 	 * If a journal handle was specified, then the encryption context is
1491 	 * being set on a new inode via inheritance and is part of a larger
1492 	 * transaction to create the inode.  Otherwise the encryption context is
1493 	 * being set on an existing inode in its own transaction.  Only in the
1494 	 * latter case should the "retry on ENOSPC" logic be used.
1495 	 */
1496 
1497 	if (handle) {
1498 		res = ext4_xattr_set_handle(handle, inode,
1499 					    EXT4_XATTR_INDEX_ENCRYPTION,
1500 					    EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1501 					    ctx, len, 0);
1502 		if (!res) {
1503 			ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1504 			ext4_clear_inode_state(inode,
1505 					EXT4_STATE_MAY_INLINE_DATA);
1506 			/*
1507 			 * Update inode->i_flags - S_ENCRYPTED will be enabled,
1508 			 * S_DAX may be disabled
1509 			 */
1510 			ext4_set_inode_flags(inode, false);
1511 		}
1512 		return res;
1513 	}
1514 
1515 	res = dquot_initialize(inode);
1516 	if (res)
1517 		return res;
1518 retry:
1519 	res = ext4_xattr_set_credits(inode, len, false /* is_create */,
1520 				     &credits);
1521 	if (res)
1522 		return res;
1523 
1524 	handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
1525 	if (IS_ERR(handle))
1526 		return PTR_ERR(handle);
1527 
1528 	res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
1529 				    EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1530 				    ctx, len, 0);
1531 	if (!res) {
1532 		ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1533 		/*
1534 		 * Update inode->i_flags - S_ENCRYPTED will be enabled,
1535 		 * S_DAX may be disabled
1536 		 */
1537 		ext4_set_inode_flags(inode, false);
1538 		res = ext4_mark_inode_dirty(handle, inode);
1539 		if (res)
1540 			EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
1541 	}
1542 	res2 = ext4_journal_stop(handle);
1543 
1544 	if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1545 		goto retry;
1546 	if (!res)
1547 		res = res2;
1548 	return res;
1549 }
1550 
ext4_get_dummy_policy(struct super_block * sb)1551 static const union fscrypt_policy *ext4_get_dummy_policy(struct super_block *sb)
1552 {
1553 	return EXT4_SB(sb)->s_dummy_enc_policy.policy;
1554 }
1555 
ext4_has_stable_inodes(struct super_block * sb)1556 static bool ext4_has_stable_inodes(struct super_block *sb)
1557 {
1558 	return ext4_has_feature_stable_inodes(sb);
1559 }
1560 
ext4_get_ino_and_lblk_bits(struct super_block * sb,int * ino_bits_ret,int * lblk_bits_ret)1561 static void ext4_get_ino_and_lblk_bits(struct super_block *sb,
1562 				       int *ino_bits_ret, int *lblk_bits_ret)
1563 {
1564 	*ino_bits_ret = 8 * sizeof(EXT4_SB(sb)->s_es->s_inodes_count);
1565 	*lblk_bits_ret = 8 * sizeof(ext4_lblk_t);
1566 }
1567 
1568 static const struct fscrypt_operations ext4_cryptops = {
1569 	.key_prefix		= "ext4:",
1570 	.get_context		= ext4_get_context,
1571 	.set_context		= ext4_set_context,
1572 	.get_dummy_policy	= ext4_get_dummy_policy,
1573 	.empty_dir		= ext4_empty_dir,
1574 	.max_namelen		= EXT4_NAME_LEN,
1575 	.has_stable_inodes	= ext4_has_stable_inodes,
1576 	.get_ino_and_lblk_bits	= ext4_get_ino_and_lblk_bits,
1577 };
1578 #endif
1579 
1580 #ifdef CONFIG_QUOTA
1581 static const char * const quotatypes[] = INITQFNAMES;
1582 #define QTYPE2NAME(t) (quotatypes[t])
1583 
1584 static int ext4_write_dquot(struct dquot *dquot);
1585 static int ext4_acquire_dquot(struct dquot *dquot);
1586 static int ext4_release_dquot(struct dquot *dquot);
1587 static int ext4_mark_dquot_dirty(struct dquot *dquot);
1588 static int ext4_write_info(struct super_block *sb, int type);
1589 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
1590 			 const struct path *path);
1591 static int ext4_quota_on_mount(struct super_block *sb, int type);
1592 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
1593 			       size_t len, loff_t off);
1594 static ssize_t ext4_quota_write(struct super_block *sb, int type,
1595 				const char *data, size_t len, loff_t off);
1596 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
1597 			     unsigned int flags);
1598 static int ext4_enable_quotas(struct super_block *sb);
1599 
ext4_get_dquots(struct inode * inode)1600 static struct dquot **ext4_get_dquots(struct inode *inode)
1601 {
1602 	return EXT4_I(inode)->i_dquot;
1603 }
1604 
1605 static const struct dquot_operations ext4_quota_operations = {
1606 	.get_reserved_space	= ext4_get_reserved_space,
1607 	.write_dquot		= ext4_write_dquot,
1608 	.acquire_dquot		= ext4_acquire_dquot,
1609 	.release_dquot		= ext4_release_dquot,
1610 	.mark_dirty		= ext4_mark_dquot_dirty,
1611 	.write_info		= ext4_write_info,
1612 	.alloc_dquot		= dquot_alloc,
1613 	.destroy_dquot		= dquot_destroy,
1614 	.get_projid		= ext4_get_projid,
1615 	.get_inode_usage	= ext4_get_inode_usage,
1616 	.get_next_id		= dquot_get_next_id,
1617 };
1618 
1619 static const struct quotactl_ops ext4_qctl_operations = {
1620 	.quota_on	= ext4_quota_on,
1621 	.quota_off	= ext4_quota_off,
1622 	.quota_sync	= dquot_quota_sync,
1623 	.get_state	= dquot_get_state,
1624 	.set_info	= dquot_set_dqinfo,
1625 	.get_dqblk	= dquot_get_dqblk,
1626 	.set_dqblk	= dquot_set_dqblk,
1627 	.get_nextdqblk	= dquot_get_next_dqblk,
1628 };
1629 #endif
1630 
1631 static const struct super_operations ext4_sops = {
1632 	.alloc_inode	= ext4_alloc_inode,
1633 	.free_inode	= ext4_free_in_core_inode,
1634 	.destroy_inode	= ext4_destroy_inode,
1635 	.write_inode	= ext4_write_inode,
1636 	.dirty_inode	= ext4_dirty_inode,
1637 	.drop_inode	= ext4_drop_inode,
1638 	.evict_inode	= ext4_evict_inode,
1639 	.put_super	= ext4_put_super,
1640 	.sync_fs	= ext4_sync_fs,
1641 	.freeze_fs	= ext4_freeze,
1642 	.unfreeze_fs	= ext4_unfreeze,
1643 	.statfs		= ext4_statfs,
1644 	.remount_fs	= ext4_remount,
1645 	.show_options	= ext4_show_options,
1646 #ifdef CONFIG_QUOTA
1647 	.quota_read	= ext4_quota_read,
1648 	.quota_write	= ext4_quota_write,
1649 	.get_dquots	= ext4_get_dquots,
1650 #endif
1651 };
1652 
1653 static const struct export_operations ext4_export_ops = {
1654 	.fh_to_dentry = ext4_fh_to_dentry,
1655 	.fh_to_parent = ext4_fh_to_parent,
1656 	.get_parent = ext4_get_parent,
1657 	.commit_metadata = ext4_nfs_commit_metadata,
1658 };
1659 
1660 enum {
1661 	Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
1662 	Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
1663 	Opt_nouid32, Opt_debug, Opt_removed,
1664 	Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
1665 	Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
1666 	Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
1667 	Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
1668 	Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
1669 	Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
1670 	Opt_inlinecrypt,
1671 	Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
1672 	Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
1673 	Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
1674 	Opt_usrquota, Opt_grpquota, Opt_prjquota, Opt_i_version,
1675 	Opt_dax, Opt_dax_always, Opt_dax_inode, Opt_dax_never,
1676 	Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_warn_on_error,
1677 	Opt_nowarn_on_error, Opt_mblk_io_submit,
1678 	Opt_lazytime, Opt_nolazytime, Opt_debug_want_extra_isize,
1679 	Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
1680 	Opt_inode_readahead_blks, Opt_journal_ioprio,
1681 	Opt_dioread_nolock, Opt_dioread_lock,
1682 	Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
1683 	Opt_max_dir_size_kb, Opt_nojournal_checksum, Opt_nombcache,
1684 	Opt_prefetch_block_bitmaps,
1685 #ifdef CONFIG_EXT4_DEBUG
1686 	Opt_fc_debug_max_replay, Opt_fc_debug_force
1687 #endif
1688 };
1689 
1690 static const match_table_t tokens = {
1691 	{Opt_bsd_df, "bsddf"},
1692 	{Opt_minix_df, "minixdf"},
1693 	{Opt_grpid, "grpid"},
1694 	{Opt_grpid, "bsdgroups"},
1695 	{Opt_nogrpid, "nogrpid"},
1696 	{Opt_nogrpid, "sysvgroups"},
1697 	{Opt_resgid, "resgid=%u"},
1698 	{Opt_resuid, "resuid=%u"},
1699 	{Opt_sb, "sb=%u"},
1700 	{Opt_err_cont, "errors=continue"},
1701 	{Opt_err_panic, "errors=panic"},
1702 	{Opt_err_ro, "errors=remount-ro"},
1703 	{Opt_nouid32, "nouid32"},
1704 	{Opt_debug, "debug"},
1705 	{Opt_removed, "oldalloc"},
1706 	{Opt_removed, "orlov"},
1707 	{Opt_user_xattr, "user_xattr"},
1708 	{Opt_nouser_xattr, "nouser_xattr"},
1709 	{Opt_acl, "acl"},
1710 	{Opt_noacl, "noacl"},
1711 	{Opt_noload, "norecovery"},
1712 	{Opt_noload, "noload"},
1713 	{Opt_removed, "nobh"},
1714 	{Opt_removed, "bh"},
1715 	{Opt_commit, "commit=%u"},
1716 	{Opt_min_batch_time, "min_batch_time=%u"},
1717 	{Opt_max_batch_time, "max_batch_time=%u"},
1718 	{Opt_journal_dev, "journal_dev=%u"},
1719 	{Opt_journal_path, "journal_path=%s"},
1720 	{Opt_journal_checksum, "journal_checksum"},
1721 	{Opt_nojournal_checksum, "nojournal_checksum"},
1722 	{Opt_journal_async_commit, "journal_async_commit"},
1723 	{Opt_abort, "abort"},
1724 	{Opt_data_journal, "data=journal"},
1725 	{Opt_data_ordered, "data=ordered"},
1726 	{Opt_data_writeback, "data=writeback"},
1727 	{Opt_data_err_abort, "data_err=abort"},
1728 	{Opt_data_err_ignore, "data_err=ignore"},
1729 	{Opt_offusrjquota, "usrjquota="},
1730 	{Opt_usrjquota, "usrjquota=%s"},
1731 	{Opt_offgrpjquota, "grpjquota="},
1732 	{Opt_grpjquota, "grpjquota=%s"},
1733 	{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
1734 	{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
1735 	{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
1736 	{Opt_grpquota, "grpquota"},
1737 	{Opt_noquota, "noquota"},
1738 	{Opt_quota, "quota"},
1739 	{Opt_usrquota, "usrquota"},
1740 	{Opt_prjquota, "prjquota"},
1741 	{Opt_barrier, "barrier=%u"},
1742 	{Opt_barrier, "barrier"},
1743 	{Opt_nobarrier, "nobarrier"},
1744 	{Opt_i_version, "i_version"},
1745 	{Opt_dax, "dax"},
1746 	{Opt_dax_always, "dax=always"},
1747 	{Opt_dax_inode, "dax=inode"},
1748 	{Opt_dax_never, "dax=never"},
1749 	{Opt_stripe, "stripe=%u"},
1750 	{Opt_delalloc, "delalloc"},
1751 	{Opt_warn_on_error, "warn_on_error"},
1752 	{Opt_nowarn_on_error, "nowarn_on_error"},
1753 	{Opt_lazytime, "lazytime"},
1754 	{Opt_nolazytime, "nolazytime"},
1755 	{Opt_debug_want_extra_isize, "debug_want_extra_isize=%u"},
1756 	{Opt_nodelalloc, "nodelalloc"},
1757 	{Opt_removed, "mblk_io_submit"},
1758 	{Opt_removed, "nomblk_io_submit"},
1759 	{Opt_block_validity, "block_validity"},
1760 	{Opt_noblock_validity, "noblock_validity"},
1761 	{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
1762 	{Opt_journal_ioprio, "journal_ioprio=%u"},
1763 	{Opt_auto_da_alloc, "auto_da_alloc=%u"},
1764 	{Opt_auto_da_alloc, "auto_da_alloc"},
1765 	{Opt_noauto_da_alloc, "noauto_da_alloc"},
1766 	{Opt_dioread_nolock, "dioread_nolock"},
1767 	{Opt_dioread_lock, "nodioread_nolock"},
1768 	{Opt_dioread_lock, "dioread_lock"},
1769 	{Opt_discard, "discard"},
1770 	{Opt_nodiscard, "nodiscard"},
1771 	{Opt_init_itable, "init_itable=%u"},
1772 	{Opt_init_itable, "init_itable"},
1773 	{Opt_noinit_itable, "noinit_itable"},
1774 #ifdef CONFIG_EXT4_DEBUG
1775 	{Opt_fc_debug_force, "fc_debug_force"},
1776 	{Opt_fc_debug_max_replay, "fc_debug_max_replay=%u"},
1777 #endif
1778 	{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
1779 	{Opt_test_dummy_encryption, "test_dummy_encryption=%s"},
1780 	{Opt_test_dummy_encryption, "test_dummy_encryption"},
1781 	{Opt_inlinecrypt, "inlinecrypt"},
1782 	{Opt_nombcache, "nombcache"},
1783 	{Opt_nombcache, "no_mbcache"},	/* for backward compatibility */
1784 	{Opt_prefetch_block_bitmaps, "prefetch_block_bitmaps"},
1785 	{Opt_removed, "check=none"},	/* mount option from ext2/3 */
1786 	{Opt_removed, "nocheck"},	/* mount option from ext2/3 */
1787 	{Opt_removed, "reservation"},	/* mount option from ext2/3 */
1788 	{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
1789 	{Opt_removed, "journal=%u"},	/* mount option from ext2/3 */
1790 	{Opt_err, NULL},
1791 };
1792 
get_sb_block(void ** data)1793 static ext4_fsblk_t get_sb_block(void **data)
1794 {
1795 	ext4_fsblk_t	sb_block;
1796 	char		*options = (char *) *data;
1797 
1798 	if (!options || strncmp(options, "sb=", 3) != 0)
1799 		return 1;	/* Default location */
1800 
1801 	options += 3;
1802 	/* TODO: use simple_strtoll with >32bit ext4 */
1803 	sb_block = simple_strtoul(options, &options, 0);
1804 	if (*options && *options != ',') {
1805 		printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
1806 		       (char *) *data);
1807 		return 1;
1808 	}
1809 	if (*options == ',')
1810 		options++;
1811 	*data = (void *) options;
1812 
1813 	return sb_block;
1814 }
1815 
1816 #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
1817 static const char deprecated_msg[] =
1818 	"Mount option \"%s\" will be removed by %s\n"
1819 	"Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
1820 
1821 #ifdef CONFIG_QUOTA
set_qf_name(struct super_block * sb,int qtype,substring_t * args)1822 static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
1823 {
1824 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1825 	char *qname, *old_qname = get_qf_name(sb, sbi, qtype);
1826 	int ret = -1;
1827 
1828 	if (sb_any_quota_loaded(sb) && !old_qname) {
1829 		ext4_msg(sb, KERN_ERR,
1830 			"Cannot change journaled "
1831 			"quota options when quota turned on");
1832 		return -1;
1833 	}
1834 	if (ext4_has_feature_quota(sb)) {
1835 		ext4_msg(sb, KERN_INFO, "Journaled quota options "
1836 			 "ignored when QUOTA feature is enabled");
1837 		return 1;
1838 	}
1839 	qname = match_strdup(args);
1840 	if (!qname) {
1841 		ext4_msg(sb, KERN_ERR,
1842 			"Not enough memory for storing quotafile name");
1843 		return -1;
1844 	}
1845 	if (old_qname) {
1846 		if (strcmp(old_qname, qname) == 0)
1847 			ret = 1;
1848 		else
1849 			ext4_msg(sb, KERN_ERR,
1850 				 "%s quota file already specified",
1851 				 QTYPE2NAME(qtype));
1852 		goto errout;
1853 	}
1854 	if (strchr(qname, '/')) {
1855 		ext4_msg(sb, KERN_ERR,
1856 			"quotafile must be on filesystem root");
1857 		goto errout;
1858 	}
1859 	rcu_assign_pointer(sbi->s_qf_names[qtype], qname);
1860 	set_opt(sb, QUOTA);
1861 	return 1;
1862 errout:
1863 	kfree(qname);
1864 	return ret;
1865 }
1866 
clear_qf_name(struct super_block * sb,int qtype)1867 static int clear_qf_name(struct super_block *sb, int qtype)
1868 {
1869 
1870 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1871 	char *old_qname = get_qf_name(sb, sbi, qtype);
1872 
1873 	if (sb_any_quota_loaded(sb) && old_qname) {
1874 		ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
1875 			" when quota turned on");
1876 		return -1;
1877 	}
1878 	rcu_assign_pointer(sbi->s_qf_names[qtype], NULL);
1879 	synchronize_rcu();
1880 	kfree(old_qname);
1881 	return 1;
1882 }
1883 #endif
1884 
1885 #define MOPT_SET	0x0001
1886 #define MOPT_CLEAR	0x0002
1887 #define MOPT_NOSUPPORT	0x0004
1888 #define MOPT_EXPLICIT	0x0008
1889 #define MOPT_CLEAR_ERR	0x0010
1890 #define MOPT_GTE0	0x0020
1891 #ifdef CONFIG_QUOTA
1892 #define MOPT_Q		0
1893 #define MOPT_QFMT	0x0040
1894 #else
1895 #define MOPT_Q		MOPT_NOSUPPORT
1896 #define MOPT_QFMT	MOPT_NOSUPPORT
1897 #endif
1898 #define MOPT_DATAJ	0x0080
1899 #define MOPT_NO_EXT2	0x0100
1900 #define MOPT_NO_EXT3	0x0200
1901 #define MOPT_EXT4_ONLY	(MOPT_NO_EXT2 | MOPT_NO_EXT3)
1902 #define MOPT_STRING	0x0400
1903 #define MOPT_SKIP	0x0800
1904 #define	MOPT_2		0x1000
1905 
1906 static const struct mount_opts {
1907 	int	token;
1908 	int	mount_opt;
1909 	int	flags;
1910 } ext4_mount_opts[] = {
1911 	{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
1912 	{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
1913 	{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
1914 	{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
1915 	{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
1916 	{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
1917 	{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
1918 	 MOPT_EXT4_ONLY | MOPT_SET},
1919 	{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
1920 	 MOPT_EXT4_ONLY | MOPT_CLEAR},
1921 	{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
1922 	{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
1923 	{Opt_delalloc, EXT4_MOUNT_DELALLOC,
1924 	 MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1925 	{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
1926 	 MOPT_EXT4_ONLY | MOPT_CLEAR},
1927 	{Opt_warn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_SET},
1928 	{Opt_nowarn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_CLEAR},
1929 	{Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1930 	 MOPT_EXT4_ONLY | MOPT_CLEAR},
1931 	{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1932 	 MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1933 	{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
1934 				    EXT4_MOUNT_JOURNAL_CHECKSUM),
1935 	 MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1936 	{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
1937 	{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
1938 	{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
1939 	{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
1940 	{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
1941 	 MOPT_NO_EXT2},
1942 	{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
1943 	 MOPT_NO_EXT2},
1944 	{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
1945 	{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
1946 	{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
1947 	{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
1948 	{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
1949 	{Opt_commit, 0, MOPT_GTE0},
1950 	{Opt_max_batch_time, 0, MOPT_GTE0},
1951 	{Opt_min_batch_time, 0, MOPT_GTE0},
1952 	{Opt_inode_readahead_blks, 0, MOPT_GTE0},
1953 	{Opt_init_itable, 0, MOPT_GTE0},
1954 	{Opt_dax, EXT4_MOUNT_DAX_ALWAYS, MOPT_SET | MOPT_SKIP},
1955 	{Opt_dax_always, EXT4_MOUNT_DAX_ALWAYS,
1956 		MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1957 	{Opt_dax_inode, EXT4_MOUNT2_DAX_INODE,
1958 		MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1959 	{Opt_dax_never, EXT4_MOUNT2_DAX_NEVER,
1960 		MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1961 	{Opt_stripe, 0, MOPT_GTE0},
1962 	{Opt_resuid, 0, MOPT_GTE0},
1963 	{Opt_resgid, 0, MOPT_GTE0},
1964 	{Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1965 	{Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
1966 	{Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1967 	{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1968 	{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1969 	{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
1970 	 MOPT_NO_EXT2 | MOPT_DATAJ},
1971 	{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
1972 	{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
1973 #ifdef CONFIG_EXT4_FS_POSIX_ACL
1974 	{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
1975 	{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
1976 #else
1977 	{Opt_acl, 0, MOPT_NOSUPPORT},
1978 	{Opt_noacl, 0, MOPT_NOSUPPORT},
1979 #endif
1980 	{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
1981 	{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
1982 	{Opt_debug_want_extra_isize, 0, MOPT_GTE0},
1983 	{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
1984 	{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
1985 							MOPT_SET | MOPT_Q},
1986 	{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
1987 							MOPT_SET | MOPT_Q},
1988 	{Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
1989 							MOPT_SET | MOPT_Q},
1990 	{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
1991 		       EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
1992 							MOPT_CLEAR | MOPT_Q},
1993 	{Opt_usrjquota, 0, MOPT_Q | MOPT_STRING},
1994 	{Opt_grpjquota, 0, MOPT_Q | MOPT_STRING},
1995 	{Opt_offusrjquota, 0, MOPT_Q},
1996 	{Opt_offgrpjquota, 0, MOPT_Q},
1997 	{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
1998 	{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
1999 	{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
2000 	{Opt_max_dir_size_kb, 0, MOPT_GTE0},
2001 	{Opt_test_dummy_encryption, 0, MOPT_STRING},
2002 	{Opt_nombcache, EXT4_MOUNT_NO_MBCACHE, MOPT_SET},
2003 	{Opt_prefetch_block_bitmaps, EXT4_MOUNT_PREFETCH_BLOCK_BITMAPS,
2004 	 MOPT_SET},
2005 #ifdef CONFIG_EXT4_DEBUG
2006 	{Opt_fc_debug_force, EXT4_MOUNT2_JOURNAL_FAST_COMMIT,
2007 	 MOPT_SET | MOPT_2 | MOPT_EXT4_ONLY},
2008 	{Opt_fc_debug_max_replay, 0, MOPT_GTE0},
2009 #endif
2010 	{Opt_err, 0, 0}
2011 };
2012 
2013 #ifdef CONFIG_UNICODE
2014 static const struct ext4_sb_encodings {
2015 	__u16 magic;
2016 	char *name;
2017 	char *version;
2018 } ext4_sb_encoding_map[] = {
2019 	{EXT4_ENC_UTF8_12_1, "utf8", "12.1.0"},
2020 };
2021 
ext4_sb_read_encoding(const struct ext4_super_block * es,const struct ext4_sb_encodings ** encoding,__u16 * flags)2022 static int ext4_sb_read_encoding(const struct ext4_super_block *es,
2023 				 const struct ext4_sb_encodings **encoding,
2024 				 __u16 *flags)
2025 {
2026 	__u16 magic = le16_to_cpu(es->s_encoding);
2027 	int i;
2028 
2029 	for (i = 0; i < ARRAY_SIZE(ext4_sb_encoding_map); i++)
2030 		if (magic == ext4_sb_encoding_map[i].magic)
2031 			break;
2032 
2033 	if (i >= ARRAY_SIZE(ext4_sb_encoding_map))
2034 		return -EINVAL;
2035 
2036 	*encoding = &ext4_sb_encoding_map[i];
2037 	*flags = le16_to_cpu(es->s_encoding_flags);
2038 
2039 	return 0;
2040 }
2041 #endif
2042 
ext4_set_test_dummy_encryption(struct super_block * sb,const char * opt,const substring_t * arg,bool is_remount)2043 static int ext4_set_test_dummy_encryption(struct super_block *sb,
2044 					  const char *opt,
2045 					  const substring_t *arg,
2046 					  bool is_remount)
2047 {
2048 #ifdef CONFIG_FS_ENCRYPTION
2049 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2050 	int err;
2051 
2052 	/*
2053 	 * This mount option is just for testing, and it's not worthwhile to
2054 	 * implement the extra complexity (e.g. RCU protection) that would be
2055 	 * needed to allow it to be set or changed during remount.  We do allow
2056 	 * it to be specified during remount, but only if there is no change.
2057 	 */
2058 	if (is_remount && !sbi->s_dummy_enc_policy.policy) {
2059 		ext4_msg(sb, KERN_WARNING,
2060 			 "Can't set test_dummy_encryption on remount");
2061 		return -1;
2062 	}
2063 	err = fscrypt_set_test_dummy_encryption(sb, arg->from,
2064 						&sbi->s_dummy_enc_policy);
2065 	if (err) {
2066 		if (err == -EEXIST)
2067 			ext4_msg(sb, KERN_WARNING,
2068 				 "Can't change test_dummy_encryption on remount");
2069 		else if (err == -EINVAL)
2070 			ext4_msg(sb, KERN_WARNING,
2071 				 "Value of option \"%s\" is unrecognized", opt);
2072 		else
2073 			ext4_msg(sb, KERN_WARNING,
2074 				 "Error processing option \"%s\" [%d]",
2075 				 opt, err);
2076 		return -1;
2077 	}
2078 	ext4_msg(sb, KERN_WARNING, "Test dummy encryption mode enabled");
2079 #else
2080 	ext4_msg(sb, KERN_WARNING,
2081 		 "Test dummy encryption mount option ignored");
2082 #endif
2083 	return 1;
2084 }
2085 
handle_mount_opt(struct super_block * sb,char * opt,int token,substring_t * args,unsigned long * journal_devnum,unsigned int * journal_ioprio,int is_remount)2086 static int handle_mount_opt(struct super_block *sb, char *opt, int token,
2087 			    substring_t *args, unsigned long *journal_devnum,
2088 			    unsigned int *journal_ioprio, int is_remount)
2089 {
2090 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2091 	const struct mount_opts *m;
2092 	kuid_t uid;
2093 	kgid_t gid;
2094 	int arg = 0;
2095 
2096 #ifdef CONFIG_QUOTA
2097 	if (token == Opt_usrjquota)
2098 		return set_qf_name(sb, USRQUOTA, &args[0]);
2099 	else if (token == Opt_grpjquota)
2100 		return set_qf_name(sb, GRPQUOTA, &args[0]);
2101 	else if (token == Opt_offusrjquota)
2102 		return clear_qf_name(sb, USRQUOTA);
2103 	else if (token == Opt_offgrpjquota)
2104 		return clear_qf_name(sb, GRPQUOTA);
2105 #endif
2106 	switch (token) {
2107 	case Opt_noacl:
2108 	case Opt_nouser_xattr:
2109 		ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
2110 		break;
2111 	case Opt_sb:
2112 		return 1;	/* handled by get_sb_block() */
2113 	case Opt_removed:
2114 		ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
2115 		return 1;
2116 	case Opt_abort:
2117 		ext4_set_mount_flag(sb, EXT4_MF_FS_ABORTED);
2118 		return 1;
2119 	case Opt_i_version:
2120 		sb->s_flags |= SB_I_VERSION;
2121 		return 1;
2122 	case Opt_lazytime:
2123 		sb->s_flags |= SB_LAZYTIME;
2124 		return 1;
2125 	case Opt_nolazytime:
2126 		sb->s_flags &= ~SB_LAZYTIME;
2127 		return 1;
2128 	case Opt_inlinecrypt:
2129 #ifdef CONFIG_FS_ENCRYPTION_INLINE_CRYPT
2130 		sb->s_flags |= SB_INLINECRYPT;
2131 #else
2132 		ext4_msg(sb, KERN_ERR, "inline encryption not supported");
2133 #endif
2134 		return 1;
2135 	}
2136 
2137 	for (m = ext4_mount_opts; m->token != Opt_err; m++)
2138 		if (token == m->token)
2139 			break;
2140 
2141 	if (m->token == Opt_err) {
2142 		ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
2143 			 "or missing value", opt);
2144 		return -1;
2145 	}
2146 
2147 	if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
2148 		ext4_msg(sb, KERN_ERR,
2149 			 "Mount option \"%s\" incompatible with ext2", opt);
2150 		return -1;
2151 	}
2152 	if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
2153 		ext4_msg(sb, KERN_ERR,
2154 			 "Mount option \"%s\" incompatible with ext3", opt);
2155 		return -1;
2156 	}
2157 
2158 	if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
2159 		return -1;
2160 	if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
2161 		return -1;
2162 	if (m->flags & MOPT_EXPLICIT) {
2163 		if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
2164 			set_opt2(sb, EXPLICIT_DELALLOC);
2165 		} else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
2166 			set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
2167 		} else
2168 			return -1;
2169 	}
2170 	if (m->flags & MOPT_CLEAR_ERR)
2171 		clear_opt(sb, ERRORS_MASK);
2172 	if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
2173 		ext4_msg(sb, KERN_ERR, "Cannot change quota "
2174 			 "options when quota turned on");
2175 		return -1;
2176 	}
2177 
2178 	if (m->flags & MOPT_NOSUPPORT) {
2179 		ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
2180 	} else if (token == Opt_commit) {
2181 		if (arg == 0)
2182 			arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
2183 		else if (arg > INT_MAX / HZ) {
2184 			ext4_msg(sb, KERN_ERR,
2185 				 "Invalid commit interval %d, "
2186 				 "must be smaller than %d",
2187 				 arg, INT_MAX / HZ);
2188 			return -1;
2189 		}
2190 		sbi->s_commit_interval = HZ * arg;
2191 	} else if (token == Opt_debug_want_extra_isize) {
2192 		if ((arg & 1) ||
2193 		    (arg < 4) ||
2194 		    (arg > (sbi->s_inode_size - EXT4_GOOD_OLD_INODE_SIZE))) {
2195 			ext4_msg(sb, KERN_ERR,
2196 				 "Invalid want_extra_isize %d", arg);
2197 			return -1;
2198 		}
2199 		sbi->s_want_extra_isize = arg;
2200 	} else if (token == Opt_max_batch_time) {
2201 		sbi->s_max_batch_time = arg;
2202 	} else if (token == Opt_min_batch_time) {
2203 		sbi->s_min_batch_time = arg;
2204 	} else if (token == Opt_inode_readahead_blks) {
2205 		if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
2206 			ext4_msg(sb, KERN_ERR,
2207 				 "EXT4-fs: inode_readahead_blks must be "
2208 				 "0 or a power of 2 smaller than 2^31");
2209 			return -1;
2210 		}
2211 		sbi->s_inode_readahead_blks = arg;
2212 	} else if (token == Opt_init_itable) {
2213 		set_opt(sb, INIT_INODE_TABLE);
2214 		if (!args->from)
2215 			arg = EXT4_DEF_LI_WAIT_MULT;
2216 		sbi->s_li_wait_mult = arg;
2217 	} else if (token == Opt_max_dir_size_kb) {
2218 		sbi->s_max_dir_size_kb = arg;
2219 #ifdef CONFIG_EXT4_DEBUG
2220 	} else if (token == Opt_fc_debug_max_replay) {
2221 		sbi->s_fc_debug_max_replay = arg;
2222 #endif
2223 	} else if (token == Opt_stripe) {
2224 		sbi->s_stripe = arg;
2225 	} else if (token == Opt_resuid) {
2226 		uid = make_kuid(current_user_ns(), arg);
2227 		if (!uid_valid(uid)) {
2228 			ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
2229 			return -1;
2230 		}
2231 		sbi->s_resuid = uid;
2232 	} else if (token == Opt_resgid) {
2233 		gid = make_kgid(current_user_ns(), arg);
2234 		if (!gid_valid(gid)) {
2235 			ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
2236 			return -1;
2237 		}
2238 		sbi->s_resgid = gid;
2239 	} else if (token == Opt_journal_dev) {
2240 		if (is_remount) {
2241 			ext4_msg(sb, KERN_ERR,
2242 				 "Cannot specify journal on remount");
2243 			return -1;
2244 		}
2245 		*journal_devnum = arg;
2246 	} else if (token == Opt_journal_path) {
2247 		char *journal_path;
2248 		struct inode *journal_inode;
2249 		struct path path;
2250 		int error;
2251 
2252 		if (is_remount) {
2253 			ext4_msg(sb, KERN_ERR,
2254 				 "Cannot specify journal on remount");
2255 			return -1;
2256 		}
2257 		journal_path = match_strdup(&args[0]);
2258 		if (!journal_path) {
2259 			ext4_msg(sb, KERN_ERR, "error: could not dup "
2260 				"journal device string");
2261 			return -1;
2262 		}
2263 
2264 		error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
2265 		if (error) {
2266 			ext4_msg(sb, KERN_ERR, "error: could not find "
2267 				"journal device path: error %d", error);
2268 			kfree(journal_path);
2269 			return -1;
2270 		}
2271 
2272 		journal_inode = d_inode(path.dentry);
2273 		if (!S_ISBLK(journal_inode->i_mode)) {
2274 			ext4_msg(sb, KERN_ERR, "error: journal path %s "
2275 				"is not a block device", journal_path);
2276 			path_put(&path);
2277 			kfree(journal_path);
2278 			return -1;
2279 		}
2280 
2281 		*journal_devnum = new_encode_dev(journal_inode->i_rdev);
2282 		path_put(&path);
2283 		kfree(journal_path);
2284 	} else if (token == Opt_journal_ioprio) {
2285 		if (arg > 7) {
2286 			ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
2287 				 " (must be 0-7)");
2288 			return -1;
2289 		}
2290 		*journal_ioprio =
2291 			IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
2292 	} else if (token == Opt_test_dummy_encryption) {
2293 		return ext4_set_test_dummy_encryption(sb, opt, &args[0],
2294 						      is_remount);
2295 	} else if (m->flags & MOPT_DATAJ) {
2296 		if (is_remount) {
2297 			if (!sbi->s_journal)
2298 				ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
2299 			else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
2300 				ext4_msg(sb, KERN_ERR,
2301 					 "Cannot change data mode on remount");
2302 				return -1;
2303 			}
2304 		} else {
2305 			clear_opt(sb, DATA_FLAGS);
2306 			sbi->s_mount_opt |= m->mount_opt;
2307 		}
2308 #ifdef CONFIG_QUOTA
2309 	} else if (m->flags & MOPT_QFMT) {
2310 		if (sb_any_quota_loaded(sb) &&
2311 		    sbi->s_jquota_fmt != m->mount_opt) {
2312 			ext4_msg(sb, KERN_ERR, "Cannot change journaled "
2313 				 "quota options when quota turned on");
2314 			return -1;
2315 		}
2316 		if (ext4_has_feature_quota(sb)) {
2317 			ext4_msg(sb, KERN_INFO,
2318 				 "Quota format mount options ignored "
2319 				 "when QUOTA feature is enabled");
2320 			return 1;
2321 		}
2322 		sbi->s_jquota_fmt = m->mount_opt;
2323 #endif
2324 	} else if (token == Opt_dax || token == Opt_dax_always ||
2325 		   token == Opt_dax_inode || token == Opt_dax_never) {
2326 #ifdef CONFIG_FS_DAX
2327 		switch (token) {
2328 		case Opt_dax:
2329 		case Opt_dax_always:
2330 			if (is_remount &&
2331 			    (!(sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
2332 			     (sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER))) {
2333 			fail_dax_change_remount:
2334 				ext4_msg(sb, KERN_ERR, "can't change "
2335 					 "dax mount option while remounting");
2336 				return -1;
2337 			}
2338 			if (is_remount &&
2339 			    (test_opt(sb, DATA_FLAGS) ==
2340 			     EXT4_MOUNT_JOURNAL_DATA)) {
2341 				    ext4_msg(sb, KERN_ERR, "can't mount with "
2342 					     "both data=journal and dax");
2343 				    return -1;
2344 			}
2345 			ext4_msg(sb, KERN_WARNING,
2346 				"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
2347 			sbi->s_mount_opt |= EXT4_MOUNT_DAX_ALWAYS;
2348 			sbi->s_mount_opt2 &= ~EXT4_MOUNT2_DAX_NEVER;
2349 			break;
2350 		case Opt_dax_never:
2351 			if (is_remount &&
2352 			    (!(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
2353 			     (sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS)))
2354 				goto fail_dax_change_remount;
2355 			sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_NEVER;
2356 			sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2357 			break;
2358 		case Opt_dax_inode:
2359 			if (is_remount &&
2360 			    ((sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
2361 			     (sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
2362 			     !(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_INODE)))
2363 				goto fail_dax_change_remount;
2364 			sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2365 			sbi->s_mount_opt2 &= ~EXT4_MOUNT2_DAX_NEVER;
2366 			/* Strictly for printing options */
2367 			sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_INODE;
2368 			break;
2369 		}
2370 #else
2371 		ext4_msg(sb, KERN_INFO, "dax option not supported");
2372 		sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_NEVER;
2373 		sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2374 		return -1;
2375 #endif
2376 	} else if (token == Opt_data_err_abort) {
2377 		sbi->s_mount_opt |= m->mount_opt;
2378 	} else if (token == Opt_data_err_ignore) {
2379 		sbi->s_mount_opt &= ~m->mount_opt;
2380 	} else {
2381 		if (!args->from)
2382 			arg = 1;
2383 		if (m->flags & MOPT_CLEAR)
2384 			arg = !arg;
2385 		else if (unlikely(!(m->flags & MOPT_SET))) {
2386 			ext4_msg(sb, KERN_WARNING,
2387 				 "buggy handling of option %s", opt);
2388 			WARN_ON(1);
2389 			return -1;
2390 		}
2391 		if (m->flags & MOPT_2) {
2392 			if (arg != 0)
2393 				sbi->s_mount_opt2 |= m->mount_opt;
2394 			else
2395 				sbi->s_mount_opt2 &= ~m->mount_opt;
2396 		} else {
2397 			if (arg != 0)
2398 				sbi->s_mount_opt |= m->mount_opt;
2399 			else
2400 				sbi->s_mount_opt &= ~m->mount_opt;
2401 		}
2402 	}
2403 	return 1;
2404 }
2405 
parse_options(char * options,struct super_block * sb,unsigned long * journal_devnum,unsigned int * journal_ioprio,int is_remount)2406 static int parse_options(char *options, struct super_block *sb,
2407 			 unsigned long *journal_devnum,
2408 			 unsigned int *journal_ioprio,
2409 			 int is_remount)
2410 {
2411 	struct ext4_sb_info __maybe_unused *sbi = EXT4_SB(sb);
2412 	char *p, __maybe_unused *usr_qf_name, __maybe_unused *grp_qf_name;
2413 	substring_t args[MAX_OPT_ARGS];
2414 	int token;
2415 
2416 	if (!options)
2417 		return 1;
2418 
2419 	while ((p = strsep(&options, ",")) != NULL) {
2420 		if (!*p)
2421 			continue;
2422 		/*
2423 		 * Initialize args struct so we know whether arg was
2424 		 * found; some options take optional arguments.
2425 		 */
2426 		args[0].to = args[0].from = NULL;
2427 		token = match_token(p, tokens, args);
2428 		if (handle_mount_opt(sb, p, token, args, journal_devnum,
2429 				     journal_ioprio, is_remount) < 0)
2430 			return 0;
2431 	}
2432 #ifdef CONFIG_QUOTA
2433 	/*
2434 	 * We do the test below only for project quotas. 'usrquota' and
2435 	 * 'grpquota' mount options are allowed even without quota feature
2436 	 * to support legacy quotas in quota files.
2437 	 */
2438 	if (test_opt(sb, PRJQUOTA) && !ext4_has_feature_project(sb)) {
2439 		ext4_msg(sb, KERN_ERR, "Project quota feature not enabled. "
2440 			 "Cannot enable project quota enforcement.");
2441 		return 0;
2442 	}
2443 	usr_qf_name = get_qf_name(sb, sbi, USRQUOTA);
2444 	grp_qf_name = get_qf_name(sb, sbi, GRPQUOTA);
2445 	if (usr_qf_name || grp_qf_name) {
2446 		if (test_opt(sb, USRQUOTA) && usr_qf_name)
2447 			clear_opt(sb, USRQUOTA);
2448 
2449 		if (test_opt(sb, GRPQUOTA) && grp_qf_name)
2450 			clear_opt(sb, GRPQUOTA);
2451 
2452 		if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
2453 			ext4_msg(sb, KERN_ERR, "old and new quota "
2454 					"format mixing");
2455 			return 0;
2456 		}
2457 
2458 		if (!sbi->s_jquota_fmt) {
2459 			ext4_msg(sb, KERN_ERR, "journaled quota format "
2460 					"not specified");
2461 			return 0;
2462 		}
2463 	}
2464 #endif
2465 	if (test_opt(sb, DIOREAD_NOLOCK)) {
2466 		int blocksize =
2467 			BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
2468 		if (blocksize < PAGE_SIZE)
2469 			ext4_msg(sb, KERN_WARNING, "Warning: mounting with an "
2470 				 "experimental mount option 'dioread_nolock' "
2471 				 "for blocksize < PAGE_SIZE");
2472 	}
2473 	return 1;
2474 }
2475 
ext4_show_quota_options(struct seq_file * seq,struct super_block * sb)2476 static inline void ext4_show_quota_options(struct seq_file *seq,
2477 					   struct super_block *sb)
2478 {
2479 #if defined(CONFIG_QUOTA)
2480 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2481 	char *usr_qf_name, *grp_qf_name;
2482 
2483 	if (sbi->s_jquota_fmt) {
2484 		char *fmtname = "";
2485 
2486 		switch (sbi->s_jquota_fmt) {
2487 		case QFMT_VFS_OLD:
2488 			fmtname = "vfsold";
2489 			break;
2490 		case QFMT_VFS_V0:
2491 			fmtname = "vfsv0";
2492 			break;
2493 		case QFMT_VFS_V1:
2494 			fmtname = "vfsv1";
2495 			break;
2496 		}
2497 		seq_printf(seq, ",jqfmt=%s", fmtname);
2498 	}
2499 
2500 	rcu_read_lock();
2501 	usr_qf_name = rcu_dereference(sbi->s_qf_names[USRQUOTA]);
2502 	grp_qf_name = rcu_dereference(sbi->s_qf_names[GRPQUOTA]);
2503 	if (usr_qf_name)
2504 		seq_show_option(seq, "usrjquota", usr_qf_name);
2505 	if (grp_qf_name)
2506 		seq_show_option(seq, "grpjquota", grp_qf_name);
2507 	rcu_read_unlock();
2508 #endif
2509 }
2510 
token2str(int token)2511 static const char *token2str(int token)
2512 {
2513 	const struct match_token *t;
2514 
2515 	for (t = tokens; t->token != Opt_err; t++)
2516 		if (t->token == token && !strchr(t->pattern, '='))
2517 			break;
2518 	return t->pattern;
2519 }
2520 
2521 /*
2522  * Show an option if
2523  *  - it's set to a non-default value OR
2524  *  - if the per-sb default is different from the global default
2525  */
_ext4_show_options(struct seq_file * seq,struct super_block * sb,int nodefs)2526 static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
2527 			      int nodefs)
2528 {
2529 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2530 	struct ext4_super_block *es = sbi->s_es;
2531 	int def_errors, def_mount_opt = sbi->s_def_mount_opt;
2532 	const struct mount_opts *m;
2533 	char sep = nodefs ? '\n' : ',';
2534 
2535 #define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
2536 #define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
2537 
2538 	if (sbi->s_sb_block != 1)
2539 		SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
2540 
2541 	for (m = ext4_mount_opts; m->token != Opt_err; m++) {
2542 		int want_set = m->flags & MOPT_SET;
2543 		if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
2544 		    (m->flags & MOPT_CLEAR_ERR) || m->flags & MOPT_SKIP)
2545 			continue;
2546 		if (!nodefs && !(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
2547 			continue; /* skip if same as the default */
2548 		if ((want_set &&
2549 		     (sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
2550 		    (!want_set && (sbi->s_mount_opt & m->mount_opt)))
2551 			continue; /* select Opt_noFoo vs Opt_Foo */
2552 		SEQ_OPTS_PRINT("%s", token2str(m->token));
2553 	}
2554 
2555 	if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
2556 	    le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
2557 		SEQ_OPTS_PRINT("resuid=%u",
2558 				from_kuid_munged(&init_user_ns, sbi->s_resuid));
2559 	if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
2560 	    le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
2561 		SEQ_OPTS_PRINT("resgid=%u",
2562 				from_kgid_munged(&init_user_ns, sbi->s_resgid));
2563 	def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
2564 	if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
2565 		SEQ_OPTS_PUTS("errors=remount-ro");
2566 	if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
2567 		SEQ_OPTS_PUTS("errors=continue");
2568 	if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
2569 		SEQ_OPTS_PUTS("errors=panic");
2570 	if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
2571 		SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
2572 	if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
2573 		SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
2574 	if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
2575 		SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
2576 	if (sb->s_flags & SB_I_VERSION)
2577 		SEQ_OPTS_PUTS("i_version");
2578 	if (nodefs || sbi->s_stripe)
2579 		SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
2580 	if (nodefs || EXT4_MOUNT_DATA_FLAGS &
2581 			(sbi->s_mount_opt ^ def_mount_opt)) {
2582 		if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
2583 			SEQ_OPTS_PUTS("data=journal");
2584 		else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
2585 			SEQ_OPTS_PUTS("data=ordered");
2586 		else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
2587 			SEQ_OPTS_PUTS("data=writeback");
2588 	}
2589 	if (nodefs ||
2590 	    sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
2591 		SEQ_OPTS_PRINT("inode_readahead_blks=%u",
2592 			       sbi->s_inode_readahead_blks);
2593 
2594 	if (test_opt(sb, INIT_INODE_TABLE) && (nodefs ||
2595 		       (sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
2596 		SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
2597 	if (nodefs || sbi->s_max_dir_size_kb)
2598 		SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
2599 	if (test_opt(sb, DATA_ERR_ABORT))
2600 		SEQ_OPTS_PUTS("data_err=abort");
2601 
2602 	fscrypt_show_test_dummy_encryption(seq, sep, sb);
2603 
2604 	if (sb->s_flags & SB_INLINECRYPT)
2605 		SEQ_OPTS_PUTS("inlinecrypt");
2606 
2607 	if (test_opt(sb, DAX_ALWAYS)) {
2608 		if (IS_EXT2_SB(sb))
2609 			SEQ_OPTS_PUTS("dax");
2610 		else
2611 			SEQ_OPTS_PUTS("dax=always");
2612 	} else if (test_opt2(sb, DAX_NEVER)) {
2613 		SEQ_OPTS_PUTS("dax=never");
2614 	} else if (test_opt2(sb, DAX_INODE)) {
2615 		SEQ_OPTS_PUTS("dax=inode");
2616 	}
2617 	ext4_show_quota_options(seq, sb);
2618 	return 0;
2619 }
2620 
ext4_show_options(struct seq_file * seq,struct dentry * root)2621 static int ext4_show_options(struct seq_file *seq, struct dentry *root)
2622 {
2623 	return _ext4_show_options(seq, root->d_sb, 0);
2624 }
2625 
ext4_seq_options_show(struct seq_file * seq,void * offset)2626 int ext4_seq_options_show(struct seq_file *seq, void *offset)
2627 {
2628 	struct super_block *sb = seq->private;
2629 	int rc;
2630 
2631 	seq_puts(seq, sb_rdonly(sb) ? "ro" : "rw");
2632 	rc = _ext4_show_options(seq, sb, 1);
2633 	seq_puts(seq, "\n");
2634 	return rc;
2635 }
2636 
ext4_setup_super(struct super_block * sb,struct ext4_super_block * es,int read_only)2637 static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
2638 			    int read_only)
2639 {
2640 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2641 	int err = 0;
2642 
2643 	if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
2644 		ext4_msg(sb, KERN_ERR, "revision level too high, "
2645 			 "forcing read-only mode");
2646 		err = -EROFS;
2647 		goto done;
2648 	}
2649 	if (read_only)
2650 		goto done;
2651 	if (!(sbi->s_mount_state & EXT4_VALID_FS))
2652 		ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
2653 			 "running e2fsck is recommended");
2654 	else if (sbi->s_mount_state & EXT4_ERROR_FS)
2655 		ext4_msg(sb, KERN_WARNING,
2656 			 "warning: mounting fs with errors, "
2657 			 "running e2fsck is recommended");
2658 	else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
2659 		 le16_to_cpu(es->s_mnt_count) >=
2660 		 (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
2661 		ext4_msg(sb, KERN_WARNING,
2662 			 "warning: maximal mount count reached, "
2663 			 "running e2fsck is recommended");
2664 	else if (le32_to_cpu(es->s_checkinterval) &&
2665 		 (ext4_get_tstamp(es, s_lastcheck) +
2666 		  le32_to_cpu(es->s_checkinterval) <= ktime_get_real_seconds()))
2667 		ext4_msg(sb, KERN_WARNING,
2668 			 "warning: checktime reached, "
2669 			 "running e2fsck is recommended");
2670 	if (!sbi->s_journal)
2671 		es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
2672 	if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
2673 		es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
2674 	le16_add_cpu(&es->s_mnt_count, 1);
2675 	ext4_update_tstamp(es, s_mtime);
2676 	if (sbi->s_journal)
2677 		ext4_set_feature_journal_needs_recovery(sb);
2678 
2679 	err = ext4_commit_super(sb);
2680 done:
2681 	if (test_opt(sb, DEBUG))
2682 		printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
2683 				"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
2684 			sb->s_blocksize,
2685 			sbi->s_groups_count,
2686 			EXT4_BLOCKS_PER_GROUP(sb),
2687 			EXT4_INODES_PER_GROUP(sb),
2688 			sbi->s_mount_opt, sbi->s_mount_opt2);
2689 
2690 	cleancache_init_fs(sb);
2691 	return err;
2692 }
2693 
ext4_alloc_flex_bg_array(struct super_block * sb,ext4_group_t ngroup)2694 int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
2695 {
2696 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2697 	struct flex_groups **old_groups, **new_groups;
2698 	int size, i, j;
2699 
2700 	if (!sbi->s_log_groups_per_flex)
2701 		return 0;
2702 
2703 	size = ext4_flex_group(sbi, ngroup - 1) + 1;
2704 	if (size <= sbi->s_flex_groups_allocated)
2705 		return 0;
2706 
2707 	new_groups = kvzalloc(roundup_pow_of_two(size *
2708 			      sizeof(*sbi->s_flex_groups)), GFP_KERNEL);
2709 	if (!new_groups) {
2710 		ext4_msg(sb, KERN_ERR,
2711 			 "not enough memory for %d flex group pointers", size);
2712 		return -ENOMEM;
2713 	}
2714 	for (i = sbi->s_flex_groups_allocated; i < size; i++) {
2715 		new_groups[i] = kvzalloc(roundup_pow_of_two(
2716 					 sizeof(struct flex_groups)),
2717 					 GFP_KERNEL);
2718 		if (!new_groups[i]) {
2719 			for (j = sbi->s_flex_groups_allocated; j < i; j++)
2720 				kvfree(new_groups[j]);
2721 			kvfree(new_groups);
2722 			ext4_msg(sb, KERN_ERR,
2723 				 "not enough memory for %d flex groups", size);
2724 			return -ENOMEM;
2725 		}
2726 	}
2727 	rcu_read_lock();
2728 	old_groups = rcu_dereference(sbi->s_flex_groups);
2729 	if (old_groups)
2730 		memcpy(new_groups, old_groups,
2731 		       (sbi->s_flex_groups_allocated *
2732 			sizeof(struct flex_groups *)));
2733 	rcu_read_unlock();
2734 	rcu_assign_pointer(sbi->s_flex_groups, new_groups);
2735 	sbi->s_flex_groups_allocated = size;
2736 	if (old_groups)
2737 		ext4_kvfree_array_rcu(old_groups);
2738 	return 0;
2739 }
2740 
ext4_fill_flex_info(struct super_block * sb)2741 static int ext4_fill_flex_info(struct super_block *sb)
2742 {
2743 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2744 	struct ext4_group_desc *gdp = NULL;
2745 	struct flex_groups *fg;
2746 	ext4_group_t flex_group;
2747 	int i, err;
2748 
2749 	sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
2750 	if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
2751 		sbi->s_log_groups_per_flex = 0;
2752 		return 1;
2753 	}
2754 
2755 	err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
2756 	if (err)
2757 		goto failed;
2758 
2759 	for (i = 0; i < sbi->s_groups_count; i++) {
2760 		gdp = ext4_get_group_desc(sb, i, NULL);
2761 
2762 		flex_group = ext4_flex_group(sbi, i);
2763 		fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
2764 		atomic_add(ext4_free_inodes_count(sb, gdp), &fg->free_inodes);
2765 		atomic64_add(ext4_free_group_clusters(sb, gdp),
2766 			     &fg->free_clusters);
2767 		atomic_add(ext4_used_dirs_count(sb, gdp), &fg->used_dirs);
2768 	}
2769 
2770 	return 1;
2771 failed:
2772 	return 0;
2773 }
2774 
ext4_group_desc_csum(struct super_block * sb,__u32 block_group,struct ext4_group_desc * gdp)2775 static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
2776 				   struct ext4_group_desc *gdp)
2777 {
2778 	int offset = offsetof(struct ext4_group_desc, bg_checksum);
2779 	__u16 crc = 0;
2780 	__le32 le_group = cpu_to_le32(block_group);
2781 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2782 
2783 	if (ext4_has_metadata_csum(sbi->s_sb)) {
2784 		/* Use new metadata_csum algorithm */
2785 		__u32 csum32;
2786 		__u16 dummy_csum = 0;
2787 
2788 		csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
2789 				     sizeof(le_group));
2790 		csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
2791 		csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
2792 				     sizeof(dummy_csum));
2793 		offset += sizeof(dummy_csum);
2794 		if (offset < sbi->s_desc_size)
2795 			csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
2796 					     sbi->s_desc_size - offset);
2797 
2798 		crc = csum32 & 0xFFFF;
2799 		goto out;
2800 	}
2801 
2802 	/* old crc16 code */
2803 	if (!ext4_has_feature_gdt_csum(sb))
2804 		return 0;
2805 
2806 	crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
2807 	crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
2808 	crc = crc16(crc, (__u8 *)gdp, offset);
2809 	offset += sizeof(gdp->bg_checksum); /* skip checksum */
2810 	/* for checksum of struct ext4_group_desc do the rest...*/
2811 	if (ext4_has_feature_64bit(sb) &&
2812 	    offset < le16_to_cpu(sbi->s_es->s_desc_size))
2813 		crc = crc16(crc, (__u8 *)gdp + offset,
2814 			    le16_to_cpu(sbi->s_es->s_desc_size) -
2815 				offset);
2816 
2817 out:
2818 	return cpu_to_le16(crc);
2819 }
2820 
ext4_group_desc_csum_verify(struct super_block * sb,__u32 block_group,struct ext4_group_desc * gdp)2821 int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
2822 				struct ext4_group_desc *gdp)
2823 {
2824 	if (ext4_has_group_desc_csum(sb) &&
2825 	    (gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
2826 		return 0;
2827 
2828 	return 1;
2829 }
2830 
ext4_group_desc_csum_set(struct super_block * sb,__u32 block_group,struct ext4_group_desc * gdp)2831 void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
2832 			      struct ext4_group_desc *gdp)
2833 {
2834 	if (!ext4_has_group_desc_csum(sb))
2835 		return;
2836 	gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
2837 }
2838 
2839 /* Called at mount-time, super-block is locked */
ext4_check_descriptors(struct super_block * sb,ext4_fsblk_t sb_block,ext4_group_t * first_not_zeroed)2840 static int ext4_check_descriptors(struct super_block *sb,
2841 				  ext4_fsblk_t sb_block,
2842 				  ext4_group_t *first_not_zeroed)
2843 {
2844 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2845 	ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
2846 	ext4_fsblk_t last_block;
2847 	ext4_fsblk_t last_bg_block = sb_block + ext4_bg_num_gdb(sb, 0);
2848 	ext4_fsblk_t block_bitmap;
2849 	ext4_fsblk_t inode_bitmap;
2850 	ext4_fsblk_t inode_table;
2851 	int flexbg_flag = 0;
2852 	ext4_group_t i, grp = sbi->s_groups_count;
2853 
2854 	if (ext4_has_feature_flex_bg(sb))
2855 		flexbg_flag = 1;
2856 
2857 	ext4_debug("Checking group descriptors");
2858 
2859 	for (i = 0; i < sbi->s_groups_count; i++) {
2860 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
2861 
2862 		if (i == sbi->s_groups_count - 1 || flexbg_flag)
2863 			last_block = ext4_blocks_count(sbi->s_es) - 1;
2864 		else
2865 			last_block = first_block +
2866 				(EXT4_BLOCKS_PER_GROUP(sb) - 1);
2867 
2868 		if ((grp == sbi->s_groups_count) &&
2869 		   !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
2870 			grp = i;
2871 
2872 		block_bitmap = ext4_block_bitmap(sb, gdp);
2873 		if (block_bitmap == sb_block) {
2874 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2875 				 "Block bitmap for group %u overlaps "
2876 				 "superblock", i);
2877 			if (!sb_rdonly(sb))
2878 				return 0;
2879 		}
2880 		if (block_bitmap >= sb_block + 1 &&
2881 		    block_bitmap <= last_bg_block) {
2882 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2883 				 "Block bitmap for group %u overlaps "
2884 				 "block group descriptors", i);
2885 			if (!sb_rdonly(sb))
2886 				return 0;
2887 		}
2888 		if (block_bitmap < first_block || block_bitmap > last_block) {
2889 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2890 			       "Block bitmap for group %u not in group "
2891 			       "(block %llu)!", i, block_bitmap);
2892 			return 0;
2893 		}
2894 		inode_bitmap = ext4_inode_bitmap(sb, gdp);
2895 		if (inode_bitmap == sb_block) {
2896 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2897 				 "Inode bitmap for group %u overlaps "
2898 				 "superblock", i);
2899 			if (!sb_rdonly(sb))
2900 				return 0;
2901 		}
2902 		if (inode_bitmap >= sb_block + 1 &&
2903 		    inode_bitmap <= last_bg_block) {
2904 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2905 				 "Inode bitmap for group %u overlaps "
2906 				 "block group descriptors", i);
2907 			if (!sb_rdonly(sb))
2908 				return 0;
2909 		}
2910 		if (inode_bitmap < first_block || inode_bitmap > last_block) {
2911 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2912 			       "Inode bitmap for group %u not in group "
2913 			       "(block %llu)!", i, inode_bitmap);
2914 			return 0;
2915 		}
2916 		inode_table = ext4_inode_table(sb, gdp);
2917 		if (inode_table == sb_block) {
2918 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2919 				 "Inode table for group %u overlaps "
2920 				 "superblock", i);
2921 			if (!sb_rdonly(sb))
2922 				return 0;
2923 		}
2924 		if (inode_table >= sb_block + 1 &&
2925 		    inode_table <= last_bg_block) {
2926 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2927 				 "Inode table for group %u overlaps "
2928 				 "block group descriptors", i);
2929 			if (!sb_rdonly(sb))
2930 				return 0;
2931 		}
2932 		if (inode_table < first_block ||
2933 		    inode_table + sbi->s_itb_per_group - 1 > last_block) {
2934 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2935 			       "Inode table for group %u not in group "
2936 			       "(block %llu)!", i, inode_table);
2937 			return 0;
2938 		}
2939 		ext4_lock_group(sb, i);
2940 		if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
2941 			ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2942 				 "Checksum for group %u failed (%u!=%u)",
2943 				 i, le16_to_cpu(ext4_group_desc_csum(sb, i,
2944 				     gdp)), le16_to_cpu(gdp->bg_checksum));
2945 			if (!sb_rdonly(sb)) {
2946 				ext4_unlock_group(sb, i);
2947 				return 0;
2948 			}
2949 		}
2950 		ext4_unlock_group(sb, i);
2951 		if (!flexbg_flag)
2952 			first_block += EXT4_BLOCKS_PER_GROUP(sb);
2953 	}
2954 	if (NULL != first_not_zeroed)
2955 		*first_not_zeroed = grp;
2956 	return 1;
2957 }
2958 
2959 /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
2960  * the superblock) which were deleted from all directories, but held open by
2961  * a process at the time of a crash.  We walk the list and try to delete these
2962  * inodes at recovery time (only with a read-write filesystem).
2963  *
2964  * In order to keep the orphan inode chain consistent during traversal (in
2965  * case of crash during recovery), we link each inode into the superblock
2966  * orphan list_head and handle it the same way as an inode deletion during
2967  * normal operation (which journals the operations for us).
2968  *
2969  * We only do an iget() and an iput() on each inode, which is very safe if we
2970  * accidentally point at an in-use or already deleted inode.  The worst that
2971  * can happen in this case is that we get a "bit already cleared" message from
2972  * ext4_free_inode().  The only reason we would point at a wrong inode is if
2973  * e2fsck was run on this filesystem, and it must have already done the orphan
2974  * inode cleanup for us, so we can safely abort without any further action.
2975  */
ext4_orphan_cleanup(struct super_block * sb,struct ext4_super_block * es)2976 static void ext4_orphan_cleanup(struct super_block *sb,
2977 				struct ext4_super_block *es)
2978 {
2979 	unsigned int s_flags = sb->s_flags;
2980 	int ret, nr_orphans = 0, nr_truncates = 0;
2981 #ifdef CONFIG_QUOTA
2982 	int quota_update = 0;
2983 	int i;
2984 #endif
2985 	if (!es->s_last_orphan) {
2986 		jbd_debug(4, "no orphan inodes to clean up\n");
2987 		return;
2988 	}
2989 
2990 	if (bdev_read_only(sb->s_bdev)) {
2991 		ext4_msg(sb, KERN_ERR, "write access "
2992 			"unavailable, skipping orphan cleanup");
2993 		return;
2994 	}
2995 
2996 	/* Check if feature set would not allow a r/w mount */
2997 	if (!ext4_feature_set_ok(sb, 0)) {
2998 		ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
2999 			 "unknown ROCOMPAT features");
3000 		return;
3001 	}
3002 
3003 	if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
3004 		/* don't clear list on RO mount w/ errors */
3005 		if (es->s_last_orphan && !(s_flags & SB_RDONLY)) {
3006 			ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
3007 				  "clearing orphan list.\n");
3008 			es->s_last_orphan = 0;
3009 		}
3010 		jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
3011 		return;
3012 	}
3013 
3014 	if (s_flags & SB_RDONLY) {
3015 		ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
3016 		sb->s_flags &= ~SB_RDONLY;
3017 	}
3018 #ifdef CONFIG_QUOTA
3019 	/*
3020 	 * Turn on quotas which were not enabled for read-only mounts if
3021 	 * filesystem has quota feature, so that they are updated correctly.
3022 	 */
3023 	if (ext4_has_feature_quota(sb) && (s_flags & SB_RDONLY)) {
3024 		int ret = ext4_enable_quotas(sb);
3025 
3026 		if (!ret)
3027 			quota_update = 1;
3028 		else
3029 			ext4_msg(sb, KERN_ERR,
3030 				"Cannot turn on quotas: error %d", ret);
3031 	}
3032 
3033 	/* Turn on journaled quotas used for old sytle */
3034 	for (i = 0; i < EXT4_MAXQUOTAS; i++) {
3035 		if (EXT4_SB(sb)->s_qf_names[i]) {
3036 			int ret = ext4_quota_on_mount(sb, i);
3037 
3038 			if (!ret)
3039 				quota_update = 1;
3040 			else
3041 				ext4_msg(sb, KERN_ERR,
3042 					"Cannot turn on journaled "
3043 					"quota: type %d: error %d", i, ret);
3044 		}
3045 	}
3046 #endif
3047 
3048 	while (es->s_last_orphan) {
3049 		struct inode *inode;
3050 
3051 		/*
3052 		 * We may have encountered an error during cleanup; if
3053 		 * so, skip the rest.
3054 		 */
3055 		if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
3056 			jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
3057 			es->s_last_orphan = 0;
3058 			break;
3059 		}
3060 
3061 		inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
3062 		if (IS_ERR(inode)) {
3063 			es->s_last_orphan = 0;
3064 			break;
3065 		}
3066 
3067 		list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
3068 		dquot_initialize(inode);
3069 		if (inode->i_nlink) {
3070 			if (test_opt(sb, DEBUG))
3071 				ext4_msg(sb, KERN_DEBUG,
3072 					"%s: truncating inode %lu to %lld bytes",
3073 					__func__, inode->i_ino, inode->i_size);
3074 			jbd_debug(2, "truncating inode %lu to %lld bytes\n",
3075 				  inode->i_ino, inode->i_size);
3076 			inode_lock(inode);
3077 			truncate_inode_pages(inode->i_mapping, inode->i_size);
3078 			ret = ext4_truncate(inode);
3079 			if (ret) {
3080 				/*
3081 				 * We need to clean up the in-core orphan list
3082 				 * manually if ext4_truncate() failed to get a
3083 				 * transaction handle.
3084 				 */
3085 				ext4_orphan_del(NULL, inode);
3086 				ext4_std_error(inode->i_sb, ret);
3087 			}
3088 			inode_unlock(inode);
3089 			nr_truncates++;
3090 		} else {
3091 			if (test_opt(sb, DEBUG))
3092 				ext4_msg(sb, KERN_DEBUG,
3093 					"%s: deleting unreferenced inode %lu",
3094 					__func__, inode->i_ino);
3095 			jbd_debug(2, "deleting unreferenced inode %lu\n",
3096 				  inode->i_ino);
3097 			nr_orphans++;
3098 		}
3099 		iput(inode);  /* The delete magic happens here! */
3100 	}
3101 
3102 #define PLURAL(x) (x), ((x) == 1) ? "" : "s"
3103 
3104 	if (nr_orphans)
3105 		ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
3106 		       PLURAL(nr_orphans));
3107 	if (nr_truncates)
3108 		ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
3109 		       PLURAL(nr_truncates));
3110 #ifdef CONFIG_QUOTA
3111 	/* Turn off quotas if they were enabled for orphan cleanup */
3112 	if (quota_update) {
3113 		for (i = 0; i < EXT4_MAXQUOTAS; i++) {
3114 			if (sb_dqopt(sb)->files[i])
3115 				dquot_quota_off(sb, i);
3116 		}
3117 	}
3118 #endif
3119 	sb->s_flags = s_flags; /* Restore SB_RDONLY status */
3120 }
3121 
3122 /*
3123  * Maximal extent format file size.
3124  * Resulting logical blkno at s_maxbytes must fit in our on-disk
3125  * extent format containers, within a sector_t, and within i_blocks
3126  * in the vfs.  ext4 inode has 48 bits of i_block in fsblock units,
3127  * so that won't be a limiting factor.
3128  *
3129  * However there is other limiting factor. We do store extents in the form
3130  * of starting block and length, hence the resulting length of the extent
3131  * covering maximum file size must fit into on-disk format containers as
3132  * well. Given that length is always by 1 unit bigger than max unit (because
3133  * we count 0 as well) we have to lower the s_maxbytes by one fs block.
3134  *
3135  * Note, this does *not* consider any metadata overhead for vfs i_blocks.
3136  */
ext4_max_size(int blkbits,int has_huge_files)3137 static loff_t ext4_max_size(int blkbits, int has_huge_files)
3138 {
3139 	loff_t res;
3140 	loff_t upper_limit = MAX_LFS_FILESIZE;
3141 
3142 	BUILD_BUG_ON(sizeof(blkcnt_t) < sizeof(u64));
3143 
3144 	if (!has_huge_files) {
3145 		upper_limit = (1LL << 32) - 1;
3146 
3147 		/* total blocks in file system block size */
3148 		upper_limit >>= (blkbits - 9);
3149 		upper_limit <<= blkbits;
3150 	}
3151 
3152 	/*
3153 	 * 32-bit extent-start container, ee_block. We lower the maxbytes
3154 	 * by one fs block, so ee_len can cover the extent of maximum file
3155 	 * size
3156 	 */
3157 	res = (1LL << 32) - 1;
3158 	res <<= blkbits;
3159 
3160 	/* Sanity check against vm- & vfs- imposed limits */
3161 	if (res > upper_limit)
3162 		res = upper_limit;
3163 
3164 	return res;
3165 }
3166 
3167 /*
3168  * Maximal bitmap file size.  There is a direct, and {,double-,triple-}indirect
3169  * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
3170  * We need to be 1 filesystem block less than the 2^48 sector limit.
3171  */
ext4_max_bitmap_size(int bits,int has_huge_files)3172 static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
3173 {
3174 	unsigned long long upper_limit, res = EXT4_NDIR_BLOCKS;
3175 	int meta_blocks;
3176 
3177 	/*
3178 	 * This is calculated to be the largest file size for a dense, block
3179 	 * mapped file such that the file's total number of 512-byte sectors,
3180 	 * including data and all indirect blocks, does not exceed (2^48 - 1).
3181 	 *
3182 	 * __u32 i_blocks_lo and _u16 i_blocks_high represent the total
3183 	 * number of 512-byte sectors of the file.
3184 	 */
3185 	if (!has_huge_files) {
3186 		/*
3187 		 * !has_huge_files or implies that the inode i_block field
3188 		 * represents total file blocks in 2^32 512-byte sectors ==
3189 		 * size of vfs inode i_blocks * 8
3190 		 */
3191 		upper_limit = (1LL << 32) - 1;
3192 
3193 		/* total blocks in file system block size */
3194 		upper_limit >>= (bits - 9);
3195 
3196 	} else {
3197 		/*
3198 		 * We use 48 bit ext4_inode i_blocks
3199 		 * With EXT4_HUGE_FILE_FL set the i_blocks
3200 		 * represent total number of blocks in
3201 		 * file system block size
3202 		 */
3203 		upper_limit = (1LL << 48) - 1;
3204 
3205 	}
3206 
3207 	/* indirect blocks */
3208 	meta_blocks = 1;
3209 	/* double indirect blocks */
3210 	meta_blocks += 1 + (1LL << (bits-2));
3211 	/* tripple indirect blocks */
3212 	meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
3213 
3214 	upper_limit -= meta_blocks;
3215 	upper_limit <<= bits;
3216 
3217 	res += 1LL << (bits-2);
3218 	res += 1LL << (2*(bits-2));
3219 	res += 1LL << (3*(bits-2));
3220 	res <<= bits;
3221 	if (res > upper_limit)
3222 		res = upper_limit;
3223 
3224 	if (res > MAX_LFS_FILESIZE)
3225 		res = MAX_LFS_FILESIZE;
3226 
3227 	return (loff_t)res;
3228 }
3229 
descriptor_loc(struct super_block * sb,ext4_fsblk_t logical_sb_block,int nr)3230 static ext4_fsblk_t descriptor_loc(struct super_block *sb,
3231 				   ext4_fsblk_t logical_sb_block, int nr)
3232 {
3233 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3234 	ext4_group_t bg, first_meta_bg;
3235 	int has_super = 0;
3236 
3237 	first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
3238 
3239 	if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
3240 		return logical_sb_block + nr + 1;
3241 	bg = sbi->s_desc_per_block * nr;
3242 	if (ext4_bg_has_super(sb, bg))
3243 		has_super = 1;
3244 
3245 	/*
3246 	 * If we have a meta_bg fs with 1k blocks, group 0's GDT is at
3247 	 * block 2, not 1.  If s_first_data_block == 0 (bigalloc is enabled
3248 	 * on modern mke2fs or blksize > 1k on older mke2fs) then we must
3249 	 * compensate.
3250 	 */
3251 	if (sb->s_blocksize == 1024 && nr == 0 &&
3252 	    le32_to_cpu(sbi->s_es->s_first_data_block) == 0)
3253 		has_super++;
3254 
3255 	return (has_super + ext4_group_first_block_no(sb, bg));
3256 }
3257 
3258 /**
3259  * ext4_get_stripe_size: Get the stripe size.
3260  * @sbi: In memory super block info
3261  *
3262  * If we have specified it via mount option, then
3263  * use the mount option value. If the value specified at mount time is
3264  * greater than the blocks per group use the super block value.
3265  * If the super block value is greater than blocks per group return 0.
3266  * Allocator needs it be less than blocks per group.
3267  *
3268  */
ext4_get_stripe_size(struct ext4_sb_info * sbi)3269 static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
3270 {
3271 	unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
3272 	unsigned long stripe_width =
3273 			le32_to_cpu(sbi->s_es->s_raid_stripe_width);
3274 	int ret;
3275 
3276 	if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
3277 		ret = sbi->s_stripe;
3278 	else if (stripe_width && stripe_width <= sbi->s_blocks_per_group)
3279 		ret = stripe_width;
3280 	else if (stride && stride <= sbi->s_blocks_per_group)
3281 		ret = stride;
3282 	else
3283 		ret = 0;
3284 
3285 	/*
3286 	 * If the stripe width is 1, this makes no sense and
3287 	 * we set it to 0 to turn off stripe handling code.
3288 	 */
3289 	if (ret <= 1)
3290 		ret = 0;
3291 
3292 	return ret;
3293 }
3294 
3295 /*
3296  * Check whether this filesystem can be mounted based on
3297  * the features present and the RDONLY/RDWR mount requested.
3298  * Returns 1 if this filesystem can be mounted as requested,
3299  * 0 if it cannot be.
3300  */
ext4_feature_set_ok(struct super_block * sb,int readonly)3301 static int ext4_feature_set_ok(struct super_block *sb, int readonly)
3302 {
3303 	if (ext4_has_unknown_ext4_incompat_features(sb)) {
3304 		ext4_msg(sb, KERN_ERR,
3305 			"Couldn't mount because of "
3306 			"unsupported optional features (%x)",
3307 			(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
3308 			~EXT4_FEATURE_INCOMPAT_SUPP));
3309 		return 0;
3310 	}
3311 
3312 #ifndef CONFIG_UNICODE
3313 	if (ext4_has_feature_casefold(sb)) {
3314 		ext4_msg(sb, KERN_ERR,
3315 			 "Filesystem with casefold feature cannot be "
3316 			 "mounted without CONFIG_UNICODE");
3317 		return 0;
3318 	}
3319 #endif
3320 
3321 	if (readonly)
3322 		return 1;
3323 
3324 	if (ext4_has_feature_readonly(sb)) {
3325 		ext4_msg(sb, KERN_INFO, "filesystem is read-only");
3326 		sb->s_flags |= SB_RDONLY;
3327 		return 1;
3328 	}
3329 
3330 	/* Check that feature set is OK for a read-write mount */
3331 	if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
3332 		ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
3333 			 "unsupported optional features (%x)",
3334 			 (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
3335 				~EXT4_FEATURE_RO_COMPAT_SUPP));
3336 		return 0;
3337 	}
3338 	if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
3339 		ext4_msg(sb, KERN_ERR,
3340 			 "Can't support bigalloc feature without "
3341 			 "extents feature\n");
3342 		return 0;
3343 	}
3344 
3345 #if !IS_ENABLED(CONFIG_QUOTA) || !IS_ENABLED(CONFIG_QFMT_V2)
3346 	if (!readonly && (ext4_has_feature_quota(sb) ||
3347 			  ext4_has_feature_project(sb))) {
3348 		ext4_msg(sb, KERN_ERR,
3349 			 "The kernel was not built with CONFIG_QUOTA and CONFIG_QFMT_V2");
3350 		return 0;
3351 	}
3352 #endif  /* CONFIG_QUOTA */
3353 	return 1;
3354 }
3355 
3356 /*
3357  * This function is called once a day if we have errors logged
3358  * on the file system
3359  */
print_daily_error_info(struct timer_list * t)3360 static void print_daily_error_info(struct timer_list *t)
3361 {
3362 	struct ext4_sb_info *sbi = from_timer(sbi, t, s_err_report);
3363 	struct super_block *sb = sbi->s_sb;
3364 	struct ext4_super_block *es = sbi->s_es;
3365 
3366 	if (es->s_error_count)
3367 		/* fsck newer than v1.41.13 is needed to clean this condition. */
3368 		ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
3369 			 le32_to_cpu(es->s_error_count));
3370 	if (es->s_first_error_time) {
3371 		printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %llu: %.*s:%d",
3372 		       sb->s_id,
3373 		       ext4_get_tstamp(es, s_first_error_time),
3374 		       (int) sizeof(es->s_first_error_func),
3375 		       es->s_first_error_func,
3376 		       le32_to_cpu(es->s_first_error_line));
3377 		if (es->s_first_error_ino)
3378 			printk(KERN_CONT ": inode %u",
3379 			       le32_to_cpu(es->s_first_error_ino));
3380 		if (es->s_first_error_block)
3381 			printk(KERN_CONT ": block %llu", (unsigned long long)
3382 			       le64_to_cpu(es->s_first_error_block));
3383 		printk(KERN_CONT "\n");
3384 	}
3385 	if (es->s_last_error_time) {
3386 		printk(KERN_NOTICE "EXT4-fs (%s): last error at time %llu: %.*s:%d",
3387 		       sb->s_id,
3388 		       ext4_get_tstamp(es, s_last_error_time),
3389 		       (int) sizeof(es->s_last_error_func),
3390 		       es->s_last_error_func,
3391 		       le32_to_cpu(es->s_last_error_line));
3392 		if (es->s_last_error_ino)
3393 			printk(KERN_CONT ": inode %u",
3394 			       le32_to_cpu(es->s_last_error_ino));
3395 		if (es->s_last_error_block)
3396 			printk(KERN_CONT ": block %llu", (unsigned long long)
3397 			       le64_to_cpu(es->s_last_error_block));
3398 		printk(KERN_CONT "\n");
3399 	}
3400 	mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);  /* Once a day */
3401 }
3402 
3403 /* Find next suitable group and run ext4_init_inode_table */
ext4_run_li_request(struct ext4_li_request * elr)3404 static int ext4_run_li_request(struct ext4_li_request *elr)
3405 {
3406 	struct ext4_group_desc *gdp = NULL;
3407 	struct super_block *sb = elr->lr_super;
3408 	ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
3409 	ext4_group_t group = elr->lr_next_group;
3410 	unsigned long timeout = 0;
3411 	unsigned int prefetch_ios = 0;
3412 	int ret = 0;
3413 
3414 	if (elr->lr_mode == EXT4_LI_MODE_PREFETCH_BBITMAP) {
3415 		elr->lr_next_group = ext4_mb_prefetch(sb, group,
3416 				EXT4_SB(sb)->s_mb_prefetch, &prefetch_ios);
3417 		if (prefetch_ios)
3418 			ext4_mb_prefetch_fini(sb, elr->lr_next_group,
3419 					      prefetch_ios);
3420 		trace_ext4_prefetch_bitmaps(sb, group, elr->lr_next_group,
3421 					    prefetch_ios);
3422 		if (group >= elr->lr_next_group) {
3423 			ret = 1;
3424 			if (elr->lr_first_not_zeroed != ngroups &&
3425 			    !sb_rdonly(sb) && test_opt(sb, INIT_INODE_TABLE)) {
3426 				elr->lr_next_group = elr->lr_first_not_zeroed;
3427 				elr->lr_mode = EXT4_LI_MODE_ITABLE;
3428 				ret = 0;
3429 			}
3430 		}
3431 		return ret;
3432 	}
3433 
3434 	for (; group < ngroups; group++) {
3435 		gdp = ext4_get_group_desc(sb, group, NULL);
3436 		if (!gdp) {
3437 			ret = 1;
3438 			break;
3439 		}
3440 
3441 		if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3442 			break;
3443 	}
3444 
3445 	if (group >= ngroups)
3446 		ret = 1;
3447 
3448 	if (!ret) {
3449 		timeout = jiffies;
3450 		ret = ext4_init_inode_table(sb, group,
3451 					    elr->lr_timeout ? 0 : 1);
3452 		trace_ext4_lazy_itable_init(sb, group);
3453 		if (elr->lr_timeout == 0) {
3454 			timeout = (jiffies - timeout) *
3455 				EXT4_SB(elr->lr_super)->s_li_wait_mult;
3456 			elr->lr_timeout = timeout;
3457 		}
3458 		elr->lr_next_sched = jiffies + elr->lr_timeout;
3459 		elr->lr_next_group = group + 1;
3460 	}
3461 	return ret;
3462 }
3463 
3464 /*
3465  * Remove lr_request from the list_request and free the
3466  * request structure. Should be called with li_list_mtx held
3467  */
ext4_remove_li_request(struct ext4_li_request * elr)3468 static void ext4_remove_li_request(struct ext4_li_request *elr)
3469 {
3470 	if (!elr)
3471 		return;
3472 
3473 	list_del(&elr->lr_request);
3474 	EXT4_SB(elr->lr_super)->s_li_request = NULL;
3475 	kfree(elr);
3476 }
3477 
ext4_unregister_li_request(struct super_block * sb)3478 static void ext4_unregister_li_request(struct super_block *sb)
3479 {
3480 	mutex_lock(&ext4_li_mtx);
3481 	if (!ext4_li_info) {
3482 		mutex_unlock(&ext4_li_mtx);
3483 		return;
3484 	}
3485 
3486 	mutex_lock(&ext4_li_info->li_list_mtx);
3487 	ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
3488 	mutex_unlock(&ext4_li_info->li_list_mtx);
3489 	mutex_unlock(&ext4_li_mtx);
3490 }
3491 
3492 static struct task_struct *ext4_lazyinit_task;
3493 
3494 /*
3495  * This is the function where ext4lazyinit thread lives. It walks
3496  * through the request list searching for next scheduled filesystem.
3497  * When such a fs is found, run the lazy initialization request
3498  * (ext4_rn_li_request) and keep track of the time spend in this
3499  * function. Based on that time we compute next schedule time of
3500  * the request. When walking through the list is complete, compute
3501  * next waking time and put itself into sleep.
3502  */
ext4_lazyinit_thread(void * arg)3503 static int ext4_lazyinit_thread(void *arg)
3504 {
3505 	struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
3506 	struct list_head *pos, *n;
3507 	struct ext4_li_request *elr;
3508 	unsigned long next_wakeup, cur;
3509 
3510 	BUG_ON(NULL == eli);
3511 
3512 cont_thread:
3513 	while (true) {
3514 		next_wakeup = MAX_JIFFY_OFFSET;
3515 
3516 		mutex_lock(&eli->li_list_mtx);
3517 		if (list_empty(&eli->li_request_list)) {
3518 			mutex_unlock(&eli->li_list_mtx);
3519 			goto exit_thread;
3520 		}
3521 		list_for_each_safe(pos, n, &eli->li_request_list) {
3522 			int err = 0;
3523 			int progress = 0;
3524 			elr = list_entry(pos, struct ext4_li_request,
3525 					 lr_request);
3526 
3527 			if (time_before(jiffies, elr->lr_next_sched)) {
3528 				if (time_before(elr->lr_next_sched, next_wakeup))
3529 					next_wakeup = elr->lr_next_sched;
3530 				continue;
3531 			}
3532 			if (down_read_trylock(&elr->lr_super->s_umount)) {
3533 				if (sb_start_write_trylock(elr->lr_super)) {
3534 					progress = 1;
3535 					/*
3536 					 * We hold sb->s_umount, sb can not
3537 					 * be removed from the list, it is
3538 					 * now safe to drop li_list_mtx
3539 					 */
3540 					mutex_unlock(&eli->li_list_mtx);
3541 					err = ext4_run_li_request(elr);
3542 					sb_end_write(elr->lr_super);
3543 					mutex_lock(&eli->li_list_mtx);
3544 					n = pos->next;
3545 				}
3546 				up_read((&elr->lr_super->s_umount));
3547 			}
3548 			/* error, remove the lazy_init job */
3549 			if (err) {
3550 				ext4_remove_li_request(elr);
3551 				continue;
3552 			}
3553 			if (!progress) {
3554 				elr->lr_next_sched = jiffies +
3555 					(prandom_u32()
3556 					 % (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3557 			}
3558 			if (time_before(elr->lr_next_sched, next_wakeup))
3559 				next_wakeup = elr->lr_next_sched;
3560 		}
3561 		mutex_unlock(&eli->li_list_mtx);
3562 
3563 		try_to_freeze();
3564 
3565 		cur = jiffies;
3566 		if ((time_after_eq(cur, next_wakeup)) ||
3567 		    (MAX_JIFFY_OFFSET == next_wakeup)) {
3568 			cond_resched();
3569 			continue;
3570 		}
3571 
3572 		schedule_timeout_interruptible(next_wakeup - cur);
3573 
3574 		if (kthread_should_stop()) {
3575 			ext4_clear_request_list();
3576 			goto exit_thread;
3577 		}
3578 	}
3579 
3580 exit_thread:
3581 	/*
3582 	 * It looks like the request list is empty, but we need
3583 	 * to check it under the li_list_mtx lock, to prevent any
3584 	 * additions into it, and of course we should lock ext4_li_mtx
3585 	 * to atomically free the list and ext4_li_info, because at
3586 	 * this point another ext4 filesystem could be registering
3587 	 * new one.
3588 	 */
3589 	mutex_lock(&ext4_li_mtx);
3590 	mutex_lock(&eli->li_list_mtx);
3591 	if (!list_empty(&eli->li_request_list)) {
3592 		mutex_unlock(&eli->li_list_mtx);
3593 		mutex_unlock(&ext4_li_mtx);
3594 		goto cont_thread;
3595 	}
3596 	mutex_unlock(&eli->li_list_mtx);
3597 	kfree(ext4_li_info);
3598 	ext4_li_info = NULL;
3599 	mutex_unlock(&ext4_li_mtx);
3600 
3601 	return 0;
3602 }
3603 
ext4_clear_request_list(void)3604 static void ext4_clear_request_list(void)
3605 {
3606 	struct list_head *pos, *n;
3607 	struct ext4_li_request *elr;
3608 
3609 	mutex_lock(&ext4_li_info->li_list_mtx);
3610 	list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
3611 		elr = list_entry(pos, struct ext4_li_request,
3612 				 lr_request);
3613 		ext4_remove_li_request(elr);
3614 	}
3615 	mutex_unlock(&ext4_li_info->li_list_mtx);
3616 }
3617 
ext4_run_lazyinit_thread(void)3618 static int ext4_run_lazyinit_thread(void)
3619 {
3620 	ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
3621 					 ext4_li_info, "ext4lazyinit");
3622 	if (IS_ERR(ext4_lazyinit_task)) {
3623 		int err = PTR_ERR(ext4_lazyinit_task);
3624 		ext4_clear_request_list();
3625 		kfree(ext4_li_info);
3626 		ext4_li_info = NULL;
3627 		printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
3628 				 "initialization thread\n",
3629 				 err);
3630 		return err;
3631 	}
3632 	ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
3633 	return 0;
3634 }
3635 
3636 /*
3637  * Check whether it make sense to run itable init. thread or not.
3638  * If there is at least one uninitialized inode table, return
3639  * corresponding group number, else the loop goes through all
3640  * groups and return total number of groups.
3641  */
ext4_has_uninit_itable(struct super_block * sb)3642 static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
3643 {
3644 	ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
3645 	struct ext4_group_desc *gdp = NULL;
3646 
3647 	if (!ext4_has_group_desc_csum(sb))
3648 		return ngroups;
3649 
3650 	for (group = 0; group < ngroups; group++) {
3651 		gdp = ext4_get_group_desc(sb, group, NULL);
3652 		if (!gdp)
3653 			continue;
3654 
3655 		if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3656 			break;
3657 	}
3658 
3659 	return group;
3660 }
3661 
ext4_li_info_new(void)3662 static int ext4_li_info_new(void)
3663 {
3664 	struct ext4_lazy_init *eli = NULL;
3665 
3666 	eli = kzalloc(sizeof(*eli), GFP_KERNEL);
3667 	if (!eli)
3668 		return -ENOMEM;
3669 
3670 	INIT_LIST_HEAD(&eli->li_request_list);
3671 	mutex_init(&eli->li_list_mtx);
3672 
3673 	eli->li_state |= EXT4_LAZYINIT_QUIT;
3674 
3675 	ext4_li_info = eli;
3676 
3677 	return 0;
3678 }
3679 
ext4_li_request_new(struct super_block * sb,ext4_group_t start)3680 static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
3681 					    ext4_group_t start)
3682 {
3683 	struct ext4_li_request *elr;
3684 
3685 	elr = kzalloc(sizeof(*elr), GFP_KERNEL);
3686 	if (!elr)
3687 		return NULL;
3688 
3689 	elr->lr_super = sb;
3690 	elr->lr_first_not_zeroed = start;
3691 	if (test_opt(sb, PREFETCH_BLOCK_BITMAPS))
3692 		elr->lr_mode = EXT4_LI_MODE_PREFETCH_BBITMAP;
3693 	else {
3694 		elr->lr_mode = EXT4_LI_MODE_ITABLE;
3695 		elr->lr_next_group = start;
3696 	}
3697 
3698 	/*
3699 	 * Randomize first schedule time of the request to
3700 	 * spread the inode table initialization requests
3701 	 * better.
3702 	 */
3703 	elr->lr_next_sched = jiffies + (prandom_u32() %
3704 				(EXT4_DEF_LI_MAX_START_DELAY * HZ));
3705 	return elr;
3706 }
3707 
ext4_register_li_request(struct super_block * sb,ext4_group_t first_not_zeroed)3708 int ext4_register_li_request(struct super_block *sb,
3709 			     ext4_group_t first_not_zeroed)
3710 {
3711 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3712 	struct ext4_li_request *elr = NULL;
3713 	ext4_group_t ngroups = sbi->s_groups_count;
3714 	int ret = 0;
3715 
3716 	mutex_lock(&ext4_li_mtx);
3717 	if (sbi->s_li_request != NULL) {
3718 		/*
3719 		 * Reset timeout so it can be computed again, because
3720 		 * s_li_wait_mult might have changed.
3721 		 */
3722 		sbi->s_li_request->lr_timeout = 0;
3723 		goto out;
3724 	}
3725 
3726 	if (!test_opt(sb, PREFETCH_BLOCK_BITMAPS) &&
3727 	    (first_not_zeroed == ngroups || sb_rdonly(sb) ||
3728 	     !test_opt(sb, INIT_INODE_TABLE)))
3729 		goto out;
3730 
3731 	elr = ext4_li_request_new(sb, first_not_zeroed);
3732 	if (!elr) {
3733 		ret = -ENOMEM;
3734 		goto out;
3735 	}
3736 
3737 	if (NULL == ext4_li_info) {
3738 		ret = ext4_li_info_new();
3739 		if (ret)
3740 			goto out;
3741 	}
3742 
3743 	mutex_lock(&ext4_li_info->li_list_mtx);
3744 	list_add(&elr->lr_request, &ext4_li_info->li_request_list);
3745 	mutex_unlock(&ext4_li_info->li_list_mtx);
3746 
3747 	sbi->s_li_request = elr;
3748 	/*
3749 	 * set elr to NULL here since it has been inserted to
3750 	 * the request_list and the removal and free of it is
3751 	 * handled by ext4_clear_request_list from now on.
3752 	 */
3753 	elr = NULL;
3754 
3755 	if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
3756 		ret = ext4_run_lazyinit_thread();
3757 		if (ret)
3758 			goto out;
3759 	}
3760 out:
3761 	mutex_unlock(&ext4_li_mtx);
3762 	if (ret)
3763 		kfree(elr);
3764 	return ret;
3765 }
3766 
3767 /*
3768  * We do not need to lock anything since this is called on
3769  * module unload.
3770  */
ext4_destroy_lazyinit_thread(void)3771 static void ext4_destroy_lazyinit_thread(void)
3772 {
3773 	/*
3774 	 * If thread exited earlier
3775 	 * there's nothing to be done.
3776 	 */
3777 	if (!ext4_li_info || !ext4_lazyinit_task)
3778 		return;
3779 
3780 	kthread_stop(ext4_lazyinit_task);
3781 }
3782 
set_journal_csum_feature_set(struct super_block * sb)3783 static int set_journal_csum_feature_set(struct super_block *sb)
3784 {
3785 	int ret = 1;
3786 	int compat, incompat;
3787 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3788 
3789 	if (ext4_has_metadata_csum(sb)) {
3790 		/* journal checksum v3 */
3791 		compat = 0;
3792 		incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
3793 	} else {
3794 		/* journal checksum v1 */
3795 		compat = JBD2_FEATURE_COMPAT_CHECKSUM;
3796 		incompat = 0;
3797 	}
3798 
3799 	jbd2_journal_clear_features(sbi->s_journal,
3800 			JBD2_FEATURE_COMPAT_CHECKSUM, 0,
3801 			JBD2_FEATURE_INCOMPAT_CSUM_V3 |
3802 			JBD2_FEATURE_INCOMPAT_CSUM_V2);
3803 	if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
3804 		ret = jbd2_journal_set_features(sbi->s_journal,
3805 				compat, 0,
3806 				JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
3807 				incompat);
3808 	} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
3809 		ret = jbd2_journal_set_features(sbi->s_journal,
3810 				compat, 0,
3811 				incompat);
3812 		jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3813 				JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3814 	} else {
3815 		jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3816 				JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3817 	}
3818 
3819 	return ret;
3820 }
3821 
3822 /*
3823  * Note: calculating the overhead so we can be compatible with
3824  * historical BSD practice is quite difficult in the face of
3825  * clusters/bigalloc.  This is because multiple metadata blocks from
3826  * different block group can end up in the same allocation cluster.
3827  * Calculating the exact overhead in the face of clustered allocation
3828  * requires either O(all block bitmaps) in memory or O(number of block
3829  * groups**2) in time.  We will still calculate the superblock for
3830  * older file systems --- and if we come across with a bigalloc file
3831  * system with zero in s_overhead_clusters the estimate will be close to
3832  * correct especially for very large cluster sizes --- but for newer
3833  * file systems, it's better to calculate this figure once at mkfs
3834  * time, and store it in the superblock.  If the superblock value is
3835  * present (even for non-bigalloc file systems), we will use it.
3836  */
count_overhead(struct super_block * sb,ext4_group_t grp,char * buf)3837 static int count_overhead(struct super_block *sb, ext4_group_t grp,
3838 			  char *buf)
3839 {
3840 	struct ext4_sb_info	*sbi = EXT4_SB(sb);
3841 	struct ext4_group_desc	*gdp;
3842 	ext4_fsblk_t		first_block, last_block, b;
3843 	ext4_group_t		i, ngroups = ext4_get_groups_count(sb);
3844 	int			s, j, count = 0;
3845 
3846 	if (!ext4_has_feature_bigalloc(sb))
3847 		return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
3848 			sbi->s_itb_per_group + 2);
3849 
3850 	first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
3851 		(grp * EXT4_BLOCKS_PER_GROUP(sb));
3852 	last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
3853 	for (i = 0; i < ngroups; i++) {
3854 		gdp = ext4_get_group_desc(sb, i, NULL);
3855 		b = ext4_block_bitmap(sb, gdp);
3856 		if (b >= first_block && b <= last_block) {
3857 			ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3858 			count++;
3859 		}
3860 		b = ext4_inode_bitmap(sb, gdp);
3861 		if (b >= first_block && b <= last_block) {
3862 			ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3863 			count++;
3864 		}
3865 		b = ext4_inode_table(sb, gdp);
3866 		if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
3867 			for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
3868 				int c = EXT4_B2C(sbi, b - first_block);
3869 				ext4_set_bit(c, buf);
3870 				count++;
3871 			}
3872 		if (i != grp)
3873 			continue;
3874 		s = 0;
3875 		if (ext4_bg_has_super(sb, grp)) {
3876 			ext4_set_bit(s++, buf);
3877 			count++;
3878 		}
3879 		j = ext4_bg_num_gdb(sb, grp);
3880 		if (s + j > EXT4_BLOCKS_PER_GROUP(sb)) {
3881 			ext4_error(sb, "Invalid number of block group "
3882 				   "descriptor blocks: %d", j);
3883 			j = EXT4_BLOCKS_PER_GROUP(sb) - s;
3884 		}
3885 		count += j;
3886 		for (; j > 0; j--)
3887 			ext4_set_bit(EXT4_B2C(sbi, s++), buf);
3888 	}
3889 	if (!count)
3890 		return 0;
3891 	return EXT4_CLUSTERS_PER_GROUP(sb) -
3892 		ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
3893 }
3894 
3895 /*
3896  * Compute the overhead and stash it in sbi->s_overhead
3897  */
ext4_calculate_overhead(struct super_block * sb)3898 int ext4_calculate_overhead(struct super_block *sb)
3899 {
3900 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3901 	struct ext4_super_block *es = sbi->s_es;
3902 	struct inode *j_inode;
3903 	unsigned int j_blocks, j_inum = le32_to_cpu(es->s_journal_inum);
3904 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
3905 	ext4_fsblk_t overhead = 0;
3906 	char *buf = (char *) get_zeroed_page(GFP_NOFS);
3907 
3908 	if (!buf)
3909 		return -ENOMEM;
3910 
3911 	/*
3912 	 * Compute the overhead (FS structures).  This is constant
3913 	 * for a given filesystem unless the number of block groups
3914 	 * changes so we cache the previous value until it does.
3915 	 */
3916 
3917 	/*
3918 	 * All of the blocks before first_data_block are overhead
3919 	 */
3920 	overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
3921 
3922 	/*
3923 	 * Add the overhead found in each block group
3924 	 */
3925 	for (i = 0; i < ngroups; i++) {
3926 		int blks;
3927 
3928 		blks = count_overhead(sb, i, buf);
3929 		overhead += blks;
3930 		if (blks)
3931 			memset(buf, 0, PAGE_SIZE);
3932 		cond_resched();
3933 	}
3934 
3935 	/*
3936 	 * Add the internal journal blocks whether the journal has been
3937 	 * loaded or not
3938 	 */
3939 	if (sbi->s_journal && !sbi->s_journal_bdev)
3940 		overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_total_len);
3941 	else if (ext4_has_feature_journal(sb) && !sbi->s_journal && j_inum) {
3942 		/* j_inum for internal journal is non-zero */
3943 		j_inode = ext4_get_journal_inode(sb, j_inum);
3944 		if (j_inode) {
3945 			j_blocks = j_inode->i_size >> sb->s_blocksize_bits;
3946 			overhead += EXT4_NUM_B2C(sbi, j_blocks);
3947 			iput(j_inode);
3948 		} else {
3949 			ext4_msg(sb, KERN_ERR, "can't get journal size");
3950 		}
3951 	}
3952 	sbi->s_overhead = overhead;
3953 	smp_wmb();
3954 	free_page((unsigned long) buf);
3955 	return 0;
3956 }
3957 
ext4_set_resv_clusters(struct super_block * sb)3958 static void ext4_set_resv_clusters(struct super_block *sb)
3959 {
3960 	ext4_fsblk_t resv_clusters;
3961 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3962 
3963 	/*
3964 	 * There's no need to reserve anything when we aren't using extents.
3965 	 * The space estimates are exact, there are no unwritten extents,
3966 	 * hole punching doesn't need new metadata... This is needed especially
3967 	 * to keep ext2/3 backward compatibility.
3968 	 */
3969 	if (!ext4_has_feature_extents(sb))
3970 		return;
3971 	/*
3972 	 * By default we reserve 2% or 4096 clusters, whichever is smaller.
3973 	 * This should cover the situations where we can not afford to run
3974 	 * out of space like for example punch hole, or converting
3975 	 * unwritten extents in delalloc path. In most cases such
3976 	 * allocation would require 1, or 2 blocks, higher numbers are
3977 	 * very rare.
3978 	 */
3979 	resv_clusters = (ext4_blocks_count(sbi->s_es) >>
3980 			 sbi->s_cluster_bits);
3981 
3982 	do_div(resv_clusters, 50);
3983 	resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
3984 
3985 	atomic64_set(&sbi->s_resv_clusters, resv_clusters);
3986 }
3987 
ext4_fill_super(struct super_block * sb,void * data,int silent)3988 static int ext4_fill_super(struct super_block *sb, void *data, int silent)
3989 {
3990 	struct dax_device *dax_dev = fs_dax_get_by_bdev(sb->s_bdev);
3991 	char *orig_data = kstrdup(data, GFP_KERNEL);
3992 	struct buffer_head *bh, **group_desc;
3993 	struct ext4_super_block *es = NULL;
3994 	struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
3995 	struct flex_groups **flex_groups;
3996 	ext4_fsblk_t block;
3997 	ext4_fsblk_t sb_block = get_sb_block(&data);
3998 	ext4_fsblk_t logical_sb_block;
3999 	unsigned long offset = 0;
4000 	unsigned long journal_devnum = 0;
4001 	unsigned long def_mount_opts;
4002 	struct inode *root;
4003 	const char *descr;
4004 	int ret = -ENOMEM;
4005 	int blocksize, clustersize;
4006 	unsigned int db_count;
4007 	unsigned int i;
4008 	int needs_recovery, has_huge_files;
4009 	__u64 blocks_count;
4010 	int err = 0;
4011 	unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
4012 	ext4_group_t first_not_zeroed;
4013 
4014 	if ((data && !orig_data) || !sbi)
4015 		goto out_free_base;
4016 
4017 	sbi->s_daxdev = dax_dev;
4018 	sbi->s_blockgroup_lock =
4019 		kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
4020 	if (!sbi->s_blockgroup_lock)
4021 		goto out_free_base;
4022 
4023 	sb->s_fs_info = sbi;
4024 	sbi->s_sb = sb;
4025 	sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
4026 	sbi->s_sb_block = sb_block;
4027 	if (sb->s_bdev->bd_part)
4028 		sbi->s_sectors_written_start =
4029 			part_stat_read(sb->s_bdev->bd_part, sectors[STAT_WRITE]);
4030 
4031 	/* Cleanup superblock name */
4032 	strreplace(sb->s_id, '/', '!');
4033 
4034 	/* -EINVAL is default */
4035 	ret = -EINVAL;
4036 	blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
4037 	if (!blocksize) {
4038 		ext4_msg(sb, KERN_ERR, "unable to set blocksize");
4039 		goto out_fail;
4040 	}
4041 
4042 	/*
4043 	 * The ext4 superblock will not be buffer aligned for other than 1kB
4044 	 * block sizes.  We need to calculate the offset from buffer start.
4045 	 */
4046 	if (blocksize != EXT4_MIN_BLOCK_SIZE) {
4047 		logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
4048 		offset = do_div(logical_sb_block, blocksize);
4049 	} else {
4050 		logical_sb_block = sb_block;
4051 	}
4052 
4053 	bh = ext4_sb_bread_unmovable(sb, logical_sb_block);
4054 	if (IS_ERR(bh)) {
4055 		ext4_msg(sb, KERN_ERR, "unable to read superblock");
4056 		ret = PTR_ERR(bh);
4057 		bh = NULL;
4058 		goto out_fail;
4059 	}
4060 	/*
4061 	 * Note: s_es must be initialized as soon as possible because
4062 	 *       some ext4 macro-instructions depend on its value
4063 	 */
4064 	es = (struct ext4_super_block *) (bh->b_data + offset);
4065 	sbi->s_es = es;
4066 	sb->s_magic = le16_to_cpu(es->s_magic);
4067 	if (sb->s_magic != EXT4_SUPER_MAGIC)
4068 		goto cantfind_ext4;
4069 	sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
4070 
4071 	/* Warn if metadata_csum and gdt_csum are both set. */
4072 	if (ext4_has_feature_metadata_csum(sb) &&
4073 	    ext4_has_feature_gdt_csum(sb))
4074 		ext4_warning(sb, "metadata_csum and uninit_bg are "
4075 			     "redundant flags; please run fsck.");
4076 
4077 	/* Check for a known checksum algorithm */
4078 	if (!ext4_verify_csum_type(sb, es)) {
4079 		ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
4080 			 "unknown checksum algorithm.");
4081 		silent = 1;
4082 		goto cantfind_ext4;
4083 	}
4084 
4085 	/* Load the checksum driver */
4086 	sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
4087 	if (IS_ERR(sbi->s_chksum_driver)) {
4088 		ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
4089 		ret = PTR_ERR(sbi->s_chksum_driver);
4090 		sbi->s_chksum_driver = NULL;
4091 		goto failed_mount;
4092 	}
4093 
4094 	/* Check superblock checksum */
4095 	if (!ext4_superblock_csum_verify(sb, es)) {
4096 		ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
4097 			 "invalid superblock checksum.  Run e2fsck?");
4098 		silent = 1;
4099 		ret = -EFSBADCRC;
4100 		goto cantfind_ext4;
4101 	}
4102 
4103 	/* Precompute checksum seed for all metadata */
4104 	if (ext4_has_feature_csum_seed(sb))
4105 		sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
4106 	else if (ext4_has_metadata_csum(sb) || ext4_has_feature_ea_inode(sb))
4107 		sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
4108 					       sizeof(es->s_uuid));
4109 
4110 	/* Set defaults before we parse the mount options */
4111 	def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
4112 	set_opt(sb, INIT_INODE_TABLE);
4113 	if (def_mount_opts & EXT4_DEFM_DEBUG)
4114 		set_opt(sb, DEBUG);
4115 	if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
4116 		set_opt(sb, GRPID);
4117 	if (def_mount_opts & EXT4_DEFM_UID16)
4118 		set_opt(sb, NO_UID32);
4119 	/* xattr user namespace & acls are now defaulted on */
4120 	set_opt(sb, XATTR_USER);
4121 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4122 	set_opt(sb, POSIX_ACL);
4123 #endif
4124 	if (ext4_has_feature_fast_commit(sb))
4125 		set_opt2(sb, JOURNAL_FAST_COMMIT);
4126 	/* don't forget to enable journal_csum when metadata_csum is enabled. */
4127 	if (ext4_has_metadata_csum(sb))
4128 		set_opt(sb, JOURNAL_CHECKSUM);
4129 
4130 	if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
4131 		set_opt(sb, JOURNAL_DATA);
4132 	else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
4133 		set_opt(sb, ORDERED_DATA);
4134 	else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
4135 		set_opt(sb, WRITEBACK_DATA);
4136 
4137 	if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
4138 		set_opt(sb, ERRORS_PANIC);
4139 	else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
4140 		set_opt(sb, ERRORS_CONT);
4141 	else
4142 		set_opt(sb, ERRORS_RO);
4143 	/* block_validity enabled by default; disable with noblock_validity */
4144 	set_opt(sb, BLOCK_VALIDITY);
4145 	if (def_mount_opts & EXT4_DEFM_DISCARD)
4146 		set_opt(sb, DISCARD);
4147 
4148 	sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
4149 	sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
4150 	sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
4151 	sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
4152 	sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
4153 
4154 	if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
4155 		set_opt(sb, BARRIER);
4156 
4157 	/*
4158 	 * enable delayed allocation by default
4159 	 * Use -o nodelalloc to turn it off
4160 	 */
4161 	if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
4162 	    ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
4163 		set_opt(sb, DELALLOC);
4164 
4165 	/*
4166 	 * set default s_li_wait_mult for lazyinit, for the case there is
4167 	 * no mount option specified.
4168 	 */
4169 	sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
4170 
4171 	if (le32_to_cpu(es->s_log_block_size) >
4172 	    (EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4173 		ext4_msg(sb, KERN_ERR,
4174 			 "Invalid log block size: %u",
4175 			 le32_to_cpu(es->s_log_block_size));
4176 		goto failed_mount;
4177 	}
4178 	if (le32_to_cpu(es->s_log_cluster_size) >
4179 	    (EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4180 		ext4_msg(sb, KERN_ERR,
4181 			 "Invalid log cluster size: %u",
4182 			 le32_to_cpu(es->s_log_cluster_size));
4183 		goto failed_mount;
4184 	}
4185 
4186 	blocksize = EXT4_MIN_BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
4187 
4188 	if (blocksize == PAGE_SIZE)
4189 		set_opt(sb, DIOREAD_NOLOCK);
4190 
4191 	if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
4192 		sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
4193 		sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
4194 	} else {
4195 		sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
4196 		sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
4197 		if (sbi->s_first_ino < EXT4_GOOD_OLD_FIRST_INO) {
4198 			ext4_msg(sb, KERN_ERR, "invalid first ino: %u",
4199 				 sbi->s_first_ino);
4200 			goto failed_mount;
4201 		}
4202 		if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
4203 		    (!is_power_of_2(sbi->s_inode_size)) ||
4204 		    (sbi->s_inode_size > blocksize)) {
4205 			ext4_msg(sb, KERN_ERR,
4206 			       "unsupported inode size: %d",
4207 			       sbi->s_inode_size);
4208 			ext4_msg(sb, KERN_ERR, "blocksize: %d", blocksize);
4209 			goto failed_mount;
4210 		}
4211 		/*
4212 		 * i_atime_extra is the last extra field available for
4213 		 * [acm]times in struct ext4_inode. Checking for that
4214 		 * field should suffice to ensure we have extra space
4215 		 * for all three.
4216 		 */
4217 		if (sbi->s_inode_size >= offsetof(struct ext4_inode, i_atime_extra) +
4218 			sizeof(((struct ext4_inode *)0)->i_atime_extra)) {
4219 			sb->s_time_gran = 1;
4220 			sb->s_time_max = EXT4_EXTRA_TIMESTAMP_MAX;
4221 		} else {
4222 			sb->s_time_gran = NSEC_PER_SEC;
4223 			sb->s_time_max = EXT4_NON_EXTRA_TIMESTAMP_MAX;
4224 		}
4225 		sb->s_time_min = EXT4_TIMESTAMP_MIN;
4226 	}
4227 	if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
4228 		sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
4229 			EXT4_GOOD_OLD_INODE_SIZE;
4230 		if (ext4_has_feature_extra_isize(sb)) {
4231 			unsigned v, max = (sbi->s_inode_size -
4232 					   EXT4_GOOD_OLD_INODE_SIZE);
4233 
4234 			v = le16_to_cpu(es->s_want_extra_isize);
4235 			if (v > max) {
4236 				ext4_msg(sb, KERN_ERR,
4237 					 "bad s_want_extra_isize: %d", v);
4238 				goto failed_mount;
4239 			}
4240 			if (sbi->s_want_extra_isize < v)
4241 				sbi->s_want_extra_isize = v;
4242 
4243 			v = le16_to_cpu(es->s_min_extra_isize);
4244 			if (v > max) {
4245 				ext4_msg(sb, KERN_ERR,
4246 					 "bad s_min_extra_isize: %d", v);
4247 				goto failed_mount;
4248 			}
4249 			if (sbi->s_want_extra_isize < v)
4250 				sbi->s_want_extra_isize = v;
4251 		}
4252 	}
4253 
4254 	if (sbi->s_es->s_mount_opts[0]) {
4255 		char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
4256 					      sizeof(sbi->s_es->s_mount_opts),
4257 					      GFP_KERNEL);
4258 		if (!s_mount_opts)
4259 			goto failed_mount;
4260 		if (!parse_options(s_mount_opts, sb, &journal_devnum,
4261 				   &journal_ioprio, 0)) {
4262 			ext4_msg(sb, KERN_WARNING,
4263 				 "failed to parse options in superblock: %s",
4264 				 s_mount_opts);
4265 		}
4266 		kfree(s_mount_opts);
4267 	}
4268 	sbi->s_def_mount_opt = sbi->s_mount_opt;
4269 	if (!parse_options((char *) data, sb, &journal_devnum,
4270 			   &journal_ioprio, 0))
4271 		goto failed_mount;
4272 
4273 #ifdef CONFIG_UNICODE
4274 	if (ext4_has_feature_casefold(sb) && !sb->s_encoding) {
4275 		const struct ext4_sb_encodings *encoding_info;
4276 		struct unicode_map *encoding;
4277 		__u16 encoding_flags;
4278 
4279 		if (ext4_has_feature_encrypt(sb)) {
4280 			ext4_msg(sb, KERN_ERR,
4281 				 "Can't mount with encoding and encryption");
4282 			goto failed_mount;
4283 		}
4284 
4285 		if (ext4_sb_read_encoding(es, &encoding_info,
4286 					  &encoding_flags)) {
4287 			ext4_msg(sb, KERN_ERR,
4288 				 "Encoding requested by superblock is unknown");
4289 			goto failed_mount;
4290 		}
4291 
4292 		encoding = utf8_load(encoding_info->version);
4293 		if (IS_ERR(encoding)) {
4294 			ext4_msg(sb, KERN_ERR,
4295 				 "can't mount with superblock charset: %s-%s "
4296 				 "not supported by the kernel. flags: 0x%x.",
4297 				 encoding_info->name, encoding_info->version,
4298 				 encoding_flags);
4299 			goto failed_mount;
4300 		}
4301 		ext4_msg(sb, KERN_INFO,"Using encoding defined by superblock: "
4302 			 "%s-%s with flags 0x%hx", encoding_info->name,
4303 			 encoding_info->version?:"\b", encoding_flags);
4304 
4305 		sb->s_encoding = encoding;
4306 		sb->s_encoding_flags = encoding_flags;
4307 	}
4308 #endif
4309 
4310 	if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
4311 		printk_once(KERN_WARNING "EXT4-fs: Warning: mounting with data=journal disables delayed allocation, dioread_nolock, O_DIRECT and fast_commit support!\n");
4312 		/* can't mount with both data=journal and dioread_nolock. */
4313 		clear_opt(sb, DIOREAD_NOLOCK);
4314 		clear_opt2(sb, JOURNAL_FAST_COMMIT);
4315 		if (test_opt2(sb, EXPLICIT_DELALLOC)) {
4316 			ext4_msg(sb, KERN_ERR, "can't mount with "
4317 				 "both data=journal and delalloc");
4318 			goto failed_mount;
4319 		}
4320 		if (test_opt(sb, DAX_ALWAYS)) {
4321 			ext4_msg(sb, KERN_ERR, "can't mount with "
4322 				 "both data=journal and dax");
4323 			goto failed_mount;
4324 		}
4325 		if (ext4_has_feature_encrypt(sb)) {
4326 			ext4_msg(sb, KERN_WARNING,
4327 				 "encrypted files will use data=ordered "
4328 				 "instead of data journaling mode");
4329 		}
4330 		if (test_opt(sb, DELALLOC))
4331 			clear_opt(sb, DELALLOC);
4332 	} else {
4333 		sb->s_iflags |= SB_I_CGROUPWB;
4334 	}
4335 
4336 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
4337 		(test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
4338 
4339 	if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
4340 	    (ext4_has_compat_features(sb) ||
4341 	     ext4_has_ro_compat_features(sb) ||
4342 	     ext4_has_incompat_features(sb)))
4343 		ext4_msg(sb, KERN_WARNING,
4344 		       "feature flags set on rev 0 fs, "
4345 		       "running e2fsck is recommended");
4346 
4347 	if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
4348 		set_opt2(sb, HURD_COMPAT);
4349 		if (ext4_has_feature_64bit(sb)) {
4350 			ext4_msg(sb, KERN_ERR,
4351 				 "The Hurd can't support 64-bit file systems");
4352 			goto failed_mount;
4353 		}
4354 
4355 		/*
4356 		 * ea_inode feature uses l_i_version field which is not
4357 		 * available in HURD_COMPAT mode.
4358 		 */
4359 		if (ext4_has_feature_ea_inode(sb)) {
4360 			ext4_msg(sb, KERN_ERR,
4361 				 "ea_inode feature is not supported for Hurd");
4362 			goto failed_mount;
4363 		}
4364 	}
4365 
4366 	if (IS_EXT2_SB(sb)) {
4367 		if (ext2_feature_set_ok(sb))
4368 			ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
4369 				 "using the ext4 subsystem");
4370 		else {
4371 			/*
4372 			 * If we're probing be silent, if this looks like
4373 			 * it's actually an ext[34] filesystem.
4374 			 */
4375 			if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
4376 				goto failed_mount;
4377 			ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
4378 				 "to feature incompatibilities");
4379 			goto failed_mount;
4380 		}
4381 	}
4382 
4383 	if (IS_EXT3_SB(sb)) {
4384 		if (ext3_feature_set_ok(sb))
4385 			ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
4386 				 "using the ext4 subsystem");
4387 		else {
4388 			/*
4389 			 * If we're probing be silent, if this looks like
4390 			 * it's actually an ext4 filesystem.
4391 			 */
4392 			if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
4393 				goto failed_mount;
4394 			ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
4395 				 "to feature incompatibilities");
4396 			goto failed_mount;
4397 		}
4398 	}
4399 
4400 	/*
4401 	 * Check feature flags regardless of the revision level, since we
4402 	 * previously didn't change the revision level when setting the flags,
4403 	 * so there is a chance incompat flags are set on a rev 0 filesystem.
4404 	 */
4405 	if (!ext4_feature_set_ok(sb, (sb_rdonly(sb))))
4406 		goto failed_mount;
4407 
4408 	if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
4409 		ext4_msg(sb, KERN_ERR,
4410 			 "Number of reserved GDT blocks insanely large: %d",
4411 			 le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
4412 		goto failed_mount;
4413 	}
4414 
4415 	if (bdev_dax_supported(sb->s_bdev, blocksize))
4416 		set_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags);
4417 
4418 	if (sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) {
4419 		if (ext4_has_feature_inline_data(sb)) {
4420 			ext4_msg(sb, KERN_ERR, "Cannot use DAX on a filesystem"
4421 					" that may contain inline data");
4422 			goto failed_mount;
4423 		}
4424 		if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags)) {
4425 			ext4_msg(sb, KERN_ERR,
4426 				"DAX unsupported by block device.");
4427 			goto failed_mount;
4428 		}
4429 	}
4430 
4431 	if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
4432 		ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
4433 			 es->s_encryption_level);
4434 		goto failed_mount;
4435 	}
4436 
4437 	if (sb->s_blocksize != blocksize) {
4438 		/*
4439 		 * bh must be released before kill_bdev(), otherwise
4440 		 * it won't be freed and its page also. kill_bdev()
4441 		 * is called by sb_set_blocksize().
4442 		 */
4443 		brelse(bh);
4444 		/* Validate the filesystem blocksize */
4445 		if (!sb_set_blocksize(sb, blocksize)) {
4446 			ext4_msg(sb, KERN_ERR, "bad block size %d",
4447 					blocksize);
4448 			bh = NULL;
4449 			goto failed_mount;
4450 		}
4451 
4452 		logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
4453 		offset = do_div(logical_sb_block, blocksize);
4454 		bh = ext4_sb_bread_unmovable(sb, logical_sb_block);
4455 		if (IS_ERR(bh)) {
4456 			ext4_msg(sb, KERN_ERR,
4457 			       "Can't read superblock on 2nd try");
4458 			ret = PTR_ERR(bh);
4459 			bh = NULL;
4460 			goto failed_mount;
4461 		}
4462 		es = (struct ext4_super_block *)(bh->b_data + offset);
4463 		sbi->s_es = es;
4464 		if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
4465 			ext4_msg(sb, KERN_ERR,
4466 			       "Magic mismatch, very weird!");
4467 			goto failed_mount;
4468 		}
4469 	}
4470 
4471 	has_huge_files = ext4_has_feature_huge_file(sb);
4472 	sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
4473 						      has_huge_files);
4474 	sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
4475 
4476 	sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
4477 	if (ext4_has_feature_64bit(sb)) {
4478 		if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
4479 		    sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
4480 		    !is_power_of_2(sbi->s_desc_size)) {
4481 			ext4_msg(sb, KERN_ERR,
4482 			       "unsupported descriptor size %lu",
4483 			       sbi->s_desc_size);
4484 			goto failed_mount;
4485 		}
4486 	} else
4487 		sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
4488 
4489 	sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
4490 	sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
4491 
4492 	sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
4493 	if (sbi->s_inodes_per_block == 0)
4494 		goto cantfind_ext4;
4495 	if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
4496 	    sbi->s_inodes_per_group > blocksize * 8) {
4497 		ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
4498 			 sbi->s_inodes_per_group);
4499 		goto failed_mount;
4500 	}
4501 	sbi->s_itb_per_group = sbi->s_inodes_per_group /
4502 					sbi->s_inodes_per_block;
4503 	sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
4504 	sbi->s_sbh = bh;
4505 	sbi->s_mount_state = le16_to_cpu(es->s_state);
4506 	sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
4507 	sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
4508 
4509 	for (i = 0; i < 4; i++)
4510 		sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
4511 	sbi->s_def_hash_version = es->s_def_hash_version;
4512 	if (ext4_has_feature_dir_index(sb)) {
4513 		i = le32_to_cpu(es->s_flags);
4514 		if (i & EXT2_FLAGS_UNSIGNED_HASH)
4515 			sbi->s_hash_unsigned = 3;
4516 		else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
4517 #ifdef __CHAR_UNSIGNED__
4518 			if (!sb_rdonly(sb))
4519 				es->s_flags |=
4520 					cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
4521 			sbi->s_hash_unsigned = 3;
4522 #else
4523 			if (!sb_rdonly(sb))
4524 				es->s_flags |=
4525 					cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
4526 #endif
4527 		}
4528 	}
4529 
4530 	/* Handle clustersize */
4531 	clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
4532 	if (ext4_has_feature_bigalloc(sb)) {
4533 		if (clustersize < blocksize) {
4534 			ext4_msg(sb, KERN_ERR,
4535 				 "cluster size (%d) smaller than "
4536 				 "block size (%d)", clustersize, blocksize);
4537 			goto failed_mount;
4538 		}
4539 		sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
4540 			le32_to_cpu(es->s_log_block_size);
4541 		sbi->s_clusters_per_group =
4542 			le32_to_cpu(es->s_clusters_per_group);
4543 		if (sbi->s_clusters_per_group > blocksize * 8) {
4544 			ext4_msg(sb, KERN_ERR,
4545 				 "#clusters per group too big: %lu",
4546 				 sbi->s_clusters_per_group);
4547 			goto failed_mount;
4548 		}
4549 		if (sbi->s_blocks_per_group !=
4550 		    (sbi->s_clusters_per_group * (clustersize / blocksize))) {
4551 			ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
4552 				 "clusters per group (%lu) inconsistent",
4553 				 sbi->s_blocks_per_group,
4554 				 sbi->s_clusters_per_group);
4555 			goto failed_mount;
4556 		}
4557 	} else {
4558 		if (clustersize != blocksize) {
4559 			ext4_msg(sb, KERN_ERR,
4560 				 "fragment/cluster size (%d) != "
4561 				 "block size (%d)", clustersize, blocksize);
4562 			goto failed_mount;
4563 		}
4564 		if (sbi->s_blocks_per_group > blocksize * 8) {
4565 			ext4_msg(sb, KERN_ERR,
4566 				 "#blocks per group too big: %lu",
4567 				 sbi->s_blocks_per_group);
4568 			goto failed_mount;
4569 		}
4570 		sbi->s_clusters_per_group = sbi->s_blocks_per_group;
4571 		sbi->s_cluster_bits = 0;
4572 	}
4573 	sbi->s_cluster_ratio = clustersize / blocksize;
4574 
4575 	/* Do we have standard group size of clustersize * 8 blocks ? */
4576 	if (sbi->s_blocks_per_group == clustersize << 3)
4577 		set_opt2(sb, STD_GROUP_SIZE);
4578 
4579 	/*
4580 	 * Test whether we have more sectors than will fit in sector_t,
4581 	 * and whether the max offset is addressable by the page cache.
4582 	 */
4583 	err = generic_check_addressable(sb->s_blocksize_bits,
4584 					ext4_blocks_count(es));
4585 	if (err) {
4586 		ext4_msg(sb, KERN_ERR, "filesystem"
4587 			 " too large to mount safely on this system");
4588 		goto failed_mount;
4589 	}
4590 
4591 	if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
4592 		goto cantfind_ext4;
4593 
4594 	/* check blocks count against device size */
4595 	blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
4596 	if (blocks_count && ext4_blocks_count(es) > blocks_count) {
4597 		ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
4598 		       "exceeds size of device (%llu blocks)",
4599 		       ext4_blocks_count(es), blocks_count);
4600 		goto failed_mount;
4601 	}
4602 
4603 	/*
4604 	 * It makes no sense for the first data block to be beyond the end
4605 	 * of the filesystem.
4606 	 */
4607 	if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
4608 		ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4609 			 "block %u is beyond end of filesystem (%llu)",
4610 			 le32_to_cpu(es->s_first_data_block),
4611 			 ext4_blocks_count(es));
4612 		goto failed_mount;
4613 	}
4614 	if ((es->s_first_data_block == 0) && (es->s_log_block_size == 0) &&
4615 	    (sbi->s_cluster_ratio == 1)) {
4616 		ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4617 			 "block is 0 with a 1k block and cluster size");
4618 		goto failed_mount;
4619 	}
4620 
4621 	blocks_count = (ext4_blocks_count(es) -
4622 			le32_to_cpu(es->s_first_data_block) +
4623 			EXT4_BLOCKS_PER_GROUP(sb) - 1);
4624 	do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
4625 	if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
4626 		ext4_msg(sb, KERN_WARNING, "groups count too large: %llu "
4627 		       "(block count %llu, first data block %u, "
4628 		       "blocks per group %lu)", blocks_count,
4629 		       ext4_blocks_count(es),
4630 		       le32_to_cpu(es->s_first_data_block),
4631 		       EXT4_BLOCKS_PER_GROUP(sb));
4632 		goto failed_mount;
4633 	}
4634 	sbi->s_groups_count = blocks_count;
4635 	sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
4636 			(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
4637 	if (((u64)sbi->s_groups_count * sbi->s_inodes_per_group) !=
4638 	    le32_to_cpu(es->s_inodes_count)) {
4639 		ext4_msg(sb, KERN_ERR, "inodes count not valid: %u vs %llu",
4640 			 le32_to_cpu(es->s_inodes_count),
4641 			 ((u64)sbi->s_groups_count * sbi->s_inodes_per_group));
4642 		ret = -EINVAL;
4643 		goto failed_mount;
4644 	}
4645 	db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
4646 		   EXT4_DESC_PER_BLOCK(sb);
4647 	if (ext4_has_feature_meta_bg(sb)) {
4648 		if (le32_to_cpu(es->s_first_meta_bg) > db_count) {
4649 			ext4_msg(sb, KERN_WARNING,
4650 				 "first meta block group too large: %u "
4651 				 "(group descriptor block count %u)",
4652 				 le32_to_cpu(es->s_first_meta_bg), db_count);
4653 			goto failed_mount;
4654 		}
4655 	}
4656 	rcu_assign_pointer(sbi->s_group_desc,
4657 			   kvmalloc_array(db_count,
4658 					  sizeof(struct buffer_head *),
4659 					  GFP_KERNEL));
4660 	if (sbi->s_group_desc == NULL) {
4661 		ext4_msg(sb, KERN_ERR, "not enough memory");
4662 		ret = -ENOMEM;
4663 		goto failed_mount;
4664 	}
4665 
4666 	bgl_lock_init(sbi->s_blockgroup_lock);
4667 
4668 	/* Pre-read the descriptors into the buffer cache */
4669 	for (i = 0; i < db_count; i++) {
4670 		block = descriptor_loc(sb, logical_sb_block, i);
4671 		ext4_sb_breadahead_unmovable(sb, block);
4672 	}
4673 
4674 	for (i = 0; i < db_count; i++) {
4675 		struct buffer_head *bh;
4676 
4677 		block = descriptor_loc(sb, logical_sb_block, i);
4678 		bh = ext4_sb_bread_unmovable(sb, block);
4679 		if (IS_ERR(bh)) {
4680 			ext4_msg(sb, KERN_ERR,
4681 			       "can't read group descriptor %d", i);
4682 			db_count = i;
4683 			ret = PTR_ERR(bh);
4684 			bh = NULL;
4685 			goto failed_mount2;
4686 		}
4687 		rcu_read_lock();
4688 		rcu_dereference(sbi->s_group_desc)[i] = bh;
4689 		rcu_read_unlock();
4690 	}
4691 	sbi->s_gdb_count = db_count;
4692 	if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
4693 		ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
4694 		ret = -EFSCORRUPTED;
4695 		goto failed_mount2;
4696 	}
4697 
4698 	timer_setup(&sbi->s_err_report, print_daily_error_info, 0);
4699 	spin_lock_init(&sbi->s_error_lock);
4700 	INIT_WORK(&sbi->s_error_work, flush_stashed_error_work);
4701 
4702 	/* Register extent status tree shrinker */
4703 	if (ext4_es_register_shrinker(sbi))
4704 		goto failed_mount3;
4705 
4706 	sbi->s_stripe = ext4_get_stripe_size(sbi);
4707 	sbi->s_extent_max_zeroout_kb = 32;
4708 
4709 	/*
4710 	 * set up enough so that it can read an inode
4711 	 */
4712 	sb->s_op = &ext4_sops;
4713 	sb->s_export_op = &ext4_export_ops;
4714 	sb->s_xattr = ext4_xattr_handlers;
4715 #ifdef CONFIG_FS_ENCRYPTION
4716 	sb->s_cop = &ext4_cryptops;
4717 #endif
4718 #ifdef CONFIG_FS_VERITY
4719 	sb->s_vop = &ext4_verityops;
4720 #endif
4721 #ifdef CONFIG_QUOTA
4722 	sb->dq_op = &ext4_quota_operations;
4723 	if (ext4_has_feature_quota(sb))
4724 		sb->s_qcop = &dquot_quotactl_sysfile_ops;
4725 	else
4726 		sb->s_qcop = &ext4_qctl_operations;
4727 	sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
4728 #endif
4729 	memcpy(&sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
4730 
4731 	INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
4732 	mutex_init(&sbi->s_orphan_lock);
4733 
4734 	/* Initialize fast commit stuff */
4735 	atomic_set(&sbi->s_fc_subtid, 0);
4736 	atomic_set(&sbi->s_fc_ineligible_updates, 0);
4737 	INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]);
4738 	INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]);
4739 	INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]);
4740 	INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]);
4741 	sbi->s_fc_bytes = 0;
4742 	ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
4743 	ext4_clear_mount_flag(sb, EXT4_MF_FC_COMMITTING);
4744 	spin_lock_init(&sbi->s_fc_lock);
4745 	memset(&sbi->s_fc_stats, 0, sizeof(sbi->s_fc_stats));
4746 	sbi->s_fc_replay_state.fc_regions = NULL;
4747 	sbi->s_fc_replay_state.fc_regions_size = 0;
4748 	sbi->s_fc_replay_state.fc_regions_used = 0;
4749 	sbi->s_fc_replay_state.fc_regions_valid = 0;
4750 	sbi->s_fc_replay_state.fc_modified_inodes = NULL;
4751 	sbi->s_fc_replay_state.fc_modified_inodes_size = 0;
4752 	sbi->s_fc_replay_state.fc_modified_inodes_used = 0;
4753 
4754 	sb->s_root = NULL;
4755 
4756 	needs_recovery = (es->s_last_orphan != 0 ||
4757 			  ext4_has_feature_journal_needs_recovery(sb));
4758 
4759 	if (ext4_has_feature_mmp(sb) && !sb_rdonly(sb))
4760 		if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
4761 			goto failed_mount3a;
4762 
4763 	/*
4764 	 * The first inode we look at is the journal inode.  Don't try
4765 	 * root first: it may be modified in the journal!
4766 	 */
4767 	if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
4768 		err = ext4_load_journal(sb, es, journal_devnum);
4769 		if (err)
4770 			goto failed_mount3a;
4771 	} else if (test_opt(sb, NOLOAD) && !sb_rdonly(sb) &&
4772 		   ext4_has_feature_journal_needs_recovery(sb)) {
4773 		ext4_msg(sb, KERN_ERR, "required journal recovery "
4774 		       "suppressed and not mounted read-only");
4775 		goto failed_mount_wq;
4776 	} else {
4777 		/* Nojournal mode, all journal mount options are illegal */
4778 		if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
4779 			ext4_msg(sb, KERN_ERR, "can't mount with "
4780 				 "journal_checksum, fs mounted w/o journal");
4781 			goto failed_mount_wq;
4782 		}
4783 		if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4784 			ext4_msg(sb, KERN_ERR, "can't mount with "
4785 				 "journal_async_commit, fs mounted w/o journal");
4786 			goto failed_mount_wq;
4787 		}
4788 		if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
4789 			ext4_msg(sb, KERN_ERR, "can't mount with "
4790 				 "commit=%lu, fs mounted w/o journal",
4791 				 sbi->s_commit_interval / HZ);
4792 			goto failed_mount_wq;
4793 		}
4794 		if (EXT4_MOUNT_DATA_FLAGS &
4795 		    (sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
4796 			ext4_msg(sb, KERN_ERR, "can't mount with "
4797 				 "data=, fs mounted w/o journal");
4798 			goto failed_mount_wq;
4799 		}
4800 		sbi->s_def_mount_opt &= ~EXT4_MOUNT_JOURNAL_CHECKSUM;
4801 		clear_opt(sb, JOURNAL_CHECKSUM);
4802 		clear_opt(sb, DATA_FLAGS);
4803 		clear_opt2(sb, JOURNAL_FAST_COMMIT);
4804 		sbi->s_journal = NULL;
4805 		needs_recovery = 0;
4806 		goto no_journal;
4807 	}
4808 
4809 	if (ext4_has_feature_64bit(sb) &&
4810 	    !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
4811 				       JBD2_FEATURE_INCOMPAT_64BIT)) {
4812 		ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
4813 		goto failed_mount_wq;
4814 	}
4815 
4816 	if (!set_journal_csum_feature_set(sb)) {
4817 		ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
4818 			 "feature set");
4819 		goto failed_mount_wq;
4820 	}
4821 
4822 	if (test_opt2(sb, JOURNAL_FAST_COMMIT) &&
4823 		!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
4824 					  JBD2_FEATURE_INCOMPAT_FAST_COMMIT)) {
4825 		ext4_msg(sb, KERN_ERR,
4826 			"Failed to set fast commit journal feature");
4827 		goto failed_mount_wq;
4828 	}
4829 
4830 	/* We have now updated the journal if required, so we can
4831 	 * validate the data journaling mode. */
4832 	switch (test_opt(sb, DATA_FLAGS)) {
4833 	case 0:
4834 		/* No mode set, assume a default based on the journal
4835 		 * capabilities: ORDERED_DATA if the journal can
4836 		 * cope, else JOURNAL_DATA
4837 		 */
4838 		if (jbd2_journal_check_available_features
4839 		    (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4840 			set_opt(sb, ORDERED_DATA);
4841 			sbi->s_def_mount_opt |= EXT4_MOUNT_ORDERED_DATA;
4842 		} else {
4843 			set_opt(sb, JOURNAL_DATA);
4844 			sbi->s_def_mount_opt |= EXT4_MOUNT_JOURNAL_DATA;
4845 		}
4846 		break;
4847 
4848 	case EXT4_MOUNT_ORDERED_DATA:
4849 	case EXT4_MOUNT_WRITEBACK_DATA:
4850 		if (!jbd2_journal_check_available_features
4851 		    (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4852 			ext4_msg(sb, KERN_ERR, "Journal does not support "
4853 			       "requested data journaling mode");
4854 			goto failed_mount_wq;
4855 		}
4856 	default:
4857 		break;
4858 	}
4859 
4860 	if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
4861 	    test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4862 		ext4_msg(sb, KERN_ERR, "can't mount with "
4863 			"journal_async_commit in data=ordered mode");
4864 		goto failed_mount_wq;
4865 	}
4866 
4867 	set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
4868 
4869 	sbi->s_journal->j_submit_inode_data_buffers =
4870 		ext4_journal_submit_inode_data_buffers;
4871 	sbi->s_journal->j_finish_inode_data_buffers =
4872 		ext4_journal_finish_inode_data_buffers;
4873 
4874 no_journal:
4875 	if (!test_opt(sb, NO_MBCACHE)) {
4876 		sbi->s_ea_block_cache = ext4_xattr_create_cache();
4877 		if (!sbi->s_ea_block_cache) {
4878 			ext4_msg(sb, KERN_ERR,
4879 				 "Failed to create ea_block_cache");
4880 			goto failed_mount_wq;
4881 		}
4882 
4883 		if (ext4_has_feature_ea_inode(sb)) {
4884 			sbi->s_ea_inode_cache = ext4_xattr_create_cache();
4885 			if (!sbi->s_ea_inode_cache) {
4886 				ext4_msg(sb, KERN_ERR,
4887 					 "Failed to create ea_inode_cache");
4888 				goto failed_mount_wq;
4889 			}
4890 		}
4891 	}
4892 
4893 	if (ext4_has_feature_verity(sb) && blocksize != PAGE_SIZE) {
4894 		ext4_msg(sb, KERN_ERR, "Unsupported blocksize for fs-verity");
4895 		goto failed_mount_wq;
4896 	}
4897 
4898 	if (DUMMY_ENCRYPTION_ENABLED(sbi) && !sb_rdonly(sb) &&
4899 	    !ext4_has_feature_encrypt(sb)) {
4900 		ext4_set_feature_encrypt(sb);
4901 		ext4_commit_super(sb);
4902 	}
4903 
4904 	/*
4905 	 * Get the # of file system overhead blocks from the
4906 	 * superblock if present.
4907 	 */
4908 	if (es->s_overhead_clusters)
4909 		sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
4910 	else {
4911 		err = ext4_calculate_overhead(sb);
4912 		if (err)
4913 			goto failed_mount_wq;
4914 	}
4915 
4916 	/*
4917 	 * The maximum number of concurrent works can be high and
4918 	 * concurrency isn't really necessary.  Limit it to 1.
4919 	 */
4920 	EXT4_SB(sb)->rsv_conversion_wq =
4921 		alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
4922 	if (!EXT4_SB(sb)->rsv_conversion_wq) {
4923 		printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
4924 		ret = -ENOMEM;
4925 		goto failed_mount4;
4926 	}
4927 
4928 	/*
4929 	 * The jbd2_journal_load will have done any necessary log recovery,
4930 	 * so we can safely mount the rest of the filesystem now.
4931 	 */
4932 
4933 	root = ext4_iget(sb, EXT4_ROOT_INO, EXT4_IGET_SPECIAL);
4934 	if (IS_ERR(root)) {
4935 		ext4_msg(sb, KERN_ERR, "get root inode failed");
4936 		ret = PTR_ERR(root);
4937 		root = NULL;
4938 		goto failed_mount4;
4939 	}
4940 	if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
4941 		ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
4942 		iput(root);
4943 		goto failed_mount4;
4944 	}
4945 
4946 #ifdef CONFIG_UNICODE
4947 	if (sb->s_encoding)
4948 		sb->s_d_op = &ext4_dentry_ops;
4949 #endif
4950 
4951 	sb->s_root = d_make_root(root);
4952 	if (!sb->s_root) {
4953 		ext4_msg(sb, KERN_ERR, "get root dentry failed");
4954 		ret = -ENOMEM;
4955 		goto failed_mount4;
4956 	}
4957 
4958 	ret = ext4_setup_super(sb, es, sb_rdonly(sb));
4959 	if (ret == -EROFS) {
4960 		sb->s_flags |= SB_RDONLY;
4961 		ret = 0;
4962 	} else if (ret)
4963 		goto failed_mount4a;
4964 
4965 	ext4_set_resv_clusters(sb);
4966 
4967 	if (test_opt(sb, BLOCK_VALIDITY)) {
4968 		err = ext4_setup_system_zone(sb);
4969 		if (err) {
4970 			ext4_msg(sb, KERN_ERR, "failed to initialize system "
4971 				 "zone (%d)", err);
4972 			goto failed_mount4a;
4973 		}
4974 	}
4975 	ext4_fc_replay_cleanup(sb);
4976 
4977 	ext4_ext_init(sb);
4978 	err = ext4_mb_init(sb);
4979 	if (err) {
4980 		ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
4981 			 err);
4982 		goto failed_mount5;
4983 	}
4984 
4985 	/*
4986 	 * We can only set up the journal commit callback once
4987 	 * mballoc is initialized
4988 	 */
4989 	if (sbi->s_journal)
4990 		sbi->s_journal->j_commit_callback =
4991 			ext4_journal_commit_callback;
4992 
4993 	block = ext4_count_free_clusters(sb);
4994 	ext4_free_blocks_count_set(sbi->s_es,
4995 				   EXT4_C2B(sbi, block));
4996 	err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
4997 				  GFP_KERNEL);
4998 	if (!err) {
4999 		unsigned long freei = ext4_count_free_inodes(sb);
5000 		sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
5001 		err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
5002 					  GFP_KERNEL);
5003 	}
5004 	/*
5005 	 * Update the checksum after updating free space/inode
5006 	 * counters.  Otherwise the superblock can have an incorrect
5007 	 * checksum in the buffer cache until it is written out and
5008 	 * e2fsprogs programs trying to open a file system immediately
5009 	 * after it is mounted can fail.
5010 	 */
5011 	ext4_superblock_csum_set(sb);
5012 	if (!err)
5013 		err = percpu_counter_init(&sbi->s_dirs_counter,
5014 					  ext4_count_dirs(sb), GFP_KERNEL);
5015 	if (!err)
5016 		err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
5017 					  GFP_KERNEL);
5018 	if (!err)
5019 		err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0,
5020 					  GFP_KERNEL);
5021 	if (!err)
5022 		err = percpu_init_rwsem(&sbi->s_writepages_rwsem);
5023 
5024 	if (err) {
5025 		ext4_msg(sb, KERN_ERR, "insufficient memory");
5026 		goto failed_mount6;
5027 	}
5028 
5029 	if (ext4_has_feature_flex_bg(sb))
5030 		if (!ext4_fill_flex_info(sb)) {
5031 			ext4_msg(sb, KERN_ERR,
5032 			       "unable to initialize "
5033 			       "flex_bg meta info!");
5034 			ret = -ENOMEM;
5035 			goto failed_mount6;
5036 		}
5037 
5038 	err = ext4_register_li_request(sb, first_not_zeroed);
5039 	if (err)
5040 		goto failed_mount6;
5041 
5042 	err = ext4_register_sysfs(sb);
5043 	if (err)
5044 		goto failed_mount7;
5045 
5046 #ifdef CONFIG_QUOTA
5047 	/* Enable quota usage during mount. */
5048 	if (ext4_has_feature_quota(sb) && !sb_rdonly(sb)) {
5049 		err = ext4_enable_quotas(sb);
5050 		if (err)
5051 			goto failed_mount8;
5052 	}
5053 #endif  /* CONFIG_QUOTA */
5054 
5055 	/*
5056 	 * Save the original bdev mapping's wb_err value which could be
5057 	 * used to detect the metadata async write error.
5058 	 */
5059 	spin_lock_init(&sbi->s_bdev_wb_lock);
5060 	errseq_check_and_advance(&sb->s_bdev->bd_inode->i_mapping->wb_err,
5061 				 &sbi->s_bdev_wb_err);
5062 	sb->s_bdev->bd_super = sb;
5063 	EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
5064 	ext4_orphan_cleanup(sb, es);
5065 	EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
5066 	if (needs_recovery) {
5067 		ext4_msg(sb, KERN_INFO, "recovery complete");
5068 		err = ext4_mark_recovery_complete(sb, es);
5069 		if (err)
5070 			goto failed_mount8;
5071 	}
5072 	if (EXT4_SB(sb)->s_journal) {
5073 		if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
5074 			descr = " journalled data mode";
5075 		else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
5076 			descr = " ordered data mode";
5077 		else
5078 			descr = " writeback data mode";
5079 	} else
5080 		descr = "out journal";
5081 
5082 	if (test_opt(sb, DISCARD)) {
5083 		struct request_queue *q = bdev_get_queue(sb->s_bdev);
5084 		if (!blk_queue_discard(q))
5085 			ext4_msg(sb, KERN_WARNING,
5086 				 "mounting with \"discard\" option, but "
5087 				 "the device does not support discard");
5088 	}
5089 
5090 	if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
5091 		ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
5092 			 "Opts: %.*s%s%s", descr,
5093 			 (int) sizeof(sbi->s_es->s_mount_opts),
5094 			 sbi->s_es->s_mount_opts,
5095 			 *sbi->s_es->s_mount_opts ? "; " : "", orig_data);
5096 
5097 	if (es->s_error_count)
5098 		mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
5099 
5100 	/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
5101 	ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
5102 	ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
5103 	ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
5104 	atomic_set(&sbi->s_warning_count, 0);
5105 	atomic_set(&sbi->s_msg_count, 0);
5106 
5107 	kfree(orig_data);
5108 	return 0;
5109 
5110 cantfind_ext4:
5111 	if (!silent)
5112 		ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
5113 	goto failed_mount;
5114 
5115 failed_mount8:
5116 	ext4_unregister_sysfs(sb);
5117 	kobject_put(&sbi->s_kobj);
5118 failed_mount7:
5119 	ext4_unregister_li_request(sb);
5120 failed_mount6:
5121 	ext4_mb_release(sb);
5122 	rcu_read_lock();
5123 	flex_groups = rcu_dereference(sbi->s_flex_groups);
5124 	if (flex_groups) {
5125 		for (i = 0; i < sbi->s_flex_groups_allocated; i++)
5126 			kvfree(flex_groups[i]);
5127 		kvfree(flex_groups);
5128 	}
5129 	rcu_read_unlock();
5130 	percpu_counter_destroy(&sbi->s_freeclusters_counter);
5131 	percpu_counter_destroy(&sbi->s_freeinodes_counter);
5132 	percpu_counter_destroy(&sbi->s_dirs_counter);
5133 	percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
5134 	percpu_counter_destroy(&sbi->s_sra_exceeded_retry_limit);
5135 	percpu_free_rwsem(&sbi->s_writepages_rwsem);
5136 failed_mount5:
5137 	ext4_ext_release(sb);
5138 	ext4_release_system_zone(sb);
5139 failed_mount4a:
5140 	dput(sb->s_root);
5141 	sb->s_root = NULL;
5142 failed_mount4:
5143 	ext4_msg(sb, KERN_ERR, "mount failed");
5144 	if (EXT4_SB(sb)->rsv_conversion_wq)
5145 		destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
5146 failed_mount_wq:
5147 	ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
5148 	sbi->s_ea_inode_cache = NULL;
5149 
5150 	ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
5151 	sbi->s_ea_block_cache = NULL;
5152 
5153 	if (sbi->s_journal) {
5154 		/* flush s_error_work before journal destroy. */
5155 		flush_work(&sbi->s_error_work);
5156 		jbd2_journal_destroy(sbi->s_journal);
5157 		sbi->s_journal = NULL;
5158 	}
5159 failed_mount3a:
5160 	ext4_es_unregister_shrinker(sbi);
5161 failed_mount3:
5162 	/* flush s_error_work before sbi destroy */
5163 	flush_work(&sbi->s_error_work);
5164 	del_timer_sync(&sbi->s_err_report);
5165 	ext4_stop_mmpd(sbi);
5166 failed_mount2:
5167 	rcu_read_lock();
5168 	group_desc = rcu_dereference(sbi->s_group_desc);
5169 	for (i = 0; i < db_count; i++)
5170 		brelse(group_desc[i]);
5171 	kvfree(group_desc);
5172 	rcu_read_unlock();
5173 failed_mount:
5174 	if (sbi->s_chksum_driver)
5175 		crypto_free_shash(sbi->s_chksum_driver);
5176 
5177 #ifdef CONFIG_UNICODE
5178 	utf8_unload(sb->s_encoding);
5179 #endif
5180 
5181 #ifdef CONFIG_QUOTA
5182 	for (i = 0; i < EXT4_MAXQUOTAS; i++)
5183 		kfree(get_qf_name(sb, sbi, i));
5184 #endif
5185 	fscrypt_free_dummy_policy(&sbi->s_dummy_enc_policy);
5186 	/* ext4_blkdev_remove() calls kill_bdev(), release bh before it. */
5187 	brelse(bh);
5188 	ext4_blkdev_remove(sbi);
5189 out_fail:
5190 	sb->s_fs_info = NULL;
5191 	kfree(sbi->s_blockgroup_lock);
5192 out_free_base:
5193 	kfree(sbi);
5194 	kfree(orig_data);
5195 	fs_put_dax(dax_dev);
5196 	return err ? err : ret;
5197 }
5198 
5199 /*
5200  * Setup any per-fs journal parameters now.  We'll do this both on
5201  * initial mount, once the journal has been initialised but before we've
5202  * done any recovery; and again on any subsequent remount.
5203  */
ext4_init_journal_params(struct super_block * sb,journal_t * journal)5204 static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
5205 {
5206 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5207 
5208 	journal->j_commit_interval = sbi->s_commit_interval;
5209 	journal->j_min_batch_time = sbi->s_min_batch_time;
5210 	journal->j_max_batch_time = sbi->s_max_batch_time;
5211 	ext4_fc_init(sb, journal);
5212 
5213 	write_lock(&journal->j_state_lock);
5214 	if (test_opt(sb, BARRIER))
5215 		journal->j_flags |= JBD2_BARRIER;
5216 	else
5217 		journal->j_flags &= ~JBD2_BARRIER;
5218 	if (test_opt(sb, DATA_ERR_ABORT))
5219 		journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
5220 	else
5221 		journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
5222 	write_unlock(&journal->j_state_lock);
5223 }
5224 
ext4_get_journal_inode(struct super_block * sb,unsigned int journal_inum)5225 static struct inode *ext4_get_journal_inode(struct super_block *sb,
5226 					     unsigned int journal_inum)
5227 {
5228 	struct inode *journal_inode;
5229 
5230 	/*
5231 	 * Test for the existence of a valid inode on disk.  Bad things
5232 	 * happen if we iget() an unused inode, as the subsequent iput()
5233 	 * will try to delete it.
5234 	 */
5235 	journal_inode = ext4_iget(sb, journal_inum, EXT4_IGET_SPECIAL);
5236 	if (IS_ERR(journal_inode)) {
5237 		ext4_msg(sb, KERN_ERR, "no journal found");
5238 		return NULL;
5239 	}
5240 	if (!journal_inode->i_nlink) {
5241 		make_bad_inode(journal_inode);
5242 		iput(journal_inode);
5243 		ext4_msg(sb, KERN_ERR, "journal inode is deleted");
5244 		return NULL;
5245 	}
5246 
5247 	jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
5248 		  journal_inode, journal_inode->i_size);
5249 	if (!S_ISREG(journal_inode->i_mode)) {
5250 		ext4_msg(sb, KERN_ERR, "invalid journal inode");
5251 		iput(journal_inode);
5252 		return NULL;
5253 	}
5254 	return journal_inode;
5255 }
5256 
ext4_get_journal(struct super_block * sb,unsigned int journal_inum)5257 static journal_t *ext4_get_journal(struct super_block *sb,
5258 				   unsigned int journal_inum)
5259 {
5260 	struct inode *journal_inode;
5261 	journal_t *journal;
5262 
5263 	if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5264 		return NULL;
5265 
5266 	journal_inode = ext4_get_journal_inode(sb, journal_inum);
5267 	if (!journal_inode)
5268 		return NULL;
5269 
5270 	journal = jbd2_journal_init_inode(journal_inode);
5271 	if (!journal) {
5272 		ext4_msg(sb, KERN_ERR, "Could not load journal inode");
5273 		iput(journal_inode);
5274 		return NULL;
5275 	}
5276 	journal->j_private = sb;
5277 	ext4_init_journal_params(sb, journal);
5278 	return journal;
5279 }
5280 
ext4_get_dev_journal(struct super_block * sb,dev_t j_dev)5281 static journal_t *ext4_get_dev_journal(struct super_block *sb,
5282 				       dev_t j_dev)
5283 {
5284 	struct buffer_head *bh;
5285 	journal_t *journal;
5286 	ext4_fsblk_t start;
5287 	ext4_fsblk_t len;
5288 	int hblock, blocksize;
5289 	ext4_fsblk_t sb_block;
5290 	unsigned long offset;
5291 	struct ext4_super_block *es;
5292 	struct block_device *bdev;
5293 
5294 	if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5295 		return NULL;
5296 
5297 	bdev = ext4_blkdev_get(j_dev, sb);
5298 	if (bdev == NULL)
5299 		return NULL;
5300 
5301 	blocksize = sb->s_blocksize;
5302 	hblock = bdev_logical_block_size(bdev);
5303 	if (blocksize < hblock) {
5304 		ext4_msg(sb, KERN_ERR,
5305 			"blocksize too small for journal device");
5306 		goto out_bdev;
5307 	}
5308 
5309 	sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
5310 	offset = EXT4_MIN_BLOCK_SIZE % blocksize;
5311 	set_blocksize(bdev, blocksize);
5312 	if (!(bh = __bread(bdev, sb_block, blocksize))) {
5313 		ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
5314 		       "external journal");
5315 		goto out_bdev;
5316 	}
5317 
5318 	es = (struct ext4_super_block *) (bh->b_data + offset);
5319 	if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
5320 	    !(le32_to_cpu(es->s_feature_incompat) &
5321 	      EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
5322 		ext4_msg(sb, KERN_ERR, "external journal has "
5323 					"bad superblock");
5324 		brelse(bh);
5325 		goto out_bdev;
5326 	}
5327 
5328 	if ((le32_to_cpu(es->s_feature_ro_compat) &
5329 	     EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
5330 	    es->s_checksum != ext4_superblock_csum(sb, es)) {
5331 		ext4_msg(sb, KERN_ERR, "external journal has "
5332 				       "corrupt superblock");
5333 		brelse(bh);
5334 		goto out_bdev;
5335 	}
5336 
5337 	if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
5338 		ext4_msg(sb, KERN_ERR, "journal UUID does not match");
5339 		brelse(bh);
5340 		goto out_bdev;
5341 	}
5342 
5343 	len = ext4_blocks_count(es);
5344 	start = sb_block + 1;
5345 	brelse(bh);	/* we're done with the superblock */
5346 
5347 	journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
5348 					start, len, blocksize);
5349 	if (!journal) {
5350 		ext4_msg(sb, KERN_ERR, "failed to create device journal");
5351 		goto out_bdev;
5352 	}
5353 	journal->j_private = sb;
5354 	if (ext4_read_bh_lock(journal->j_sb_buffer, REQ_META | REQ_PRIO, true)) {
5355 		ext4_msg(sb, KERN_ERR, "I/O error on journal device");
5356 		goto out_journal;
5357 	}
5358 	if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
5359 		ext4_msg(sb, KERN_ERR, "External journal has more than one "
5360 					"user (unsupported) - %d",
5361 			be32_to_cpu(journal->j_superblock->s_nr_users));
5362 		goto out_journal;
5363 	}
5364 	EXT4_SB(sb)->s_journal_bdev = bdev;
5365 	ext4_init_journal_params(sb, journal);
5366 	return journal;
5367 
5368 out_journal:
5369 	jbd2_journal_destroy(journal);
5370 out_bdev:
5371 	ext4_blkdev_put(bdev);
5372 	return NULL;
5373 }
5374 
ext4_load_journal(struct super_block * sb,struct ext4_super_block * es,unsigned long journal_devnum)5375 static int ext4_load_journal(struct super_block *sb,
5376 			     struct ext4_super_block *es,
5377 			     unsigned long journal_devnum)
5378 {
5379 	journal_t *journal;
5380 	unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
5381 	dev_t journal_dev;
5382 	int err = 0;
5383 	int really_read_only;
5384 	int journal_dev_ro;
5385 
5386 	if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5387 		return -EFSCORRUPTED;
5388 
5389 	if (journal_devnum &&
5390 	    journal_devnum != le32_to_cpu(es->s_journal_dev)) {
5391 		ext4_msg(sb, KERN_INFO, "external journal device major/minor "
5392 			"numbers have changed");
5393 		journal_dev = new_decode_dev(journal_devnum);
5394 	} else
5395 		journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
5396 
5397 	if (journal_inum && journal_dev) {
5398 		ext4_msg(sb, KERN_ERR,
5399 			 "filesystem has both journal inode and journal device!");
5400 		return -EINVAL;
5401 	}
5402 
5403 	if (journal_inum) {
5404 		journal = ext4_get_journal(sb, journal_inum);
5405 		if (!journal)
5406 			return -EINVAL;
5407 	} else {
5408 		journal = ext4_get_dev_journal(sb, journal_dev);
5409 		if (!journal)
5410 			return -EINVAL;
5411 	}
5412 
5413 	journal_dev_ro = bdev_read_only(journal->j_dev);
5414 	really_read_only = bdev_read_only(sb->s_bdev) | journal_dev_ro;
5415 
5416 	if (journal_dev_ro && !sb_rdonly(sb)) {
5417 		ext4_msg(sb, KERN_ERR,
5418 			 "journal device read-only, try mounting with '-o ro'");
5419 		err = -EROFS;
5420 		goto err_out;
5421 	}
5422 
5423 	/*
5424 	 * Are we loading a blank journal or performing recovery after a
5425 	 * crash?  For recovery, we need to check in advance whether we
5426 	 * can get read-write access to the device.
5427 	 */
5428 	if (ext4_has_feature_journal_needs_recovery(sb)) {
5429 		if (sb_rdonly(sb)) {
5430 			ext4_msg(sb, KERN_INFO, "INFO: recovery "
5431 					"required on readonly filesystem");
5432 			if (really_read_only) {
5433 				ext4_msg(sb, KERN_ERR, "write access "
5434 					"unavailable, cannot proceed "
5435 					"(try mounting with noload)");
5436 				err = -EROFS;
5437 				goto err_out;
5438 			}
5439 			ext4_msg(sb, KERN_INFO, "write access will "
5440 			       "be enabled during recovery");
5441 		}
5442 	}
5443 
5444 	if (!(journal->j_flags & JBD2_BARRIER))
5445 		ext4_msg(sb, KERN_INFO, "barriers disabled");
5446 
5447 	if (!ext4_has_feature_journal_needs_recovery(sb))
5448 		err = jbd2_journal_wipe(journal, !really_read_only);
5449 	if (!err) {
5450 		char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
5451 		if (save)
5452 			memcpy(save, ((char *) es) +
5453 			       EXT4_S_ERR_START, EXT4_S_ERR_LEN);
5454 		err = jbd2_journal_load(journal);
5455 		if (save)
5456 			memcpy(((char *) es) + EXT4_S_ERR_START,
5457 			       save, EXT4_S_ERR_LEN);
5458 		kfree(save);
5459 	}
5460 
5461 	if (err) {
5462 		ext4_msg(sb, KERN_ERR, "error loading journal");
5463 		goto err_out;
5464 	}
5465 
5466 	EXT4_SB(sb)->s_journal = journal;
5467 	err = ext4_clear_journal_err(sb, es);
5468 	if (err) {
5469 		EXT4_SB(sb)->s_journal = NULL;
5470 		jbd2_journal_destroy(journal);
5471 		return err;
5472 	}
5473 
5474 	if (!really_read_only && journal_devnum &&
5475 	    journal_devnum != le32_to_cpu(es->s_journal_dev)) {
5476 		es->s_journal_dev = cpu_to_le32(journal_devnum);
5477 
5478 		/* Make sure we flush the recovery flag to disk. */
5479 		ext4_commit_super(sb);
5480 	}
5481 
5482 	return 0;
5483 
5484 err_out:
5485 	jbd2_journal_destroy(journal);
5486 	return err;
5487 }
5488 
5489 /* Copy state of EXT4_SB(sb) into buffer for on-disk superblock */
ext4_update_super(struct super_block * sb)5490 static void ext4_update_super(struct super_block *sb)
5491 {
5492 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5493 	struct ext4_super_block *es = sbi->s_es;
5494 	struct buffer_head *sbh = sbi->s_sbh;
5495 
5496 	lock_buffer(sbh);
5497 	/*
5498 	 * If the file system is mounted read-only, don't update the
5499 	 * superblock write time.  This avoids updating the superblock
5500 	 * write time when we are mounting the root file system
5501 	 * read/only but we need to replay the journal; at that point,
5502 	 * for people who are east of GMT and who make their clock
5503 	 * tick in localtime for Windows bug-for-bug compatibility,
5504 	 * the clock is set in the future, and this will cause e2fsck
5505 	 * to complain and force a full file system check.
5506 	 */
5507 	if (!(sb->s_flags & SB_RDONLY))
5508 		ext4_update_tstamp(es, s_wtime);
5509 	if (sb->s_bdev->bd_part)
5510 		es->s_kbytes_written =
5511 			cpu_to_le64(sbi->s_kbytes_written +
5512 			    ((part_stat_read(sb->s_bdev->bd_part,
5513 					     sectors[STAT_WRITE]) -
5514 			      sbi->s_sectors_written_start) >> 1));
5515 	else
5516 		es->s_kbytes_written = cpu_to_le64(sbi->s_kbytes_written);
5517 	if (percpu_counter_initialized(&sbi->s_freeclusters_counter))
5518 		ext4_free_blocks_count_set(es,
5519 			EXT4_C2B(sbi, percpu_counter_sum_positive(
5520 				&sbi->s_freeclusters_counter)));
5521 	if (percpu_counter_initialized(&sbi->s_freeinodes_counter))
5522 		es->s_free_inodes_count =
5523 			cpu_to_le32(percpu_counter_sum_positive(
5524 				&sbi->s_freeinodes_counter));
5525 	/* Copy error information to the on-disk superblock */
5526 	spin_lock(&sbi->s_error_lock);
5527 	if (sbi->s_add_error_count > 0) {
5528 		es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
5529 		if (!es->s_first_error_time && !es->s_first_error_time_hi) {
5530 			__ext4_update_tstamp(&es->s_first_error_time,
5531 					     &es->s_first_error_time_hi,
5532 					     sbi->s_first_error_time);
5533 			strncpy(es->s_first_error_func, sbi->s_first_error_func,
5534 				sizeof(es->s_first_error_func));
5535 			es->s_first_error_line =
5536 				cpu_to_le32(sbi->s_first_error_line);
5537 			es->s_first_error_ino =
5538 				cpu_to_le32(sbi->s_first_error_ino);
5539 			es->s_first_error_block =
5540 				cpu_to_le64(sbi->s_first_error_block);
5541 			es->s_first_error_errcode =
5542 				ext4_errno_to_code(sbi->s_first_error_code);
5543 		}
5544 		__ext4_update_tstamp(&es->s_last_error_time,
5545 				     &es->s_last_error_time_hi,
5546 				     sbi->s_last_error_time);
5547 		strncpy(es->s_last_error_func, sbi->s_last_error_func,
5548 			sizeof(es->s_last_error_func));
5549 		es->s_last_error_line = cpu_to_le32(sbi->s_last_error_line);
5550 		es->s_last_error_ino = cpu_to_le32(sbi->s_last_error_ino);
5551 		es->s_last_error_block = cpu_to_le64(sbi->s_last_error_block);
5552 		es->s_last_error_errcode =
5553 				ext4_errno_to_code(sbi->s_last_error_code);
5554 		/*
5555 		 * Start the daily error reporting function if it hasn't been
5556 		 * started already
5557 		 */
5558 		if (!es->s_error_count)
5559 			mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);
5560 		le32_add_cpu(&es->s_error_count, sbi->s_add_error_count);
5561 		sbi->s_add_error_count = 0;
5562 	}
5563 	spin_unlock(&sbi->s_error_lock);
5564 
5565 	ext4_superblock_csum_set(sb);
5566 	unlock_buffer(sbh);
5567 }
5568 
ext4_commit_super(struct super_block * sb)5569 static int ext4_commit_super(struct super_block *sb)
5570 {
5571 	struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
5572 	int error = 0;
5573 
5574 	if (!sbh)
5575 		return -EINVAL;
5576 	if (block_device_ejected(sb))
5577 		return -ENODEV;
5578 
5579 	ext4_update_super(sb);
5580 
5581 	if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
5582 		/*
5583 		 * Oh, dear.  A previous attempt to write the
5584 		 * superblock failed.  This could happen because the
5585 		 * USB device was yanked out.  Or it could happen to
5586 		 * be a transient write error and maybe the block will
5587 		 * be remapped.  Nothing we can do but to retry the
5588 		 * write and hope for the best.
5589 		 */
5590 		ext4_msg(sb, KERN_ERR, "previous I/O error to "
5591 		       "superblock detected");
5592 		clear_buffer_write_io_error(sbh);
5593 		set_buffer_uptodate(sbh);
5594 	}
5595 	BUFFER_TRACE(sbh, "marking dirty");
5596 	mark_buffer_dirty(sbh);
5597 	error = __sync_dirty_buffer(sbh,
5598 		REQ_SYNC | (test_opt(sb, BARRIER) ? REQ_FUA : 0));
5599 	if (buffer_write_io_error(sbh)) {
5600 		ext4_msg(sb, KERN_ERR, "I/O error while writing "
5601 		       "superblock");
5602 		clear_buffer_write_io_error(sbh);
5603 		set_buffer_uptodate(sbh);
5604 	}
5605 	return error;
5606 }
5607 
5608 /*
5609  * Have we just finished recovery?  If so, and if we are mounting (or
5610  * remounting) the filesystem readonly, then we will end up with a
5611  * consistent fs on disk.  Record that fact.
5612  */
ext4_mark_recovery_complete(struct super_block * sb,struct ext4_super_block * es)5613 static int ext4_mark_recovery_complete(struct super_block *sb,
5614 				       struct ext4_super_block *es)
5615 {
5616 	int err;
5617 	journal_t *journal = EXT4_SB(sb)->s_journal;
5618 
5619 	if (!ext4_has_feature_journal(sb)) {
5620 		if (journal != NULL) {
5621 			ext4_error(sb, "Journal got removed while the fs was "
5622 				   "mounted!");
5623 			return -EFSCORRUPTED;
5624 		}
5625 		return 0;
5626 	}
5627 	jbd2_journal_lock_updates(journal);
5628 	err = jbd2_journal_flush(journal);
5629 	if (err < 0)
5630 		goto out;
5631 
5632 	if (ext4_has_feature_journal_needs_recovery(sb) && sb_rdonly(sb)) {
5633 		ext4_clear_feature_journal_needs_recovery(sb);
5634 		ext4_commit_super(sb);
5635 	}
5636 out:
5637 	jbd2_journal_unlock_updates(journal);
5638 	return err;
5639 }
5640 
5641 /*
5642  * If we are mounting (or read-write remounting) a filesystem whose journal
5643  * has recorded an error from a previous lifetime, move that error to the
5644  * main filesystem now.
5645  */
ext4_clear_journal_err(struct super_block * sb,struct ext4_super_block * es)5646 static int ext4_clear_journal_err(struct super_block *sb,
5647 				   struct ext4_super_block *es)
5648 {
5649 	journal_t *journal;
5650 	int j_errno;
5651 	const char *errstr;
5652 
5653 	if (!ext4_has_feature_journal(sb)) {
5654 		ext4_error(sb, "Journal got removed while the fs was mounted!");
5655 		return -EFSCORRUPTED;
5656 	}
5657 
5658 	journal = EXT4_SB(sb)->s_journal;
5659 
5660 	/*
5661 	 * Now check for any error status which may have been recorded in the
5662 	 * journal by a prior ext4_error() or ext4_abort()
5663 	 */
5664 
5665 	j_errno = jbd2_journal_errno(journal);
5666 	if (j_errno) {
5667 		char nbuf[16];
5668 
5669 		errstr = ext4_decode_error(sb, j_errno, nbuf);
5670 		ext4_warning(sb, "Filesystem error recorded "
5671 			     "from previous mount: %s", errstr);
5672 		ext4_warning(sb, "Marking fs in need of filesystem check.");
5673 
5674 		EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
5675 		es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
5676 		ext4_commit_super(sb);
5677 
5678 		jbd2_journal_clear_err(journal);
5679 		jbd2_journal_update_sb_errno(journal);
5680 	}
5681 	return 0;
5682 }
5683 
5684 /*
5685  * Force the running and committing transactions to commit,
5686  * and wait on the commit.
5687  */
ext4_force_commit(struct super_block * sb)5688 int ext4_force_commit(struct super_block *sb)
5689 {
5690 	journal_t *journal;
5691 
5692 	if (sb_rdonly(sb))
5693 		return 0;
5694 
5695 	journal = EXT4_SB(sb)->s_journal;
5696 	return ext4_journal_force_commit(journal);
5697 }
5698 
ext4_sync_fs(struct super_block * sb,int wait)5699 static int ext4_sync_fs(struct super_block *sb, int wait)
5700 {
5701 	int ret = 0;
5702 	tid_t target;
5703 	bool needs_barrier = false;
5704 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5705 
5706 	if (unlikely(ext4_forced_shutdown(sbi)))
5707 		return 0;
5708 
5709 	trace_ext4_sync_fs(sb, wait);
5710 	flush_workqueue(sbi->rsv_conversion_wq);
5711 	/*
5712 	 * Writeback quota in non-journalled quota case - journalled quota has
5713 	 * no dirty dquots
5714 	 */
5715 	dquot_writeback_dquots(sb, -1);
5716 	/*
5717 	 * Data writeback is possible w/o journal transaction, so barrier must
5718 	 * being sent at the end of the function. But we can skip it if
5719 	 * transaction_commit will do it for us.
5720 	 */
5721 	if (sbi->s_journal) {
5722 		target = jbd2_get_latest_transaction(sbi->s_journal);
5723 		if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
5724 		    !jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
5725 			needs_barrier = true;
5726 
5727 		if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
5728 			if (wait)
5729 				ret = jbd2_log_wait_commit(sbi->s_journal,
5730 							   target);
5731 		}
5732 	} else if (wait && test_opt(sb, BARRIER))
5733 		needs_barrier = true;
5734 	if (needs_barrier) {
5735 		int err;
5736 		err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL);
5737 		if (!ret)
5738 			ret = err;
5739 	}
5740 
5741 	return ret;
5742 }
5743 
5744 /*
5745  * LVM calls this function before a (read-only) snapshot is created.  This
5746  * gives us a chance to flush the journal completely and mark the fs clean.
5747  *
5748  * Note that only this function cannot bring a filesystem to be in a clean
5749  * state independently. It relies on upper layer to stop all data & metadata
5750  * modifications.
5751  */
ext4_freeze(struct super_block * sb)5752 static int ext4_freeze(struct super_block *sb)
5753 {
5754 	int error = 0;
5755 	journal_t *journal;
5756 
5757 	if (sb_rdonly(sb))
5758 		return 0;
5759 
5760 	journal = EXT4_SB(sb)->s_journal;
5761 
5762 	if (journal) {
5763 		/* Now we set up the journal barrier. */
5764 		jbd2_journal_lock_updates(journal);
5765 
5766 		/*
5767 		 * Don't clear the needs_recovery flag if we failed to
5768 		 * flush the journal.
5769 		 */
5770 		error = jbd2_journal_flush(journal);
5771 		if (error < 0)
5772 			goto out;
5773 
5774 		/* Journal blocked and flushed, clear needs_recovery flag. */
5775 		ext4_clear_feature_journal_needs_recovery(sb);
5776 	}
5777 
5778 	error = ext4_commit_super(sb);
5779 out:
5780 	if (journal)
5781 		/* we rely on upper layer to stop further updates */
5782 		jbd2_journal_unlock_updates(journal);
5783 	return error;
5784 }
5785 
5786 /*
5787  * Called by LVM after the snapshot is done.  We need to reset the RECOVER
5788  * flag here, even though the filesystem is not technically dirty yet.
5789  */
ext4_unfreeze(struct super_block * sb)5790 static int ext4_unfreeze(struct super_block *sb)
5791 {
5792 	if (sb_rdonly(sb) || ext4_forced_shutdown(EXT4_SB(sb)))
5793 		return 0;
5794 
5795 	if (EXT4_SB(sb)->s_journal) {
5796 		/* Reset the needs_recovery flag before the fs is unlocked. */
5797 		ext4_set_feature_journal_needs_recovery(sb);
5798 	}
5799 
5800 	ext4_commit_super(sb);
5801 	return 0;
5802 }
5803 
5804 /*
5805  * Structure to save mount options for ext4_remount's benefit
5806  */
5807 struct ext4_mount_options {
5808 	unsigned long s_mount_opt;
5809 	unsigned long s_mount_opt2;
5810 	kuid_t s_resuid;
5811 	kgid_t s_resgid;
5812 	unsigned long s_commit_interval;
5813 	u32 s_min_batch_time, s_max_batch_time;
5814 #ifdef CONFIG_QUOTA
5815 	int s_jquota_fmt;
5816 	char *s_qf_names[EXT4_MAXQUOTAS];
5817 #endif
5818 };
5819 
ext4_remount(struct super_block * sb,int * flags,char * data)5820 static int ext4_remount(struct super_block *sb, int *flags, char *data)
5821 {
5822 	struct ext4_super_block *es;
5823 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5824 	unsigned long old_sb_flags, vfs_flags;
5825 	struct ext4_mount_options old_opts;
5826 	int enable_quota = 0;
5827 	ext4_group_t g;
5828 	unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
5829 	int err = 0;
5830 #ifdef CONFIG_QUOTA
5831 	int i, j;
5832 	char *to_free[EXT4_MAXQUOTAS];
5833 #endif
5834 	char *orig_data = kstrdup(data, GFP_KERNEL);
5835 
5836 	if (data && !orig_data)
5837 		return -ENOMEM;
5838 
5839 	/* Store the original options */
5840 	old_sb_flags = sb->s_flags;
5841 	old_opts.s_mount_opt = sbi->s_mount_opt;
5842 	old_opts.s_mount_opt2 = sbi->s_mount_opt2;
5843 	old_opts.s_resuid = sbi->s_resuid;
5844 	old_opts.s_resgid = sbi->s_resgid;
5845 	old_opts.s_commit_interval = sbi->s_commit_interval;
5846 	old_opts.s_min_batch_time = sbi->s_min_batch_time;
5847 	old_opts.s_max_batch_time = sbi->s_max_batch_time;
5848 #ifdef CONFIG_QUOTA
5849 	old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
5850 	for (i = 0; i < EXT4_MAXQUOTAS; i++)
5851 		if (sbi->s_qf_names[i]) {
5852 			char *qf_name = get_qf_name(sb, sbi, i);
5853 
5854 			old_opts.s_qf_names[i] = kstrdup(qf_name, GFP_KERNEL);
5855 			if (!old_opts.s_qf_names[i]) {
5856 				for (j = 0; j < i; j++)
5857 					kfree(old_opts.s_qf_names[j]);
5858 				kfree(orig_data);
5859 				return -ENOMEM;
5860 			}
5861 		} else
5862 			old_opts.s_qf_names[i] = NULL;
5863 #endif
5864 	if (sbi->s_journal && sbi->s_journal->j_task->io_context)
5865 		journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
5866 
5867 	/*
5868 	 * Some options can be enabled by ext4 and/or by VFS mount flag
5869 	 * either way we need to make sure it matches in both *flags and
5870 	 * s_flags. Copy those selected flags from *flags to s_flags
5871 	 */
5872 	vfs_flags = SB_LAZYTIME | SB_I_VERSION;
5873 	sb->s_flags = (sb->s_flags & ~vfs_flags) | (*flags & vfs_flags);
5874 
5875 	if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
5876 		err = -EINVAL;
5877 		goto restore_opts;
5878 	}
5879 
5880 	if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
5881 	    test_opt(sb, JOURNAL_CHECKSUM)) {
5882 		ext4_msg(sb, KERN_ERR, "changing journal_checksum "
5883 			 "during remount not supported; ignoring");
5884 		sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
5885 	}
5886 
5887 	if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
5888 		if (test_opt2(sb, EXPLICIT_DELALLOC)) {
5889 			ext4_msg(sb, KERN_ERR, "can't mount with "
5890 				 "both data=journal and delalloc");
5891 			err = -EINVAL;
5892 			goto restore_opts;
5893 		}
5894 		if (test_opt(sb, DIOREAD_NOLOCK)) {
5895 			ext4_msg(sb, KERN_ERR, "can't mount with "
5896 				 "both data=journal and dioread_nolock");
5897 			err = -EINVAL;
5898 			goto restore_opts;
5899 		}
5900 	} else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) {
5901 		if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
5902 			ext4_msg(sb, KERN_ERR, "can't mount with "
5903 				"journal_async_commit in data=ordered mode");
5904 			err = -EINVAL;
5905 			goto restore_opts;
5906 		}
5907 	}
5908 
5909 	if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_NO_MBCACHE) {
5910 		ext4_msg(sb, KERN_ERR, "can't enable nombcache during remount");
5911 		err = -EINVAL;
5912 		goto restore_opts;
5913 	}
5914 
5915 	if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
5916 		ext4_abort(sb, EXT4_ERR_ESHUTDOWN, "Abort forced by user");
5917 
5918 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
5919 		(test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
5920 
5921 	es = sbi->s_es;
5922 
5923 	if (sbi->s_journal) {
5924 		ext4_init_journal_params(sb, sbi->s_journal);
5925 		set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
5926 	}
5927 
5928 	/* Flush outstanding errors before changing fs state */
5929 	flush_work(&sbi->s_error_work);
5930 
5931 	if ((bool)(*flags & SB_RDONLY) != sb_rdonly(sb)) {
5932 		if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED)) {
5933 			err = -EROFS;
5934 			goto restore_opts;
5935 		}
5936 
5937 		if (*flags & SB_RDONLY) {
5938 			err = sync_filesystem(sb);
5939 			if (err < 0)
5940 				goto restore_opts;
5941 			err = dquot_suspend(sb, -1);
5942 			if (err < 0)
5943 				goto restore_opts;
5944 
5945 			/*
5946 			 * First of all, the unconditional stuff we have to do
5947 			 * to disable replay of the journal when we next remount
5948 			 */
5949 			sb->s_flags |= SB_RDONLY;
5950 
5951 			/*
5952 			 * OK, test if we are remounting a valid rw partition
5953 			 * readonly, and if so set the rdonly flag and then
5954 			 * mark the partition as valid again.
5955 			 */
5956 			if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
5957 			    (sbi->s_mount_state & EXT4_VALID_FS))
5958 				es->s_state = cpu_to_le16(sbi->s_mount_state);
5959 
5960 			if (sbi->s_journal) {
5961 				/*
5962 				 * We let remount-ro finish even if marking fs
5963 				 * as clean failed...
5964 				 */
5965 				ext4_mark_recovery_complete(sb, es);
5966 			}
5967 		} else {
5968 			/* Make sure we can mount this feature set readwrite */
5969 			if (ext4_has_feature_readonly(sb) ||
5970 			    !ext4_feature_set_ok(sb, 0)) {
5971 				err = -EROFS;
5972 				goto restore_opts;
5973 			}
5974 			/*
5975 			 * Make sure the group descriptor checksums
5976 			 * are sane.  If they aren't, refuse to remount r/w.
5977 			 */
5978 			for (g = 0; g < sbi->s_groups_count; g++) {
5979 				struct ext4_group_desc *gdp =
5980 					ext4_get_group_desc(sb, g, NULL);
5981 
5982 				if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
5983 					ext4_msg(sb, KERN_ERR,
5984 	       "ext4_remount: Checksum for group %u failed (%u!=%u)",
5985 		g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
5986 					       le16_to_cpu(gdp->bg_checksum));
5987 					err = -EFSBADCRC;
5988 					goto restore_opts;
5989 				}
5990 			}
5991 
5992 			/*
5993 			 * If we have an unprocessed orphan list hanging
5994 			 * around from a previously readonly bdev mount,
5995 			 * require a full umount/remount for now.
5996 			 */
5997 			if (es->s_last_orphan) {
5998 				ext4_msg(sb, KERN_WARNING, "Couldn't "
5999 				       "remount RDWR because of unprocessed "
6000 				       "orphan inode list.  Please "
6001 				       "umount/remount instead");
6002 				err = -EINVAL;
6003 				goto restore_opts;
6004 			}
6005 
6006 			/*
6007 			 * Mounting a RDONLY partition read-write, so reread
6008 			 * and store the current valid flag.  (It may have
6009 			 * been changed by e2fsck since we originally mounted
6010 			 * the partition.)
6011 			 */
6012 			if (sbi->s_journal) {
6013 				err = ext4_clear_journal_err(sb, es);
6014 				if (err)
6015 					goto restore_opts;
6016 			}
6017 			sbi->s_mount_state = le16_to_cpu(es->s_state);
6018 
6019 			err = ext4_setup_super(sb, es, 0);
6020 			if (err)
6021 				goto restore_opts;
6022 
6023 			sb->s_flags &= ~SB_RDONLY;
6024 			if (ext4_has_feature_mmp(sb))
6025 				if (ext4_multi_mount_protect(sb,
6026 						le64_to_cpu(es->s_mmp_block))) {
6027 					err = -EROFS;
6028 					goto restore_opts;
6029 				}
6030 			enable_quota = 1;
6031 		}
6032 	}
6033 
6034 	/*
6035 	 * Reinitialize lazy itable initialization thread based on
6036 	 * current settings
6037 	 */
6038 	if (sb_rdonly(sb) || !test_opt(sb, INIT_INODE_TABLE))
6039 		ext4_unregister_li_request(sb);
6040 	else {
6041 		ext4_group_t first_not_zeroed;
6042 		first_not_zeroed = ext4_has_uninit_itable(sb);
6043 		ext4_register_li_request(sb, first_not_zeroed);
6044 	}
6045 
6046 	/*
6047 	 * Handle creation of system zone data early because it can fail.
6048 	 * Releasing of existing data is done when we are sure remount will
6049 	 * succeed.
6050 	 */
6051 	if (test_opt(sb, BLOCK_VALIDITY) && !sbi->s_system_blks) {
6052 		err = ext4_setup_system_zone(sb);
6053 		if (err)
6054 			goto restore_opts;
6055 	}
6056 
6057 	if (sbi->s_journal == NULL && !(old_sb_flags & SB_RDONLY)) {
6058 		err = ext4_commit_super(sb);
6059 		if (err)
6060 			goto restore_opts;
6061 	}
6062 
6063 #ifdef CONFIG_QUOTA
6064 	/* Release old quota file names */
6065 	for (i = 0; i < EXT4_MAXQUOTAS; i++)
6066 		kfree(old_opts.s_qf_names[i]);
6067 	if (enable_quota) {
6068 		if (sb_any_quota_suspended(sb))
6069 			dquot_resume(sb, -1);
6070 		else if (ext4_has_feature_quota(sb)) {
6071 			err = ext4_enable_quotas(sb);
6072 			if (err)
6073 				goto restore_opts;
6074 		}
6075 	}
6076 #endif
6077 	if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
6078 		ext4_release_system_zone(sb);
6079 
6080 	if (!ext4_has_feature_mmp(sb) || sb_rdonly(sb))
6081 		ext4_stop_mmpd(sbi);
6082 
6083 	/*
6084 	 * Some options can be enabled by ext4 and/or by VFS mount flag
6085 	 * either way we need to make sure it matches in both *flags and
6086 	 * s_flags. Copy those selected flags from s_flags to *flags
6087 	 */
6088 	*flags = (*flags & ~vfs_flags) | (sb->s_flags & vfs_flags);
6089 
6090 	ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
6091 	kfree(orig_data);
6092 	return 0;
6093 
6094 restore_opts:
6095 	sb->s_flags = old_sb_flags;
6096 	sbi->s_mount_opt = old_opts.s_mount_opt;
6097 	sbi->s_mount_opt2 = old_opts.s_mount_opt2;
6098 	sbi->s_resuid = old_opts.s_resuid;
6099 	sbi->s_resgid = old_opts.s_resgid;
6100 	sbi->s_commit_interval = old_opts.s_commit_interval;
6101 	sbi->s_min_batch_time = old_opts.s_min_batch_time;
6102 	sbi->s_max_batch_time = old_opts.s_max_batch_time;
6103 	if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
6104 		ext4_release_system_zone(sb);
6105 #ifdef CONFIG_QUOTA
6106 	sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
6107 	for (i = 0; i < EXT4_MAXQUOTAS; i++) {
6108 		to_free[i] = get_qf_name(sb, sbi, i);
6109 		rcu_assign_pointer(sbi->s_qf_names[i], old_opts.s_qf_names[i]);
6110 	}
6111 	synchronize_rcu();
6112 	for (i = 0; i < EXT4_MAXQUOTAS; i++)
6113 		kfree(to_free[i]);
6114 #endif
6115 	if (!ext4_has_feature_mmp(sb) || sb_rdonly(sb))
6116 		ext4_stop_mmpd(sbi);
6117 	kfree(orig_data);
6118 	return err;
6119 }
6120 
6121 #ifdef CONFIG_QUOTA
ext4_statfs_project(struct super_block * sb,kprojid_t projid,struct kstatfs * buf)6122 static int ext4_statfs_project(struct super_block *sb,
6123 			       kprojid_t projid, struct kstatfs *buf)
6124 {
6125 	struct kqid qid;
6126 	struct dquot *dquot;
6127 	u64 limit;
6128 	u64 curblock;
6129 
6130 	qid = make_kqid_projid(projid);
6131 	dquot = dqget(sb, qid);
6132 	if (IS_ERR(dquot))
6133 		return PTR_ERR(dquot);
6134 	spin_lock(&dquot->dq_dqb_lock);
6135 
6136 	limit = min_not_zero(dquot->dq_dqb.dqb_bsoftlimit,
6137 			     dquot->dq_dqb.dqb_bhardlimit);
6138 	limit >>= sb->s_blocksize_bits;
6139 
6140 	if (limit && buf->f_blocks > limit) {
6141 		curblock = (dquot->dq_dqb.dqb_curspace +
6142 			    dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
6143 		buf->f_blocks = limit;
6144 		buf->f_bfree = buf->f_bavail =
6145 			(buf->f_blocks > curblock) ?
6146 			 (buf->f_blocks - curblock) : 0;
6147 	}
6148 
6149 	limit = min_not_zero(dquot->dq_dqb.dqb_isoftlimit,
6150 			     dquot->dq_dqb.dqb_ihardlimit);
6151 	if (limit && buf->f_files > limit) {
6152 		buf->f_files = limit;
6153 		buf->f_ffree =
6154 			(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
6155 			 (buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
6156 	}
6157 
6158 	spin_unlock(&dquot->dq_dqb_lock);
6159 	dqput(dquot);
6160 	return 0;
6161 }
6162 #endif
6163 
ext4_statfs(struct dentry * dentry,struct kstatfs * buf)6164 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
6165 {
6166 	struct super_block *sb = dentry->d_sb;
6167 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6168 	struct ext4_super_block *es = sbi->s_es;
6169 	ext4_fsblk_t overhead = 0, resv_blocks;
6170 	u64 fsid;
6171 	s64 bfree;
6172 	resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
6173 
6174 	if (!test_opt(sb, MINIX_DF))
6175 		overhead = sbi->s_overhead;
6176 
6177 	buf->f_type = EXT4_SUPER_MAGIC;
6178 	buf->f_bsize = sb->s_blocksize;
6179 	buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
6180 	bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
6181 		percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
6182 	/* prevent underflow in case that few free space is available */
6183 	buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
6184 	buf->f_bavail = buf->f_bfree -
6185 			(ext4_r_blocks_count(es) + resv_blocks);
6186 	if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
6187 		buf->f_bavail = 0;
6188 	buf->f_files = le32_to_cpu(es->s_inodes_count);
6189 	buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
6190 	buf->f_namelen = EXT4_NAME_LEN;
6191 	fsid = le64_to_cpup((void *)es->s_uuid) ^
6192 	       le64_to_cpup((void *)es->s_uuid + sizeof(u64));
6193 	buf->f_fsid = u64_to_fsid(fsid);
6194 
6195 #ifdef CONFIG_QUOTA
6196 	if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
6197 	    sb_has_quota_limits_enabled(sb, PRJQUOTA))
6198 		ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
6199 #endif
6200 	return 0;
6201 }
6202 
6203 
6204 #ifdef CONFIG_QUOTA
6205 
6206 /*
6207  * Helper functions so that transaction is started before we acquire dqio_sem
6208  * to keep correct lock ordering of transaction > dqio_sem
6209  */
dquot_to_inode(struct dquot * dquot)6210 static inline struct inode *dquot_to_inode(struct dquot *dquot)
6211 {
6212 	return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
6213 }
6214 
ext4_write_dquot(struct dquot * dquot)6215 static int ext4_write_dquot(struct dquot *dquot)
6216 {
6217 	int ret, err;
6218 	handle_t *handle;
6219 	struct inode *inode;
6220 
6221 	inode = dquot_to_inode(dquot);
6222 	handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
6223 				    EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
6224 	if (IS_ERR(handle))
6225 		return PTR_ERR(handle);
6226 	ret = dquot_commit(dquot);
6227 	err = ext4_journal_stop(handle);
6228 	if (!ret)
6229 		ret = err;
6230 	return ret;
6231 }
6232 
ext4_acquire_dquot(struct dquot * dquot)6233 static int ext4_acquire_dquot(struct dquot *dquot)
6234 {
6235 	int ret, err;
6236 	handle_t *handle;
6237 
6238 	handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
6239 				    EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
6240 	if (IS_ERR(handle))
6241 		return PTR_ERR(handle);
6242 	ret = dquot_acquire(dquot);
6243 	err = ext4_journal_stop(handle);
6244 	if (!ret)
6245 		ret = err;
6246 	return ret;
6247 }
6248 
ext4_release_dquot(struct dquot * dquot)6249 static int ext4_release_dquot(struct dquot *dquot)
6250 {
6251 	int ret, err;
6252 	handle_t *handle;
6253 
6254 	handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
6255 				    EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
6256 	if (IS_ERR(handle)) {
6257 		/* Release dquot anyway to avoid endless cycle in dqput() */
6258 		dquot_release(dquot);
6259 		return PTR_ERR(handle);
6260 	}
6261 	ret = dquot_release(dquot);
6262 	err = ext4_journal_stop(handle);
6263 	if (!ret)
6264 		ret = err;
6265 	return ret;
6266 }
6267 
ext4_mark_dquot_dirty(struct dquot * dquot)6268 static int ext4_mark_dquot_dirty(struct dquot *dquot)
6269 {
6270 	struct super_block *sb = dquot->dq_sb;
6271 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6272 
6273 	/* Are we journaling quotas? */
6274 	if (ext4_has_feature_quota(sb) ||
6275 	    sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
6276 		dquot_mark_dquot_dirty(dquot);
6277 		return ext4_write_dquot(dquot);
6278 	} else {
6279 		return dquot_mark_dquot_dirty(dquot);
6280 	}
6281 }
6282 
ext4_write_info(struct super_block * sb,int type)6283 static int ext4_write_info(struct super_block *sb, int type)
6284 {
6285 	int ret, err;
6286 	handle_t *handle;
6287 
6288 	/* Data block + inode block */
6289 	handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
6290 	if (IS_ERR(handle))
6291 		return PTR_ERR(handle);
6292 	ret = dquot_commit_info(sb, type);
6293 	err = ext4_journal_stop(handle);
6294 	if (!ret)
6295 		ret = err;
6296 	return ret;
6297 }
6298 
6299 /*
6300  * Turn on quotas during mount time - we need to find
6301  * the quota file and such...
6302  */
ext4_quota_on_mount(struct super_block * sb,int type)6303 static int ext4_quota_on_mount(struct super_block *sb, int type)
6304 {
6305 	return dquot_quota_on_mount(sb, get_qf_name(sb, EXT4_SB(sb), type),
6306 					EXT4_SB(sb)->s_jquota_fmt, type);
6307 }
6308 
lockdep_set_quota_inode(struct inode * inode,int subclass)6309 static void lockdep_set_quota_inode(struct inode *inode, int subclass)
6310 {
6311 	struct ext4_inode_info *ei = EXT4_I(inode);
6312 
6313 	/* The first argument of lockdep_set_subclass has to be
6314 	 * *exactly* the same as the argument to init_rwsem() --- in
6315 	 * this case, in init_once() --- or lockdep gets unhappy
6316 	 * because the name of the lock is set using the
6317 	 * stringification of the argument to init_rwsem().
6318 	 */
6319 	(void) ei;	/* shut up clang warning if !CONFIG_LOCKDEP */
6320 	lockdep_set_subclass(&ei->i_data_sem, subclass);
6321 }
6322 
6323 /*
6324  * Standard function to be called on quota_on
6325  */
ext4_quota_on(struct super_block * sb,int type,int format_id,const struct path * path)6326 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
6327 			 const struct path *path)
6328 {
6329 	int err;
6330 
6331 	if (!test_opt(sb, QUOTA))
6332 		return -EINVAL;
6333 
6334 	/* Quotafile not on the same filesystem? */
6335 	if (path->dentry->d_sb != sb)
6336 		return -EXDEV;
6337 
6338 	/* Quota already enabled for this file? */
6339 	if (IS_NOQUOTA(d_inode(path->dentry)))
6340 		return -EBUSY;
6341 
6342 	/* Journaling quota? */
6343 	if (EXT4_SB(sb)->s_qf_names[type]) {
6344 		/* Quotafile not in fs root? */
6345 		if (path->dentry->d_parent != sb->s_root)
6346 			ext4_msg(sb, KERN_WARNING,
6347 				"Quota file not on filesystem root. "
6348 				"Journaled quota will not work");
6349 		sb_dqopt(sb)->flags |= DQUOT_NOLIST_DIRTY;
6350 	} else {
6351 		/*
6352 		 * Clear the flag just in case mount options changed since
6353 		 * last time.
6354 		 */
6355 		sb_dqopt(sb)->flags &= ~DQUOT_NOLIST_DIRTY;
6356 	}
6357 
6358 	/*
6359 	 * When we journal data on quota file, we have to flush journal to see
6360 	 * all updates to the file when we bypass pagecache...
6361 	 */
6362 	if (EXT4_SB(sb)->s_journal &&
6363 	    ext4_should_journal_data(d_inode(path->dentry))) {
6364 		/*
6365 		 * We don't need to lock updates but journal_flush() could
6366 		 * otherwise be livelocked...
6367 		 */
6368 		jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
6369 		err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
6370 		jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
6371 		if (err)
6372 			return err;
6373 	}
6374 
6375 	lockdep_set_quota_inode(path->dentry->d_inode, I_DATA_SEM_QUOTA);
6376 	err = dquot_quota_on(sb, type, format_id, path);
6377 	if (err) {
6378 		lockdep_set_quota_inode(path->dentry->d_inode,
6379 					     I_DATA_SEM_NORMAL);
6380 	} else {
6381 		struct inode *inode = d_inode(path->dentry);
6382 		handle_t *handle;
6383 
6384 		/*
6385 		 * Set inode flags to prevent userspace from messing with quota
6386 		 * files. If this fails, we return success anyway since quotas
6387 		 * are already enabled and this is not a hard failure.
6388 		 */
6389 		inode_lock(inode);
6390 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
6391 		if (IS_ERR(handle))
6392 			goto unlock_inode;
6393 		EXT4_I(inode)->i_flags |= EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL;
6394 		inode_set_flags(inode, S_NOATIME | S_IMMUTABLE,
6395 				S_NOATIME | S_IMMUTABLE);
6396 		err = ext4_mark_inode_dirty(handle, inode);
6397 		ext4_journal_stop(handle);
6398 	unlock_inode:
6399 		inode_unlock(inode);
6400 	}
6401 	return err;
6402 }
6403 
ext4_quota_enable(struct super_block * sb,int type,int format_id,unsigned int flags)6404 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
6405 			     unsigned int flags)
6406 {
6407 	int err;
6408 	struct inode *qf_inode;
6409 	unsigned long qf_inums[EXT4_MAXQUOTAS] = {
6410 		le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
6411 		le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
6412 		le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
6413 	};
6414 
6415 	BUG_ON(!ext4_has_feature_quota(sb));
6416 
6417 	if (!qf_inums[type])
6418 		return -EPERM;
6419 
6420 	qf_inode = ext4_iget(sb, qf_inums[type], EXT4_IGET_SPECIAL);
6421 	if (IS_ERR(qf_inode)) {
6422 		ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
6423 		return PTR_ERR(qf_inode);
6424 	}
6425 
6426 	/* Don't account quota for quota files to avoid recursion */
6427 	qf_inode->i_flags |= S_NOQUOTA;
6428 	lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA);
6429 	err = dquot_load_quota_inode(qf_inode, type, format_id, flags);
6430 	if (err)
6431 		lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL);
6432 	iput(qf_inode);
6433 
6434 	return err;
6435 }
6436 
6437 /* Enable usage tracking for all quota types. */
ext4_enable_quotas(struct super_block * sb)6438 static int ext4_enable_quotas(struct super_block *sb)
6439 {
6440 	int type, err = 0;
6441 	unsigned long qf_inums[EXT4_MAXQUOTAS] = {
6442 		le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
6443 		le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
6444 		le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
6445 	};
6446 	bool quota_mopt[EXT4_MAXQUOTAS] = {
6447 		test_opt(sb, USRQUOTA),
6448 		test_opt(sb, GRPQUOTA),
6449 		test_opt(sb, PRJQUOTA),
6450 	};
6451 
6452 	sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
6453 	for (type = 0; type < EXT4_MAXQUOTAS; type++) {
6454 		if (qf_inums[type]) {
6455 			err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
6456 				DQUOT_USAGE_ENABLED |
6457 				(quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
6458 			if (err) {
6459 				ext4_warning(sb,
6460 					"Failed to enable quota tracking "
6461 					"(type=%d, err=%d). Please run "
6462 					"e2fsck to fix.", type, err);
6463 				for (type--; type >= 0; type--)
6464 					dquot_quota_off(sb, type);
6465 
6466 				return err;
6467 			}
6468 		}
6469 	}
6470 	return 0;
6471 }
6472 
ext4_quota_off(struct super_block * sb,int type)6473 static int ext4_quota_off(struct super_block *sb, int type)
6474 {
6475 	struct inode *inode = sb_dqopt(sb)->files[type];
6476 	handle_t *handle;
6477 	int err;
6478 
6479 	/* Force all delayed allocation blocks to be allocated.
6480 	 * Caller already holds s_umount sem */
6481 	if (test_opt(sb, DELALLOC))
6482 		sync_filesystem(sb);
6483 
6484 	if (!inode || !igrab(inode))
6485 		goto out;
6486 
6487 	err = dquot_quota_off(sb, type);
6488 	if (err || ext4_has_feature_quota(sb))
6489 		goto out_put;
6490 
6491 	inode_lock(inode);
6492 	/*
6493 	 * Update modification times of quota files when userspace can
6494 	 * start looking at them. If we fail, we return success anyway since
6495 	 * this is not a hard failure and quotas are already disabled.
6496 	 */
6497 	handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
6498 	if (IS_ERR(handle)) {
6499 		err = PTR_ERR(handle);
6500 		goto out_unlock;
6501 	}
6502 	EXT4_I(inode)->i_flags &= ~(EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL);
6503 	inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
6504 	inode->i_mtime = inode->i_ctime = current_time(inode);
6505 	err = ext4_mark_inode_dirty(handle, inode);
6506 	ext4_journal_stop(handle);
6507 out_unlock:
6508 	inode_unlock(inode);
6509 out_put:
6510 	lockdep_set_quota_inode(inode, I_DATA_SEM_NORMAL);
6511 	iput(inode);
6512 	return err;
6513 out:
6514 	return dquot_quota_off(sb, type);
6515 }
6516 
6517 /* Read data from quotafile - avoid pagecache and such because we cannot afford
6518  * acquiring the locks... As quota files are never truncated and quota code
6519  * itself serializes the operations (and no one else should touch the files)
6520  * we don't have to be afraid of races */
ext4_quota_read(struct super_block * sb,int type,char * data,size_t len,loff_t off)6521 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
6522 			       size_t len, loff_t off)
6523 {
6524 	struct inode *inode = sb_dqopt(sb)->files[type];
6525 	ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
6526 	int offset = off & (sb->s_blocksize - 1);
6527 	int tocopy;
6528 	size_t toread;
6529 	struct buffer_head *bh;
6530 	loff_t i_size = i_size_read(inode);
6531 
6532 	if (off > i_size)
6533 		return 0;
6534 	if (off+len > i_size)
6535 		len = i_size-off;
6536 	toread = len;
6537 	while (toread > 0) {
6538 		tocopy = sb->s_blocksize - offset < toread ?
6539 				sb->s_blocksize - offset : toread;
6540 		bh = ext4_bread(NULL, inode, blk, 0);
6541 		if (IS_ERR(bh))
6542 			return PTR_ERR(bh);
6543 		if (!bh)	/* A hole? */
6544 			memset(data, 0, tocopy);
6545 		else
6546 			memcpy(data, bh->b_data+offset, tocopy);
6547 		brelse(bh);
6548 		offset = 0;
6549 		toread -= tocopy;
6550 		data += tocopy;
6551 		blk++;
6552 	}
6553 	return len;
6554 }
6555 
6556 /* Write to quotafile (we know the transaction is already started and has
6557  * enough credits) */
ext4_quota_write(struct super_block * sb,int type,const char * data,size_t len,loff_t off)6558 static ssize_t ext4_quota_write(struct super_block *sb, int type,
6559 				const char *data, size_t len, loff_t off)
6560 {
6561 	struct inode *inode = sb_dqopt(sb)->files[type];
6562 	ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
6563 	int err = 0, err2 = 0, offset = off & (sb->s_blocksize - 1);
6564 	int retries = 0;
6565 	struct buffer_head *bh;
6566 	handle_t *handle = journal_current_handle();
6567 
6568 	if (EXT4_SB(sb)->s_journal && !handle) {
6569 		ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6570 			" cancelled because transaction is not started",
6571 			(unsigned long long)off, (unsigned long long)len);
6572 		return -EIO;
6573 	}
6574 	/*
6575 	 * Since we account only one data block in transaction credits,
6576 	 * then it is impossible to cross a block boundary.
6577 	 */
6578 	if (sb->s_blocksize - offset < len) {
6579 		ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6580 			" cancelled because not block aligned",
6581 			(unsigned long long)off, (unsigned long long)len);
6582 		return -EIO;
6583 	}
6584 
6585 	do {
6586 		bh = ext4_bread(handle, inode, blk,
6587 				EXT4_GET_BLOCKS_CREATE |
6588 				EXT4_GET_BLOCKS_METADATA_NOFAIL);
6589 	} while (PTR_ERR(bh) == -ENOSPC &&
6590 		 ext4_should_retry_alloc(inode->i_sb, &retries));
6591 	if (IS_ERR(bh))
6592 		return PTR_ERR(bh);
6593 	if (!bh)
6594 		goto out;
6595 	BUFFER_TRACE(bh, "get write access");
6596 	err = ext4_journal_get_write_access(handle, bh);
6597 	if (err) {
6598 		brelse(bh);
6599 		return err;
6600 	}
6601 	lock_buffer(bh);
6602 	memcpy(bh->b_data+offset, data, len);
6603 	flush_dcache_page(bh->b_page);
6604 	unlock_buffer(bh);
6605 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
6606 	brelse(bh);
6607 out:
6608 	if (inode->i_size < off + len) {
6609 		i_size_write(inode, off + len);
6610 		EXT4_I(inode)->i_disksize = inode->i_size;
6611 		err2 = ext4_mark_inode_dirty(handle, inode);
6612 		if (unlikely(err2 && !err))
6613 			err = err2;
6614 	}
6615 	return err ? err : len;
6616 }
6617 #endif
6618 
ext4_mount(struct file_system_type * fs_type,int flags,const char * dev_name,void * data)6619 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
6620 		       const char *dev_name, void *data)
6621 {
6622 	return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
6623 }
6624 
6625 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
register_as_ext2(void)6626 static inline void register_as_ext2(void)
6627 {
6628 	int err = register_filesystem(&ext2_fs_type);
6629 	if (err)
6630 		printk(KERN_WARNING
6631 		       "EXT4-fs: Unable to register as ext2 (%d)\n", err);
6632 }
6633 
unregister_as_ext2(void)6634 static inline void unregister_as_ext2(void)
6635 {
6636 	unregister_filesystem(&ext2_fs_type);
6637 }
6638 
ext2_feature_set_ok(struct super_block * sb)6639 static inline int ext2_feature_set_ok(struct super_block *sb)
6640 {
6641 	if (ext4_has_unknown_ext2_incompat_features(sb))
6642 		return 0;
6643 	if (sb_rdonly(sb))
6644 		return 1;
6645 	if (ext4_has_unknown_ext2_ro_compat_features(sb))
6646 		return 0;
6647 	return 1;
6648 }
6649 #else
register_as_ext2(void)6650 static inline void register_as_ext2(void) { }
unregister_as_ext2(void)6651 static inline void unregister_as_ext2(void) { }
ext2_feature_set_ok(struct super_block * sb)6652 static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
6653 #endif
6654 
register_as_ext3(void)6655 static inline void register_as_ext3(void)
6656 {
6657 	int err = register_filesystem(&ext3_fs_type);
6658 	if (err)
6659 		printk(KERN_WARNING
6660 		       "EXT4-fs: Unable to register as ext3 (%d)\n", err);
6661 }
6662 
unregister_as_ext3(void)6663 static inline void unregister_as_ext3(void)
6664 {
6665 	unregister_filesystem(&ext3_fs_type);
6666 }
6667 
ext3_feature_set_ok(struct super_block * sb)6668 static inline int ext3_feature_set_ok(struct super_block *sb)
6669 {
6670 	if (ext4_has_unknown_ext3_incompat_features(sb))
6671 		return 0;
6672 	if (!ext4_has_feature_journal(sb))
6673 		return 0;
6674 	if (sb_rdonly(sb))
6675 		return 1;
6676 	if (ext4_has_unknown_ext3_ro_compat_features(sb))
6677 		return 0;
6678 	return 1;
6679 }
6680 
6681 static struct file_system_type ext4_fs_type = {
6682 	.owner		= THIS_MODULE,
6683 	.name		= "ext4",
6684 	.mount		= ext4_mount,
6685 	.kill_sb	= kill_block_super,
6686 	.fs_flags	= FS_REQUIRES_DEV,
6687 };
6688 MODULE_ALIAS_FS("ext4");
6689 
6690 /* Shared across all ext4 file systems */
6691 wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
6692 
ext4_init_fs(void)6693 static int __init ext4_init_fs(void)
6694 {
6695 	int i, err;
6696 
6697 	ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
6698 	ext4_li_info = NULL;
6699 	mutex_init(&ext4_li_mtx);
6700 
6701 	/* Build-time check for flags consistency */
6702 	ext4_check_flag_values();
6703 
6704 	for (i = 0; i < EXT4_WQ_HASH_SZ; i++)
6705 		init_waitqueue_head(&ext4__ioend_wq[i]);
6706 
6707 	err = ext4_init_es();
6708 	if (err)
6709 		return err;
6710 
6711 	err = ext4_init_pending();
6712 	if (err)
6713 		goto out7;
6714 
6715 	err = ext4_init_post_read_processing();
6716 	if (err)
6717 		goto out6;
6718 
6719 	err = ext4_init_pageio();
6720 	if (err)
6721 		goto out5;
6722 
6723 	err = ext4_init_system_zone();
6724 	if (err)
6725 		goto out4;
6726 
6727 	err = ext4_init_sysfs();
6728 	if (err)
6729 		goto out3;
6730 
6731 	err = ext4_init_mballoc();
6732 	if (err)
6733 		goto out2;
6734 	err = init_inodecache();
6735 	if (err)
6736 		goto out1;
6737 
6738 	err = ext4_fc_init_dentry_cache();
6739 	if (err)
6740 		goto out05;
6741 
6742 	register_as_ext3();
6743 	register_as_ext2();
6744 	err = register_filesystem(&ext4_fs_type);
6745 	if (err)
6746 		goto out;
6747 
6748 	return 0;
6749 out:
6750 	unregister_as_ext2();
6751 	unregister_as_ext3();
6752 out05:
6753 	destroy_inodecache();
6754 out1:
6755 	ext4_exit_mballoc();
6756 out2:
6757 	ext4_exit_sysfs();
6758 out3:
6759 	ext4_exit_system_zone();
6760 out4:
6761 	ext4_exit_pageio();
6762 out5:
6763 	ext4_exit_post_read_processing();
6764 out6:
6765 	ext4_exit_pending();
6766 out7:
6767 	ext4_exit_es();
6768 
6769 	return err;
6770 }
6771 
ext4_exit_fs(void)6772 static void __exit ext4_exit_fs(void)
6773 {
6774 	ext4_destroy_lazyinit_thread();
6775 	unregister_as_ext2();
6776 	unregister_as_ext3();
6777 	unregister_filesystem(&ext4_fs_type);
6778 	destroy_inodecache();
6779 	ext4_exit_mballoc();
6780 	ext4_exit_sysfs();
6781 	ext4_exit_system_zone();
6782 	ext4_exit_pageio();
6783 	ext4_exit_post_read_processing();
6784 	ext4_exit_es();
6785 	ext4_exit_pending();
6786 }
6787 
6788 MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
6789 MODULE_DESCRIPTION("Fourth Extended Filesystem");
6790 MODULE_LICENSE("GPL");
6791 MODULE_SOFTDEP("pre: crc32c");
6792 module_init(ext4_init_fs)
6793 module_exit(ext4_exit_fs)
6794