xref: /linux/fs/fat/inode.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/fat/inode.c
4  *
5  *  Written 1992,1993 by Werner Almesberger
6  *  VFAT extensions by Gordon Chaffee, merged with msdos fs by Henrik Storner
7  *  Rewritten for the constant inumbers support by Al Viro
8  *
9  *  Fixes:
10  *
11  *	Max Cohan: Fixed invalid FSINFO offset when info_sector is 0
12  */
13 
14 #include <linux/module.h>
15 #include <linux/pagemap.h>
16 #include <linux/mpage.h>
17 #include <linux/vfs.h>
18 #include <linux/seq_file.h>
19 #include <linux/uio.h>
20 #include <linux/blkdev.h>
21 #include <linux/backing-dev.h>
22 #include <linux/unaligned.h>
23 #include <linux/overflow.h>
24 #include <linux/random.h>
25 #include <linux/iversion.h>
26 #include <linux/fs_struct.h>
27 #include "fat.h"
28 
29 #ifndef CONFIG_FAT_DEFAULT_IOCHARSET
30 /* if user don't select VFAT, this is undefined. */
31 #define CONFIG_FAT_DEFAULT_IOCHARSET	""
32 #endif
33 
34 #define KB_IN_SECTORS 2
35 
36 /* DOS dates from 1980/1/1 through 2107/12/31 */
37 #define FAT_DATE_MIN (0<<9 | 1<<5 | 1)
38 #define FAT_DATE_MAX (127<<9 | 12<<5 | 31)
39 #define FAT_TIME_MAX (23<<11 | 59<<5 | 29)
40 
41 /*
42  * A deserialized copy of the on-disk structure laid out in struct
43  * fat_boot_sector.
44  */
45 struct fat_bios_param_block {
46 	u16	fat_sector_size;
47 	u8	fat_sec_per_clus;
48 	u16	fat_reserved;
49 	u8	fat_fats;
50 	u16	fat_dir_entries;
51 	u16	fat_sectors;
52 	u16	fat_fat_length;
53 	u32	fat_total_sect;
54 
55 	u8	fat16_state;
56 	u32	fat16_vol_id;
57 
58 	u32	fat32_length;
59 	u32	fat32_root_cluster;
60 	u16	fat32_info_sector;
61 	u8	fat32_state;
62 	u32	fat32_vol_id;
63 };
64 
65 static int fat_default_codepage = CONFIG_FAT_DEFAULT_CODEPAGE;
66 static char fat_default_iocharset[] = CONFIG_FAT_DEFAULT_IOCHARSET;
67 
68 static struct fat_floppy_defaults {
69 	unsigned nr_sectors;
70 	unsigned sec_per_clus;
71 	unsigned dir_entries;
72 	unsigned media;
73 	unsigned fat_length;
74 } floppy_defaults[] = {
75 {
76 	.nr_sectors = 160 * KB_IN_SECTORS,
77 	.sec_per_clus = 1,
78 	.dir_entries = 64,
79 	.media = 0xFE,
80 	.fat_length = 1,
81 },
82 {
83 	.nr_sectors = 180 * KB_IN_SECTORS,
84 	.sec_per_clus = 1,
85 	.dir_entries = 64,
86 	.media = 0xFC,
87 	.fat_length = 2,
88 },
89 {
90 	.nr_sectors = 320 * KB_IN_SECTORS,
91 	.sec_per_clus = 2,
92 	.dir_entries = 112,
93 	.media = 0xFF,
94 	.fat_length = 1,
95 },
96 {
97 	.nr_sectors = 360 * KB_IN_SECTORS,
98 	.sec_per_clus = 2,
99 	.dir_entries = 112,
100 	.media = 0xFD,
101 	.fat_length = 2,
102 },
103 };
104 
105 int fat_add_clusters(struct inode *inode, int nr_cluster)
106 {
107 	int err, cluster;
108 
109 	err = fat_alloc_chain(inode, &cluster, nr_cluster);
110 	if (err)
111 		return err;
112 	/* FIXME: this cluster should be added after data of this
113 	 * cluster is writed */
114 	err = fat_chain_add(inode, cluster, nr_cluster);
115 	if (err)
116 		fat_free_clusters(inode, cluster);
117 	return err;
118 }
119 
120 static inline int __fat_get_block(struct inode *inode, sector_t iblock,
121 				  unsigned long *max_blocks,
122 				  struct buffer_head *bh_result, int create)
123 {
124 	struct super_block *sb = inode->i_sb;
125 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
126 	unsigned long mapped_blocks;
127 	sector_t phys, last_block;
128 	int err, offset;
129 
130 	err = fat_bmap(inode, iblock, &phys, &mapped_blocks, create, false);
131 	if (err)
132 		return err;
133 	if (phys) {
134 		map_bh(bh_result, sb, phys);
135 		*max_blocks = min(mapped_blocks, *max_blocks);
136 		return 0;
137 	}
138 	if (!create)
139 		return 0;
140 
141 	if (iblock != MSDOS_I(inode)->mmu_private >> sb->s_blocksize_bits) {
142 		fat_fs_error(sb, "corrupted file size (i_pos %lld, %lld)",
143 			MSDOS_I(inode)->i_pos, MSDOS_I(inode)->mmu_private);
144 		return -EIO;
145 	}
146 
147 	last_block = inode->i_blocks >> (sb->s_blocksize_bits - 9);
148 	offset = (unsigned long)iblock & (sbi->sec_per_clus - 1);
149 	/*
150 	 * allocate a cluster according to the following.
151 	 * 1) no more available blocks
152 	 * 2) not part of fallocate region
153 	 */
154 	if (!offset && !(iblock < last_block)) {
155 		/* TODO: multiple cluster allocation would be desirable. */
156 		err = fat_add_clusters(inode, 1);
157 		if (err)
158 			return err;
159 	}
160 	/* available blocks on this cluster */
161 	mapped_blocks = sbi->sec_per_clus - offset;
162 
163 	*max_blocks = min(mapped_blocks, *max_blocks);
164 	MSDOS_I(inode)->mmu_private += *max_blocks << sb->s_blocksize_bits;
165 
166 	err = fat_bmap(inode, iblock, &phys, &mapped_blocks, create, false);
167 	if (err)
168 		return err;
169 	if (!phys) {
170 		fat_fs_error(sb,
171 			     "invalid FAT chain (i_pos %lld, last_block %llu)",
172 			     MSDOS_I(inode)->i_pos,
173 			     (unsigned long long)last_block);
174 		return -EIO;
175 	}
176 
177 	BUG_ON(*max_blocks != mapped_blocks);
178 	set_buffer_new(bh_result);
179 	map_bh(bh_result, sb, phys);
180 
181 	return 0;
182 }
183 
184 static int fat_get_block(struct inode *inode, sector_t iblock,
185 			 struct buffer_head *bh_result, int create)
186 {
187 	struct super_block *sb = inode->i_sb;
188 	unsigned long max_blocks = bh_result->b_size >> inode->i_blkbits;
189 	int err;
190 
191 	err = __fat_get_block(inode, iblock, &max_blocks, bh_result, create);
192 	if (err)
193 		return err;
194 	bh_result->b_size = max_blocks << sb->s_blocksize_bits;
195 	return 0;
196 }
197 
198 static int fat_writepages(struct address_space *mapping,
199 			  struct writeback_control *wbc)
200 {
201 	return mpage_writepages(mapping, wbc, fat_get_block);
202 }
203 
204 static int fat_read_folio(struct file *file, struct folio *folio)
205 {
206 	return mpage_read_folio(folio, fat_get_block);
207 }
208 
209 static void fat_readahead(struct readahead_control *rac)
210 {
211 	mpage_readahead(rac, fat_get_block);
212 }
213 
214 static void fat_write_failed(struct address_space *mapping, loff_t to)
215 {
216 	struct inode *inode = mapping->host;
217 
218 	if (to > inode->i_size) {
219 		truncate_pagecache(inode, inode->i_size);
220 		down_write(&MSDOS_I(inode)->truncate_lock);
221 		fat_truncate_blocks(inode, inode->i_size);
222 		up_write(&MSDOS_I(inode)->truncate_lock);
223 	}
224 }
225 
226 static int fat_write_begin(const struct kiocb *iocb,
227 			   struct address_space *mapping,
228 			   loff_t pos, unsigned len,
229 			   struct folio **foliop, void **fsdata)
230 {
231 	int err;
232 
233 	err = cont_write_begin(iocb, mapping, pos, len,
234 				foliop, fsdata, fat_get_block,
235 				&MSDOS_I(mapping->host)->mmu_private);
236 	if (err < 0)
237 		fat_write_failed(mapping, pos + len);
238 	return err;
239 }
240 
241 static int fat_write_end(const struct kiocb *iocb,
242 			 struct address_space *mapping,
243 			 loff_t pos, unsigned len, unsigned copied,
244 			 struct folio *folio, void *fsdata)
245 {
246 	struct inode *inode = mapping->host;
247 	int err;
248 	err = generic_write_end(iocb, mapping, pos, len, copied, folio, fsdata);
249 	if (err < len)
250 		fat_write_failed(mapping, pos + len);
251 	if (!(err < 0) && !(MSDOS_I(inode)->i_attrs & ATTR_ARCH)) {
252 		fat_truncate_time(inode, NULL, FAT_UPDATE_CMTIME);
253 		MSDOS_I(inode)->i_attrs |= ATTR_ARCH;
254 		mark_inode_dirty(inode);
255 	}
256 	return err;
257 }
258 
259 static ssize_t fat_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
260 {
261 	struct file *file = iocb->ki_filp;
262 	struct address_space *mapping = file->f_mapping;
263 	struct inode *inode = mapping->host;
264 	size_t count = iov_iter_count(iter);
265 	loff_t offset = iocb->ki_pos;
266 	ssize_t ret;
267 
268 	if (iov_iter_rw(iter) == WRITE) {
269 		/*
270 		 * FIXME: blockdev_direct_IO() doesn't use ->write_begin(),
271 		 * so we need to update the ->mmu_private to block boundary.
272 		 *
273 		 * But we must fill the remaining area or hole by nul for
274 		 * updating ->mmu_private.
275 		 *
276 		 * Return 0, and fallback to normal buffered write.
277 		 */
278 		loff_t size = offset + count;
279 		if (MSDOS_I(inode)->mmu_private < size)
280 			return 0;
281 	}
282 
283 	/*
284 	 * FAT need to use the DIO_LOCKING for avoiding the race
285 	 * condition of fat_get_block() and ->truncate().
286 	 */
287 	ret = blockdev_direct_IO(iocb, inode, iter, fat_get_block);
288 	if (ret < 0 && iov_iter_rw(iter) == WRITE)
289 		fat_write_failed(mapping, offset + count);
290 
291 	return ret;
292 }
293 
294 static int fat_get_block_bmap(struct inode *inode, sector_t iblock,
295 		struct buffer_head *bh_result, int create)
296 {
297 	struct super_block *sb = inode->i_sb;
298 	unsigned long max_blocks = bh_result->b_size >> inode->i_blkbits;
299 	int err;
300 	sector_t bmap;
301 	unsigned long mapped_blocks;
302 
303 	BUG_ON(create != 0);
304 
305 	err = fat_bmap(inode, iblock, &bmap, &mapped_blocks, create, true);
306 	if (err)
307 		return err;
308 
309 	if (bmap) {
310 		map_bh(bh_result, sb, bmap);
311 		max_blocks = min(mapped_blocks, max_blocks);
312 	}
313 
314 	bh_result->b_size = max_blocks << sb->s_blocksize_bits;
315 
316 	return 0;
317 }
318 
319 static sector_t _fat_bmap(struct address_space *mapping, sector_t block)
320 {
321 	sector_t blocknr;
322 
323 	/* fat_get_cluster() assumes the requested blocknr isn't truncated. */
324 	down_read(&MSDOS_I(mapping->host)->truncate_lock);
325 	blocknr = generic_block_bmap(mapping, block, fat_get_block_bmap);
326 	up_read(&MSDOS_I(mapping->host)->truncate_lock);
327 
328 	return blocknr;
329 }
330 
331 /*
332  * fat_block_truncate_page() zeroes out a mapping from file offset `from'
333  * up to the end of the block which corresponds to `from'.
334  * This is required during truncate to physically zeroout the tail end
335  * of that block so it doesn't yield old data if the file is later grown.
336  * Also, avoid causing failure from fsx for cases of "data past EOF"
337  */
338 int fat_block_truncate_page(struct inode *inode, loff_t from)
339 {
340 	return block_truncate_page(inode->i_mapping, from, fat_get_block);
341 }
342 
343 static const struct address_space_operations fat_aops = {
344 	.dirty_folio	= block_dirty_folio,
345 	.invalidate_folio = block_invalidate_folio,
346 	.read_folio	= fat_read_folio,
347 	.readahead	= fat_readahead,
348 	.writepages	= fat_writepages,
349 	.write_begin	= fat_write_begin,
350 	.write_end	= fat_write_end,
351 	.direct_IO	= fat_direct_IO,
352 	.bmap		= _fat_bmap,
353 	.migrate_folio	= buffer_migrate_folio,
354 };
355 
356 /*
357  * New FAT inode stuff. We do the following:
358  *	a) i_ino is constant and has nothing with on-disk location.
359  *	b) FAT manages its own cache of directory entries.
360  *	c) *This* cache is indexed by on-disk location.
361  *	d) inode has an associated directory entry, all right, but
362  *		it may be unhashed.
363  *	e) currently entries are stored within struct inode. That should
364  *		change.
365  *	f) we deal with races in the following way:
366  *		1. readdir() and lookup() do FAT-dir-cache lookup.
367  *		2. rename() unhashes the F-d-c entry and rehashes it in
368  *			a new place.
369  *		3. unlink() and rmdir() unhash F-d-c entry.
370  *		4. fat_write_inode() checks whether the thing is unhashed.
371  *			If it is we silently return. If it isn't we do bread(),
372  *			check if the location is still valid and retry if it
373  *			isn't. Otherwise we do changes.
374  *		5. Spinlock is used to protect hash/unhash/location check/lookup
375  *		6. fat_evict_inode() unhashes the F-d-c entry.
376  *		7. lookup() and readdir() do igrab() if they find a F-d-c entry
377  *			and consider negative result as cache miss.
378  */
379 
380 static void fat_hash_init(struct super_block *sb)
381 {
382 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
383 	int i;
384 
385 	spin_lock_init(&sbi->inode_hash_lock);
386 	for (i = 0; i < FAT_HASH_SIZE; i++)
387 		INIT_HLIST_HEAD(&sbi->inode_hashtable[i]);
388 }
389 
390 static inline unsigned long fat_hash(loff_t i_pos)
391 {
392 	return hash_32(i_pos, FAT_HASH_BITS);
393 }
394 
395 static void dir_hash_init(struct super_block *sb)
396 {
397 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
398 	int i;
399 
400 	spin_lock_init(&sbi->dir_hash_lock);
401 	for (i = 0; i < FAT_HASH_SIZE; i++)
402 		INIT_HLIST_HEAD(&sbi->dir_hashtable[i]);
403 }
404 
405 void fat_attach(struct inode *inode, loff_t i_pos)
406 {
407 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
408 
409 	if (inode->i_ino != MSDOS_ROOT_INO) {
410 		struct hlist_head *head =   sbi->inode_hashtable
411 					  + fat_hash(i_pos);
412 
413 		spin_lock(&sbi->inode_hash_lock);
414 		MSDOS_I(inode)->i_pos = i_pos;
415 		hlist_add_head(&MSDOS_I(inode)->i_fat_hash, head);
416 		spin_unlock(&sbi->inode_hash_lock);
417 	}
418 
419 	/* If NFS support is enabled, cache the mapping of start cluster
420 	 * to directory inode. This is used during reconnection of
421 	 * dentries to the filesystem root.
422 	 */
423 	if (S_ISDIR(inode->i_mode) && sbi->options.nfs) {
424 		struct hlist_head *d_head = sbi->dir_hashtable;
425 		d_head += fat_dir_hash(MSDOS_I(inode)->i_logstart);
426 
427 		spin_lock(&sbi->dir_hash_lock);
428 		hlist_add_head(&MSDOS_I(inode)->i_dir_hash, d_head);
429 		spin_unlock(&sbi->dir_hash_lock);
430 	}
431 }
432 EXPORT_SYMBOL_GPL(fat_attach);
433 
434 void fat_detach(struct inode *inode)
435 {
436 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
437 	spin_lock(&sbi->inode_hash_lock);
438 	MSDOS_I(inode)->i_pos = 0;
439 	hlist_del_init(&MSDOS_I(inode)->i_fat_hash);
440 	spin_unlock(&sbi->inode_hash_lock);
441 
442 	if (S_ISDIR(inode->i_mode) && sbi->options.nfs) {
443 		spin_lock(&sbi->dir_hash_lock);
444 		hlist_del_init(&MSDOS_I(inode)->i_dir_hash);
445 		spin_unlock(&sbi->dir_hash_lock);
446 	}
447 }
448 EXPORT_SYMBOL_GPL(fat_detach);
449 
450 struct inode *fat_iget(struct super_block *sb, loff_t i_pos)
451 {
452 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
453 	struct hlist_head *head = sbi->inode_hashtable + fat_hash(i_pos);
454 	struct msdos_inode_info *i;
455 	struct inode *inode = NULL;
456 
457 	spin_lock(&sbi->inode_hash_lock);
458 	hlist_for_each_entry(i, head, i_fat_hash) {
459 		BUG_ON(i->vfs_inode.i_sb != sb);
460 		if (i->i_pos != i_pos)
461 			continue;
462 		inode = igrab(&i->vfs_inode);
463 		if (inode)
464 			break;
465 	}
466 	spin_unlock(&sbi->inode_hash_lock);
467 	return inode;
468 }
469 
470 static int is_exec(unsigned char *extension)
471 {
472 	unsigned char exe_extensions[] = "EXECOMBAT", *walk;
473 
474 	for (walk = exe_extensions; *walk; walk += 3)
475 		if (!strncmp(extension, walk, 3))
476 			return 1;
477 	return 0;
478 }
479 
480 static int fat_calc_dir_size(struct inode *inode)
481 {
482 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
483 	int ret, fclus, dclus;
484 
485 	inode->i_size = 0;
486 	if (MSDOS_I(inode)->i_start == 0)
487 		return 0;
488 
489 	ret = fat_get_cluster(inode, FAT_ENT_EOF, &fclus, &dclus);
490 	if (ret < 0)
491 		return ret;
492 	inode->i_size = (fclus + 1) << sbi->cluster_bits;
493 
494 	return 0;
495 }
496 
497 static int fat_validate_dir(struct inode *dir)
498 {
499 	struct super_block *sb = dir->i_sb;
500 
501 	if (dir->i_nlink < 2) {
502 		/* Directory should have "."/".." entries at least. */
503 		fat_fs_error(sb, "corrupted directory (invalid entries)");
504 		return -EIO;
505 	}
506 	if (MSDOS_I(dir)->i_start == 0 ||
507 	    MSDOS_I(dir)->i_start == MSDOS_SB(sb)->root_cluster) {
508 		/* Directory should point valid cluster. */
509 		fat_fs_error(sb, "corrupted directory (invalid i_start)");
510 		return -EIO;
511 	}
512 	return 0;
513 }
514 
515 /* doesn't deal with root inode */
516 int fat_fill_inode(struct inode *inode, struct msdos_dir_entry *de)
517 {
518 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
519 	struct timespec64 mtime;
520 	int error;
521 
522 	MSDOS_I(inode)->i_pos = 0;
523 	inode->i_uid = sbi->options.fs_uid;
524 	inode->i_gid = sbi->options.fs_gid;
525 	inode_inc_iversion(inode);
526 	inode->i_generation = get_random_u32();
527 
528 	if ((de->attr & ATTR_DIR) && !IS_FREE(de->name)) {
529 		inode->i_generation &= ~1;
530 		inode->i_mode = fat_make_mode(sbi, de->attr, S_IRWXUGO);
531 		inode->i_op = sbi->dir_ops;
532 		inode->i_fop = &fat_dir_operations;
533 
534 		MSDOS_I(inode)->i_start = fat_get_start(sbi, de);
535 		MSDOS_I(inode)->i_logstart = MSDOS_I(inode)->i_start;
536 		error = fat_calc_dir_size(inode);
537 		if (error < 0)
538 			return error;
539 		MSDOS_I(inode)->mmu_private = inode->i_size;
540 
541 		set_nlink(inode, fat_subdirs(inode));
542 
543 		error = fat_validate_dir(inode);
544 		if (error < 0)
545 			return error;
546 	} else { /* not a directory */
547 		inode->i_generation |= 1;
548 		inode->i_mode = fat_make_mode(sbi, de->attr,
549 			((sbi->options.showexec && !is_exec(de->name + 8))
550 			 ? S_IRUGO|S_IWUGO : S_IRWXUGO));
551 		MSDOS_I(inode)->i_start = fat_get_start(sbi, de);
552 
553 		MSDOS_I(inode)->i_logstart = MSDOS_I(inode)->i_start;
554 		inode->i_size = le32_to_cpu(de->size);
555 		inode->i_op = &fat_file_inode_operations;
556 		inode->i_fop = &fat_file_operations;
557 		inode->i_mapping->a_ops = &fat_aops;
558 		MSDOS_I(inode)->mmu_private = inode->i_size;
559 	}
560 	if (de->attr & ATTR_SYS) {
561 		if (sbi->options.sys_immutable)
562 			inode->i_flags |= S_IMMUTABLE;
563 	}
564 	fat_save_attrs(inode, de->attr);
565 
566 	inode->i_blocks = ((inode->i_size + (sbi->cluster_size - 1))
567 			   & ~((loff_t)sbi->cluster_size - 1)) >> 9;
568 
569 	fat_time_fat2unix(sbi, &mtime, de->time, de->date, 0);
570 	inode_set_mtime_to_ts(inode, mtime);
571 	inode_set_ctime_to_ts(inode, mtime);
572 	if (sbi->options.isvfat) {
573 		struct timespec64 atime;
574 
575 		fat_time_fat2unix(sbi, &atime, 0, de->adate, 0);
576 		inode_set_atime_to_ts(inode, atime);
577 		fat_time_fat2unix(sbi, &MSDOS_I(inode)->i_crtime, de->ctime,
578 				  de->cdate, de->ctime_cs);
579 	} else
580 		inode_set_atime_to_ts(inode, fat_truncate_atime(sbi, &mtime));
581 
582 	return 0;
583 }
584 
585 static inline void fat_lock_build_inode(struct msdos_sb_info *sbi)
586 {
587 	if (sbi->options.nfs == FAT_NFS_NOSTALE_RO)
588 		mutex_lock(&sbi->nfs_build_inode_lock);
589 }
590 
591 static inline void fat_unlock_build_inode(struct msdos_sb_info *sbi)
592 {
593 	if (sbi->options.nfs == FAT_NFS_NOSTALE_RO)
594 		mutex_unlock(&sbi->nfs_build_inode_lock);
595 }
596 
597 struct inode *fat_build_inode(struct super_block *sb,
598 			struct msdos_dir_entry *de, loff_t i_pos)
599 {
600 	struct inode *inode;
601 	int err;
602 
603 	fat_lock_build_inode(MSDOS_SB(sb));
604 	inode = fat_iget(sb, i_pos);
605 	if (inode)
606 		goto out;
607 	inode = new_inode(sb);
608 	if (!inode) {
609 		inode = ERR_PTR(-ENOMEM);
610 		goto out;
611 	}
612 	inode->i_ino = iunique(sb, MSDOS_ROOT_INO);
613 	inode_set_iversion(inode, 1);
614 	err = fat_fill_inode(inode, de);
615 	if (err) {
616 		iput(inode);
617 		inode = ERR_PTR(err);
618 		goto out;
619 	}
620 	fat_attach(inode, i_pos);
621 	insert_inode_hash(inode);
622 out:
623 	fat_unlock_build_inode(MSDOS_SB(sb));
624 	return inode;
625 }
626 
627 EXPORT_SYMBOL_GPL(fat_build_inode);
628 
629 static int __fat_write_inode(struct inode *inode);
630 
631 static int fat_sync_inode_metadata(struct inode *inode,
632 				   struct writeback_control *wbc)
633 {
634 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
635 	struct buffer_head *bh;
636 	loff_t i_pos;
637 	sector_t blocknr;
638 	int offset;
639 
640 	/* The root directory has no directory entry of its own. */
641 	if (inode->i_ino == MSDOS_ROOT_INO)
642 		goto sync_bhs;
643 	i_pos = fat_i_pos_read(sbi, inode);
644 	if (!i_pos)
645 		goto sync_bhs;
646 
647 	fat_get_blknr_offset(sbi, i_pos, &blocknr, &offset);
648 	bh = sb_find_get_block_nonatomic(inode->i_sb, blocknr);
649 	/*
650 	 * Buffer present? We leave buffer_dirty check for sync_dirty_buffer()
651 	 * for proper synchronization with ongoing IO.
652 	 */
653 	if (bh && buffer_uptodate(bh)) {
654 		sync_dirty_buffer(bh);
655 		if (buffer_write_io_error(bh)) {
656 			brelse(bh);
657 			return -EIO;
658 		}
659 	}
660 	brelse(bh);
661 sync_bhs:
662 	return mmb_sync(&MSDOS_I(inode)->i_metadata_bhs);
663 }
664 
665 static void fat_free_eofblocks(struct inode *inode)
666 {
667 	/* Release unwritten fallocated blocks on inode eviction. */
668 	if ((inode->i_blocks << 9) >
669 			round_up(MSDOS_I(inode)->mmu_private,
670 				MSDOS_SB(inode->i_sb)->cluster_size)) {
671 		int err;
672 
673 		fat_truncate_blocks(inode, MSDOS_I(inode)->mmu_private);
674 		/* Fallocate results in updating the i_start/iogstart
675 		 * for the zero byte file. So, make it return to
676 		 * original state during evict and commit it to avoid
677 		 * any corruption on the next access to the cluster
678 		 * chain for the file.
679 		 */
680 		err = sync_inode_metadata(inode, inode_needs_sync(inode));
681 		if (err) {
682 			fat_msg(inode->i_sb, KERN_WARNING, "Failed to "
683 					"update on disk inode for unused "
684 					"fallocated blocks, inode could be "
685 					"corrupted. Please run fsck");
686 		}
687 
688 	}
689 }
690 
691 static void fat_evict_inode(struct inode *inode)
692 {
693 	truncate_inode_pages_final(&inode->i_data);
694 	if (!inode->i_nlink) {
695 		inode->i_size = 0;
696 		fat_truncate_blocks(inode, 0);
697 	} else {
698 		fat_free_eofblocks(inode);
699 	}
700 
701 	mmb_invalidate(&MSDOS_I(inode)->i_metadata_bhs);
702 	clear_inode(inode);
703 	fat_cache_inval_inode(inode);
704 	fat_detach(inode);
705 }
706 
707 static void fat_set_state(struct super_block *sb,
708 			unsigned int set, unsigned int force)
709 {
710 	struct buffer_head *bh;
711 	struct fat_boot_sector *b;
712 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
713 
714 	/* do not change any thing if mounted read only */
715 	if (sb_rdonly(sb) && !force)
716 		return;
717 
718 	/* do not change state if fs was dirty */
719 	if (sbi->dirty) {
720 		/* warn only on set (mount). */
721 		if (set)
722 			fat_msg(sb, KERN_WARNING, "Volume was not properly "
723 				"unmounted. Some data may be corrupt. "
724 				"Please run fsck.");
725 		return;
726 	}
727 
728 	bh = sb_bread(sb, 0);
729 	if (bh == NULL) {
730 		fat_msg(sb, KERN_ERR, "unable to read boot sector "
731 			"to mark fs as dirty");
732 		return;
733 	}
734 
735 	b = (struct fat_boot_sector *) bh->b_data;
736 
737 	if (is_fat32(sbi)) {
738 		if (set)
739 			b->fat32.state |= FAT_STATE_DIRTY;
740 		else
741 			b->fat32.state &= ~FAT_STATE_DIRTY;
742 	} else /* fat 16 and 12 */ {
743 		if (set)
744 			b->fat16.state |= FAT_STATE_DIRTY;
745 		else
746 			b->fat16.state &= ~FAT_STATE_DIRTY;
747 	}
748 
749 	mark_buffer_dirty(bh);
750 	sync_dirty_buffer(bh);
751 	brelse(bh);
752 }
753 
754 static void fat_reset_iocharset(struct fat_mount_options *opts)
755 {
756 	if (opts->iocharset != fat_default_iocharset) {
757 		/* Note: opts->iocharset can be NULL here */
758 		kfree(opts->iocharset);
759 		opts->iocharset = fat_default_iocharset;
760 	}
761 }
762 
763 static void delayed_free(struct rcu_head *p)
764 {
765 	struct msdos_sb_info *sbi = container_of(p, struct msdos_sb_info, rcu);
766 	unload_nls(sbi->nls_disk);
767 	unload_nls(sbi->nls_io);
768 	fat_reset_iocharset(&sbi->options);
769 	kfree(sbi);
770 }
771 
772 static void fat_put_super(struct super_block *sb)
773 {
774 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
775 
776 	fat_set_state(sb, 0, 0);
777 
778 	iput(sbi->fsinfo_inode);
779 	iput(sbi->fat_inode);
780 
781 	call_rcu(&sbi->rcu, delayed_free);
782 }
783 
784 static struct kmem_cache *fat_inode_cachep;
785 
786 static struct inode *fat_alloc_inode(struct super_block *sb)
787 {
788 	struct msdos_inode_info *ei;
789 	ei = alloc_inode_sb(sb, fat_inode_cachep, GFP_NOFS);
790 	if (!ei)
791 		return NULL;
792 
793 	init_rwsem(&ei->truncate_lock);
794 	/* Zeroing to allow iput() even if partial initialized inode. */
795 	ei->mmu_private = 0;
796 	ei->i_start = 0;
797 	ei->i_logstart = 0;
798 	ei->i_attrs = 0;
799 	ei->i_pos = 0;
800 	ei->i_crtime.tv_sec = 0;
801 	ei->i_crtime.tv_nsec = 0;
802 	mmb_init(&ei->i_metadata_bhs, &ei->vfs_inode.i_data);
803 
804 	return &ei->vfs_inode;
805 }
806 
807 static void fat_free_inode(struct inode *inode)
808 {
809 	kmem_cache_free(fat_inode_cachep, MSDOS_I(inode));
810 }
811 
812 static void init_once(void *foo)
813 {
814 	struct msdos_inode_info *ei = (struct msdos_inode_info *)foo;
815 
816 	spin_lock_init(&ei->cache_lru_lock);
817 	ei->nr_caches = 0;
818 	ei->cache_valid_id = FAT_CACHE_VALID + 1;
819 	INIT_LIST_HEAD(&ei->cache_lru);
820 	INIT_HLIST_NODE(&ei->i_fat_hash);
821 	INIT_HLIST_NODE(&ei->i_dir_hash);
822 	inode_init_once(&ei->vfs_inode);
823 }
824 
825 static int __init fat_init_inodecache(void)
826 {
827 	fat_inode_cachep = kmem_cache_create("fat_inode_cache",
828 					     sizeof(struct msdos_inode_info),
829 					     0, (SLAB_RECLAIM_ACCOUNT|
830 						SLAB_ACCOUNT),
831 					     init_once);
832 	if (fat_inode_cachep == NULL)
833 		return -ENOMEM;
834 	return 0;
835 }
836 
837 static void __exit fat_destroy_inodecache(void)
838 {
839 	/*
840 	 * Make sure all delayed rcu free inodes are flushed before we
841 	 * destroy cache.
842 	 */
843 	rcu_barrier();
844 	kmem_cache_destroy(fat_inode_cachep);
845 }
846 
847 int fat_reconfigure(struct fs_context *fc)
848 {
849 	bool new_rdonly;
850 	struct super_block *sb = fc->root->d_sb;
851 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
852 	fc->sb_flags |= SB_NODIRATIME | (sbi->options.isvfat ? 0 : SB_NOATIME);
853 
854 	sync_filesystem(sb);
855 
856 	/* make sure we update state on remount. */
857 	new_rdonly = fc->sb_flags & SB_RDONLY;
858 	if (new_rdonly != sb_rdonly(sb)) {
859 		if (new_rdonly)
860 			fat_set_state(sb, 0, 0);
861 		else
862 			fat_set_state(sb, 1, 1);
863 	}
864 	return 0;
865 }
866 EXPORT_SYMBOL_GPL(fat_reconfigure);
867 
868 static int fat_statfs(struct dentry *dentry, struct kstatfs *buf)
869 {
870 	struct super_block *sb = dentry->d_sb;
871 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
872 	u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
873 
874 	/* If the count of free cluster is still unknown, counts it here. */
875 	if (sbi->free_clusters == -1 || !sbi->free_clus_valid) {
876 		int err = fat_count_free_clusters(dentry->d_sb);
877 		if (err)
878 			return err;
879 	}
880 
881 	buf->f_type = dentry->d_sb->s_magic;
882 	buf->f_bsize = sbi->cluster_size;
883 	buf->f_blocks = sbi->max_cluster - FAT_START_ENT;
884 	buf->f_bfree = sbi->free_clusters;
885 	buf->f_bavail = sbi->free_clusters;
886 	buf->f_fsid = u64_to_fsid(id);
887 	buf->f_namelen =
888 		(sbi->options.isvfat ? FAT_LFN_LEN : 12) * NLS_MAX_CHARSET_SIZE;
889 
890 	return 0;
891 }
892 
893 static int __fat_write_inode(struct inode *inode)
894 {
895 	struct super_block *sb = inode->i_sb;
896 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
897 	struct buffer_head *bh;
898 	struct msdos_dir_entry *raw_entry;
899 	struct timespec64 mtime;
900 	loff_t i_pos;
901 	sector_t blocknr;
902 	int offset;
903 
904 	if (inode->i_ino == MSDOS_ROOT_INO) {
905 		/* No entry to update but the metadata bh list may need syncing. */
906 		set_inode_metadata_writeback(inode);
907 		return 0;
908 	}
909 
910 retry:
911 	i_pos = fat_i_pos_read(sbi, inode);
912 	if (!i_pos)
913 		return 0;
914 
915 	fat_get_blknr_offset(sbi, i_pos, &blocknr, &offset);
916 	bh = sb_bread(sb, blocknr);
917 	if (!bh) {
918 		fat_msg(sb, KERN_ERR, "unable to read inode block "
919 		       "for updating (i_pos %lld)", i_pos);
920 		return -EIO;
921 	}
922 	spin_lock(&sbi->inode_hash_lock);
923 	if (i_pos != MSDOS_I(inode)->i_pos) {
924 		spin_unlock(&sbi->inode_hash_lock);
925 		brelse(bh);
926 		goto retry;
927 	}
928 
929 	raw_entry = &((struct msdos_dir_entry *) (bh->b_data))[offset];
930 	if (S_ISDIR(inode->i_mode))
931 		raw_entry->size = 0;
932 	else
933 		raw_entry->size = cpu_to_le32(inode->i_size);
934 	raw_entry->attr = fat_make_attrs(inode);
935 	fat_set_start(raw_entry, MSDOS_I(inode)->i_logstart);
936 	mtime = inode_get_mtime(inode);
937 	fat_time_unix2fat(sbi, &mtime, &raw_entry->time,
938 			  &raw_entry->date, NULL);
939 	if (sbi->options.isvfat) {
940 		struct timespec64 ts = inode_get_atime(inode);
941 		__le16 atime;
942 
943 		fat_time_unix2fat(sbi, &ts, &atime, &raw_entry->adate, NULL);
944 		fat_time_unix2fat(sbi, &MSDOS_I(inode)->i_crtime, &raw_entry->ctime,
945 				  &raw_entry->cdate, &raw_entry->ctime_cs);
946 	}
947 	spin_unlock(&sbi->inode_hash_lock);
948 	mark_buffer_dirty(bh);
949 	brelse(bh);
950 	set_inode_metadata_writeback(inode);
951 	return 0;
952 }
953 
954 static int fat_write_inode(struct inode *inode, struct writeback_control *wbc)
955 {
956 	int err;
957 
958 	if (inode->i_ino == MSDOS_FSINFO_INO) {
959 		struct super_block *sb = inode->i_sb;
960 
961 		mutex_lock(&MSDOS_SB(sb)->s_lock);
962 		err = fat_clusters_flush(sb);
963 		mutex_unlock(&MSDOS_SB(sb)->s_lock);
964 	} else
965 		err = __fat_write_inode(inode);
966 
967 	return err;
968 }
969 
970 static int fat_show_options(struct seq_file *m, struct dentry *root);
971 static const struct super_operations fat_sops = {
972 	.alloc_inode	= fat_alloc_inode,
973 	.free_inode	= fat_free_inode,
974 	.write_inode	= fat_write_inode,
975 	.sync_inode_metadata = fat_sync_inode_metadata,
976 	.evict_inode	= fat_evict_inode,
977 	.put_super	= fat_put_super,
978 	.statfs		= fat_statfs,
979 	.show_options	= fat_show_options,
980 };
981 
982 static int fat_show_options(struct seq_file *m, struct dentry *root)
983 {
984 	struct msdos_sb_info *sbi = MSDOS_SB(root->d_sb);
985 	struct fat_mount_options *opts = &sbi->options;
986 	int isvfat = opts->isvfat;
987 
988 	if (!uid_eq(opts->fs_uid, GLOBAL_ROOT_UID))
989 		seq_printf(m, ",uid=%u",
990 				from_kuid_munged(&init_user_ns, opts->fs_uid));
991 	if (!gid_eq(opts->fs_gid, GLOBAL_ROOT_GID))
992 		seq_printf(m, ",gid=%u",
993 				from_kgid_munged(&init_user_ns, opts->fs_gid));
994 	seq_printf(m, ",fmask=%04o", opts->fs_fmask);
995 	seq_printf(m, ",dmask=%04o", opts->fs_dmask);
996 	if (opts->allow_utime)
997 		seq_printf(m, ",allow_utime=%04o", opts->allow_utime);
998 	if (sbi->nls_disk)
999 		/* strip "cp" prefix from displayed option */
1000 		seq_printf(m, ",codepage=%s", &sbi->nls_disk->charset[2]);
1001 	if (isvfat) {
1002 		if (sbi->nls_io)
1003 			seq_printf(m, ",iocharset=%s", sbi->nls_io->charset);
1004 
1005 		switch (opts->shortname) {
1006 		case VFAT_SFN_DISPLAY_WIN95 | VFAT_SFN_CREATE_WIN95:
1007 			seq_puts(m, ",shortname=win95");
1008 			break;
1009 		case VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WINNT:
1010 			seq_puts(m, ",shortname=winnt");
1011 			break;
1012 		case VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WIN95:
1013 			seq_puts(m, ",shortname=mixed");
1014 			break;
1015 		case VFAT_SFN_DISPLAY_LOWER | VFAT_SFN_CREATE_WIN95:
1016 			seq_puts(m, ",shortname=lower");
1017 			break;
1018 		default:
1019 			seq_puts(m, ",shortname=unknown");
1020 			break;
1021 		}
1022 	}
1023 	if (opts->name_check != 'n')
1024 		seq_printf(m, ",check=%c", opts->name_check);
1025 	if (opts->usefree)
1026 		seq_puts(m, ",usefree");
1027 	if (opts->quiet)
1028 		seq_puts(m, ",quiet");
1029 	if (opts->showexec)
1030 		seq_puts(m, ",showexec");
1031 	if (opts->sys_immutable)
1032 		seq_puts(m, ",sys_immutable");
1033 	if (!isvfat) {
1034 		if (opts->dotsOK)
1035 			seq_puts(m, ",dotsOK=yes");
1036 		if (opts->nocase)
1037 			seq_puts(m, ",nocase");
1038 	} else {
1039 		if (opts->utf8)
1040 			seq_puts(m, ",utf8");
1041 		if (opts->unicode_xlate)
1042 			seq_puts(m, ",uni_xlate");
1043 		if (!opts->numtail)
1044 			seq_puts(m, ",nonumtail");
1045 		if (opts->rodir)
1046 			seq_puts(m, ",rodir");
1047 	}
1048 	if (opts->flush)
1049 		seq_puts(m, ",flush");
1050 	if (opts->tz_set) {
1051 		if (opts->time_offset)
1052 			seq_printf(m, ",time_offset=%d", opts->time_offset);
1053 		else
1054 			seq_puts(m, ",tz=UTC");
1055 	}
1056 	if (opts->errors == FAT_ERRORS_CONT)
1057 		seq_puts(m, ",errors=continue");
1058 	else if (opts->errors == FAT_ERRORS_PANIC)
1059 		seq_puts(m, ",errors=panic");
1060 	else
1061 		seq_puts(m, ",errors=remount-ro");
1062 	if (opts->nfs == FAT_NFS_NOSTALE_RO)
1063 		seq_puts(m, ",nfs=nostale_ro");
1064 	else if (opts->nfs)
1065 		seq_puts(m, ",nfs=stale_rw");
1066 	if (opts->discard)
1067 		seq_puts(m, ",discard");
1068 	if (opts->dos1xfloppy)
1069 		seq_puts(m, ",dos1xfloppy");
1070 
1071 	return 0;
1072 }
1073 
1074 enum {
1075 	Opt_check, Opt_uid, Opt_gid, Opt_umask, Opt_dmask, Opt_fmask,
1076 	Opt_allow_utime, Opt_codepage, Opt_usefree, Opt_nocase, Opt_quiet,
1077 	Opt_showexec, Opt_debug, Opt_immutable, Opt_dots, Opt_dotsOK,
1078 	Opt_charset, Opt_shortname, Opt_utf8, Opt_utf8_bool,
1079 	Opt_uni_xl, Opt_uni_xl_bool, Opt_nonumtail, Opt_nonumtail_bool,
1080 	Opt_obsolete, Opt_flush, Opt_tz, Opt_rodir, Opt_errors, Opt_discard,
1081 	Opt_nfs, Opt_nfs_enum, Opt_time_offset, Opt_dos1xfloppy,
1082 };
1083 
1084 static const struct constant_table fat_param_check[] = {
1085 	{"relaxed",	'r'},
1086 	{"r",		'r'},
1087 	{"strict",	's'},
1088 	{"s",		's'},
1089 	{"normal",	'n'},
1090 	{"n",		'n'},
1091 	{}
1092 };
1093 
1094 static const struct constant_table fat_param_tz[] = {
1095 	{"UTC",		0},
1096 	{}
1097 };
1098 
1099 static const struct constant_table fat_param_errors[] = {
1100 	{"continue",	FAT_ERRORS_CONT},
1101 	{"panic",	FAT_ERRORS_PANIC},
1102 	{"remount-ro",	FAT_ERRORS_RO},
1103 	{}
1104 };
1105 
1106 
1107 static const struct constant_table fat_param_nfs[] = {
1108 	{"stale_rw",	FAT_NFS_STALE_RW},
1109 	{"nostale_ro",	FAT_NFS_NOSTALE_RO},
1110 	{}
1111 };
1112 
1113 /*
1114  * These are all obsolete but we still reject invalid options.
1115  * The corresponding values are therefore meaningless.
1116  */
1117 static const struct constant_table fat_param_conv[] = {
1118 	{"binary",	0},
1119 	{"text",	0},
1120 	{"auto",	0},
1121 	{"b",		0},
1122 	{"t",		0},
1123 	{"a",		0},
1124 	{}
1125 };
1126 
1127 /* Core options. See below for vfat and msdos extras */
1128 const struct fs_parameter_spec fat_param_spec[] = {
1129 	fsparam_enum	("check",	Opt_check, fat_param_check),
1130 	fsparam_uid	("uid",		Opt_uid),
1131 	fsparam_gid	("gid",		Opt_gid),
1132 	fsparam_u32oct	("umask",	Opt_umask),
1133 	fsparam_u32oct	("dmask",	Opt_dmask),
1134 	fsparam_u32oct	("fmask",	Opt_fmask),
1135 	fsparam_u32oct	("allow_utime",	Opt_allow_utime),
1136 	fsparam_u32	("codepage",	Opt_codepage),
1137 	fsparam_flag	("usefree",	Opt_usefree),
1138 	fsparam_flag	("nocase",	Opt_nocase),
1139 	fsparam_flag	("quiet",	Opt_quiet),
1140 	fsparam_flag	("showexec",	Opt_showexec),
1141 	fsparam_flag	("debug",	Opt_debug),
1142 	fsparam_flag	("sys_immutable", Opt_immutable),
1143 	fsparam_flag	("flush",	Opt_flush),
1144 	fsparam_enum	("tz",		Opt_tz, fat_param_tz),
1145 	fsparam_s32	("time_offset",	Opt_time_offset),
1146 	fsparam_enum	("errors",	Opt_errors, fat_param_errors),
1147 	fsparam_flag	("discard",	Opt_discard),
1148 	fsparam_flag	("nfs",		Opt_nfs),
1149 	fsparam_enum	("nfs",		Opt_nfs_enum, fat_param_nfs),
1150 	fsparam_flag	("dos1xfloppy",	Opt_dos1xfloppy),
1151 	__fsparam(fs_param_is_enum,	"conv",
1152 		  Opt_obsolete, fs_param_deprecated, fat_param_conv),
1153 	__fsparam(fs_param_is_u32,	"fat",
1154 		  Opt_obsolete, fs_param_deprecated, NULL),
1155 	__fsparam(fs_param_is_u32,	"blocksize",
1156 		  Opt_obsolete, fs_param_deprecated, NULL),
1157 	__fsparam(fs_param_is_string,	"cvf_format",
1158 		  Opt_obsolete, fs_param_deprecated, NULL),
1159 	__fsparam(fs_param_is_string,	"cvf_options",
1160 		  Opt_obsolete, fs_param_deprecated, NULL),
1161 	__fsparam(NULL,			"posix",
1162 		  Opt_obsolete, fs_param_deprecated, NULL),
1163 	{}
1164 };
1165 EXPORT_SYMBOL_GPL(fat_param_spec);
1166 
1167 static const struct fs_parameter_spec msdos_param_spec[] = {
1168 	fsparam_flag_no	("dots",	Opt_dots),
1169 	fsparam_bool	("dotsOK",	Opt_dotsOK),
1170 	{}
1171 };
1172 
1173 static const struct constant_table fat_param_shortname[] = {
1174 	{"lower",	VFAT_SFN_DISPLAY_LOWER | VFAT_SFN_CREATE_WIN95},
1175 	{"win95",	VFAT_SFN_DISPLAY_WIN95 | VFAT_SFN_CREATE_WIN95},
1176 	{"winnt",	VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WINNT},
1177 	{"mixed",	VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WIN95},
1178 	{}
1179 };
1180 
1181 static const struct fs_parameter_spec vfat_param_spec[] = {
1182 	fsparam_string	("iocharset",	Opt_charset),
1183 	fsparam_enum	("shortname",	Opt_shortname, fat_param_shortname),
1184 	fsparam_flag	("utf8",	Opt_utf8),
1185 	fsparam_bool	("utf8",	Opt_utf8_bool),
1186 	fsparam_flag	("uni_xlate",	Opt_uni_xl),
1187 	fsparam_bool	("uni_xlate",	Opt_uni_xl_bool),
1188 	fsparam_flag	("nonumtail",	Opt_nonumtail),
1189 	fsparam_bool	("nonumtail",	Opt_nonumtail_bool),
1190 	fsparam_flag	("rodir",	Opt_rodir),
1191 	{}
1192 };
1193 
1194 int fat_parse_param(struct fs_context *fc, struct fs_parameter *param,
1195 			   bool is_vfat)
1196 {
1197 	struct fat_mount_options *opts = fc->fs_private;
1198 	struct fs_parse_result result;
1199 	int opt;
1200 
1201 	/* remount options have traditionally been ignored */
1202 	if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE)
1203 		return 0;
1204 
1205 	opt = fs_parse(fc, fat_param_spec, param, &result);
1206 	/* If option not found in fat_param_spec, try vfat/msdos options */
1207 	if (opt == -ENOPARAM) {
1208 		if (is_vfat)
1209 			opt = fs_parse(fc, vfat_param_spec, param, &result);
1210 		else
1211 			opt = fs_parse(fc, msdos_param_spec, param, &result);
1212 	}
1213 
1214 	if (opt < 0)
1215 		return opt;
1216 
1217 	switch (opt) {
1218 	case Opt_check:
1219 		opts->name_check = result.uint_32;
1220 		break;
1221 	case Opt_usefree:
1222 		opts->usefree = 1;
1223 		break;
1224 	case Opt_nocase:
1225 		if (!is_vfat)
1226 			opts->nocase = 1;
1227 		else {
1228 			/* for backward compatibility */
1229 			opts->shortname = VFAT_SFN_DISPLAY_WIN95
1230 				| VFAT_SFN_CREATE_WIN95;
1231 		}
1232 		break;
1233 	case Opt_quiet:
1234 		opts->quiet = 1;
1235 		break;
1236 	case Opt_showexec:
1237 		opts->showexec = 1;
1238 		break;
1239 	case Opt_debug:
1240 		opts->debug = 1;
1241 		break;
1242 	case Opt_immutable:
1243 		opts->sys_immutable = 1;
1244 		break;
1245 	case Opt_uid:
1246 		opts->fs_uid = result.uid;
1247 		break;
1248 	case Opt_gid:
1249 		opts->fs_gid = result.gid;
1250 		break;
1251 	case Opt_umask:
1252 		opts->fs_fmask = opts->fs_dmask = result.uint_32;
1253 		break;
1254 	case Opt_dmask:
1255 		opts->fs_dmask = result.uint_32;
1256 		break;
1257 	case Opt_fmask:
1258 		opts->fs_fmask = result.uint_32;
1259 		break;
1260 	case Opt_allow_utime:
1261 		opts->allow_utime = result.uint_32 & (S_IWGRP | S_IWOTH);
1262 		break;
1263 	case Opt_codepage:
1264 		opts->codepage = result.uint_32;
1265 		break;
1266 	case Opt_flush:
1267 		opts->flush = 1;
1268 		break;
1269 	case Opt_time_offset:
1270 		/*
1271 		 * GMT+-12 zones may have DST corrections so at least
1272 		 * 13 hours difference is needed. Make the limit 24
1273 		 * just in case someone invents something unusual.
1274 		 */
1275 		if (result.int_32 < -24 * 60 || result.int_32 > 24 * 60)
1276 			return -EINVAL;
1277 		opts->tz_set = 1;
1278 		opts->time_offset = result.int_32;
1279 		break;
1280 	case Opt_tz:
1281 		opts->tz_set = 1;
1282 		opts->time_offset = result.uint_32;
1283 		break;
1284 	case Opt_errors:
1285 		opts->errors = result.uint_32;
1286 		break;
1287 	case Opt_nfs:
1288 		opts->nfs = FAT_NFS_STALE_RW;
1289 		break;
1290 	case Opt_nfs_enum:
1291 		opts->nfs = result.uint_32;
1292 		break;
1293 	case Opt_dos1xfloppy:
1294 		opts->dos1xfloppy = 1;
1295 		break;
1296 
1297 	/* msdos specific */
1298 	case Opt_dots:	/* dots / nodots */
1299 		opts->dotsOK = !result.negated;
1300 		break;
1301 	case Opt_dotsOK:	/* dotsOK = yes/no */
1302 		opts->dotsOK = result.boolean;
1303 		break;
1304 
1305 	/* vfat specific */
1306 	case Opt_charset:
1307 		fat_reset_iocharset(opts);
1308 		opts->iocharset = param->string;
1309 		param->string = NULL;	/* Steal string */
1310 		break;
1311 	case Opt_shortname:
1312 		opts->shortname = result.uint_32;
1313 		break;
1314 	case Opt_utf8:
1315 		opts->utf8 = 1;
1316 		break;
1317 	case Opt_utf8_bool:
1318 		opts->utf8 = result.boolean;
1319 		break;
1320 	case Opt_uni_xl:
1321 		opts->unicode_xlate = 1;
1322 		break;
1323 	case Opt_uni_xl_bool:
1324 		opts->unicode_xlate = result.boolean;
1325 		break;
1326 	case Opt_nonumtail:
1327 		opts->numtail = 0;	/* negated option */
1328 		break;
1329 	case Opt_nonumtail_bool:
1330 		opts->numtail = !result.boolean; /* negated option */
1331 		break;
1332 	case Opt_rodir:
1333 		opts->rodir = 1;
1334 		break;
1335 	case Opt_discard:
1336 		opts->discard = 1;
1337 		break;
1338 
1339 	/* obsolete mount options */
1340 	case Opt_obsolete:
1341 		printk(KERN_INFO "FAT-fs: \"%s\" option is obsolete, "
1342 			"not supported now", param->key);
1343 		break;
1344 	default:
1345 		return -EINVAL;
1346 	}
1347 
1348 	return 0;
1349 }
1350 EXPORT_SYMBOL_GPL(fat_parse_param);
1351 
1352 static int fat_read_root(struct inode *inode)
1353 {
1354 	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
1355 	int error;
1356 
1357 	MSDOS_I(inode)->i_pos = MSDOS_ROOT_INO;
1358 	inode->i_uid = sbi->options.fs_uid;
1359 	inode->i_gid = sbi->options.fs_gid;
1360 	inode_inc_iversion(inode);
1361 	inode->i_generation = 0;
1362 	inode->i_mode = fat_make_mode(sbi, ATTR_DIR, S_IRWXUGO);
1363 	inode->i_op = sbi->dir_ops;
1364 	inode->i_fop = &fat_dir_operations;
1365 	if (is_fat32(sbi)) {
1366 		MSDOS_I(inode)->i_start = sbi->root_cluster;
1367 		error = fat_calc_dir_size(inode);
1368 		if (error < 0)
1369 			return error;
1370 	} else {
1371 		MSDOS_I(inode)->i_start = 0;
1372 		inode->i_size = sbi->dir_entries * sizeof(struct msdos_dir_entry);
1373 	}
1374 	inode->i_blocks = ((inode->i_size + (sbi->cluster_size - 1))
1375 			   & ~((loff_t)sbi->cluster_size - 1)) >> 9;
1376 	MSDOS_I(inode)->i_logstart = 0;
1377 	MSDOS_I(inode)->mmu_private = inode->i_size;
1378 
1379 	fat_save_attrs(inode, ATTR_DIR);
1380 	inode_set_mtime_to_ts(inode,
1381 			      inode_set_atime_to_ts(inode, inode_set_ctime(inode, 0, 0)));
1382 	set_nlink(inode, fat_subdirs(inode)+2);
1383 
1384 	return 0;
1385 }
1386 
1387 static unsigned long calc_fat_clusters(struct super_block *sb)
1388 {
1389 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
1390 
1391 	/* Divide first to avoid overflow */
1392 	if (!is_fat12(sbi)) {
1393 		unsigned long ent_per_sec = sb->s_blocksize * 8 / sbi->fat_bits;
1394 		return ent_per_sec * sbi->fat_length;
1395 	}
1396 
1397 	return sbi->fat_length * sb->s_blocksize * 8 / sbi->fat_bits;
1398 }
1399 
1400 static bool fat_bpb_is_zero(struct fat_boot_sector *b)
1401 {
1402 	if (get_unaligned_le16(&b->sector_size))
1403 		return false;
1404 	if (b->sec_per_clus)
1405 		return false;
1406 	if (b->reserved)
1407 		return false;
1408 	if (b->fats)
1409 		return false;
1410 	if (get_unaligned_le16(&b->dir_entries))
1411 		return false;
1412 	if (get_unaligned_le16(&b->sectors))
1413 		return false;
1414 	if (b->media)
1415 		return false;
1416 	if (b->fat_length)
1417 		return false;
1418 	if (b->secs_track)
1419 		return false;
1420 	if (b->heads)
1421 		return false;
1422 	return true;
1423 }
1424 
1425 static int fat_read_bpb(struct super_block *sb, struct fat_boot_sector *b,
1426 	int silent, struct fat_bios_param_block *bpb)
1427 {
1428 	int error = -EINVAL;
1429 
1430 	/* Read in BPB ... */
1431 	memset(bpb, 0, sizeof(*bpb));
1432 	bpb->fat_sector_size = get_unaligned_le16(&b->sector_size);
1433 	bpb->fat_sec_per_clus = b->sec_per_clus;
1434 	bpb->fat_reserved = le16_to_cpu(b->reserved);
1435 	bpb->fat_fats = b->fats;
1436 	bpb->fat_dir_entries = get_unaligned_le16(&b->dir_entries);
1437 	bpb->fat_sectors = get_unaligned_le16(&b->sectors);
1438 	bpb->fat_fat_length = le16_to_cpu(b->fat_length);
1439 	bpb->fat_total_sect = le32_to_cpu(b->total_sect);
1440 
1441 	bpb->fat16_state = b->fat16.state;
1442 	bpb->fat16_vol_id = get_unaligned_le32(b->fat16.vol_id);
1443 
1444 	bpb->fat32_length = le32_to_cpu(b->fat32.length);
1445 	bpb->fat32_root_cluster = le32_to_cpu(b->fat32.root_cluster);
1446 	bpb->fat32_info_sector = le16_to_cpu(b->fat32.info_sector);
1447 	bpb->fat32_state = b->fat32.state;
1448 	bpb->fat32_vol_id = get_unaligned_le32(b->fat32.vol_id);
1449 
1450 	/* Validate this looks like a FAT filesystem BPB */
1451 	if (!bpb->fat_reserved) {
1452 		if (!silent)
1453 			fat_msg(sb, KERN_ERR,
1454 				"bogus number of reserved sectors");
1455 		goto out;
1456 	}
1457 	if (!bpb->fat_fats) {
1458 		if (!silent)
1459 			fat_msg(sb, KERN_ERR, "bogus number of FAT structure");
1460 		goto out;
1461 	}
1462 
1463 	/*
1464 	 * Earlier we checked here that b->secs_track and b->head are nonzero,
1465 	 * but it turns out valid FAT filesystems can have zero there.
1466 	 */
1467 
1468 	if (!fat_valid_media(b->media)) {
1469 		if (!silent)
1470 			fat_msg(sb, KERN_ERR, "invalid media value (0x%02x)",
1471 				(unsigned)b->media);
1472 		goto out;
1473 	}
1474 
1475 	if (!is_power_of_2(bpb->fat_sector_size)
1476 	    || (bpb->fat_sector_size < 512)
1477 	    || (bpb->fat_sector_size > 4096)) {
1478 		if (!silent)
1479 			fat_msg(sb, KERN_ERR, "bogus logical sector size %u",
1480 			       (unsigned)bpb->fat_sector_size);
1481 		goto out;
1482 	}
1483 
1484 	if (!is_power_of_2(bpb->fat_sec_per_clus)) {
1485 		if (!silent)
1486 			fat_msg(sb, KERN_ERR, "bogus sectors per cluster %u",
1487 				(unsigned)bpb->fat_sec_per_clus);
1488 		goto out;
1489 	}
1490 
1491 	if (bpb->fat_fat_length == 0 && bpb->fat32_length == 0) {
1492 		if (!silent)
1493 			fat_msg(sb, KERN_ERR, "bogus number of FAT sectors");
1494 		goto out;
1495 	}
1496 
1497 	error = 0;
1498 
1499 out:
1500 	return error;
1501 }
1502 
1503 static int fat_read_static_bpb(struct super_block *sb,
1504 	struct fat_boot_sector *b, int silent,
1505 	struct fat_bios_param_block *bpb)
1506 {
1507 	static const char *notdos1x = "This doesn't look like a DOS 1.x volume";
1508 	sector_t bd_sects = bdev_nr_sectors(sb->s_bdev);
1509 	struct fat_floppy_defaults *fdefaults = NULL;
1510 	int error = -EINVAL;
1511 	unsigned i;
1512 
1513 	/* 16-bit DOS 1.x reliably wrote bootstrap short-jmp or near-jmp code */
1514 	if ((b->ignored[0] != 0xeb || b->ignored[2] != 0x90) &&
1515 	    (b->ignored[0] != 0xe9)) {
1516 		if (!silent)
1517 			fat_msg(sb, KERN_ERR,
1518 				"%s; no bootstrapping code", notdos1x);
1519 		goto out;
1520 	}
1521 
1522 	/*
1523 	 * If any value in this region is non-zero, it isn't archaic
1524 	 * DOS.
1525 	 */
1526 	if (!fat_bpb_is_zero(b)) {
1527 		if (!silent)
1528 			fat_msg(sb, KERN_ERR,
1529 				"%s; DOS 2.x BPB is non-zero", notdos1x);
1530 		goto out;
1531 	}
1532 
1533 	for (i = 0; i < ARRAY_SIZE(floppy_defaults); i++) {
1534 		if (floppy_defaults[i].nr_sectors == bd_sects) {
1535 			fdefaults = &floppy_defaults[i];
1536 			break;
1537 		}
1538 	}
1539 
1540 	if (fdefaults == NULL) {
1541 		if (!silent)
1542 			fat_msg(sb, KERN_WARNING,
1543 				"This looks like a DOS 1.x volume, but isn't a recognized floppy size (%llu sectors)",
1544 				(u64)bd_sects);
1545 		goto out;
1546 	}
1547 
1548 	if (!silent)
1549 		fat_msg(sb, KERN_INFO,
1550 			"This looks like a DOS 1.x volume; assuming default BPB values");
1551 
1552 	memset(bpb, 0, sizeof(*bpb));
1553 	bpb->fat_sector_size = SECTOR_SIZE;
1554 	bpb->fat_sec_per_clus = fdefaults->sec_per_clus;
1555 	bpb->fat_reserved = 1;
1556 	bpb->fat_fats = 2;
1557 	bpb->fat_dir_entries = fdefaults->dir_entries;
1558 	bpb->fat_sectors = fdefaults->nr_sectors;
1559 	bpb->fat_fat_length = fdefaults->fat_length;
1560 
1561 	error = 0;
1562 
1563 out:
1564 	return error;
1565 }
1566 
1567 /*
1568  * Read the super block of an MS-DOS FS.
1569  */
1570 int fat_fill_super(struct super_block *sb, struct fs_context *fc,
1571 		   void (*setup)(struct super_block *))
1572 {
1573 	struct fat_mount_options *opts = fc->fs_private;
1574 	int silent = fc->sb_flags & SB_SILENT;
1575 	struct inode *root_inode = NULL, *fat_inode = NULL;
1576 	struct inode *fsinfo_inode = NULL;
1577 	struct buffer_head *bh;
1578 	struct fat_bios_param_block bpb;
1579 	struct msdos_sb_info *sbi;
1580 	u16 logical_sector_size;
1581 	u32 total_sectors, total_clusters, fat_clusters, rootdir_sectors;
1582 	u32 dir_start, data_start;
1583 	long error;
1584 	char buf[50];
1585 	struct timespec64 ts;
1586 
1587 	/*
1588 	 * GFP_KERNEL is ok here, because while we do hold the
1589 	 * superblock lock, memory pressure can't call back into
1590 	 * the filesystem, since we're only just about to mount
1591 	 * it and have no inodes etc active!
1592 	 */
1593 	sbi = kzalloc_obj(struct msdos_sb_info);
1594 	if (!sbi)
1595 		return -ENOMEM;
1596 	sb->s_fs_info = sbi;
1597 
1598 	sb->s_flags |= SB_NODIRATIME;
1599 	sb->s_magic = MSDOS_SUPER_MAGIC;
1600 	sb->s_op = &fat_sops;
1601 	sb->s_export_op = &fat_export_ops;
1602 	/*
1603 	 * fat timestamps are complex and truncated by fat itself, so
1604 	 * we set 1 here to be fast
1605 	 */
1606 	sb->s_time_gran = 1;
1607 	mutex_init(&sbi->nfs_build_inode_lock);
1608 	ratelimit_state_init(&sbi->ratelimit, DEFAULT_RATELIMIT_INTERVAL,
1609 			     DEFAULT_RATELIMIT_BURST);
1610 
1611 	/* UTF-8 doesn't provide FAT semantics */
1612 	if (!strcmp(opts->iocharset, "utf8")) {
1613 		fat_msg(sb, KERN_WARNING, "utf8 is not a recommended IO charset"
1614 		       " for FAT filesystems, filesystem will be"
1615 		       " case sensitive!");
1616 	}
1617 
1618 	/* If user doesn't specify allow_utime, it's initialized from dmask. */
1619 	if (opts->allow_utime == (unsigned short)-1)
1620 		opts->allow_utime = ~opts->fs_dmask & (S_IWGRP | S_IWOTH);
1621 	if (opts->unicode_xlate)
1622 		opts->utf8 = 0;
1623 	if (opts->nfs == FAT_NFS_NOSTALE_RO) {
1624 		sb->s_flags |= SB_RDONLY;
1625 		sb->s_export_op = &fat_export_ops_nostale;
1626 	}
1627 
1628 	/* Apply parsed options to sbi (structure copy) */
1629 	sbi->options = *opts;
1630 	/* Transfer ownership of iocharset to sbi->options */
1631 	opts->iocharset = NULL;
1632 
1633 	setup(sb); /* flavour-specific stuff that needs options */
1634 
1635 	error = -EINVAL;
1636 	if (!sb_min_blocksize(sb, 512)) {
1637 		fat_msg(sb, KERN_ERR, "unable to set blocksize");
1638 		goto out_fail;
1639 	}
1640 	error = -EIO;
1641 	bh = sb_bread(sb, 0);
1642 	if (bh == NULL) {
1643 		fat_msg(sb, KERN_ERR, "unable to read boot sector");
1644 		goto out_fail;
1645 	}
1646 
1647 	error = fat_read_bpb(sb, (struct fat_boot_sector *)bh->b_data, silent,
1648 		&bpb);
1649 	if (error == -EINVAL && sbi->options.dos1xfloppy)
1650 		error = fat_read_static_bpb(sb,
1651 			(struct fat_boot_sector *)bh->b_data, silent, &bpb);
1652 	brelse(bh);
1653 
1654 	if (error == -EINVAL)
1655 		goto out_invalid;
1656 	else if (error)
1657 		goto out_fail;
1658 
1659 	logical_sector_size = bpb.fat_sector_size;
1660 	sbi->sec_per_clus = bpb.fat_sec_per_clus;
1661 
1662 	error = -EIO;
1663 	if (logical_sector_size < sb->s_blocksize) {
1664 		fat_msg(sb, KERN_ERR, "logical sector size too small for device"
1665 		       " (logical sector size = %u)", logical_sector_size);
1666 		goto out_fail;
1667 	}
1668 
1669 	if (logical_sector_size > sb->s_blocksize) {
1670 		struct buffer_head *bh_resize;
1671 
1672 		if (!sb_set_blocksize(sb, logical_sector_size)) {
1673 			fat_msg(sb, KERN_ERR, "unable to set blocksize %u",
1674 			       logical_sector_size);
1675 			goto out_fail;
1676 		}
1677 
1678 		/* Verify that the larger boot sector is fully readable */
1679 		bh_resize = sb_bread(sb, 0);
1680 		if (bh_resize == NULL) {
1681 			fat_msg(sb, KERN_ERR, "unable to read boot sector"
1682 			       " (logical sector size = %lu)",
1683 			       sb->s_blocksize);
1684 			goto out_fail;
1685 		}
1686 		brelse(bh_resize);
1687 	}
1688 
1689 	mutex_init(&sbi->s_lock);
1690 	sbi->cluster_size = sb->s_blocksize * sbi->sec_per_clus;
1691 	sbi->cluster_bits = ffs(sbi->cluster_size) - 1;
1692 	sbi->fats = bpb.fat_fats;
1693 	sbi->fat_bits = 0;		/* Don't know yet */
1694 	sbi->fat_start = bpb.fat_reserved;
1695 	sbi->fat_length = bpb.fat_fat_length;
1696 	sbi->root_cluster = 0;
1697 	sbi->free_clusters = -1;	/* Don't know yet */
1698 	sbi->free_clus_valid = 0;
1699 	sbi->prev_free = FAT_START_ENT;
1700 	sb->s_maxbytes = 0xffffffff;
1701 	fat_time_fat2unix(sbi, &ts, 0, cpu_to_le16(FAT_DATE_MIN), 0);
1702 	sb->s_time_min = ts.tv_sec;
1703 
1704 	fat_time_fat2unix(sbi, &ts, cpu_to_le16(FAT_TIME_MAX),
1705 			  cpu_to_le16(FAT_DATE_MAX), 0);
1706 	sb->s_time_max = ts.tv_sec;
1707 
1708 	if (!sbi->fat_length && bpb.fat32_length) {
1709 		struct fat_boot_fsinfo *fsinfo;
1710 		struct buffer_head *fsinfo_bh;
1711 
1712 		/* Must be FAT32 */
1713 		sbi->fat_bits = 32;
1714 		sbi->fat_length = bpb.fat32_length;
1715 		sbi->root_cluster = bpb.fat32_root_cluster;
1716 
1717 		/* MC - if info_sector is 0, don't multiply by 0 */
1718 		sbi->fsinfo_sector = bpb.fat32_info_sector;
1719 		if (sbi->fsinfo_sector == 0)
1720 			sbi->fsinfo_sector = 1;
1721 
1722 		fsinfo_bh = sb_bread(sb, sbi->fsinfo_sector);
1723 		if (fsinfo_bh == NULL) {
1724 			fat_msg(sb, KERN_ERR, "bread failed, FSINFO block"
1725 			       " (sector = %lu)", sbi->fsinfo_sector);
1726 			goto out_fail;
1727 		}
1728 
1729 		fsinfo = (struct fat_boot_fsinfo *)fsinfo_bh->b_data;
1730 		if (!IS_FSINFO(fsinfo)) {
1731 			fat_msg(sb, KERN_WARNING, "Invalid FSINFO signature: "
1732 			       "0x%08x, 0x%08x (sector = %lu)",
1733 			       le32_to_cpu(fsinfo->signature1),
1734 			       le32_to_cpu(fsinfo->signature2),
1735 			       sbi->fsinfo_sector);
1736 		} else {
1737 			if (sbi->options.usefree)
1738 				sbi->free_clus_valid = 1;
1739 			sbi->free_clusters = le32_to_cpu(fsinfo->free_clusters);
1740 			sbi->prev_free = le32_to_cpu(fsinfo->next_cluster);
1741 		}
1742 
1743 		brelse(fsinfo_bh);
1744 	}
1745 
1746 	/* interpret volume ID as a little endian 32 bit integer */
1747 	if (is_fat32(sbi))
1748 		sbi->vol_id = bpb.fat32_vol_id;
1749 	else /* fat 16 or 12 */
1750 		sbi->vol_id = bpb.fat16_vol_id;
1751 
1752 	__le32 vol_id_le = cpu_to_le32(sbi->vol_id);
1753 	super_set_uuid(sb, (void *) &vol_id_le, sizeof(vol_id_le));
1754 
1755 	sbi->dir_per_block = sb->s_blocksize / sizeof(struct msdos_dir_entry);
1756 	sbi->dir_per_block_bits = ffs(sbi->dir_per_block) - 1;
1757 
1758 	sbi->dir_entries = bpb.fat_dir_entries;
1759 	if (sbi->dir_entries & (sbi->dir_per_block - 1)) {
1760 		if (!silent)
1761 			fat_msg(sb, KERN_ERR, "bogus number of directory entries"
1762 			       " (%u)", sbi->dir_entries);
1763 		goto out_invalid;
1764 	}
1765 
1766 	rootdir_sectors = sbi->dir_entries
1767 		* sizeof(struct msdos_dir_entry) / sb->s_blocksize;
1768 	if (check_mul_overflow(sbi->fats, sbi->fat_length, &dir_start) ||
1769 	    check_add_overflow(sbi->fat_start, dir_start, &dir_start) ||
1770 	    check_add_overflow(dir_start, rootdir_sectors, &data_start)) {
1771 		if (!silent)
1772 			fat_msg(sb, KERN_ERR,
1773 				"overflow of root dir or data layout");
1774 		goto out_invalid;
1775 	}
1776 
1777 	total_sectors = bpb.fat_sectors;
1778 	if (total_sectors == 0)
1779 		total_sectors = bpb.fat_total_sect;
1780 
1781 	if (total_sectors < data_start) {
1782 		if (!silent)
1783 			fat_msg(sb, KERN_ERR,
1784 				"data area starts beyond volume (%u > %u)",
1785 				data_start, total_sectors);
1786 		goto out_invalid;
1787 	}
1788 
1789 	sbi->dir_start = dir_start;
1790 	sbi->data_start = data_start;
1791 	total_clusters = (total_sectors - data_start) / sbi->sec_per_clus;
1792 
1793 	if (!is_fat32(sbi))
1794 		sbi->fat_bits = (total_clusters > MAX_FAT12) ? 16 : 12;
1795 
1796 	/* some OSes set FAT_STATE_DIRTY and clean it on unmount. */
1797 	if (is_fat32(sbi))
1798 		sbi->dirty = bpb.fat32_state & FAT_STATE_DIRTY;
1799 	else /* fat 16 or 12 */
1800 		sbi->dirty = bpb.fat16_state & FAT_STATE_DIRTY;
1801 
1802 	/* check that FAT table does not overflow */
1803 	fat_clusters = calc_fat_clusters(sb);
1804 	total_clusters = min(total_clusters, fat_clusters - FAT_START_ENT);
1805 	if (total_clusters > max_fat(sb)) {
1806 		if (!silent)
1807 			fat_msg(sb, KERN_ERR, "count of clusters too big (%u)",
1808 			       total_clusters);
1809 		goto out_invalid;
1810 	}
1811 
1812 	sbi->max_cluster = total_clusters + FAT_START_ENT;
1813 	/* check the free_clusters, it's not necessarily correct */
1814 	if (sbi->free_clusters != -1 && sbi->free_clusters > total_clusters)
1815 		sbi->free_clusters = -1;
1816 	/* check the prev_free, it's not necessarily correct */
1817 	sbi->prev_free %= sbi->max_cluster;
1818 	if (sbi->prev_free < FAT_START_ENT)
1819 		sbi->prev_free = FAT_START_ENT;
1820 
1821 	/* set up enough so that it can read an inode */
1822 	fat_hash_init(sb);
1823 	dir_hash_init(sb);
1824 	fat_ent_access_init(sb);
1825 
1826 	/*
1827 	 * The low byte of the first FAT entry must have the same value as
1828 	 * the media field of the boot sector. But in real world, too many
1829 	 * devices are writing wrong values. So, removed that validity check.
1830 	 *
1831 	 * The removed check compared the first FAT entry to a value dependent
1832 	 * on the media field like this:
1833 	 * == (0x0F00 | media), for FAT12
1834 	 * == (0XFF00 | media), for FAT16
1835 	 * == (0x0FFFFF | media), for FAT32
1836 	 */
1837 
1838 	error = -EINVAL;
1839 	scnprintf(buf, sizeof(buf), "cp%d", sbi->options.codepage);
1840 	sbi->nls_disk = load_nls(buf);
1841 	if (!sbi->nls_disk) {
1842 		fat_msg(sb, KERN_ERR, "codepage %s not found", buf);
1843 		goto out_fail;
1844 	}
1845 
1846 	/* FIXME: utf8 is using iocharset for upper/lower conversion */
1847 	if (sbi->options.isvfat) {
1848 		sbi->nls_io = load_nls(sbi->options.iocharset);
1849 		if (!sbi->nls_io) {
1850 			fat_msg(sb, KERN_ERR, "IO charset %s not found",
1851 			       sbi->options.iocharset);
1852 			goto out_fail;
1853 		}
1854 	}
1855 
1856 	error = -ENOMEM;
1857 	fat_inode = new_inode(sb);
1858 	if (!fat_inode)
1859 		goto out_fail;
1860 	sbi->fat_inode = fat_inode;
1861 
1862 	fsinfo_inode = new_inode(sb);
1863 	if (!fsinfo_inode)
1864 		goto out_fail;
1865 	fsinfo_inode->i_ino = MSDOS_FSINFO_INO;
1866 	sbi->fsinfo_inode = fsinfo_inode;
1867 	insert_inode_hash(fsinfo_inode);
1868 
1869 	root_inode = new_inode(sb);
1870 	if (!root_inode)
1871 		goto out_fail;
1872 	root_inode->i_ino = MSDOS_ROOT_INO;
1873 	inode_set_iversion(root_inode, 1);
1874 	error = fat_read_root(root_inode);
1875 	if (error < 0) {
1876 		iput(root_inode);
1877 		goto out_fail;
1878 	}
1879 	error = -ENOMEM;
1880 	insert_inode_hash(root_inode);
1881 	fat_attach(root_inode, 0);
1882 	sb->s_root = d_make_root(root_inode);
1883 	if (!sb->s_root) {
1884 		fat_msg(sb, KERN_ERR, "get root inode failed");
1885 		goto out_fail;
1886 	}
1887 
1888 	if (sbi->options.discard && !bdev_max_discard_sectors(sb->s_bdev))
1889 		fat_msg(sb, KERN_WARNING,
1890 			"mounting with \"discard\" option, but the device does not support discard");
1891 
1892 	fat_set_state(sb, 1, 0);
1893 	return 0;
1894 
1895 out_invalid:
1896 	error = -EINVAL;
1897 	if (!silent)
1898 		fat_msg(sb, KERN_INFO, "Can't find a valid FAT filesystem");
1899 
1900 out_fail:
1901 	iput(fsinfo_inode);
1902 	iput(fat_inode);
1903 	unload_nls(sbi->nls_io);
1904 	unload_nls(sbi->nls_disk);
1905 	fat_reset_iocharset(&sbi->options);
1906 	sb->s_fs_info = NULL;
1907 	kfree(sbi);
1908 	return error;
1909 }
1910 
1911 EXPORT_SYMBOL_GPL(fat_fill_super);
1912 
1913 /*
1914  * helper function for fat_flush_inodes.  This writes both the inode
1915  * and the file data blocks, waiting for in flight data blocks before
1916  * the start of the call.  It does not wait for any io started
1917  * during the call
1918  */
1919 static int writeback_inode(struct inode *inode)
1920 {
1921 
1922 	int ret;
1923 
1924 	/* if we used wait=1, sync_inode_metadata waits for the io for the
1925 	* inode to finish.  So wait=0 is sent down to sync_inode_metadata
1926 	* and filemap_fdatawrite is used for the data blocks
1927 	*/
1928 	ret = sync_inode_metadata(inode, 0);
1929 	if (!ret)
1930 		ret = filemap_fdatawrite(inode->i_mapping);
1931 	return ret;
1932 }
1933 
1934 /*
1935  * write data and metadata corresponding to i1 and i2.  The io is
1936  * started but we do not wait for any of it to finish.
1937  *
1938  * filemap_flush is used for the block device, so if there is a dirty
1939  * page for a block already in flight, we will not wait and start the
1940  * io over again
1941  */
1942 int fat_flush_inodes(struct super_block *sb, struct inode *i1, struct inode *i2)
1943 {
1944 	int ret = 0;
1945 	if (!MSDOS_SB(sb)->options.flush)
1946 		return 0;
1947 	if (i1)
1948 		ret = writeback_inode(i1);
1949 	if (!ret && i2)
1950 		ret = writeback_inode(i2);
1951 	if (!ret)
1952 		ret = sync_blockdev_nowait(sb->s_bdev);
1953 	return ret;
1954 }
1955 EXPORT_SYMBOL_GPL(fat_flush_inodes);
1956 
1957 int fat_init_fs_context(struct fs_context *fc, bool is_vfat)
1958 {
1959 	struct fat_mount_options *opts;
1960 
1961 	opts = kzalloc_obj(*opts);
1962 	if (!opts)
1963 		return -ENOMEM;
1964 
1965 	opts->isvfat = is_vfat;
1966 	opts->fs_uid = current_uid();
1967 	opts->fs_gid = current_gid();
1968 	opts->fs_fmask = opts->fs_dmask = current_umask();
1969 	opts->allow_utime = -1;
1970 	opts->codepage = fat_default_codepage;
1971 	fat_reset_iocharset(opts);
1972 	if (is_vfat) {
1973 		opts->shortname = VFAT_SFN_DISPLAY_WINNT|VFAT_SFN_CREATE_WIN95;
1974 		opts->rodir = 0;
1975 	} else {
1976 		opts->shortname = 0;
1977 		opts->rodir = 1;
1978 	}
1979 	opts->name_check = 'n';
1980 	opts->quiet = opts->showexec = opts->sys_immutable = opts->dotsOK =  0;
1981 	opts->unicode_xlate = 0;
1982 	opts->numtail = 1;
1983 	opts->usefree = opts->nocase = 0;
1984 	opts->tz_set = 0;
1985 	opts->nfs = 0;
1986 	opts->errors = FAT_ERRORS_RO;
1987 	opts->debug = 0;
1988 
1989 	opts->utf8 = IS_ENABLED(CONFIG_FAT_DEFAULT_UTF8) && is_vfat;
1990 
1991 	fc->fs_private = opts;
1992 	/* fc->ops assigned by caller */
1993 
1994 	return 0;
1995 }
1996 EXPORT_SYMBOL_GPL(fat_init_fs_context);
1997 
1998 void fat_free_fc(struct fs_context *fc)
1999 {
2000 	struct fat_mount_options *opts = fc->fs_private;
2001 
2002 	if (opts->iocharset != fat_default_iocharset)
2003 		kfree(opts->iocharset);
2004 	kfree(fc->fs_private);
2005 }
2006 EXPORT_SYMBOL_GPL(fat_free_fc);
2007 
2008 static int __init init_fat_fs(void)
2009 {
2010 	int err;
2011 
2012 	err = fat_cache_init();
2013 	if (err)
2014 		return err;
2015 
2016 	err = fat_init_inodecache();
2017 	if (err)
2018 		goto failed;
2019 
2020 	return 0;
2021 
2022 failed:
2023 	fat_cache_destroy();
2024 	return err;
2025 }
2026 
2027 static void __exit exit_fat_fs(void)
2028 {
2029 	fat_cache_destroy();
2030 	fat_destroy_inodecache();
2031 }
2032 
2033 module_init(init_fat_fs)
2034 module_exit(exit_fat_fs)
2035 
2036 MODULE_DESCRIPTION("Core FAT filesystem support");
2037 MODULE_LICENSE("GPL");
2038