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