xref: /linux/fs/ntfs3/super.c (revision 56c3824de56b5275c02ff6b6aa27ddbacfbb9b25)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  *
7  *                 terminology
8  *
9  * cluster - allocation unit     - 512,1K,2K,4K,...,2M
10  * vcn - virtual cluster number  - Offset inside the file in clusters.
11  * vbo - virtual byte offset     - Offset inside the file in bytes.
12  * lcn - logical cluster number  - 0 based cluster in clusters heap.
13  * lbo - logical byte offset     - Absolute position inside volume.
14  * run - maps VCN to LCN         - Stored in attributes in packed form.
15  * attr - attribute segment      - std/name/data etc records inside MFT.
16  * mi  - MFT inode               - One MFT record(usually 1024 bytes or 4K), consists of attributes.
17  * ni  - NTFS inode              - Extends linux inode. consists of one or more mft inodes.
18  * index - unit inside directory - 2K, 4K, <=page size, does not depend on cluster size.
19  * resident attribute            - Attribute with content stored directly in the MFT record
20  * non-resident attribute        - Attribute with content stored in clusters
21  * data_size                     - Size of attribute content in bytes. Equal to inode->i_size
22  * valid_size                    - Number of bytes written to the non-resident attribute
23  * allocated_size                - Total size of clusters allocated for non-resident content
24  * total_size                    - Actual size of allocated clusters for sparse or compressed attributes
25  *                               - Constraint: valid_size <= data_size <= allocated_size
26  * ADS                           - Alternative data stream: Named data attribute (0x80)
27  *
28  * WSL - Windows Subsystem for Linux
29  * https://docs.microsoft.com/en-us/windows/wsl/file-permissions
30  * It stores uid/gid/mode/dev in xattr
31  *
32  * ntfs allows up to 2^64 clusters per volume.
33  * It means you should use 64 bits lcn to operate with ntfs.
34  * Implementation of ntfs.sys uses only 32 bits lcn.
35  * Default ntfs3 uses 32 bits lcn too.
36  * ntfs3 built with CONFIG_NTFS3_64BIT_CLUSTER (ntfs3_64) uses 64 bits per lcn.
37  *
38  *
39  *     ntfs limits, cluster size is 4K (2^12)
40  * -----------------------------------------------------------------------------
41  * | Volume size   | Clusters | ntfs.sys | ntfs3  | ntfs3_64 | mkntfs | chkdsk |
42  * -----------------------------------------------------------------------------
43  * | < 16T, 2^44   |  < 2^32  |  yes     |  yes   |   yes    |  yes   |  yes   |
44  * | > 16T, 2^44   |  > 2^32  |  no      |  no    |   yes    |  yes   |  yes   |
45  * ----------------------------------------------------------|------------------
46  *
47  * To mount large volumes as ntfs one should use large cluster size (up to 2M)
48  * The maximum volume size in this case is 2^32 * 2^21 = 2^53 = 8P
49  *
50  *     ntfs limits, cluster size is 2M (2^21)
51  * -----------------------------------------------------------------------------
52  * | < 8P, 2^53    |  < 2^32  |  yes     |  yes   |   yes    |  yes   |  yes   |
53  * | > 8P, 2^53    |  > 2^32  |  no      |  no    |   yes    |  yes   |  yes   |
54  * ----------------------------------------------------------|------------------
55  *
56  */
57 
58 #include <linux/blkdev.h>
59 #include <linux/buffer_head.h>
60 #include <linux/exportfs.h>
61 #include <linux/fs.h>
62 #include <linux/fs_context.h>
63 #include <linux/fs_parser.h>
64 #include <linux/fs_struct.h>
65 #include <linux/log2.h>
66 #include <linux/minmax.h>
67 #include <linux/module.h>
68 #include <linux/nls.h>
69 #include <linux/overflow.h>
70 #include <linux/proc_fs.h>
71 #include <linux/seq_file.h>
72 #include <linux/statfs.h>
73 
74 #include "debug.h"
75 #include "ntfs.h"
76 #include "ntfs_fs.h"
77 #ifdef CONFIG_NTFS3_LZX_XPRESS
78 #include "lib/lib.h"
79 #endif
80 
81 #ifdef CONFIG_PRINTK
82 /*
83  * ntfs_printk - Trace warnings/notices/errors.
84  *
85  * Thanks Joe Perches <joe@perches.com> for implementation
86  */
87 void ntfs_printk(const struct super_block *sb, const char *fmt, ...)
88 {
89 	struct va_format vaf;
90 	va_list args;
91 	int level;
92 	struct ntfs_sb_info *sbi = sb->s_fs_info;
93 
94 	/* Should we use different ratelimits for warnings/notices/errors? */
95 	if (!___ratelimit(&sbi->msg_ratelimit, "ntfs3"))
96 		return;
97 
98 	va_start(args, fmt);
99 
100 	level = printk_get_level(fmt);
101 	vaf.fmt = printk_skip_level(fmt);
102 	vaf.va = &args;
103 	printk("%c%cntfs3(%s): %pV\n", KERN_SOH_ASCII, level, sb->s_id, &vaf);
104 
105 	va_end(args);
106 }
107 
108 static char s_name_buf[512];
109 static atomic_t s_name_buf_cnt = ATOMIC_INIT(1); // 1 means 'free s_name_buf'.
110 
111 /*
112  * ntfs_inode_printk
113  *
114  * Print warnings/notices/errors about inode using name or inode number.
115  */
116 void ntfs_inode_printk(struct inode *inode, const char *fmt, ...)
117 {
118 	struct super_block *sb = inode->i_sb;
119 	struct ntfs_sb_info *sbi = sb->s_fs_info;
120 	char *name;
121 	va_list args;
122 	struct va_format vaf;
123 	int level;
124 
125 	if (!___ratelimit(&sbi->msg_ratelimit, "ntfs3"))
126 		return;
127 
128 	/* Use static allocated buffer, if possible. */
129 	name = atomic_dec_and_test(&s_name_buf_cnt) ?
130 		       s_name_buf :
131 		       kmalloc(sizeof(s_name_buf), GFP_NOFS);
132 
133 	if (name) {
134 		struct dentry *de = d_find_alias(inode);
135 
136 		if (de) {
137 			int len;
138 			spin_lock(&de->d_lock);
139 			len = snprintf(name, sizeof(s_name_buf), " \"%s\"",
140 				       de->d_name.name);
141 			spin_unlock(&de->d_lock);
142 			if (len <= 0)
143 				name[0] = 0;
144 			else if (len >= sizeof(s_name_buf))
145 				name[sizeof(s_name_buf) - 1] = 0;
146 		} else {
147 			name[0] = 0;
148 		}
149 		dput(de); /* Cocci warns if placed in branch "if (de)" */
150 	}
151 
152 	va_start(args, fmt);
153 
154 	level = printk_get_level(fmt);
155 	vaf.fmt = printk_skip_level(fmt);
156 	vaf.va = &args;
157 
158 	printk("%c%cntfs3(%s): ino=%llx,%s %pV\n", KERN_SOH_ASCII, level,
159 	       sb->s_id, inode->i_ino, name ? name : "", &vaf);
160 
161 	va_end(args);
162 
163 	atomic_inc(&s_name_buf_cnt);
164 	if (name != s_name_buf)
165 		kfree(name);
166 }
167 #endif
168 
169 /*
170  * Shared memory struct.
171  *
172  * On-disk ntfs's upcase table is created by ntfs formatter.
173  * 'upcase' table is 128K bytes of memory.
174  * We should read it into memory when mounting.
175  * Several ntfs volumes likely use the same 'upcase' table.
176  * It is good idea to share in-memory 'upcase' table between different volumes.
177  * Unfortunately winxp/vista/win7 use different upcase tables.
178  */
179 static DEFINE_SPINLOCK(s_shared_lock);
180 
181 static struct {
182 	void *ptr;
183 	u32 len;
184 	int cnt;
185 } s_shared[8];
186 
187 /*
188  * ntfs_set_shared
189  *
190  * Return:
191  * * @ptr - If pointer was saved in shared memory.
192  * * NULL - If pointer was not shared.
193  */
194 void *ntfs_set_shared(void *ptr, u32 bytes)
195 {
196 	void *ret = NULL;
197 	int i, j = -1;
198 
199 	spin_lock_bh(&s_shared_lock);
200 	for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
201 		if (!s_shared[i].cnt) {
202 			j = i;
203 		} else if (bytes == s_shared[i].len &&
204 			   !memcmp(s_shared[i].ptr, ptr, bytes)) {
205 			s_shared[i].cnt += 1;
206 			ret = s_shared[i].ptr;
207 			break;
208 		}
209 	}
210 
211 	if (!ret && j != -1) {
212 		s_shared[j].ptr = ptr;
213 		s_shared[j].len = bytes;
214 		s_shared[j].cnt = 1;
215 		ret = ptr;
216 	}
217 	spin_unlock_bh(&s_shared_lock);
218 
219 	return ret;
220 }
221 
222 /*
223  * ntfs_put_shared
224  *
225  * Return:
226  * * @ptr - If pointer is not shared anymore.
227  * * NULL - If pointer is still shared.
228  */
229 void *ntfs_put_shared(void *ptr)
230 {
231 	void *ret = ptr;
232 	int i;
233 
234 	spin_lock_bh(&s_shared_lock);
235 	for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
236 		if (s_shared[i].cnt && s_shared[i].ptr == ptr) {
237 			if (--s_shared[i].cnt)
238 				ret = NULL;
239 			break;
240 		}
241 	}
242 	spin_unlock_bh(&s_shared_lock);
243 
244 	return ret;
245 }
246 
247 static inline void put_mount_options(struct ntfs_mount_options *options)
248 {
249 	kfree(options->nls_name);
250 	unload_nls(options->nls);
251 	kfree(options);
252 }
253 
254 static void put_mount_options_rcu(struct rcu_head *head)
255 {
256 	put_mount_options(container_of(head, struct ntfs_mount_options, rcu));
257 }
258 
259 enum Opt {
260 	Opt_uid,
261 	Opt_gid,
262 	Opt_umask,
263 	Opt_dmask,
264 	Opt_fmask,
265 	Opt_immutable,
266 	Opt_discard,
267 	Opt_force,
268 	Opt_sparse,
269 	Opt_nohidden,
270 	Opt_hide_dot_files,
271 	Opt_windows_names,
272 	Opt_showmeta,
273 	Opt_acl,
274 	Opt_acl_bool,
275 	Opt_iocharset,
276 	Opt_prealloc,
277 	Opt_prealloc_bool,
278 	Opt_nocase,
279 	Opt_delalloc,
280 	Opt_delalloc_bool,
281 	Opt_ads,
282 	Opt_ads_bool,
283 	Opt_err,
284 };
285 
286 // clang-format off
287 static const struct fs_parameter_spec ntfs_fs_parameters[] = {
288 	fsparam_uid("uid",		Opt_uid),
289 	fsparam_gid("gid",		Opt_gid),
290 	fsparam_u32oct("umask",		Opt_umask),
291 	fsparam_u32oct("dmask",		Opt_dmask),
292 	fsparam_u32oct("fmask",		Opt_fmask),
293 	fsparam_flag("sys_immutable",	Opt_immutable),
294 	fsparam_flag("discard",		Opt_discard),
295 	fsparam_flag("force",		Opt_force),
296 	fsparam_flag("sparse",		Opt_sparse),
297 	fsparam_flag("nohidden",	Opt_nohidden),
298 	fsparam_flag("hide_dot_files",	Opt_hide_dot_files),
299 	fsparam_flag("windows_names",	Opt_windows_names),
300 	fsparam_flag("showmeta",	Opt_showmeta),
301 	fsparam_flag("acl",		Opt_acl),
302 	fsparam_bool("acl",		Opt_acl_bool),
303 	fsparam_string("iocharset",	Opt_iocharset),
304 	fsparam_flag("prealloc",	Opt_prealloc),
305 	fsparam_bool("prealloc",	Opt_prealloc_bool),
306 	fsparam_flag("nocase",		Opt_nocase),
307 	fsparam_flag("delalloc",	Opt_delalloc),
308 	fsparam_bool("delalloc",	Opt_delalloc_bool),
309 	fsparam_flag("ads",		Opt_ads),
310 	fsparam_bool("ads",		Opt_ads_bool),
311 	{}
312 };
313 // clang-format on
314 
315 /*
316  * Load nls table or if @nls is utf8 then return NULL.
317  *
318  */
319 static struct nls_table *ntfs_load_nls(const char *nls)
320 {
321 	struct nls_table *ret;
322 
323 	if (!nls)
324 		nls = CONFIG_NLS_DEFAULT;
325 
326 	if (strcmp(nls, "utf8") == 0)
327 		return NULL;
328 
329 	if (strcmp(nls, CONFIG_NLS_DEFAULT) == 0)
330 		return load_nls_default();
331 
332 	ret = load_nls(nls);
333 	if (ret)
334 		return ret;
335 
336 	return ERR_PTR(-EINVAL);
337 }
338 
339 static int ntfs_fs_parse_param(struct fs_context *fc,
340 			       struct fs_parameter *param)
341 {
342 	struct ntfs_mount_options *opts = fc->fs_private;
343 	struct fs_parse_result result;
344 	int opt;
345 
346 	opt = fs_parse(fc, ntfs_fs_parameters, param, &result);
347 	if (opt < 0)
348 		return opt;
349 
350 	switch (opt) {
351 	case Opt_uid:
352 		opts->fs_uid = result.uid;
353 		break;
354 	case Opt_gid:
355 		opts->fs_gid = result.gid;
356 		break;
357 	case Opt_umask:
358 		if (result.uint_32 & ~07777)
359 			return invalf(fc, "ntfs3: Invalid value for umask.");
360 		opts->fs_fmask_inv = ~result.uint_32;
361 		opts->fs_dmask_inv = ~result.uint_32;
362 		opts->fmask = 1;
363 		opts->dmask = 1;
364 		break;
365 	case Opt_dmask:
366 		if (result.uint_32 & ~07777)
367 			return invalf(fc, "ntfs3: Invalid value for dmask.");
368 		opts->fs_dmask_inv = ~result.uint_32;
369 		opts->dmask = 1;
370 		break;
371 	case Opt_fmask:
372 		if (result.uint_32 & ~07777)
373 			return invalf(fc, "ntfs3: Invalid value for fmask.");
374 		opts->fs_fmask_inv = ~result.uint_32;
375 		opts->fmask = 1;
376 		break;
377 	case Opt_immutable:
378 		opts->sys_immutable = 1;
379 		break;
380 	case Opt_discard:
381 		opts->discard = 1;
382 		break;
383 	case Opt_force:
384 		opts->force = 1;
385 		break;
386 	case Opt_sparse:
387 		opts->sparse = 1;
388 		break;
389 	case Opt_nohidden:
390 		opts->nohidden = 1;
391 		break;
392 	case Opt_hide_dot_files:
393 		opts->hide_dot_files = 1;
394 		break;
395 	case Opt_windows_names:
396 		opts->windows_names = 1;
397 		break;
398 	case Opt_showmeta:
399 		opts->showmeta = 1;
400 		break;
401 	case Opt_acl_bool:
402 		if (result.boolean) {
403 			fallthrough;
404 		case Opt_acl:
405 #ifdef CONFIG_NTFS3_FS_POSIX_ACL
406 			fc->sb_flags |= SB_POSIXACL;
407 #else
408 			return invalf(
409 				fc, "ntfs3: Support for ACL not compiled in!");
410 #endif
411 		} else
412 			fc->sb_flags &= ~SB_POSIXACL;
413 		break;
414 	case Opt_iocharset:
415 		kfree(opts->nls_name);
416 		opts->nls_name = param->string;
417 		param->string = NULL;
418 		break;
419 	case Opt_prealloc:
420 		opts->prealloc = 1;
421 		break;
422 	case Opt_prealloc_bool:
423 		opts->prealloc = result.boolean;
424 		break;
425 	case Opt_nocase:
426 		opts->nocase = 1;
427 		break;
428 	case Opt_delalloc:
429 		opts->delalloc = 1;
430 		break;
431 	case Opt_delalloc_bool:
432 		opts->delalloc = result.boolean;
433 		break;
434 	case Opt_ads:
435 		opts->ads = 1;
436 		break;
437 	case Opt_ads_bool:
438 		opts->ads = result.boolean;
439 		break;
440 	default:
441 		/* Should not be here unless we forget add case. */
442 		return -EINVAL;
443 	}
444 	return 0;
445 }
446 
447 static int ntfs_fs_reconfigure(struct fs_context *fc)
448 {
449 	struct super_block *sb = fc->root->d_sb;
450 	struct ntfs_sb_info *sbi = sb->s_fs_info;
451 	struct ntfs_mount_options *new_opts = fc->fs_private;
452 	struct ntfs_mount_options *old_opts;
453 	int ro_rw;
454 
455 	ro_rw = sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY);
456 	if (ro_rw && (sbi->flags & NTFS_FLAGS_NEED_REPLAY)) {
457 		errorf(fc,
458 		       "ntfs3: Couldn't remount rw because journal is not replayed. Please umount/remount instead\n");
459 		return -EINVAL;
460 	}
461 
462 	new_opts->nls = ntfs_load_nls(new_opts->nls_name);
463 	if (IS_ERR(new_opts->nls)) {
464 		new_opts->nls = NULL;
465 		errorf(fc, "ntfs3: Cannot load iocharset %s",
466 		       new_opts->nls_name);
467 		return -EINVAL;
468 	}
469 	if (new_opts->nls != sbi->options->nls)
470 		return invalf(
471 			fc,
472 			"ntfs3: Cannot use different iocharset when remounting!");
473 
474 	if (ro_rw && (sbi->volume.flags & VOLUME_FLAG_DIRTY) &&
475 	    !new_opts->force) {
476 		errorf(fc,
477 		       "ntfs3: Volume is dirty and \"force\" flag is not set!");
478 		return -EINVAL;
479 	}
480 
481 	sync_filesystem(sb);
482 	old_opts = sbi->options;
483 	/* pairs with the READ_ONCE() in ntfs_nls_to_utf16() */
484 	smp_store_release(&sbi->options, new_opts);
485 	fc->fs_private = NULL;
486 	/*
487 	 * ntfs_d_hash() and ntfs_d_compare() of a pathwalk in rcu mode may
488 	 * still read the old options through the sbi.
489 	 */
490 	call_rcu(&old_opts->rcu, put_mount_options_rcu);
491 
492 	return 0;
493 }
494 
495 #ifdef CONFIG_PROC_FS
496 static struct proc_dir_entry *proc_info_root;
497 
498 /*
499  * ntfs3_volinfo:
500  *
501  * The content of /proc/fs/ntfs3/<dev>/volinfo
502  *
503  * ntfs3.1
504  * cluster size
505  * number of clusters
506  * total number of mft records
507  * number of used mft records ~= number of files + folders
508  * real state of ntfs "dirty"/"clean"
509  * current state of ntfs "dirty"/"clean"
510 */
511 static int ntfs3_volinfo(struct seq_file *m, void *o)
512 {
513 	struct super_block *sb = m->private;
514 	struct ntfs_sb_info *sbi = sb->s_fs_info;
515 
516 	seq_printf(m, "ntfs%d.%d\n%u\n%zu\n%zu\n%zu\n%s\n%s\n",
517 		   sbi->volume.major_ver, sbi->volume.minor_ver,
518 		   sbi->cluster_size, sbi->used.bitmap.nbits,
519 		   sbi->mft.bitmap.nbits,
520 		   sbi->mft.bitmap.nbits - wnd_zeroes(&sbi->mft.bitmap),
521 		   sbi->volume.real_dirty ? "dirty" : "clean",
522 		   (sbi->volume.flags & VOLUME_FLAG_DIRTY) ? "dirty" : "clean");
523 
524 	return 0;
525 }
526 
527 static int ntfs3_volinfo_open(struct inode *inode, struct file *file)
528 {
529 	return single_open(file, ntfs3_volinfo, pde_data(inode));
530 }
531 
532 /* read /proc/fs/ntfs3/<dev>/label */
533 static int ntfs3_label_show(struct seq_file *m, void *o)
534 {
535 	struct super_block *sb = m->private;
536 	struct ntfs_sb_info *sbi = sb->s_fs_info;
537 
538 	seq_printf(m, "%s\n", sbi->volume.label);
539 
540 	return 0;
541 }
542 
543 /* write /proc/fs/ntfs3/<dev>/label */
544 static ssize_t ntfs3_label_write(struct file *file, const char __user *buffer,
545 				 size_t count, loff_t *ppos)
546 {
547 	int err;
548 	struct super_block *sb = pde_data(file_inode(file));
549 	ssize_t ret = count;
550 	u8 *label;
551 
552 	if (sb_rdonly(sb))
553 		return -EROFS;
554 
555 	label = kmalloc(count, GFP_NOFS);
556 
557 	if (!label)
558 		return -ENOMEM;
559 
560 	if (copy_from_user(label, buffer, ret)) {
561 		ret = -EFAULT;
562 		goto out;
563 	}
564 	while (ret > 0 && label[ret - 1] == '\n')
565 		ret -= 1;
566 
567 	err = ntfs_set_label(sb->s_fs_info, label, ret);
568 
569 	if (err < 0) {
570 		ntfs_err(sb, "failed (%d) to write label", err);
571 		ret = err;
572 		goto out;
573 	}
574 
575 	*ppos += count;
576 	ret = count;
577 out:
578 	kfree(label);
579 	return ret;
580 }
581 
582 static int ntfs3_label_open(struct inode *inode, struct file *file)
583 {
584 	return single_open(file, ntfs3_label_show, pde_data(inode));
585 }
586 
587 static const struct proc_ops ntfs3_volinfo_fops = {
588 	.proc_read = seq_read,
589 	.proc_lseek = seq_lseek,
590 	.proc_release = single_release,
591 	.proc_open = ntfs3_volinfo_open,
592 };
593 
594 static const struct proc_ops ntfs3_label_fops = {
595 	.proc_read = seq_read,
596 	.proc_lseek = seq_lseek,
597 	.proc_release = single_release,
598 	.proc_open = ntfs3_label_open,
599 	.proc_write = ntfs3_label_write,
600 };
601 
602 static void ntfs_create_procdir(struct super_block *sb)
603 {
604 	struct proc_dir_entry *e;
605 
606 	if (!proc_info_root)
607 		return;
608 
609 	e = proc_mkdir(sb->s_id, proc_info_root);
610 	if (e) {
611 		struct ntfs_sb_info *sbi = sb->s_fs_info;
612 
613 		proc_create_data("volinfo", 0444, e, &ntfs3_volinfo_fops, sb);
614 		proc_create_data("label", 0644, e, &ntfs3_label_fops, sb);
615 		sbi->procdir = e;
616 	}
617 }
618 
619 static void ntfs_remove_procdir(struct super_block *sb)
620 {
621 	struct ntfs_sb_info *sbi = sb->s_fs_info;
622 
623 	if (!sbi->procdir)
624 		return;
625 
626 	remove_proc_entry("label", sbi->procdir);
627 	remove_proc_entry("volinfo", sbi->procdir);
628 	remove_proc_entry(sb->s_id, proc_info_root);
629 	sbi->procdir = NULL;
630 }
631 
632 static void ntfs_create_proc_root(void)
633 {
634 	proc_info_root = proc_mkdir("fs/ntfs3", NULL);
635 }
636 
637 static void ntfs_remove_proc_root(void)
638 {
639 	if (proc_info_root) {
640 		remove_proc_entry("fs/ntfs3", NULL);
641 		proc_info_root = NULL;
642 	}
643 }
644 #else
645 // clang-format off
646 static void ntfs_create_procdir(struct super_block *sb){}
647 static void ntfs_remove_procdir(struct super_block *sb){}
648 static void ntfs_create_proc_root(void){}
649 static void ntfs_remove_proc_root(void){}
650 // clang-format on
651 #endif
652 
653 static struct kmem_cache *ntfs_inode_cachep;
654 
655 static struct inode *ntfs_alloc_inode(struct super_block *sb)
656 {
657 	struct ntfs_inode *ni = alloc_inode_sb(sb, ntfs_inode_cachep, GFP_NOFS);
658 
659 	if (!ni)
660 		return NULL;
661 
662 	memset(ni, 0, offsetof(struct ntfs_inode, vfs_inode));
663 	mutex_init(&ni->ni_lock);
664 	return &ni->vfs_inode;
665 }
666 
667 static void ntfs_free_inode(struct inode *inode)
668 {
669 	struct ntfs_inode *ni = ntfs_i(inode);
670 
671 	mutex_destroy(&ni->ni_lock);
672 	kmem_cache_free(ntfs_inode_cachep, ni);
673 }
674 
675 static void init_once(void *foo)
676 {
677 	struct ntfs_inode *ni = foo;
678 
679 	inode_init_once(&ni->vfs_inode);
680 }
681 
682 /*
683  * Noinline to reduce binary size.
684  */
685 static noinline void ntfs3_put_sbi(struct ntfs_sb_info *sbi)
686 {
687 	wnd_close(&sbi->mft.bitmap);
688 	wnd_close(&sbi->used.bitmap);
689 
690 	if (sbi->mft.ni) {
691 		iput(&sbi->mft.ni->vfs_inode);
692 		sbi->mft.ni = NULL;
693 	}
694 
695 	if (sbi->security.ni) {
696 		iput(&sbi->security.ni->vfs_inode);
697 		sbi->security.ni = NULL;
698 	}
699 
700 	if (sbi->reparse.ni) {
701 		iput(&sbi->reparse.ni->vfs_inode);
702 		sbi->reparse.ni = NULL;
703 	}
704 
705 	if (sbi->objid.ni) {
706 		iput(&sbi->objid.ni->vfs_inode);
707 		sbi->objid.ni = NULL;
708 	}
709 
710 	if (sbi->volume.ni) {
711 		iput(&sbi->volume.ni->vfs_inode);
712 		sbi->volume.ni = NULL;
713 	}
714 
715 	ntfs_update_mftmirr(sbi);
716 
717 	indx_clear(&sbi->security.index_sii);
718 	indx_clear(&sbi->security.index_sdh);
719 	indx_clear(&sbi->reparse.index_r);
720 	indx_clear(&sbi->objid.index_o);
721 }
722 
723 static void ntfs3_free_sbi(struct ntfs_sb_info *sbi)
724 {
725 	if (sbi->options)
726 		put_mount_options(sbi->options);
727 	kfree(sbi->new_rec);
728 	kvfree(ntfs_put_shared(sbi->upcase));
729 	kvfree(sbi->def_table);
730 	kfree(sbi->compress.lznt);
731 #ifdef CONFIG_NTFS3_LZX_XPRESS
732 	xpress_free_decompressor(sbi->compress.xpress);
733 	lzx_free_decompressor(sbi->compress.lzx);
734 #endif
735 	kfree(sbi);
736 }
737 
738 static void ntfs3_free_sbi_rcu(struct rcu_head *head)
739 {
740 	ntfs3_free_sbi(container_of(head, struct ntfs_sb_info, rcu));
741 }
742 
743 static void ntfs_put_super(struct super_block *sb)
744 {
745 	struct ntfs_sb_info *sbi = sb->s_fs_info;
746 
747 	ntfs_remove_procdir(sb);
748 
749 	/* Mark rw ntfs as clear, if possible. */
750 	ntfs_set_state(sbi, NTFS_DIRTY_CLEAR);
751 
752 	/*
753 	 * The mount options stay until the sbi is freed: ->d_hash() and
754 	 * ->d_compare() of a pathwalk in rcu mode read the nls table through
755 	 * them.
756 	 */
757 	ntfs3_put_sbi(sbi);
758 }
759 
760 static int ntfs_statfs(struct dentry *dentry, struct kstatfs *buf)
761 {
762 	struct super_block *sb = dentry->d_sb;
763 	struct ntfs_sb_info *sbi = sb->s_fs_info;
764 	struct wnd_bitmap *wnd = &sbi->used.bitmap;
765 	CLST da_clusters = ntfs_get_da(sbi);
766 
767 	buf->f_type = sb->s_magic;
768 	buf->f_bsize = buf->f_frsize = sbi->cluster_size;
769 	buf->f_blocks = wnd->nbits;
770 
771 	buf->f_bfree = wnd_zeroes(wnd);
772 	if (buf->f_bfree > da_clusters) {
773 		buf->f_bfree -= da_clusters;
774 	} else {
775 		buf->f_bfree = 0;
776 	}
777 	buf->f_bavail = buf->f_bfree;
778 
779 	buf->f_fsid.val[0] = sbi->volume.ser_num;
780 	buf->f_fsid.val[1] = sbi->volume.ser_num >> 32;
781 	buf->f_namelen = NTFS_NAME_LEN;
782 
783 	return 0;
784 }
785 
786 static int ntfs_show_options(struct seq_file *m, struct dentry *root)
787 {
788 	struct super_block *sb = root->d_sb;
789 	struct ntfs_sb_info *sbi = sb->s_fs_info;
790 	struct ntfs_mount_options *opts = sbi->options;
791 	struct user_namespace *user_ns = seq_user_ns(m);
792 
793 	seq_printf(m, ",uid=%u", from_kuid_munged(user_ns, opts->fs_uid));
794 	seq_printf(m, ",gid=%u", from_kgid_munged(user_ns, opts->fs_gid));
795 	if (opts->dmask)
796 		seq_printf(m, ",dmask=%04o", opts->fs_dmask_inv ^ 0xffff);
797 	if (opts->fmask)
798 		seq_printf(m, ",fmask=%04o", opts->fs_fmask_inv ^ 0xffff);
799 	if (opts->sys_immutable)
800 		seq_puts(m, ",sys_immutable");
801 	if (opts->discard)
802 		seq_puts(m, ",discard");
803 	if (opts->force)
804 		seq_puts(m, ",force");
805 	if (opts->sparse)
806 		seq_puts(m, ",sparse");
807 	if (opts->nohidden)
808 		seq_puts(m, ",nohidden");
809 	if (opts->hide_dot_files)
810 		seq_puts(m, ",hide_dot_files");
811 	if (opts->windows_names)
812 		seq_puts(m, ",windows_names");
813 	if (opts->showmeta)
814 		seq_puts(m, ",showmeta");
815 	if (sb->s_flags & SB_POSIXACL)
816 		seq_puts(m, ",acl");
817 	if (opts->nls)
818 		seq_printf(m, ",iocharset=%s", opts->nls->charset);
819 	else
820 		seq_puts(m, ",iocharset=utf8");
821 	if (opts->prealloc)
822 		seq_puts(m, ",prealloc");
823 	if (opts->nocase)
824 		seq_puts(m, ",nocase");
825 	if (opts->delalloc)
826 		seq_puts(m, ",delalloc");
827 	if (opts->ads)
828 		seq_puts(m, ",ads");
829 
830 	return 0;
831 }
832 
833 /*
834  * ntfs_shutdown - super_operations::shutdown
835  */
836 static void ntfs_shutdown(struct super_block *sb)
837 {
838 	set_bit(NTFS_FLAGS_SHUTDOWN_BIT, &ntfs_sb(sb)->flags);
839 }
840 
841 /*
842  * ntfs_sync_fs - super_operations::sync_fs
843  */
844 static int ntfs_sync_fs(struct super_block *sb, int wait)
845 {
846 	int err = 0, err2;
847 	struct ntfs_sb_info *sbi = sb->s_fs_info;
848 	struct ntfs_inode *ni;
849 	struct inode *inode;
850 
851 	if (unlikely(ntfs3_forced_shutdown(sb)))
852 		return -EIO;
853 
854 	ni = sbi->security.ni;
855 	if (ni) {
856 		inode = &ni->vfs_inode;
857 		err2 = _ni_write_inode(inode, wait);
858 		if (err2 && !err)
859 			err = err2;
860 	}
861 
862 	ni = sbi->objid.ni;
863 	if (ni) {
864 		inode = &ni->vfs_inode;
865 		err2 = _ni_write_inode(inode, wait);
866 		if (err2 && !err)
867 			err = err2;
868 	}
869 
870 	ni = sbi->reparse.ni;
871 	if (ni) {
872 		inode = &ni->vfs_inode;
873 		err2 = _ni_write_inode(inode, wait);
874 		if (err2 && !err)
875 			err = err2;
876 	}
877 
878 	if (!err)
879 		ntfs_set_state(sbi, NTFS_DIRTY_CLEAR);
880 
881 	ntfs_update_mftmirr(sbi);
882 
883 	if (wait) {
884 		sync_blockdev(sb->s_bdev);
885 		blkdev_issue_flush(sb->s_bdev);
886 	}
887 
888 	return err;
889 }
890 
891 static const struct super_operations ntfs_sops = {
892 	.alloc_inode = ntfs_alloc_inode,
893 	.free_inode = ntfs_free_inode,
894 	.evict_inode = ntfs_evict_inode,
895 	.put_super = ntfs_put_super,
896 	.statfs = ntfs_statfs,
897 	.show_options = ntfs_show_options,
898 	.shutdown = ntfs_shutdown,
899 	.sync_fs = ntfs_sync_fs,
900 	.write_inode = ntfs3_write_inode,
901 };
902 
903 static struct inode *ntfs_export_get_inode(struct super_block *sb, u64 ino,
904 					   u32 generation)
905 {
906 	struct MFT_REF ref;
907 	struct inode *inode;
908 
909 	ref.low = cpu_to_le32(ino);
910 #ifdef CONFIG_NTFS3_64BIT_CLUSTER
911 	ref.high = cpu_to_le16(ino >> 32);
912 #else
913 	ref.high = 0;
914 #endif
915 	ref.seq = cpu_to_le16(generation);
916 
917 	inode = ntfs_iget5(sb, &ref, NULL);
918 	if (!IS_ERR(inode) && is_bad_inode(inode)) {
919 		iput(inode);
920 		inode = ERR_PTR(-ESTALE);
921 	}
922 
923 	return inode;
924 }
925 
926 static struct dentry *ntfs_fh_to_dentry(struct super_block *sb, struct fid *fid,
927 					int fh_len, int fh_type)
928 {
929 	return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
930 				    ntfs_export_get_inode);
931 }
932 
933 static struct dentry *ntfs_fh_to_parent(struct super_block *sb, struct fid *fid,
934 					int fh_len, int fh_type)
935 {
936 	return generic_fh_to_parent(sb, fid, fh_len, fh_type,
937 				    ntfs_export_get_inode);
938 }
939 
940 /* TODO: == ntfs_sync_inode */
941 static int ntfs_nfs_commit_metadata(struct inode *inode)
942 {
943 	return _ni_write_inode(inode, 1);
944 }
945 
946 static const struct export_operations ntfs_export_ops = {
947 	.encode_fh = generic_encode_ino32_fh,
948 	.fh_to_dentry = ntfs_fh_to_dentry,
949 	.fh_to_parent = ntfs_fh_to_parent,
950 	.get_parent = ntfs3_get_parent,
951 	.commit_metadata = ntfs_nfs_commit_metadata,
952 };
953 
954 /*
955  * format_size_gb - Return Gb,Mb to print with "%u.%02u Gb".
956  */
957 static u32 format_size_gb(const u64 bytes, u32 *mb)
958 {
959 	/* Do simple right 30 bit shift of 64 bit value. */
960 	u64 kbytes = bytes >> 10;
961 	u32 kbytes32 = kbytes;
962 
963 	*mb = (100 * (kbytes32 & 0xfffff) + 0x7ffff) >> 20;
964 	if (*mb >= 100)
965 		*mb = 99;
966 
967 	return (kbytes32 >> 20) | (((u32)(kbytes >> 32)) << 12);
968 }
969 
970 static u32 true_sectors_per_clst(const struct NTFS_BOOT *boot)
971 {
972 	if (boot->sectors_per_clusters <= 0x80)
973 		return boot->sectors_per_clusters;
974 	if (boot->sectors_per_clusters >= 0xf4) /* limit shift to 2MB max */
975 		return 1U << (-(s8)boot->sectors_per_clusters);
976 	return -EINVAL;
977 }
978 
979 /*
980  * ntfs_init_from_boot - Init internal info from on-disk boot sector.
981  *
982  * NTFS mount begins from boot - special formatted 512 bytes.
983  * There are two boots: the first and the last 512 bytes of volume.
984  * The content of boot is not changed during ntfs life.
985  *
986  * NOTE: ntfs.sys checks only first (primary) boot.
987  * chkdsk checks both boots.
988  */
989 static int ntfs_init_from_boot(struct super_block *sb, u32 sector_size,
990 			       u64 dev_size, struct NTFS_BOOT **boot2)
991 {
992 	struct ntfs_sb_info *sbi = sb->s_fs_info;
993 	int err;
994 	u32 mb, gb, boot_sector_size, sct_per_clst, record_size;
995 	u64 sectors, clusters, mlcn, mlcn2, mft_pos, mft2_pos, dev_size0;
996 	struct NTFS_BOOT *boot;
997 	struct buffer_head *bh;
998 	struct MFT_REC *rec;
999 	u16 fn, ao;
1000 	u8 cluster_bits;
1001 	u32 boot_off = 0;
1002 	sector_t boot_block = 0;
1003 	const char *hint = "Primary boot";
1004 
1005 	/* Save original dev_size. Used with alternative boot. */
1006 	dev_size0 = dev_size;
1007 
1008 	sbi->volume.blocks = dev_size >> PAGE_SHIFT;
1009 
1010 	/* Set dummy blocksize to read boot_block. */
1011 	if (!sb_min_blocksize(sb, PAGE_SIZE)) {
1012 		return -EINVAL;
1013 	}
1014 
1015 read_boot:
1016 	bh = ntfs_bread(sb, boot_block);
1017 	if (!bh)
1018 		return boot_block ? -EINVAL : -EIO;
1019 
1020 	err = -EINVAL;
1021 
1022 	/* Corrupted image; do not read OOB */
1023 	if (bh->b_size - sizeof(*boot) < boot_off)
1024 		goto out;
1025 
1026 	boot = (struct NTFS_BOOT *)Add2Ptr(bh->b_data, boot_off);
1027 
1028 	if (memcmp(boot->system_id, "NTFS    ", sizeof("NTFS    ") - 1)) {
1029 		ntfs_err(sb, "%s signature is not NTFS.", hint);
1030 		goto out;
1031 	}
1032 
1033 	/* 0x55AA is not mandaroty. Thanks Maxim Suhanov*/
1034 	/*if (0x55 != boot->boot_magic[0] || 0xAA != boot->boot_magic[1])
1035 	 *	goto out;
1036 	 */
1037 
1038 	boot_sector_size = ((u32)boot->bytes_per_sector[1] << 8) |
1039 			   boot->bytes_per_sector[0];
1040 	if (boot_sector_size < SECTOR_SIZE ||
1041 	    !is_power_of_2(boot_sector_size)) {
1042 		ntfs_err(sb, "%s: invalid bytes per sector %u.", hint,
1043 			 boot_sector_size);
1044 		goto out;
1045 	}
1046 
1047 	/* cluster size: 512, 1K, 2K, 4K, ... 2M */
1048 	sct_per_clst = true_sectors_per_clst(boot);
1049 	if ((int)sct_per_clst < 0 || !is_power_of_2(sct_per_clst)) {
1050 		ntfs_err(sb, "%s: invalid sectors per cluster %u.", hint,
1051 			 sct_per_clst);
1052 		goto out;
1053 	}
1054 
1055 	sbi->cluster_size = boot_sector_size * sct_per_clst;
1056 	sbi->cluster_bits = cluster_bits = blksize_bits(sbi->cluster_size);
1057 	sbi->cluster_mask = sbi->cluster_size - 1;
1058 	sbi->cluster_mask_inv = ~(u64)sbi->cluster_mask;
1059 
1060 	mlcn = le64_to_cpu(boot->mft_clst);
1061 	mlcn2 = le64_to_cpu(boot->mft2_clst);
1062 	sectors = le64_to_cpu(boot->sectors_per_volume);
1063 
1064 	/*
1065 	 * Convert mlcn/mlcn2 to sector positions before comparing with
1066 	 * 'sectors'.  All three are u64 values that come from the boot
1067 	 * sector, so use check_mul_overflow() to keep a wraparound from
1068 	 * silently bypassing the comparison.
1069 	 */
1070 	if (check_mul_overflow(mlcn, (u64)sct_per_clst, &mft_pos) ||
1071 	    check_mul_overflow(mlcn2, (u64)sct_per_clst, &mft2_pos) ||
1072 	    mft_pos >= sectors || mft2_pos >= sectors) {
1073 		ntfs_err(
1074 			sb,
1075 			"%s: start of MFT 0x%llx (0x%llx) is out of volume 0x%llx.",
1076 			hint, mlcn, mlcn2, sectors);
1077 		goto out;
1078 	}
1079 
1080 	if (boot->record_size >= 0) {
1081 		record_size = (u32)boot->record_size << cluster_bits;
1082 	} else if (-boot->record_size <= MAXIMUM_SHIFT_BYTES_PER_MFT) {
1083 		record_size = 1u << (-boot->record_size);
1084 	} else {
1085 		ntfs_err(sb, "%s: invalid record size %d.", hint,
1086 			 boot->record_size);
1087 		goto out;
1088 	}
1089 
1090 	sbi->record_size = record_size;
1091 	sbi->record_bits = blksize_bits(record_size);
1092 	sbi->attr_size_tr = (5 * record_size >> 4); // ~320 bytes
1093 
1094 	/* Check MFT record size. */
1095 	if (record_size < SECTOR_SIZE || !is_power_of_2(record_size)) {
1096 		ntfs_err(sb, "%s: invalid bytes per MFT record %u (%d).", hint,
1097 			 record_size, boot->record_size);
1098 		goto out;
1099 	}
1100 
1101 	if (record_size > MAXIMUM_BYTES_PER_MFT) {
1102 		ntfs_err(sb, "Unsupported bytes per MFT record %u.",
1103 			 record_size);
1104 		goto out;
1105 	}
1106 
1107 	if (boot->index_size >= 0) {
1108 		sbi->index_size = (u32)boot->index_size << cluster_bits;
1109 	} else if (-boot->index_size <= MAXIMUM_SHIFT_BYTES_PER_INDEX) {
1110 		sbi->index_size = 1u << (-boot->index_size);
1111 	} else {
1112 		ntfs_err(sb, "%s: invalid index size %d.", hint,
1113 			 boot->index_size);
1114 		goto out;
1115 	}
1116 
1117 	/* Check index record size. */
1118 	if (sbi->index_size < SECTOR_SIZE || !is_power_of_2(sbi->index_size)) {
1119 		ntfs_err(sb, "%s: invalid bytes per index %u(%d).", hint,
1120 			 sbi->index_size, boot->index_size);
1121 		goto out;
1122 	}
1123 
1124 	if (sbi->index_size > MAXIMUM_BYTES_PER_INDEX) {
1125 		ntfs_err(sb, "%s: unsupported bytes per index %u.", hint,
1126 			 sbi->index_size);
1127 		goto out;
1128 	}
1129 
1130 	sbi->volume.size = sectors * boot_sector_size;
1131 
1132 	gb = format_size_gb(sbi->volume.size + boot_sector_size, &mb);
1133 
1134 	/*
1135 	 * - Volume formatted and mounted with the same sector size.
1136 	 * - Volume formatted 4K and mounted as 512.
1137 	 * - Volume formatted 512 and mounted as 4K.
1138 	 */
1139 	if (boot_sector_size != sector_size) {
1140 		ntfs_warn(
1141 			sb,
1142 			"Different NTFS sector size (%u) and media sector size (%u).",
1143 			boot_sector_size, sector_size);
1144 		dev_size += sector_size - 1;
1145 	}
1146 
1147 	sbi->bdev_blocksize = max(boot_sector_size, sector_size);
1148 	sbi->mft.lbo = mlcn << cluster_bits;
1149 	sbi->mft.lbo2 = mlcn2 << cluster_bits;
1150 
1151 	/* Compare boot's cluster and sector. */
1152 	if (sbi->cluster_size < boot_sector_size) {
1153 		ntfs_err(sb, "%s: invalid bytes per cluster (%u).", hint,
1154 			 sbi->cluster_size);
1155 		goto out;
1156 	}
1157 
1158 	/* Compare boot's cluster and media sector. */
1159 	if (sbi->cluster_size < sector_size) {
1160 		/* No way to use ntfs_get_block in this case. */
1161 		ntfs_err(
1162 			sb,
1163 			"Failed to mount 'cause NTFS's cluster size (%u) is less than media sector size (%u).",
1164 			sbi->cluster_size, sector_size);
1165 		goto out;
1166 	}
1167 
1168 	sbi->max_bytes_per_attr =
1169 		record_size - ALIGN(MFTRECORD_FIXUP_OFFSET, 8) -
1170 		ALIGN(((record_size >> SECTOR_SHIFT) * sizeof(short)), 8) -
1171 		ALIGN(sizeof(enum ATTR_TYPE), 8);
1172 
1173 	sbi->volume.ser_num = le64_to_cpu(boot->serial_num);
1174 
1175 	/* Warning if RAW volume. */
1176 	if (dev_size < sbi->volume.size + boot_sector_size) {
1177 		u32 mb0, gb0;
1178 
1179 		gb0 = format_size_gb(dev_size, &mb0);
1180 		ntfs_warn(
1181 			sb,
1182 			"RAW NTFS volume: Filesystem size %u.%02u Gb > volume size %u.%02u Gb. Mount in read-only.",
1183 			gb, mb, gb0, mb0);
1184 		sb->s_flags |= SB_RDONLY;
1185 	}
1186 
1187 	clusters = sbi->volume.size >> cluster_bits;
1188 #ifndef CONFIG_NTFS3_64BIT_CLUSTER
1189 	/* 32 bits per cluster. */
1190 	if (clusters >> 32) {
1191 		ntfs_notice(
1192 			sb,
1193 			"NTFS %u.%02u Gb is too big to use 32 bits per cluster.",
1194 			gb, mb);
1195 		goto out;
1196 	}
1197 #elif BITS_PER_LONG < 64
1198 #error "CONFIG_NTFS3_64BIT_CLUSTER incompatible in 32 bit OS"
1199 #endif
1200 
1201 	sbi->used.bitmap.nbits = clusters;
1202 
1203 	rec = kzalloc(record_size, GFP_NOFS);
1204 	if (!rec) {
1205 		err = -ENOMEM;
1206 		goto out;
1207 	}
1208 
1209 	sbi->new_rec = rec;
1210 	rec->rhdr.sign = NTFS_FILE_SIGNATURE;
1211 	rec->rhdr.fix_off = cpu_to_le16(MFTRECORD_FIXUP_OFFSET);
1212 	fn = (sbi->record_size >> SECTOR_SHIFT) + 1;
1213 	rec->rhdr.fix_num = cpu_to_le16(fn);
1214 	ao = ALIGN(MFTRECORD_FIXUP_OFFSET + sizeof(short) * fn, 8);
1215 	rec->attr_off = cpu_to_le16(ao);
1216 	rec->used = cpu_to_le32(ao + ALIGN(sizeof(enum ATTR_TYPE), 8));
1217 	rec->total = cpu_to_le32(sbi->record_size);
1218 	((struct ATTRIB *)Add2Ptr(rec, ao))->type = ATTR_END;
1219 
1220 	if (!sb_set_blocksize(sb, min_t(u32, sbi->cluster_size, PAGE_SIZE))) {
1221 		err = -EINVAL;
1222 		goto out;
1223 	}
1224 
1225 	sbi->block_mask = sb->s_blocksize - 1;
1226 	sbi->blocks_per_cluster = sbi->cluster_size >> sb->s_blocksize_bits;
1227 	sbi->volume.blocks = sbi->volume.size >> sb->s_blocksize_bits;
1228 
1229 	/* Maximum size for normal files. */
1230 	sbi->maxbytes = (clusters << cluster_bits) - 1;
1231 
1232 #ifdef CONFIG_NTFS3_64BIT_CLUSTER
1233 	if (clusters >= (1ull << (64 - cluster_bits)))
1234 		sbi->maxbytes = -1;
1235 	sbi->maxbytes_sparse = MAX_LFS_FILESIZE;
1236 	sb->s_maxbytes = MAX_LFS_FILESIZE;
1237 #else
1238 	/* Maximum size for sparse file. */
1239 	sbi->maxbytes_sparse = (1ull << (cluster_bits + 32)) - 1;
1240 	sb->s_maxbytes = 0xFFFFFFFFull << cluster_bits;
1241 #endif
1242 
1243 	/*
1244 	 * Compute the MFT zone at two steps.
1245 	 * It would be nice if we are able to allocate 1/8 of
1246 	 * total clusters for MFT but not more then 512 MB.
1247 	 */
1248 	sbi->zone_max = min_t(CLST, 0x20000000 >> cluster_bits, clusters >> 3);
1249 
1250 	err = 0;
1251 
1252 	if (bh->b_blocknr && !sb_rdonly(sb)) {
1253 		/*
1254 	 	 * Alternative boot is ok but primary is not ok.
1255 	 	 * Do not update primary boot here 'cause it may be faked boot.
1256 	 	 * Let ntfs to be mounted and update boot later.
1257 		 */
1258 		*boot2 = kmemdup(boot, sizeof(*boot), GFP_NOFS | __GFP_NOWARN);
1259 	}
1260 
1261 out:
1262 	brelse(bh);
1263 
1264 	if (err == -EINVAL && !boot_block && dev_size0 > PAGE_SHIFT) {
1265 		u32 block_size = min_t(u32, sector_size, PAGE_SIZE);
1266 		u64 lbo = dev_size0 - sizeof(*boot);
1267 
1268 		boot_block = lbo >> blksize_bits(block_size);
1269 		boot_off = lbo & (block_size - 1);
1270 		if (boot_block && block_size >= boot_off + sizeof(*boot)) {
1271 			/*
1272 			 * Try alternative boot (last sector)
1273 			 */
1274 			if (!sb_set_blocksize(sb, block_size))
1275 				return -EINVAL;
1276 			hint = "Alternative boot";
1277 			dev_size = dev_size0; /* restore original size. */
1278 			goto read_boot;
1279 		}
1280 	}
1281 
1282 	return err;
1283 }
1284 
1285 /*
1286  * ntfs_fill_super - Try to mount.
1287  */
1288 static int ntfs_fill_super(struct super_block *sb, struct fs_context *fc)
1289 {
1290 	int err;
1291 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1292 	struct block_device *bdev = sb->s_bdev;
1293 	struct ntfs_mount_options *fc_opts;
1294 	struct ntfs_mount_options *options = NULL;
1295 	struct inode *inode;
1296 	struct ntfs_inode *ni;
1297 	size_t i, tt, bad_len, bad_frags;
1298 	CLST vcn, lcn, len;
1299 	struct ATTRIB *attr;
1300 	const struct VOLUME_INFO *info;
1301 	u32 done, bytes;
1302 	struct ATTR_DEF_ENTRY *t;
1303 	u16 *shared;
1304 	struct MFT_REF ref;
1305 	bool ro = sb_rdonly(sb);
1306 	struct NTFS_BOOT *boot2 = NULL;
1307 
1308 	ref.high = 0;
1309 
1310 	sbi->sb = sb;
1311 	fc_opts = fc->fs_private;
1312 	if (!fc_opts) {
1313 		errorf(fc, "missing mount options");
1314 		return -EINVAL;
1315 	}
1316 	options = kmemdup(fc_opts, sizeof(*fc_opts), GFP_KERNEL);
1317 	if (!options)
1318 		return -ENOMEM;
1319 
1320 	if (fc_opts->nls_name) {
1321 		options->nls_name = kstrdup(fc_opts->nls_name, GFP_KERNEL);
1322 		if (!options->nls_name) {
1323 			kfree(options);
1324 			return -ENOMEM;
1325 		}
1326 	}
1327 	sbi->options = options;
1328 	sb->s_flags |= SB_NODIRATIME;
1329 	sb->s_magic = 0x7366746e; // "ntfs"
1330 	sb->s_op = &ntfs_sops;
1331 	sb->s_export_op = &ntfs_export_ops;
1332 	sb->s_time_gran = NTFS_TIME_GRAN; // 100 nsec
1333 	sb->s_xattr = ntfs_xattr_handlers;
1334 	set_default_d_op(sb, options->nocase ? &ntfs_dentry_ops : NULL);
1335 
1336 	options->nls = ntfs_load_nls(options->nls_name);
1337 	if (IS_ERR(options->nls)) {
1338 		options->nls = NULL;
1339 		errorf(fc, "Cannot load nls %s", options->nls_name);
1340 		err = -EINVAL;
1341 		goto out;
1342 	}
1343 
1344 	if (bdev_max_discard_sectors(bdev) && bdev_discard_granularity(bdev)) {
1345 		sbi->discard_granularity = bdev_discard_granularity(bdev);
1346 		sbi->discard_granularity_mask_inv =
1347 			~(u64)(sbi->discard_granularity - 1);
1348 	}
1349 
1350 	/* Parse boot. */
1351 	err = ntfs_init_from_boot(sb, bdev_logical_block_size(bdev),
1352 				  bdev_nr_bytes(bdev), &boot2);
1353 	if (err)
1354 		goto out;
1355 
1356 	/*
1357 	 * Load $Volume. This should be done before $LogFile
1358 	 * 'cause 'sbi->volume.ni' is used in 'ntfs_set_state'.
1359 	 */
1360 	ref.low = cpu_to_le32(MFT_REC_VOL);
1361 	ref.seq = cpu_to_le16(MFT_REC_VOL);
1362 	inode = ntfs_iget5(sb, &ref, &NAME_VOLUME);
1363 	if (IS_ERR(inode)) {
1364 		err = PTR_ERR(inode);
1365 		ntfs_err(sb, "Failed to load $Volume (%d).", err);
1366 		goto out;
1367 	}
1368 
1369 	ni = ntfs_i(inode);
1370 
1371 	/* Load and save label (not necessary). */
1372 	attr = ni_find_attr(ni, NULL, NULL, ATTR_LABEL, NULL, 0, NULL, NULL);
1373 
1374 	if (!attr) {
1375 		/* It is ok if no ATTR_LABEL */
1376 	} else if (!attr->non_res && !is_attr_ext(attr)) {
1377 		/* $AttrDef allows labels to be up to 128 symbols. */
1378 		err = utf16s_to_utf8s(resident_data(attr),
1379 				      le32_to_cpu(attr->res.data_size) >> 1,
1380 				      UTF16_LITTLE_ENDIAN, sbi->volume.label,
1381 				      sizeof(sbi->volume.label));
1382 		if (err < 0) {
1383 			sbi->volume.label[0] = 0;
1384 		} else if (err >= sizeof(sbi->volume.label)) {
1385 			sbi->volume.label[sizeof(sbi->volume.label) - 1] = 0;
1386 		} else {
1387 			sbi->volume.label[err] = 0;
1388 		}
1389 	} else {
1390 		/* Should we break mounting here? */
1391 		//err = -EINVAL;
1392 		//goto put_inode_out;
1393 	}
1394 
1395 	attr = ni_find_attr(ni, attr, NULL, ATTR_VOL_INFO, NULL, 0, NULL, NULL);
1396 	if (!attr || is_attr_ext(attr) ||
1397 	    !(info = resident_data_ex(attr, SIZEOF_ATTRIBUTE_VOLUME_INFO))) {
1398 		ntfs_err(sb, "$Volume is corrupted.");
1399 		err = -EINVAL;
1400 		goto put_inode_out;
1401 	}
1402 
1403 	sbi->volume.major_ver = info->major_ver;
1404 	sbi->volume.minor_ver = info->minor_ver;
1405 	sbi->volume.flags = info->flags;
1406 	sbi->volume.ni = ni;
1407 	if (info->flags & VOLUME_FLAG_DIRTY) {
1408 		sbi->volume.real_dirty = true;
1409 		ntfs_info(sb, "It is recommended to use chkdsk.");
1410 	}
1411 
1412 	/* Load $MFTMirr to estimate recs_mirr. */
1413 	ref.low = cpu_to_le32(MFT_REC_MIRR);
1414 	ref.seq = cpu_to_le16(MFT_REC_MIRR);
1415 	inode = ntfs_iget5(sb, &ref, &NAME_MIRROR);
1416 	if (IS_ERR(inode)) {
1417 		err = PTR_ERR(inode);
1418 		ntfs_err(sb, "Failed to load $MFTMirr (%d).", err);
1419 		goto out;
1420 	}
1421 
1422 	sbi->mft.recs_mirr = ntfs_up_cluster(sbi, inode->i_size) >>
1423 			     sbi->record_bits;
1424 
1425 	iput(inode);
1426 
1427 	/* Load LogFile to replay. */
1428 	ref.low = cpu_to_le32(MFT_REC_LOG);
1429 	ref.seq = cpu_to_le16(MFT_REC_LOG);
1430 	inode = ntfs_iget5(sb, &ref, &NAME_LOGFILE);
1431 	if (IS_ERR(inode)) {
1432 		err = PTR_ERR(inode);
1433 		ntfs_err(sb, "Failed to load \x24LogFile (%d).", err);
1434 		goto out;
1435 	}
1436 
1437 	ni = ntfs_i(inode);
1438 
1439 	err = ntfs_loadlog_and_replay(ni, sbi);
1440 	if (err)
1441 		goto put_inode_out;
1442 
1443 	iput(inode);
1444 
1445 	if ((sbi->flags & NTFS_FLAGS_NEED_REPLAY) && !ro) {
1446 		ntfs_warn(sb, "failed to replay log file. Can't mount rw!");
1447 		err = -EINVAL;
1448 		goto out;
1449 	}
1450 
1451 	if ((sbi->volume.flags & VOLUME_FLAG_DIRTY) && !ro && !options->force) {
1452 		ntfs_warn(sb, "volume is dirty and \"force\" flag is not set!");
1453 		err = -EINVAL;
1454 		goto out;
1455 	}
1456 
1457 	/* Load $MFT. */
1458 	ref.low = cpu_to_le32(MFT_REC_MFT);
1459 	ref.seq = cpu_to_le16(1);
1460 
1461 	inode = ntfs_iget5(sb, &ref, &NAME_MFT);
1462 	if (IS_ERR(inode)) {
1463 		err = PTR_ERR(inode);
1464 		ntfs_err(sb, "Failed to load $MFT (%d).", err);
1465 		goto out;
1466 	}
1467 
1468 	ni = ntfs_i(inode);
1469 
1470 	sbi->mft.used = ni->i_valid >> sbi->record_bits;
1471 	tt = inode->i_size >> sbi->record_bits;
1472 	sbi->mft.next_free = MFT_REC_USER;
1473 
1474 	err = ni_load_all_mi(ni);
1475 	if (err) {
1476 		ntfs_err(sb, "Failed to load $MFT's subrecords (%d).", err);
1477 		goto put_inode_out;
1478 	}
1479 
1480 	/* Merge MFT bitmap runs from extent records loaded by ni_load_all_mi. */
1481 	{
1482 		struct ATTRIB *a = NULL;
1483 		struct ATTR_LIST_ENTRY *le = NULL;
1484 
1485 		while ((a = ni_enum_attr_ex(ni, a, &le, NULL))) {
1486 			CLST svcn, evcn;
1487 			u16 roff;
1488 
1489 			if (a->type != ATTR_BITMAP || !a->non_res)
1490 				continue;
1491 
1492 			svcn = le64_to_cpu(a->nres.svcn);
1493 			if (!svcn)
1494 				continue; /* Base record runs already loaded. */
1495 
1496 			evcn = le64_to_cpu(a->nres.evcn);
1497 			roff = le16_to_cpu(a->nres.run_off);
1498 
1499 			err = run_unpack_ex(&sbi->mft.bitmap.run, sbi,
1500 					    MFT_REC_MFT, svcn, evcn, svcn,
1501 					    Add2Ptr(a, roff),
1502 					    le32_to_cpu(a->size) - roff);
1503 			if (err < 0) {
1504 				ntfs_err(
1505 					sb,
1506 					"Failed to unpack $MFT bitmap extent (%d).",
1507 					err);
1508 				goto put_inode_out;
1509 			}
1510 			err = 0;
1511 		}
1512 	}
1513 
1514 	err = wnd_init(&sbi->mft.bitmap, sb, tt);
1515 	if (err)
1516 		goto put_inode_out;
1517 
1518 	sbi->mft.ni = ni;
1519 
1520 	/* Load $Bitmap. */
1521 	ref.low = cpu_to_le32(MFT_REC_BITMAP);
1522 	ref.seq = cpu_to_le16(MFT_REC_BITMAP);
1523 	inode = ntfs_iget5(sb, &ref, &NAME_BITMAP);
1524 	if (IS_ERR(inode)) {
1525 		err = PTR_ERR(inode);
1526 		ntfs_err(sb, "Failed to load $Bitmap (%d).", err);
1527 		goto out;
1528 	}
1529 
1530 #ifndef CONFIG_NTFS3_64BIT_CLUSTER
1531 	if (inode->i_size >> 32) {
1532 		err = -EINVAL;
1533 		goto put_inode_out;
1534 	}
1535 #endif
1536 
1537 	/* Check bitmap boundary. */
1538 	tt = sbi->used.bitmap.nbits;
1539 	if (inode->i_size < ntfs3_bitmap_size(tt)) {
1540 		ntfs_err(sb, "$Bitmap is corrupted.");
1541 		err = -EINVAL;
1542 		goto put_inode_out;
1543 	}
1544 
1545 	err = wnd_init(&sbi->used.bitmap, sb, tt);
1546 	if (err) {
1547 		ntfs_err(sb, "Failed to initialize $Bitmap (%d).", err);
1548 		goto put_inode_out;
1549 	}
1550 
1551 	iput(inode);
1552 
1553 	/* Compute the MFT zone. */
1554 	err = ntfs_refresh_zone(sbi);
1555 	if (err) {
1556 		ntfs_err(sb, "Failed to initialize MFT zone (%d).", err);
1557 		goto out;
1558 	}
1559 
1560 	/* Load $BadClus. */
1561 	ref.low = cpu_to_le32(MFT_REC_BADCLUST);
1562 	ref.seq = cpu_to_le16(MFT_REC_BADCLUST);
1563 	inode = ntfs_iget5(sb, &ref, &NAME_BADCLUS);
1564 	if (IS_ERR(inode)) {
1565 		err = PTR_ERR(inode);
1566 		ntfs_err(sb, "Failed to load $BadClus (%d).", err);
1567 		goto out;
1568 	}
1569 
1570 	ni = ntfs_i(inode);
1571 	bad_len = bad_frags = 0;
1572 	for (i = 0; run_get_entry(&ni->file.run, i, &vcn, &lcn, &len); i++) {
1573 		if (lcn == SPARSE_LCN)
1574 			continue;
1575 
1576 		bad_len += len;
1577 		bad_frags += 1;
1578 		if (ro)
1579 			continue;
1580 
1581 		if (wnd_set_used_safe(&sbi->used.bitmap, lcn, len, &tt) || tt) {
1582 			/* Bad blocks marked as free in bitmap. */
1583 			ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
1584 		}
1585 	}
1586 	if (bad_len) {
1587 		/*
1588 		 * Notice about bad blocks.
1589 		 * In normal cases these blocks are marked as used in bitmap.
1590 		 * And we never allocate space in it.
1591 		 */
1592 		ntfs_notice(sb,
1593 			    "Volume contains %zu bad blocks in %zu fragments.",
1594 			    bad_len, bad_frags);
1595 	}
1596 	iput(inode);
1597 
1598 	/* Load $AttrDef. */
1599 	ref.low = cpu_to_le32(MFT_REC_ATTR);
1600 	ref.seq = cpu_to_le16(MFT_REC_ATTR);
1601 	inode = ntfs_iget5(sb, &ref, &NAME_ATTRDEF);
1602 	if (IS_ERR(inode)) {
1603 		err = PTR_ERR(inode);
1604 		ntfs_err(sb, "Failed to load $AttrDef (%d)", err);
1605 		goto out;
1606 	}
1607 
1608 	/*
1609 	 * Typical $AttrDef contains up to 20 entries.
1610 	 * Check for extremely large/small size.
1611 	 */
1612 	if (inode->i_size < sizeof(struct ATTR_DEF_ENTRY) ||
1613 	    inode->i_size > 100 * sizeof(struct ATTR_DEF_ENTRY)) {
1614 		ntfs_err(sb, "Looks like $AttrDef is corrupted (size=%llu).",
1615 			 inode->i_size);
1616 		err = -EINVAL;
1617 		goto put_inode_out;
1618 	}
1619 
1620 	bytes = inode->i_size;
1621 	sbi->def_table = t = kvmalloc(bytes, GFP_KERNEL);
1622 	if (!t) {
1623 		err = -ENOMEM;
1624 		goto put_inode_out;
1625 	}
1626 
1627 	/* Read the entire file. */
1628 	err = inode_read_data(inode, sbi->def_table, bytes);
1629 	if (err) {
1630 		ntfs_err(sb, "Failed to read $AttrDef (%d).", err);
1631 		goto put_inode_out;
1632 	}
1633 
1634 	if (ATTR_STD != t->type) {
1635 		ntfs_err(sb, "$AttrDef is corrupted.");
1636 		err = -EINVAL;
1637 		goto put_inode_out;
1638 	}
1639 
1640 	t += 1;
1641 	sbi->def_entries = 1;
1642 	done = sizeof(struct ATTR_DEF_ENTRY);
1643 
1644 	while (done + sizeof(struct ATTR_DEF_ENTRY) <= bytes) {
1645 		u32 t32 = le32_to_cpu(t->type);
1646 		u64 sz = le64_to_cpu(t->max_sz);
1647 
1648 		if ((t32 & 0xF) || le32_to_cpu(t[-1].type) >= t32)
1649 			break;
1650 
1651 		if (t->type == ATTR_REPARSE)
1652 			sbi->reparse.max_size = sz;
1653 		else if (t->type == ATTR_EA)
1654 			sbi->ea_max_size = sz;
1655 
1656 		done += sizeof(struct ATTR_DEF_ENTRY);
1657 		t += 1;
1658 		sbi->def_entries += 1;
1659 	}
1660 	iput(inode);
1661 
1662 	/* Load $UpCase. */
1663 	ref.low = cpu_to_le32(MFT_REC_UPCASE);
1664 	ref.seq = cpu_to_le16(MFT_REC_UPCASE);
1665 	inode = ntfs_iget5(sb, &ref, &NAME_UPCASE);
1666 	if (IS_ERR(inode)) {
1667 		err = PTR_ERR(inode);
1668 		ntfs_err(sb, "Failed to load $UpCase (%d).", err);
1669 		goto out;
1670 	}
1671 
1672 	if (inode->i_size != 0x10000 * sizeof(short)) {
1673 		err = -EINVAL;
1674 		ntfs_err(sb, "$UpCase is corrupted.");
1675 		goto put_inode_out;
1676 	}
1677 
1678 	/* Read the entire file. */
1679 	err = inode_read_data(inode, sbi->upcase, 0x10000 * sizeof(short));
1680 	if (err) {
1681 		ntfs_err(sb, "Failed to read $UpCase (%d).", err);
1682 		goto put_inode_out;
1683 	}
1684 
1685 #ifdef __BIG_ENDIAN
1686 	{
1687 		u16 *dst = sbi->upcase;
1688 
1689 		for (i = 0; i < 0x10000; i++)
1690 			__swab16s(dst++);
1691 	}
1692 #endif
1693 
1694 	shared = ntfs_set_shared(sbi->upcase, 0x10000 * sizeof(short));
1695 	if (shared && sbi->upcase != shared) {
1696 		kvfree(sbi->upcase);
1697 		sbi->upcase = shared;
1698 	}
1699 
1700 	iput(inode);
1701 
1702 	if (is_ntfs3(sbi)) {
1703 		/* Load $Secure. */
1704 		err = ntfs_security_init(sbi);
1705 		if (err) {
1706 			ntfs_err(sb, "Failed to initialize $Secure (%d).", err);
1707 			goto out;
1708 		}
1709 
1710 		/* Load $Extend. */
1711 		err = ntfs_extend_init(sbi);
1712 		if (err) {
1713 			ntfs_warn(sb, "Failed to initialize $Extend.");
1714 			goto load_root;
1715 		}
1716 
1717 		/* Load $Extend/$Reparse. */
1718 		err = ntfs_reparse_init(sbi);
1719 		if (err) {
1720 			ntfs_warn(sb, "Failed to initialize $Extend/$Reparse.");
1721 			goto load_root;
1722 		}
1723 
1724 		/* Load $Extend/$ObjId. */
1725 		err = ntfs_objid_init(sbi);
1726 		if (err) {
1727 			ntfs_warn(sb, "Failed to initialize $Extend/$ObjId.");
1728 			goto load_root;
1729 		}
1730 	}
1731 
1732 load_root:
1733 	/* Load root. */
1734 	ref.low = cpu_to_le32(MFT_REC_ROOT);
1735 	ref.seq = cpu_to_le16(MFT_REC_ROOT);
1736 	inode = ntfs_iget5(sb, &ref, &NAME_ROOT);
1737 	if (IS_ERR(inode)) {
1738 		err = PTR_ERR(inode);
1739 		ntfs_err(sb, "Failed to load root (%d).", err);
1740 		goto out;
1741 	}
1742 
1743 	/*
1744 	 * Final check. Looks like this case should never occurs.
1745 	 */
1746 	if (!inode->i_op) {
1747 		err = -EINVAL;
1748 		ntfs_err(sb, "Failed to load root (%d).", err);
1749 		goto put_inode_out;
1750 	}
1751 
1752 	sb->s_root = d_make_root(inode);
1753 	if (!sb->s_root) {
1754 		err = -ENOMEM;
1755 		goto out;
1756 	}
1757 
1758 	if (boot2) {
1759 		/*
1760 	 	 * Alternative boot is ok but primary is not ok.
1761 	 	 * Volume is recognized as NTFS. Update primary boot.
1762 		 */
1763 		struct buffer_head *bh0 = sb_getblk(sb, 0);
1764 		if (bh0) {
1765 			wait_on_buffer(bh0);
1766 			lock_buffer(bh0);
1767 			memcpy(bh0->b_data, boot2, sizeof(*boot2));
1768 			set_buffer_uptodate(bh0);
1769 			mark_buffer_dirty(bh0);
1770 			unlock_buffer(bh0);
1771 			if (!sync_dirty_buffer(bh0))
1772 				ntfs_warn(sb, "primary boot is updated");
1773 			put_bh(bh0);
1774 		}
1775 
1776 		kfree(boot2);
1777 	}
1778 
1779 	ntfs_create_procdir(sb);
1780 
1781 	return 0;
1782 
1783 put_inode_out:
1784 	iput(inode);
1785 out:
1786 	/* sbi->options == options */
1787 	if (options) {
1788 		put_mount_options(sbi->options);
1789 		sbi->options = NULL;
1790 	}
1791 
1792 	ntfs3_put_sbi(sbi);
1793 	kfree(boot2);
1794 	return err;
1795 }
1796 
1797 void ntfs_unmap_meta(struct super_block *sb, CLST lcn, CLST len)
1798 {
1799 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1800 	struct block_device *bdev = sb->s_bdev;
1801 	sector_t devblock = (u64)lcn * sbi->blocks_per_cluster;
1802 	unsigned long blocks = (u64)len * sbi->blocks_per_cluster;
1803 	unsigned long cnt = 0;
1804 	unsigned long limit = global_zone_page_state(NR_FREE_PAGES)
1805 			      << (PAGE_SHIFT - sb->s_blocksize_bits);
1806 
1807 	if (limit >= 0x2000)
1808 		limit -= 0x1000;
1809 	else if (limit < 32)
1810 		limit = 32;
1811 	else
1812 		limit >>= 1;
1813 
1814 	while (blocks--) {
1815 		clean_bdev_aliases(bdev, devblock++, 1);
1816 		if (cnt++ >= limit) {
1817 			sync_blockdev(bdev);
1818 			cnt = 0;
1819 		}
1820 	}
1821 }
1822 
1823 /*
1824  * ntfs_discard - Issue a discard request (trim for SSD).
1825  */
1826 int ntfs_discard(struct ntfs_sb_info *sbi, CLST lcn, CLST len)
1827 {
1828 	int err;
1829 	u64 lbo, bytes, start, end;
1830 	struct super_block *sb;
1831 
1832 	if (sbi->used.next_free_lcn == lcn + len)
1833 		sbi->used.next_free_lcn = lcn;
1834 
1835 	if (sbi->flags & NTFS_FLAGS_NODISCARD)
1836 		return -EOPNOTSUPP;
1837 
1838 	if (!sbi->options->discard)
1839 		return -EOPNOTSUPP;
1840 
1841 	lbo = (u64)lcn << sbi->cluster_bits;
1842 	bytes = (u64)len << sbi->cluster_bits;
1843 
1844 	/* Align up 'start' on discard_granularity. */
1845 	start = (lbo + sbi->discard_granularity - 1) &
1846 		sbi->discard_granularity_mask_inv;
1847 	/* Align down 'end' on discard_granularity. */
1848 	end = (lbo + bytes) & sbi->discard_granularity_mask_inv;
1849 
1850 	sb = sbi->sb;
1851 	if (start >= end)
1852 		return 0;
1853 
1854 	err = blkdev_issue_discard(sb->s_bdev, start >> 9, (end - start) >> 9,
1855 				   GFP_NOFS);
1856 
1857 	if (err == -EOPNOTSUPP)
1858 		sbi->flags |= NTFS_FLAGS_NODISCARD;
1859 
1860 	return err;
1861 }
1862 
1863 static int ntfs_fs_get_tree(struct fs_context *fc)
1864 {
1865 	return get_tree_bdev(fc, ntfs_fill_super);
1866 }
1867 
1868 /*
1869  * ntfs_fs_free - Free fs_context.
1870  *
1871  * Note that this will be called after fill_super and reconfigure
1872  * even when they pass. So they have to take pointers if they pass.
1873  */
1874 static void ntfs_fs_free(struct fs_context *fc)
1875 {
1876 	struct ntfs_mount_options *opts = fc->fs_private;
1877 	struct ntfs_sb_info *sbi = fc->s_fs_info;
1878 
1879 	if (sbi) {
1880 		ntfs3_put_sbi(sbi);
1881 		ntfs3_free_sbi(sbi);
1882 	}
1883 
1884 	if (opts)
1885 		put_mount_options(opts);
1886 }
1887 
1888 // clang-format off
1889 static const struct fs_context_operations ntfs_context_ops = {
1890 	.parse_param	= ntfs_fs_parse_param,
1891 	.get_tree	= ntfs_fs_get_tree,
1892 	.reconfigure	= ntfs_fs_reconfigure,
1893 	.free		= ntfs_fs_free,
1894 };
1895 // clang-format on
1896 
1897 /*
1898  * ntfs_init_fs_context - Initialize sbi and opts
1899  *
1900  * This will called when mount/remount. We will first initialize
1901  * options so that if remount we can use just that.
1902  */
1903 static int ntfs_init_fs_context(struct fs_context *fc)
1904 {
1905 	struct ntfs_mount_options *opts;
1906 	struct ntfs_sb_info *sbi;
1907 
1908 	opts = kzalloc_obj(struct ntfs_mount_options, GFP_NOFS);
1909 	if (!opts)
1910 		return -ENOMEM;
1911 
1912 	/* Default options. */
1913 	opts->fs_uid = current_uid();
1914 	opts->fs_gid = current_gid();
1915 	opts->fs_fmask_inv = opts->fs_dmask_inv = ~current_umask();
1916 	opts->prealloc = 1;
1917 	opts->ads = 1;
1918 
1919 #ifdef CONFIG_NTFS3_FS_POSIX_ACL
1920 	/* Set the default value 'acl' */
1921 	fc->sb_flags |= SB_POSIXACL;
1922 #endif
1923 
1924 	if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE)
1925 		goto ok;
1926 
1927 	sbi = kzalloc_obj(struct ntfs_sb_info, GFP_NOFS);
1928 	if (!sbi)
1929 		goto free_opts;
1930 
1931 	sbi->upcase = kvmalloc(0x10000 * sizeof(short), GFP_KERNEL);
1932 	if (!sbi->upcase)
1933 		goto free_sbi;
1934 
1935 	ratelimit_state_init(&sbi->msg_ratelimit, DEFAULT_RATELIMIT_INTERVAL,
1936 			     DEFAULT_RATELIMIT_BURST);
1937 
1938 	mutex_init(&sbi->compress.mtx_lznt);
1939 #ifdef CONFIG_NTFS3_LZX_XPRESS
1940 	mutex_init(&sbi->compress.mtx_xpress);
1941 	mutex_init(&sbi->compress.mtx_lzx);
1942 #endif
1943 
1944 	fc->s_fs_info = sbi;
1945 ok:
1946 	fc->fs_private = opts;
1947 	fc->ops = &ntfs_context_ops;
1948 
1949 	return 0;
1950 free_sbi:
1951 	kfree(sbi);
1952 free_opts:
1953 	kfree(opts);
1954 	return -ENOMEM;
1955 }
1956 
1957 static void ntfs3_kill_sb(struct super_block *sb)
1958 {
1959 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1960 
1961 	kill_block_super(sb);
1962 
1963 	/*
1964 	 * A pathwalk in rcu mode may still be in ->d_hash() or ->d_compare()
1965 	 * and read the upcase table and the nls table through the sbi.
1966 	 */
1967 	call_rcu(&sbi->rcu, ntfs3_free_sbi_rcu);
1968 }
1969 
1970 // clang-format off
1971 static struct file_system_type ntfs_fs_type = {
1972 	.owner			= THIS_MODULE,
1973 	.name			= "ntfs3",
1974 	.init_fs_context	= ntfs_init_fs_context,
1975 	.parameters		= ntfs_fs_parameters,
1976 	.kill_sb		= ntfs3_kill_sb,
1977 	.fs_flags		= FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
1978 };
1979 // clang-format on
1980 
1981 static int __init init_ntfs_fs(void)
1982 {
1983 	int err;
1984 
1985 	if (IS_ENABLED(CONFIG_NTFS3_FS_POSIX_ACL))
1986 		pr_info("ntfs3: Enabled Linux POSIX ACLs support\n");
1987 	if (IS_ENABLED(CONFIG_NTFS3_64BIT_CLUSTER))
1988 		pr_notice(
1989 			"ntfs3: Warning: Activated 64 bits per cluster. Windows does not support this\n");
1990 	if (IS_ENABLED(CONFIG_NTFS3_LZX_XPRESS))
1991 		pr_info("ntfs3: Read-only LZX/Xpress compression included\n");
1992 
1993 	ntfs_create_proc_root();
1994 
1995 	err = ntfs3_init_bitmap();
1996 	if (err)
1997 		goto out2;
1998 
1999 	ntfs_inode_cachep = kmem_cache_create(
2000 		"ntfs_inode_cache", sizeof(struct ntfs_inode), 0,
2001 		(SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT), init_once);
2002 	if (!ntfs_inode_cachep) {
2003 		err = -ENOMEM;
2004 		goto out1;
2005 	}
2006 
2007 	err = register_filesystem(&ntfs_fs_type);
2008 	if (err)
2009 		goto out;
2010 
2011 	return 0;
2012 out:
2013 	kmem_cache_destroy(ntfs_inode_cachep);
2014 out1:
2015 	ntfs3_exit_bitmap();
2016 out2:
2017 	ntfs_remove_proc_root();
2018 	return err;
2019 }
2020 
2021 static void __exit exit_ntfs_fs(void)
2022 {
2023 	rcu_barrier();
2024 	kmem_cache_destroy(ntfs_inode_cachep);
2025 	unregister_filesystem(&ntfs_fs_type);
2026 	ntfs3_exit_bitmap();
2027 	ntfs_remove_proc_root();
2028 }
2029 
2030 MODULE_LICENSE("GPL");
2031 MODULE_DESCRIPTION("ntfs3 read/write filesystem");
2032 #ifdef CONFIG_NTFS3_FS_POSIX_ACL
2033 MODULE_INFO(behaviour, "Enabled Linux POSIX ACLs support");
2034 #endif
2035 #ifdef CONFIG_NTFS3_64BIT_CLUSTER
2036 MODULE_INFO(
2037 	cluster,
2038 	"Warning: Activated 64 bits per cluster. Windows does not support this");
2039 #endif
2040 #ifdef CONFIG_NTFS3_LZX_XPRESS
2041 MODULE_INFO(compression, "Read-only lzx/xpress compression included");
2042 #endif
2043 
2044 MODULE_AUTHOR("Konstantin Komarov");
2045 MODULE_ALIAS_FS("ntfs3");
2046 
2047 module_init(init_ntfs_fs);
2048 module_exit(exit_ntfs_fs);
2049