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