1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * super.c - NTFS kernel super block handling. Part of the Linux-NTFS project.
4 *
5 * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
6 * Copyright (c) 2001,2002 Richard Russon
7 */
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9
10 #include <linux/stddef.h>
11 #include <linux/init.h>
12 #include <linux/slab.h>
13 #include <linux/string.h>
14 #include <linux/spinlock.h>
15 #include <linux/blkdev.h> /* For bdev_logical_block_size(). */
16 #include <linux/backing-dev.h>
17 #include <linux/buffer_head.h>
18 #include <linux/vfs.h>
19 #include <linux/moduleparam.h>
20 #include <linux/bitmap.h>
21
22 #include "sysctl.h"
23 #include "logfile.h"
24 #include "quota.h"
25 #include "usnjrnl.h"
26 #include "dir.h"
27 #include "debug.h"
28 #include "index.h"
29 #include "inode.h"
30 #include "aops.h"
31 #include "layout.h"
32 #include "malloc.h"
33 #include "ntfs.h"
34
35 /* Number of mounted filesystems which have compression enabled. */
36 static unsigned long ntfs_nr_compression_users;
37
38 /* A global default upcase table and a corresponding reference count. */
39 static ntfschar *default_upcase;
40 static unsigned long ntfs_nr_upcase_users;
41
42 /* Error constants/strings used in inode.c::ntfs_show_options(). */
43 typedef enum {
44 /* One of these must be present, default is ON_ERRORS_CONTINUE. */
45 ON_ERRORS_PANIC = 0x01,
46 ON_ERRORS_REMOUNT_RO = 0x02,
47 ON_ERRORS_CONTINUE = 0x04,
48 /* Optional, can be combined with any of the above. */
49 ON_ERRORS_RECOVER = 0x10,
50 } ON_ERRORS_ACTIONS;
51
52 const option_t on_errors_arr[] = {
53 { ON_ERRORS_PANIC, "panic" },
54 { ON_ERRORS_REMOUNT_RO, "remount-ro", },
55 { ON_ERRORS_CONTINUE, "continue", },
56 { ON_ERRORS_RECOVER, "recover" },
57 { 0, NULL }
58 };
59
60 /**
61 * simple_getbool -
62 *
63 * Copied from old ntfs driver (which copied from vfat driver).
64 */
simple_getbool(char * s,bool * setval)65 static int simple_getbool(char *s, bool *setval)
66 {
67 if (s) {
68 if (!strcmp(s, "1") || !strcmp(s, "yes") || !strcmp(s, "true"))
69 *setval = true;
70 else if (!strcmp(s, "0") || !strcmp(s, "no") ||
71 !strcmp(s, "false"))
72 *setval = false;
73 else
74 return 0;
75 } else
76 *setval = true;
77 return 1;
78 }
79
80 /**
81 * parse_options - parse the (re)mount options
82 * @vol: ntfs volume
83 * @opt: string containing the (re)mount options
84 *
85 * Parse the recognized options in @opt for the ntfs volume described by @vol.
86 */
parse_options(ntfs_volume * vol,char * opt)87 static bool parse_options(ntfs_volume *vol, char *opt)
88 {
89 char *p, *v, *ov;
90 static char *utf8 = "utf8";
91 int errors = 0, sloppy = 0;
92 kuid_t uid = INVALID_UID;
93 kgid_t gid = INVALID_GID;
94 umode_t fmask = (umode_t)-1, dmask = (umode_t)-1;
95 int mft_zone_multiplier = -1, on_errors = -1;
96 int show_sys_files = -1, case_sensitive = -1, disable_sparse = -1;
97 struct nls_table *nls_map = NULL, *old_nls;
98
99 /* I am lazy... (-8 */
100 #define NTFS_GETOPT_WITH_DEFAULT(option, variable, default_value) \
101 if (!strcmp(p, option)) { \
102 if (!v || !*v) \
103 variable = default_value; \
104 else { \
105 variable = simple_strtoul(ov = v, &v, 0); \
106 if (*v) \
107 goto needs_val; \
108 } \
109 }
110 #define NTFS_GETOPT(option, variable) \
111 if (!strcmp(p, option)) { \
112 if (!v || !*v) \
113 goto needs_arg; \
114 variable = simple_strtoul(ov = v, &v, 0); \
115 if (*v) \
116 goto needs_val; \
117 }
118 #define NTFS_GETOPT_UID(option, variable) \
119 if (!strcmp(p, option)) { \
120 uid_t uid_value; \
121 if (!v || !*v) \
122 goto needs_arg; \
123 uid_value = simple_strtoul(ov = v, &v, 0); \
124 if (*v) \
125 goto needs_val; \
126 variable = make_kuid(current_user_ns(), uid_value); \
127 if (!uid_valid(variable)) \
128 goto needs_val; \
129 }
130 #define NTFS_GETOPT_GID(option, variable) \
131 if (!strcmp(p, option)) { \
132 gid_t gid_value; \
133 if (!v || !*v) \
134 goto needs_arg; \
135 gid_value = simple_strtoul(ov = v, &v, 0); \
136 if (*v) \
137 goto needs_val; \
138 variable = make_kgid(current_user_ns(), gid_value); \
139 if (!gid_valid(variable)) \
140 goto needs_val; \
141 }
142 #define NTFS_GETOPT_OCTAL(option, variable) \
143 if (!strcmp(p, option)) { \
144 if (!v || !*v) \
145 goto needs_arg; \
146 variable = simple_strtoul(ov = v, &v, 8); \
147 if (*v) \
148 goto needs_val; \
149 }
150 #define NTFS_GETOPT_BOOL(option, variable) \
151 if (!strcmp(p, option)) { \
152 bool val; \
153 if (!simple_getbool(v, &val)) \
154 goto needs_bool; \
155 variable = val; \
156 }
157 #define NTFS_GETOPT_OPTIONS_ARRAY(option, variable, opt_array) \
158 if (!strcmp(p, option)) { \
159 int _i; \
160 if (!v || !*v) \
161 goto needs_arg; \
162 ov = v; \
163 if (variable == -1) \
164 variable = 0; \
165 for (_i = 0; opt_array[_i].str && *opt_array[_i].str; _i++) \
166 if (!strcmp(opt_array[_i].str, v)) { \
167 variable |= opt_array[_i].val; \
168 break; \
169 } \
170 if (!opt_array[_i].str || !*opt_array[_i].str) \
171 goto needs_val; \
172 }
173 if (!opt || !*opt)
174 goto no_mount_options;
175 ntfs_debug("Entering with mount options string: %s", opt);
176 while ((p = strsep(&opt, ","))) {
177 if ((v = strchr(p, '=')))
178 *v++ = 0;
179 NTFS_GETOPT_UID("uid", uid)
180 else NTFS_GETOPT_GID("gid", gid)
181 else NTFS_GETOPT_OCTAL("umask", fmask = dmask)
182 else NTFS_GETOPT_OCTAL("fmask", fmask)
183 else NTFS_GETOPT_OCTAL("dmask", dmask)
184 else NTFS_GETOPT("mft_zone_multiplier", mft_zone_multiplier)
185 else NTFS_GETOPT_WITH_DEFAULT("sloppy", sloppy, true)
186 else NTFS_GETOPT_BOOL("show_sys_files", show_sys_files)
187 else NTFS_GETOPT_BOOL("case_sensitive", case_sensitive)
188 else NTFS_GETOPT_BOOL("disable_sparse", disable_sparse)
189 else NTFS_GETOPT_OPTIONS_ARRAY("errors", on_errors,
190 on_errors_arr)
191 else if (!strcmp(p, "posix") || !strcmp(p, "show_inodes"))
192 ntfs_warning(vol->sb, "Ignoring obsolete option %s.",
193 p);
194 else if (!strcmp(p, "nls") || !strcmp(p, "iocharset")) {
195 if (!strcmp(p, "iocharset"))
196 ntfs_warning(vol->sb, "Option iocharset is "
197 "deprecated. Please use "
198 "option nls=<charsetname> in "
199 "the future.");
200 if (!v || !*v)
201 goto needs_arg;
202 use_utf8:
203 old_nls = nls_map;
204 nls_map = load_nls(v);
205 if (!nls_map) {
206 if (!old_nls) {
207 ntfs_error(vol->sb, "NLS character set "
208 "%s not found.", v);
209 return false;
210 }
211 ntfs_error(vol->sb, "NLS character set %s not "
212 "found. Using previous one %s.",
213 v, old_nls->charset);
214 nls_map = old_nls;
215 } else /* nls_map */ {
216 unload_nls(old_nls);
217 }
218 } else if (!strcmp(p, "utf8")) {
219 bool val = false;
220 ntfs_warning(vol->sb, "Option utf8 is no longer "
221 "supported, using option nls=utf8. Please "
222 "use option nls=utf8 in the future and "
223 "make sure utf8 is compiled either as a "
224 "module or into the kernel.");
225 if (!v || !*v)
226 val = true;
227 else if (!simple_getbool(v, &val))
228 goto needs_bool;
229 if (val) {
230 v = utf8;
231 goto use_utf8;
232 }
233 } else {
234 ntfs_error(vol->sb, "Unrecognized mount option %s.", p);
235 if (errors < INT_MAX)
236 errors++;
237 }
238 #undef NTFS_GETOPT_OPTIONS_ARRAY
239 #undef NTFS_GETOPT_BOOL
240 #undef NTFS_GETOPT
241 #undef NTFS_GETOPT_WITH_DEFAULT
242 }
243 no_mount_options:
244 if (errors && !sloppy)
245 return false;
246 if (sloppy)
247 ntfs_warning(vol->sb, "Sloppy option given. Ignoring "
248 "unrecognized mount option(s) and continuing.");
249 /* Keep this first! */
250 if (on_errors != -1) {
251 if (!on_errors) {
252 ntfs_error(vol->sb, "Invalid errors option argument "
253 "or bug in options parser.");
254 return false;
255 }
256 }
257 if (nls_map) {
258 if (vol->nls_map && vol->nls_map != nls_map) {
259 ntfs_error(vol->sb, "Cannot change NLS character set "
260 "on remount.");
261 return false;
262 } /* else (!vol->nls_map) */
263 ntfs_debug("Using NLS character set %s.", nls_map->charset);
264 vol->nls_map = nls_map;
265 } else /* (!nls_map) */ {
266 if (!vol->nls_map) {
267 vol->nls_map = load_nls_default();
268 if (!vol->nls_map) {
269 ntfs_error(vol->sb, "Failed to load default "
270 "NLS character set.");
271 return false;
272 }
273 ntfs_debug("Using default NLS character set (%s).",
274 vol->nls_map->charset);
275 }
276 }
277 if (mft_zone_multiplier != -1) {
278 if (vol->mft_zone_multiplier && vol->mft_zone_multiplier !=
279 mft_zone_multiplier) {
280 ntfs_error(vol->sb, "Cannot change mft_zone_multiplier "
281 "on remount.");
282 return false;
283 }
284 if (mft_zone_multiplier < 1 || mft_zone_multiplier > 4) {
285 ntfs_error(vol->sb, "Invalid mft_zone_multiplier. "
286 "Using default value, i.e. 1.");
287 mft_zone_multiplier = 1;
288 }
289 vol->mft_zone_multiplier = mft_zone_multiplier;
290 }
291 if (!vol->mft_zone_multiplier)
292 vol->mft_zone_multiplier = 1;
293 if (on_errors != -1)
294 vol->on_errors = on_errors;
295 if (!vol->on_errors || vol->on_errors == ON_ERRORS_RECOVER)
296 vol->on_errors |= ON_ERRORS_CONTINUE;
297 if (uid_valid(uid))
298 vol->uid = uid;
299 if (gid_valid(gid))
300 vol->gid = gid;
301 if (fmask != (umode_t)-1)
302 vol->fmask = fmask;
303 if (dmask != (umode_t)-1)
304 vol->dmask = dmask;
305 if (show_sys_files != -1) {
306 if (show_sys_files)
307 NVolSetShowSystemFiles(vol);
308 else
309 NVolClearShowSystemFiles(vol);
310 }
311 if (case_sensitive != -1) {
312 if (case_sensitive)
313 NVolSetCaseSensitive(vol);
314 else
315 NVolClearCaseSensitive(vol);
316 }
317 if (disable_sparse != -1) {
318 if (disable_sparse)
319 NVolClearSparseEnabled(vol);
320 else {
321 if (!NVolSparseEnabled(vol) &&
322 vol->major_ver && vol->major_ver < 3)
323 ntfs_warning(vol->sb, "Not enabling sparse "
324 "support due to NTFS volume "
325 "version %i.%i (need at least "
326 "version 3.0).", vol->major_ver,
327 vol->minor_ver);
328 else
329 NVolSetSparseEnabled(vol);
330 }
331 }
332 return true;
333 needs_arg:
334 ntfs_error(vol->sb, "The %s option requires an argument.", p);
335 return false;
336 needs_bool:
337 ntfs_error(vol->sb, "The %s option requires a boolean argument.", p);
338 return false;
339 needs_val:
340 ntfs_error(vol->sb, "Invalid %s option argument: %s", p, ov);
341 return false;
342 }
343
344 #ifdef NTFS_RW
345
346 /**
347 * ntfs_write_volume_flags - write new flags to the volume information flags
348 * @vol: ntfs volume on which to modify the flags
349 * @flags: new flags value for the volume information flags
350 *
351 * Internal function. You probably want to use ntfs_{set,clear}_volume_flags()
352 * instead (see below).
353 *
354 * Replace the volume information flags on the volume @vol with the value
355 * supplied in @flags. Note, this overwrites the volume information flags, so
356 * make sure to combine the flags you want to modify with the old flags and use
357 * the result when calling ntfs_write_volume_flags().
358 *
359 * Return 0 on success and -errno on error.
360 */
ntfs_write_volume_flags(ntfs_volume * vol,const VOLUME_FLAGS flags)361 static int ntfs_write_volume_flags(ntfs_volume *vol, const VOLUME_FLAGS flags)
362 {
363 ntfs_inode *ni = NTFS_I(vol->vol_ino);
364 MFT_RECORD *m;
365 VOLUME_INFORMATION *vi;
366 ntfs_attr_search_ctx *ctx;
367 int err;
368
369 ntfs_debug("Entering, old flags = 0x%x, new flags = 0x%x.",
370 le16_to_cpu(vol->vol_flags), le16_to_cpu(flags));
371 if (vol->vol_flags == flags)
372 goto done;
373 BUG_ON(!ni);
374 m = map_mft_record(ni);
375 if (IS_ERR(m)) {
376 err = PTR_ERR(m);
377 goto err_out;
378 }
379 ctx = ntfs_attr_get_search_ctx(ni, m);
380 if (!ctx) {
381 err = -ENOMEM;
382 goto put_unm_err_out;
383 }
384 err = ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
385 ctx);
386 if (err)
387 goto put_unm_err_out;
388 vi = (VOLUME_INFORMATION*)((u8*)ctx->attr +
389 le16_to_cpu(ctx->attr->data.resident.value_offset));
390 vol->vol_flags = vi->flags = flags;
391 flush_dcache_mft_record_page(ctx->ntfs_ino);
392 mark_mft_record_dirty(ctx->ntfs_ino);
393 ntfs_attr_put_search_ctx(ctx);
394 unmap_mft_record(ni);
395 done:
396 ntfs_debug("Done.");
397 return 0;
398 put_unm_err_out:
399 if (ctx)
400 ntfs_attr_put_search_ctx(ctx);
401 unmap_mft_record(ni);
402 err_out:
403 ntfs_error(vol->sb, "Failed with error code %i.", -err);
404 return err;
405 }
406
407 /**
408 * ntfs_set_volume_flags - set bits in the volume information flags
409 * @vol: ntfs volume on which to modify the flags
410 * @flags: flags to set on the volume
411 *
412 * Set the bits in @flags in the volume information flags on the volume @vol.
413 *
414 * Return 0 on success and -errno on error.
415 */
ntfs_set_volume_flags(ntfs_volume * vol,VOLUME_FLAGS flags)416 static inline int ntfs_set_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
417 {
418 flags &= VOLUME_FLAGS_MASK;
419 return ntfs_write_volume_flags(vol, vol->vol_flags | flags);
420 }
421
422 /**
423 * ntfs_clear_volume_flags - clear bits in the volume information flags
424 * @vol: ntfs volume on which to modify the flags
425 * @flags: flags to clear on the volume
426 *
427 * Clear the bits in @flags in the volume information flags on the volume @vol.
428 *
429 * Return 0 on success and -errno on error.
430 */
ntfs_clear_volume_flags(ntfs_volume * vol,VOLUME_FLAGS flags)431 static inline int ntfs_clear_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
432 {
433 flags &= VOLUME_FLAGS_MASK;
434 flags = vol->vol_flags & cpu_to_le16(~le16_to_cpu(flags));
435 return ntfs_write_volume_flags(vol, flags);
436 }
437
438 #endif /* NTFS_RW */
439
440 /**
441 * ntfs_remount - change the mount options of a mounted ntfs filesystem
442 * @sb: superblock of mounted ntfs filesystem
443 * @flags: remount flags
444 * @opt: remount options string
445 *
446 * Change the mount options of an already mounted ntfs filesystem.
447 *
448 * NOTE: The VFS sets the @sb->s_flags remount flags to @flags after
449 * ntfs_remount() returns successfully (i.e. returns 0). Otherwise,
450 * @sb->s_flags are not changed.
451 */
ntfs_remount(struct super_block * sb,int * flags,char * opt)452 static int ntfs_remount(struct super_block *sb, int *flags, char *opt)
453 {
454 ntfs_volume *vol = NTFS_SB(sb);
455
456 ntfs_debug("Entering with remount options string: %s", opt);
457
458 sync_filesystem(sb);
459
460 #ifndef NTFS_RW
461 /* For read-only compiled driver, enforce read-only flag. */
462 *flags |= SB_RDONLY;
463 #else /* NTFS_RW */
464 /*
465 * For the read-write compiled driver, if we are remounting read-write,
466 * make sure there are no volume errors and that no unsupported volume
467 * flags are set. Also, empty the logfile journal as it would become
468 * stale as soon as something is written to the volume and mark the
469 * volume dirty so that chkdsk is run if the volume is not umounted
470 * cleanly. Finally, mark the quotas out of date so Windows rescans
471 * the volume on boot and updates them.
472 *
473 * When remounting read-only, mark the volume clean if no volume errors
474 * have occurred.
475 */
476 if (sb_rdonly(sb) && !(*flags & SB_RDONLY)) {
477 static const char *es = ". Cannot remount read-write.";
478
479 /* Remounting read-write. */
480 if (NVolErrors(vol)) {
481 ntfs_error(sb, "Volume has errors and is read-only%s",
482 es);
483 return -EROFS;
484 }
485 if (vol->vol_flags & VOLUME_IS_DIRTY) {
486 ntfs_error(sb, "Volume is dirty and read-only%s", es);
487 return -EROFS;
488 }
489 if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
490 ntfs_error(sb, "Volume has been modified by chkdsk "
491 "and is read-only%s", es);
492 return -EROFS;
493 }
494 if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
495 ntfs_error(sb, "Volume has unsupported flags set "
496 "(0x%x) and is read-only%s",
497 (unsigned)le16_to_cpu(vol->vol_flags),
498 es);
499 return -EROFS;
500 }
501 if (ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
502 ntfs_error(sb, "Failed to set dirty bit in volume "
503 "information flags%s", es);
504 return -EROFS;
505 }
506 #if 0
507 // TODO: Enable this code once we start modifying anything that
508 // is different between NTFS 1.2 and 3.x...
509 /* Set NT4 compatibility flag on newer NTFS version volumes. */
510 if ((vol->major_ver > 1)) {
511 if (ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
512 ntfs_error(sb, "Failed to set NT4 "
513 "compatibility flag%s", es);
514 NVolSetErrors(vol);
515 return -EROFS;
516 }
517 }
518 #endif
519 if (!ntfs_empty_logfile(vol->logfile_ino)) {
520 ntfs_error(sb, "Failed to empty journal $LogFile%s",
521 es);
522 NVolSetErrors(vol);
523 return -EROFS;
524 }
525 if (!ntfs_mark_quotas_out_of_date(vol)) {
526 ntfs_error(sb, "Failed to mark quotas out of date%s",
527 es);
528 NVolSetErrors(vol);
529 return -EROFS;
530 }
531 if (!ntfs_stamp_usnjrnl(vol)) {
532 ntfs_error(sb, "Failed to stamp transaction log "
533 "($UsnJrnl)%s", es);
534 NVolSetErrors(vol);
535 return -EROFS;
536 }
537 } else if (!sb_rdonly(sb) && (*flags & SB_RDONLY)) {
538 /* Remounting read-only. */
539 if (!NVolErrors(vol)) {
540 if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
541 ntfs_warning(sb, "Failed to clear dirty bit "
542 "in volume information "
543 "flags. Run chkdsk.");
544 }
545 }
546 #endif /* NTFS_RW */
547
548 // TODO: Deal with *flags.
549
550 if (!parse_options(vol, opt))
551 return -EINVAL;
552
553 ntfs_debug("Done.");
554 return 0;
555 }
556
557 /**
558 * is_boot_sector_ntfs - check whether a boot sector is a valid NTFS boot sector
559 * @sb: Super block of the device to which @b belongs.
560 * @b: Boot sector of device @sb to check.
561 * @silent: If 'true', all output will be silenced.
562 *
563 * is_boot_sector_ntfs() checks whether the boot sector @b is a valid NTFS boot
564 * sector. Returns 'true' if it is valid and 'false' if not.
565 *
566 * @sb is only needed for warning/error output, i.e. it can be NULL when silent
567 * is 'true'.
568 */
is_boot_sector_ntfs(const struct super_block * sb,const NTFS_BOOT_SECTOR * b,const bool silent)569 static bool is_boot_sector_ntfs(const struct super_block *sb,
570 const NTFS_BOOT_SECTOR *b, const bool silent)
571 {
572 /*
573 * Check that checksum == sum of u32 values from b to the checksum
574 * field. If checksum is zero, no checking is done. We will work when
575 * the checksum test fails, since some utilities update the boot sector
576 * ignoring the checksum which leaves the checksum out-of-date. We
577 * report a warning if this is the case.
578 */
579 if ((void*)b < (void*)&b->checksum && b->checksum && !silent) {
580 le32 *u;
581 u32 i;
582
583 for (i = 0, u = (le32*)b; u < (le32*)(&b->checksum); ++u)
584 i += le32_to_cpup(u);
585 if (le32_to_cpu(b->checksum) != i)
586 ntfs_warning(sb, "Invalid boot sector checksum.");
587 }
588 /* Check OEMidentifier is "NTFS " */
589 if (b->oem_id != magicNTFS)
590 goto not_ntfs;
591 /* Check bytes per sector value is between 256 and 4096. */
592 if (le16_to_cpu(b->bpb.bytes_per_sector) < 0x100 ||
593 le16_to_cpu(b->bpb.bytes_per_sector) > 0x1000)
594 goto not_ntfs;
595 /* Check sectors per cluster value is valid. */
596 switch (b->bpb.sectors_per_cluster) {
597 case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128:
598 break;
599 default:
600 goto not_ntfs;
601 }
602 /* Check the cluster size is not above the maximum (64kiB). */
603 if ((u32)le16_to_cpu(b->bpb.bytes_per_sector) *
604 b->bpb.sectors_per_cluster > NTFS_MAX_CLUSTER_SIZE)
605 goto not_ntfs;
606 /* Check reserved/unused fields are really zero. */
607 if (le16_to_cpu(b->bpb.reserved_sectors) ||
608 le16_to_cpu(b->bpb.root_entries) ||
609 le16_to_cpu(b->bpb.sectors) ||
610 le16_to_cpu(b->bpb.sectors_per_fat) ||
611 le32_to_cpu(b->bpb.large_sectors) || b->bpb.fats)
612 goto not_ntfs;
613 /* Check clusters per file mft record value is valid. */
614 if ((u8)b->clusters_per_mft_record < 0xe1 ||
615 (u8)b->clusters_per_mft_record > 0xf7)
616 switch (b->clusters_per_mft_record) {
617 case 1: case 2: case 4: case 8: case 16: case 32: case 64:
618 break;
619 default:
620 goto not_ntfs;
621 }
622 /* Check clusters per index block value is valid. */
623 if ((u8)b->clusters_per_index_record < 0xe1 ||
624 (u8)b->clusters_per_index_record > 0xf7)
625 switch (b->clusters_per_index_record) {
626 case 1: case 2: case 4: case 8: case 16: case 32: case 64:
627 break;
628 default:
629 goto not_ntfs;
630 }
631 /*
632 * Check for valid end of sector marker. We will work without it, but
633 * many BIOSes will refuse to boot from a bootsector if the magic is
634 * incorrect, so we emit a warning.
635 */
636 if (!silent && b->end_of_sector_marker != cpu_to_le16(0xaa55))
637 ntfs_warning(sb, "Invalid end of sector marker.");
638 return true;
639 not_ntfs:
640 return false;
641 }
642
643 /**
644 * read_ntfs_boot_sector - read the NTFS boot sector of a device
645 * @sb: super block of device to read the boot sector from
646 * @silent: if true, suppress all output
647 *
648 * Reads the boot sector from the device and validates it. If that fails, tries
649 * to read the backup boot sector, first from the end of the device a-la NT4 and
650 * later and then from the middle of the device a-la NT3.51 and before.
651 *
652 * If a valid boot sector is found but it is not the primary boot sector, we
653 * repair the primary boot sector silently (unless the device is read-only or
654 * the primary boot sector is not accessible).
655 *
656 * NOTE: To call this function, @sb must have the fields s_dev, the ntfs super
657 * block (u.ntfs_sb), nr_blocks and the device flags (s_flags) initialized
658 * to their respective values.
659 *
660 * Return the unlocked buffer head containing the boot sector or NULL on error.
661 */
read_ntfs_boot_sector(struct super_block * sb,const int silent)662 static struct buffer_head *read_ntfs_boot_sector(struct super_block *sb,
663 const int silent)
664 {
665 const char *read_err_str = "Unable to read %s boot sector.";
666 struct buffer_head *bh_primary, *bh_backup;
667 sector_t nr_blocks = NTFS_SB(sb)->nr_blocks;
668
669 /* Try to read primary boot sector. */
670 if ((bh_primary = sb_bread(sb, 0))) {
671 if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
672 bh_primary->b_data, silent))
673 return bh_primary;
674 if (!silent)
675 ntfs_error(sb, "Primary boot sector is invalid.");
676 } else if (!silent)
677 ntfs_error(sb, read_err_str, "primary");
678 if (!(NTFS_SB(sb)->on_errors & ON_ERRORS_RECOVER)) {
679 if (bh_primary)
680 brelse(bh_primary);
681 if (!silent)
682 ntfs_error(sb, "Mount option errors=recover not used. "
683 "Aborting without trying to recover.");
684 return NULL;
685 }
686 /* Try to read NT4+ backup boot sector. */
687 if ((bh_backup = sb_bread(sb, nr_blocks - 1))) {
688 if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
689 bh_backup->b_data, silent))
690 goto hotfix_primary_boot_sector;
691 brelse(bh_backup);
692 } else if (!silent)
693 ntfs_error(sb, read_err_str, "backup");
694 /* Try to read NT3.51- backup boot sector. */
695 if ((bh_backup = sb_bread(sb, nr_blocks >> 1))) {
696 if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
697 bh_backup->b_data, silent))
698 goto hotfix_primary_boot_sector;
699 if (!silent)
700 ntfs_error(sb, "Could not find a valid backup boot "
701 "sector.");
702 brelse(bh_backup);
703 } else if (!silent)
704 ntfs_error(sb, read_err_str, "backup");
705 /* We failed. Cleanup and return. */
706 if (bh_primary)
707 brelse(bh_primary);
708 return NULL;
709 hotfix_primary_boot_sector:
710 if (bh_primary) {
711 /*
712 * If we managed to read sector zero and the volume is not
713 * read-only, copy the found, valid backup boot sector to the
714 * primary boot sector. Note we only copy the actual boot
715 * sector structure, not the actual whole device sector as that
716 * may be bigger and would potentially damage the $Boot system
717 * file (FIXME: Would be nice to know if the backup boot sector
718 * on a large sector device contains the whole boot loader or
719 * just the first 512 bytes).
720 */
721 if (!sb_rdonly(sb)) {
722 ntfs_warning(sb, "Hot-fix: Recovering invalid primary "
723 "boot sector from backup copy.");
724 memcpy(bh_primary->b_data, bh_backup->b_data,
725 NTFS_BLOCK_SIZE);
726 mark_buffer_dirty(bh_primary);
727 sync_dirty_buffer(bh_primary);
728 if (buffer_uptodate(bh_primary)) {
729 brelse(bh_backup);
730 return bh_primary;
731 }
732 ntfs_error(sb, "Hot-fix: Device write error while "
733 "recovering primary boot sector.");
734 } else {
735 ntfs_warning(sb, "Hot-fix: Recovery of primary boot "
736 "sector failed: Read-only mount.");
737 }
738 brelse(bh_primary);
739 }
740 ntfs_warning(sb, "Using backup boot sector.");
741 return bh_backup;
742 }
743
744 /**
745 * parse_ntfs_boot_sector - parse the boot sector and store the data in @vol
746 * @vol: volume structure to initialise with data from boot sector
747 * @b: boot sector to parse
748 *
749 * Parse the ntfs boot sector @b and store all imporant information therein in
750 * the ntfs super block @vol. Return 'true' on success and 'false' on error.
751 */
parse_ntfs_boot_sector(ntfs_volume * vol,const NTFS_BOOT_SECTOR * b)752 static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)
753 {
754 unsigned int sectors_per_cluster_bits, nr_hidden_sects;
755 int clusters_per_mft_record, clusters_per_index_record;
756 s64 ll;
757
758 vol->sector_size = le16_to_cpu(b->bpb.bytes_per_sector);
759 vol->sector_size_bits = ffs(vol->sector_size) - 1;
760 ntfs_debug("vol->sector_size = %i (0x%x)", vol->sector_size,
761 vol->sector_size);
762 ntfs_debug("vol->sector_size_bits = %i (0x%x)", vol->sector_size_bits,
763 vol->sector_size_bits);
764 if (vol->sector_size < vol->sb->s_blocksize) {
765 ntfs_error(vol->sb, "Sector size (%i) is smaller than the "
766 "device block size (%lu). This is not "
767 "supported. Sorry.", vol->sector_size,
768 vol->sb->s_blocksize);
769 return false;
770 }
771 ntfs_debug("sectors_per_cluster = 0x%x", b->bpb.sectors_per_cluster);
772 sectors_per_cluster_bits = ffs(b->bpb.sectors_per_cluster) - 1;
773 ntfs_debug("sectors_per_cluster_bits = 0x%x",
774 sectors_per_cluster_bits);
775 nr_hidden_sects = le32_to_cpu(b->bpb.hidden_sectors);
776 ntfs_debug("number of hidden sectors = 0x%x", nr_hidden_sects);
777 vol->cluster_size = vol->sector_size << sectors_per_cluster_bits;
778 vol->cluster_size_mask = vol->cluster_size - 1;
779 vol->cluster_size_bits = ffs(vol->cluster_size) - 1;
780 ntfs_debug("vol->cluster_size = %i (0x%x)", vol->cluster_size,
781 vol->cluster_size);
782 ntfs_debug("vol->cluster_size_mask = 0x%x", vol->cluster_size_mask);
783 ntfs_debug("vol->cluster_size_bits = %i", vol->cluster_size_bits);
784 if (vol->cluster_size < vol->sector_size) {
785 ntfs_error(vol->sb, "Cluster size (%i) is smaller than the "
786 "sector size (%i). This is not supported. "
787 "Sorry.", vol->cluster_size, vol->sector_size);
788 return false;
789 }
790 clusters_per_mft_record = b->clusters_per_mft_record;
791 ntfs_debug("clusters_per_mft_record = %i (0x%x)",
792 clusters_per_mft_record, clusters_per_mft_record);
793 if (clusters_per_mft_record > 0)
794 vol->mft_record_size = vol->cluster_size <<
795 (ffs(clusters_per_mft_record) - 1);
796 else
797 /*
798 * When mft_record_size < cluster_size, clusters_per_mft_record
799 * = -log2(mft_record_size) bytes. mft_record_size normaly is
800 * 1024 bytes, which is encoded as 0xF6 (-10 in decimal).
801 */
802 vol->mft_record_size = 1 << -clusters_per_mft_record;
803 vol->mft_record_size_mask = vol->mft_record_size - 1;
804 vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1;
805 ntfs_debug("vol->mft_record_size = %i (0x%x)", vol->mft_record_size,
806 vol->mft_record_size);
807 ntfs_debug("vol->mft_record_size_mask = 0x%x",
808 vol->mft_record_size_mask);
809 ntfs_debug("vol->mft_record_size_bits = %i (0x%x)",
810 vol->mft_record_size_bits, vol->mft_record_size_bits);
811 /*
812 * We cannot support mft record sizes above the PAGE_SIZE since
813 * we store $MFT/$DATA, the table of mft records in the page cache.
814 */
815 if (vol->mft_record_size > PAGE_SIZE) {
816 ntfs_error(vol->sb, "Mft record size (%i) exceeds the "
817 "PAGE_SIZE on your system (%lu). "
818 "This is not supported. Sorry.",
819 vol->mft_record_size, PAGE_SIZE);
820 return false;
821 }
822 /* We cannot support mft record sizes below the sector size. */
823 if (vol->mft_record_size < vol->sector_size) {
824 ntfs_error(vol->sb, "Mft record size (%i) is smaller than the "
825 "sector size (%i). This is not supported. "
826 "Sorry.", vol->mft_record_size,
827 vol->sector_size);
828 return false;
829 }
830 clusters_per_index_record = b->clusters_per_index_record;
831 ntfs_debug("clusters_per_index_record = %i (0x%x)",
832 clusters_per_index_record, clusters_per_index_record);
833 if (clusters_per_index_record > 0)
834 vol->index_record_size = vol->cluster_size <<
835 (ffs(clusters_per_index_record) - 1);
836 else
837 /*
838 * When index_record_size < cluster_size,
839 * clusters_per_index_record = -log2(index_record_size) bytes.
840 * index_record_size normaly equals 4096 bytes, which is
841 * encoded as 0xF4 (-12 in decimal).
842 */
843 vol->index_record_size = 1 << -clusters_per_index_record;
844 vol->index_record_size_mask = vol->index_record_size - 1;
845 vol->index_record_size_bits = ffs(vol->index_record_size) - 1;
846 ntfs_debug("vol->index_record_size = %i (0x%x)",
847 vol->index_record_size, vol->index_record_size);
848 ntfs_debug("vol->index_record_size_mask = 0x%x",
849 vol->index_record_size_mask);
850 ntfs_debug("vol->index_record_size_bits = %i (0x%x)",
851 vol->index_record_size_bits,
852 vol->index_record_size_bits);
853 /* We cannot support index record sizes below the sector size. */
854 if (vol->index_record_size < vol->sector_size) {
855 ntfs_error(vol->sb, "Index record size (%i) is smaller than "
856 "the sector size (%i). This is not "
857 "supported. Sorry.", vol->index_record_size,
858 vol->sector_size);
859 return false;
860 }
861 /*
862 * Get the size of the volume in clusters and check for 64-bit-ness.
863 * Windows currently only uses 32 bits to save the clusters so we do
864 * the same as it is much faster on 32-bit CPUs.
865 */
866 ll = sle64_to_cpu(b->number_of_sectors) >> sectors_per_cluster_bits;
867 if ((u64)ll >= 1ULL << 32) {
868 ntfs_error(vol->sb, "Cannot handle 64-bit clusters. Sorry.");
869 return false;
870 }
871 vol->nr_clusters = ll;
872 ntfs_debug("vol->nr_clusters = 0x%llx", (long long)vol->nr_clusters);
873 /*
874 * On an architecture where unsigned long is 32-bits, we restrict the
875 * volume size to 2TiB (2^41). On a 64-bit architecture, the compiler
876 * will hopefully optimize the whole check away.
877 */
878 if (sizeof(unsigned long) < 8) {
879 if ((ll << vol->cluster_size_bits) >= (1ULL << 41)) {
880 ntfs_error(vol->sb, "Volume size (%lluTiB) is too "
881 "large for this architecture. "
882 "Maximum supported is 2TiB. Sorry.",
883 (unsigned long long)ll >> (40 -
884 vol->cluster_size_bits));
885 return false;
886 }
887 }
888 ll = sle64_to_cpu(b->mft_lcn);
889 if (ll >= vol->nr_clusters) {
890 ntfs_error(vol->sb, "MFT LCN (%lli, 0x%llx) is beyond end of "
891 "volume. Weird.", (unsigned long long)ll,
892 (unsigned long long)ll);
893 return false;
894 }
895 vol->mft_lcn = ll;
896 ntfs_debug("vol->mft_lcn = 0x%llx", (long long)vol->mft_lcn);
897 ll = sle64_to_cpu(b->mftmirr_lcn);
898 if (ll >= vol->nr_clusters) {
899 ntfs_error(vol->sb, "MFTMirr LCN (%lli, 0x%llx) is beyond end "
900 "of volume. Weird.", (unsigned long long)ll,
901 (unsigned long long)ll);
902 return false;
903 }
904 vol->mftmirr_lcn = ll;
905 ntfs_debug("vol->mftmirr_lcn = 0x%llx", (long long)vol->mftmirr_lcn);
906 #ifdef NTFS_RW
907 /*
908 * Work out the size of the mft mirror in number of mft records. If the
909 * cluster size is less than or equal to the size taken by four mft
910 * records, the mft mirror stores the first four mft records. If the
911 * cluster size is bigger than the size taken by four mft records, the
912 * mft mirror contains as many mft records as will fit into one
913 * cluster.
914 */
915 if (vol->cluster_size <= (4 << vol->mft_record_size_bits))
916 vol->mftmirr_size = 4;
917 else
918 vol->mftmirr_size = vol->cluster_size >>
919 vol->mft_record_size_bits;
920 ntfs_debug("vol->mftmirr_size = %i", vol->mftmirr_size);
921 #endif /* NTFS_RW */
922 vol->serial_no = le64_to_cpu(b->volume_serial_number);
923 ntfs_debug("vol->serial_no = 0x%llx",
924 (unsigned long long)vol->serial_no);
925 return true;
926 }
927
928 /**
929 * ntfs_setup_allocators - initialize the cluster and mft allocators
930 * @vol: volume structure for which to setup the allocators
931 *
932 * Setup the cluster (lcn) and mft allocators to the starting values.
933 */
ntfs_setup_allocators(ntfs_volume * vol)934 static void ntfs_setup_allocators(ntfs_volume *vol)
935 {
936 #ifdef NTFS_RW
937 LCN mft_zone_size, mft_lcn;
938 #endif /* NTFS_RW */
939
940 ntfs_debug("vol->mft_zone_multiplier = 0x%x",
941 vol->mft_zone_multiplier);
942 #ifdef NTFS_RW
943 /* Determine the size of the MFT zone. */
944 mft_zone_size = vol->nr_clusters;
945 switch (vol->mft_zone_multiplier) { /* % of volume size in clusters */
946 case 4:
947 mft_zone_size >>= 1; /* 50% */
948 break;
949 case 3:
950 mft_zone_size = (mft_zone_size +
951 (mft_zone_size >> 1)) >> 2; /* 37.5% */
952 break;
953 case 2:
954 mft_zone_size >>= 2; /* 25% */
955 break;
956 /* case 1: */
957 default:
958 mft_zone_size >>= 3; /* 12.5% */
959 break;
960 }
961 /* Setup the mft zone. */
962 vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
963 ntfs_debug("vol->mft_zone_pos = 0x%llx",
964 (unsigned long long)vol->mft_zone_pos);
965 /*
966 * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
967 * source) and if the actual mft_lcn is in the expected place or even
968 * further to the front of the volume, extend the mft_zone to cover the
969 * beginning of the volume as well. This is in order to protect the
970 * area reserved for the mft bitmap as well within the mft_zone itself.
971 * On non-standard volumes we do not protect it as the overhead would
972 * be higher than the speed increase we would get by doing it.
973 */
974 mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size;
975 if (mft_lcn * vol->cluster_size < 16 * 1024)
976 mft_lcn = (16 * 1024 + vol->cluster_size - 1) /
977 vol->cluster_size;
978 if (vol->mft_zone_start <= mft_lcn)
979 vol->mft_zone_start = 0;
980 ntfs_debug("vol->mft_zone_start = 0x%llx",
981 (unsigned long long)vol->mft_zone_start);
982 /*
983 * Need to cap the mft zone on non-standard volumes so that it does
984 * not point outside the boundaries of the volume. We do this by
985 * halving the zone size until we are inside the volume.
986 */
987 vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
988 while (vol->mft_zone_end >= vol->nr_clusters) {
989 mft_zone_size >>= 1;
990 vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
991 }
992 ntfs_debug("vol->mft_zone_end = 0x%llx",
993 (unsigned long long)vol->mft_zone_end);
994 /*
995 * Set the current position within each data zone to the start of the
996 * respective zone.
997 */
998 vol->data1_zone_pos = vol->mft_zone_end;
999 ntfs_debug("vol->data1_zone_pos = 0x%llx",
1000 (unsigned long long)vol->data1_zone_pos);
1001 vol->data2_zone_pos = 0;
1002 ntfs_debug("vol->data2_zone_pos = 0x%llx",
1003 (unsigned long long)vol->data2_zone_pos);
1004
1005 /* Set the mft data allocation position to mft record 24. */
1006 vol->mft_data_pos = 24;
1007 ntfs_debug("vol->mft_data_pos = 0x%llx",
1008 (unsigned long long)vol->mft_data_pos);
1009 #endif /* NTFS_RW */
1010 }
1011
1012 #ifdef NTFS_RW
1013
1014 /**
1015 * load_and_init_mft_mirror - load and setup the mft mirror inode for a volume
1016 * @vol: ntfs super block describing device whose mft mirror to load
1017 *
1018 * Return 'true' on success or 'false' on error.
1019 */
load_and_init_mft_mirror(ntfs_volume * vol)1020 static bool load_and_init_mft_mirror(ntfs_volume *vol)
1021 {
1022 struct inode *tmp_ino;
1023 ntfs_inode *tmp_ni;
1024
1025 ntfs_debug("Entering.");
1026 /* Get mft mirror inode. */
1027 tmp_ino = ntfs_iget(vol->sb, FILE_MFTMirr);
1028 if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1029 if (!IS_ERR(tmp_ino))
1030 iput(tmp_ino);
1031 /* Caller will display error message. */
1032 return false;
1033 }
1034 /*
1035 * Re-initialize some specifics about $MFTMirr's inode as
1036 * ntfs_read_inode() will have set up the default ones.
1037 */
1038 /* Set uid and gid to root. */
1039 tmp_ino->i_uid = GLOBAL_ROOT_UID;
1040 tmp_ino->i_gid = GLOBAL_ROOT_GID;
1041 /* Regular file. No access for anyone. */
1042 tmp_ino->i_mode = S_IFREG;
1043 /* No VFS initiated operations allowed for $MFTMirr. */
1044 tmp_ino->i_op = &ntfs_empty_inode_ops;
1045 tmp_ino->i_fop = &ntfs_empty_file_ops;
1046 /* Put in our special address space operations. */
1047 tmp_ino->i_mapping->a_ops = &ntfs_mst_aops;
1048 tmp_ni = NTFS_I(tmp_ino);
1049 /* The $MFTMirr, like the $MFT is multi sector transfer protected. */
1050 NInoSetMstProtected(tmp_ni);
1051 NInoSetSparseDisabled(tmp_ni);
1052 /*
1053 * Set up our little cheat allowing us to reuse the async read io
1054 * completion handler for directories.
1055 */
1056 tmp_ni->itype.index.block_size = vol->mft_record_size;
1057 tmp_ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1058 vol->mftmirr_ino = tmp_ino;
1059 ntfs_debug("Done.");
1060 return true;
1061 }
1062
1063 /**
1064 * check_mft_mirror - compare contents of the mft mirror with the mft
1065 * @vol: ntfs super block describing device whose mft mirror to check
1066 *
1067 * Return 'true' on success or 'false' on error.
1068 *
1069 * Note, this function also results in the mft mirror runlist being completely
1070 * mapped into memory. The mft mirror write code requires this and will BUG()
1071 * should it find an unmapped runlist element.
1072 */
check_mft_mirror(ntfs_volume * vol)1073 static bool check_mft_mirror(ntfs_volume *vol)
1074 {
1075 struct super_block *sb = vol->sb;
1076 ntfs_inode *mirr_ni;
1077 struct page *mft_page, *mirr_page;
1078 u8 *kmft, *kmirr;
1079 runlist_element *rl, rl2[2];
1080 pgoff_t index;
1081 int mrecs_per_page, i;
1082
1083 ntfs_debug("Entering.");
1084 /* Compare contents of $MFT and $MFTMirr. */
1085 mrecs_per_page = PAGE_SIZE / vol->mft_record_size;
1086 BUG_ON(!mrecs_per_page);
1087 BUG_ON(!vol->mftmirr_size);
1088 mft_page = mirr_page = NULL;
1089 kmft = kmirr = NULL;
1090 index = i = 0;
1091 do {
1092 u32 bytes;
1093
1094 /* Switch pages if necessary. */
1095 if (!(i % mrecs_per_page)) {
1096 if (index) {
1097 ntfs_unmap_page(mft_page);
1098 ntfs_unmap_page(mirr_page);
1099 }
1100 /* Get the $MFT page. */
1101 mft_page = ntfs_map_page(vol->mft_ino->i_mapping,
1102 index);
1103 if (IS_ERR(mft_page)) {
1104 ntfs_error(sb, "Failed to read $MFT.");
1105 return false;
1106 }
1107 kmft = page_address(mft_page);
1108 /* Get the $MFTMirr page. */
1109 mirr_page = ntfs_map_page(vol->mftmirr_ino->i_mapping,
1110 index);
1111 if (IS_ERR(mirr_page)) {
1112 ntfs_error(sb, "Failed to read $MFTMirr.");
1113 goto mft_unmap_out;
1114 }
1115 kmirr = page_address(mirr_page);
1116 ++index;
1117 }
1118 /* Do not check the record if it is not in use. */
1119 if (((MFT_RECORD*)kmft)->flags & MFT_RECORD_IN_USE) {
1120 /* Make sure the record is ok. */
1121 if (ntfs_is_baad_recordp((le32*)kmft)) {
1122 ntfs_error(sb, "Incomplete multi sector "
1123 "transfer detected in mft "
1124 "record %i.", i);
1125 mm_unmap_out:
1126 ntfs_unmap_page(mirr_page);
1127 mft_unmap_out:
1128 ntfs_unmap_page(mft_page);
1129 return false;
1130 }
1131 }
1132 /* Do not check the mirror record if it is not in use. */
1133 if (((MFT_RECORD*)kmirr)->flags & MFT_RECORD_IN_USE) {
1134 if (ntfs_is_baad_recordp((le32*)kmirr)) {
1135 ntfs_error(sb, "Incomplete multi sector "
1136 "transfer detected in mft "
1137 "mirror record %i.", i);
1138 goto mm_unmap_out;
1139 }
1140 }
1141 /* Get the amount of data in the current record. */
1142 bytes = le32_to_cpu(((MFT_RECORD*)kmft)->bytes_in_use);
1143 if (bytes < sizeof(MFT_RECORD_OLD) ||
1144 bytes > vol->mft_record_size ||
1145 ntfs_is_baad_recordp((le32*)kmft)) {
1146 bytes = le32_to_cpu(((MFT_RECORD*)kmirr)->bytes_in_use);
1147 if (bytes < sizeof(MFT_RECORD_OLD) ||
1148 bytes > vol->mft_record_size ||
1149 ntfs_is_baad_recordp((le32*)kmirr))
1150 bytes = vol->mft_record_size;
1151 }
1152 /* Compare the two records. */
1153 if (memcmp(kmft, kmirr, bytes)) {
1154 ntfs_error(sb, "$MFT and $MFTMirr (record %i) do not "
1155 "match. Run ntfsfix or chkdsk.", i);
1156 goto mm_unmap_out;
1157 }
1158 kmft += vol->mft_record_size;
1159 kmirr += vol->mft_record_size;
1160 } while (++i < vol->mftmirr_size);
1161 /* Release the last pages. */
1162 ntfs_unmap_page(mft_page);
1163 ntfs_unmap_page(mirr_page);
1164
1165 /* Construct the mft mirror runlist by hand. */
1166 rl2[0].vcn = 0;
1167 rl2[0].lcn = vol->mftmirr_lcn;
1168 rl2[0].length = (vol->mftmirr_size * vol->mft_record_size +
1169 vol->cluster_size - 1) / vol->cluster_size;
1170 rl2[1].vcn = rl2[0].length;
1171 rl2[1].lcn = LCN_ENOENT;
1172 rl2[1].length = 0;
1173 /*
1174 * Because we have just read all of the mft mirror, we know we have
1175 * mapped the full runlist for it.
1176 */
1177 mirr_ni = NTFS_I(vol->mftmirr_ino);
1178 down_read(&mirr_ni->runlist.lock);
1179 rl = mirr_ni->runlist.rl;
1180 /* Compare the two runlists. They must be identical. */
1181 i = 0;
1182 do {
1183 if (rl2[i].vcn != rl[i].vcn || rl2[i].lcn != rl[i].lcn ||
1184 rl2[i].length != rl[i].length) {
1185 ntfs_error(sb, "$MFTMirr location mismatch. "
1186 "Run chkdsk.");
1187 up_read(&mirr_ni->runlist.lock);
1188 return false;
1189 }
1190 } while (rl2[i++].length);
1191 up_read(&mirr_ni->runlist.lock);
1192 ntfs_debug("Done.");
1193 return true;
1194 }
1195
1196 /**
1197 * load_and_check_logfile - load and check the logfile inode for a volume
1198 * @vol: ntfs super block describing device whose logfile to load
1199 *
1200 * Return 'true' on success or 'false' on error.
1201 */
load_and_check_logfile(ntfs_volume * vol,RESTART_PAGE_HEADER ** rp)1202 static bool load_and_check_logfile(ntfs_volume *vol,
1203 RESTART_PAGE_HEADER **rp)
1204 {
1205 struct inode *tmp_ino;
1206
1207 ntfs_debug("Entering.");
1208 tmp_ino = ntfs_iget(vol->sb, FILE_LogFile);
1209 if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1210 if (!IS_ERR(tmp_ino))
1211 iput(tmp_ino);
1212 /* Caller will display error message. */
1213 return false;
1214 }
1215 if (!ntfs_check_logfile(tmp_ino, rp)) {
1216 iput(tmp_ino);
1217 /* ntfs_check_logfile() will have displayed error output. */
1218 return false;
1219 }
1220 NInoSetSparseDisabled(NTFS_I(tmp_ino));
1221 vol->logfile_ino = tmp_ino;
1222 ntfs_debug("Done.");
1223 return true;
1224 }
1225
1226 #define NTFS_HIBERFIL_HEADER_SIZE 4096
1227
1228 /**
1229 * check_windows_hibernation_status - check if Windows is suspended on a volume
1230 * @vol: ntfs super block of device to check
1231 *
1232 * Check if Windows is hibernated on the ntfs volume @vol. This is done by
1233 * looking for the file hiberfil.sys in the root directory of the volume. If
1234 * the file is not present Windows is definitely not suspended.
1235 *
1236 * If hiberfil.sys exists and is less than 4kiB in size it means Windows is
1237 * definitely suspended (this volume is not the system volume). Caveat: on a
1238 * system with many volumes it is possible that the < 4kiB check is bogus but
1239 * for now this should do fine.
1240 *
1241 * If hiberfil.sys exists and is larger than 4kiB in size, we need to read the
1242 * hiberfil header (which is the first 4kiB). If this begins with "hibr",
1243 * Windows is definitely suspended. If it is completely full of zeroes,
1244 * Windows is definitely not hibernated. Any other case is treated as if
1245 * Windows is suspended. This caters for the above mentioned caveat of a
1246 * system with many volumes where no "hibr" magic would be present and there is
1247 * no zero header.
1248 *
1249 * Return 0 if Windows is not hibernated on the volume, >0 if Windows is
1250 * hibernated on the volume, and -errno on error.
1251 */
check_windows_hibernation_status(ntfs_volume * vol)1252 static int check_windows_hibernation_status(ntfs_volume *vol)
1253 {
1254 MFT_REF mref;
1255 struct inode *vi;
1256 struct page *page;
1257 u32 *kaddr, *kend;
1258 ntfs_name *name = NULL;
1259 int ret = 1;
1260 static const ntfschar hiberfil[13] = { cpu_to_le16('h'),
1261 cpu_to_le16('i'), cpu_to_le16('b'),
1262 cpu_to_le16('e'), cpu_to_le16('r'),
1263 cpu_to_le16('f'), cpu_to_le16('i'),
1264 cpu_to_le16('l'), cpu_to_le16('.'),
1265 cpu_to_le16('s'), cpu_to_le16('y'),
1266 cpu_to_le16('s'), 0 };
1267
1268 ntfs_debug("Entering.");
1269 /*
1270 * Find the inode number for the hibernation file by looking up the
1271 * filename hiberfil.sys in the root directory.
1272 */
1273 inode_lock(vol->root_ino);
1274 mref = ntfs_lookup_inode_by_name(NTFS_I(vol->root_ino), hiberfil, 12,
1275 &name);
1276 inode_unlock(vol->root_ino);
1277 if (IS_ERR_MREF(mref)) {
1278 ret = MREF_ERR(mref);
1279 /* If the file does not exist, Windows is not hibernated. */
1280 if (ret == -ENOENT) {
1281 ntfs_debug("hiberfil.sys not present. Windows is not "
1282 "hibernated on the volume.");
1283 return 0;
1284 }
1285 /* A real error occurred. */
1286 ntfs_error(vol->sb, "Failed to find inode number for "
1287 "hiberfil.sys.");
1288 return ret;
1289 }
1290 /* We do not care for the type of match that was found. */
1291 kfree(name);
1292 /* Get the inode. */
1293 vi = ntfs_iget(vol->sb, MREF(mref));
1294 if (IS_ERR(vi) || is_bad_inode(vi)) {
1295 if (!IS_ERR(vi))
1296 iput(vi);
1297 ntfs_error(vol->sb, "Failed to load hiberfil.sys.");
1298 return IS_ERR(vi) ? PTR_ERR(vi) : -EIO;
1299 }
1300 if (unlikely(i_size_read(vi) < NTFS_HIBERFIL_HEADER_SIZE)) {
1301 ntfs_debug("hiberfil.sys is smaller than 4kiB (0x%llx). "
1302 "Windows is hibernated on the volume. This "
1303 "is not the system volume.", i_size_read(vi));
1304 goto iput_out;
1305 }
1306 page = ntfs_map_page(vi->i_mapping, 0);
1307 if (IS_ERR(page)) {
1308 ntfs_error(vol->sb, "Failed to read from hiberfil.sys.");
1309 ret = PTR_ERR(page);
1310 goto iput_out;
1311 }
1312 kaddr = (u32*)page_address(page);
1313 if (*(le32*)kaddr == cpu_to_le32(0x72626968)/*'hibr'*/) {
1314 ntfs_debug("Magic \"hibr\" found in hiberfil.sys. Windows is "
1315 "hibernated on the volume. This is the "
1316 "system volume.");
1317 goto unm_iput_out;
1318 }
1319 kend = kaddr + NTFS_HIBERFIL_HEADER_SIZE/sizeof(*kaddr);
1320 do {
1321 if (unlikely(*kaddr)) {
1322 ntfs_debug("hiberfil.sys is larger than 4kiB "
1323 "(0x%llx), does not contain the "
1324 "\"hibr\" magic, and does not have a "
1325 "zero header. Windows is hibernated "
1326 "on the volume. This is not the "
1327 "system volume.", i_size_read(vi));
1328 goto unm_iput_out;
1329 }
1330 } while (++kaddr < kend);
1331 ntfs_debug("hiberfil.sys contains a zero header. Windows is not "
1332 "hibernated on the volume. This is the system "
1333 "volume.");
1334 ret = 0;
1335 unm_iput_out:
1336 ntfs_unmap_page(page);
1337 iput_out:
1338 iput(vi);
1339 return ret;
1340 }
1341
1342 /**
1343 * load_and_init_quota - load and setup the quota file for a volume if present
1344 * @vol: ntfs super block describing device whose quota file to load
1345 *
1346 * Return 'true' on success or 'false' on error. If $Quota is not present, we
1347 * leave vol->quota_ino as NULL and return success.
1348 */
load_and_init_quota(ntfs_volume * vol)1349 static bool load_and_init_quota(ntfs_volume *vol)
1350 {
1351 MFT_REF mref;
1352 struct inode *tmp_ino;
1353 ntfs_name *name = NULL;
1354 static const ntfschar Quota[7] = { cpu_to_le16('$'),
1355 cpu_to_le16('Q'), cpu_to_le16('u'),
1356 cpu_to_le16('o'), cpu_to_le16('t'),
1357 cpu_to_le16('a'), 0 };
1358 static ntfschar Q[3] = { cpu_to_le16('$'),
1359 cpu_to_le16('Q'), 0 };
1360
1361 ntfs_debug("Entering.");
1362 /*
1363 * Find the inode number for the quota file by looking up the filename
1364 * $Quota in the extended system files directory $Extend.
1365 */
1366 inode_lock(vol->extend_ino);
1367 mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), Quota, 6,
1368 &name);
1369 inode_unlock(vol->extend_ino);
1370 if (IS_ERR_MREF(mref)) {
1371 /*
1372 * If the file does not exist, quotas are disabled and have
1373 * never been enabled on this volume, just return success.
1374 */
1375 if (MREF_ERR(mref) == -ENOENT) {
1376 ntfs_debug("$Quota not present. Volume does not have "
1377 "quotas enabled.");
1378 /*
1379 * No need to try to set quotas out of date if they are
1380 * not enabled.
1381 */
1382 NVolSetQuotaOutOfDate(vol);
1383 return true;
1384 }
1385 /* A real error occurred. */
1386 ntfs_error(vol->sb, "Failed to find inode number for $Quota.");
1387 return false;
1388 }
1389 /* We do not care for the type of match that was found. */
1390 kfree(name);
1391 /* Get the inode. */
1392 tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1393 if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1394 if (!IS_ERR(tmp_ino))
1395 iput(tmp_ino);
1396 ntfs_error(vol->sb, "Failed to load $Quota.");
1397 return false;
1398 }
1399 vol->quota_ino = tmp_ino;
1400 /* Get the $Q index allocation attribute. */
1401 tmp_ino = ntfs_index_iget(vol->quota_ino, Q, 2);
1402 if (IS_ERR(tmp_ino)) {
1403 ntfs_error(vol->sb, "Failed to load $Quota/$Q index.");
1404 return false;
1405 }
1406 vol->quota_q_ino = tmp_ino;
1407 ntfs_debug("Done.");
1408 return true;
1409 }
1410
1411 /**
1412 * load_and_init_usnjrnl - load and setup the transaction log if present
1413 * @vol: ntfs super block describing device whose usnjrnl file to load
1414 *
1415 * Return 'true' on success or 'false' on error.
1416 *
1417 * If $UsnJrnl is not present or in the process of being disabled, we set
1418 * NVolUsnJrnlStamped() and return success.
1419 *
1420 * If the $UsnJrnl $DATA/$J attribute has a size equal to the lowest valid usn,
1421 * i.e. transaction logging has only just been enabled or the journal has been
1422 * stamped and nothing has been logged since, we also set NVolUsnJrnlStamped()
1423 * and return success.
1424 */
load_and_init_usnjrnl(ntfs_volume * vol)1425 static bool load_and_init_usnjrnl(ntfs_volume *vol)
1426 {
1427 MFT_REF mref;
1428 struct inode *tmp_ino;
1429 ntfs_inode *tmp_ni;
1430 struct page *page;
1431 ntfs_name *name = NULL;
1432 USN_HEADER *uh;
1433 static const ntfschar UsnJrnl[9] = { cpu_to_le16('$'),
1434 cpu_to_le16('U'), cpu_to_le16('s'),
1435 cpu_to_le16('n'), cpu_to_le16('J'),
1436 cpu_to_le16('r'), cpu_to_le16('n'),
1437 cpu_to_le16('l'), 0 };
1438 static ntfschar Max[5] = { cpu_to_le16('$'),
1439 cpu_to_le16('M'), cpu_to_le16('a'),
1440 cpu_to_le16('x'), 0 };
1441 static ntfschar J[3] = { cpu_to_le16('$'),
1442 cpu_to_le16('J'), 0 };
1443
1444 ntfs_debug("Entering.");
1445 /*
1446 * Find the inode number for the transaction log file by looking up the
1447 * filename $UsnJrnl in the extended system files directory $Extend.
1448 */
1449 inode_lock(vol->extend_ino);
1450 mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), UsnJrnl, 8,
1451 &name);
1452 inode_unlock(vol->extend_ino);
1453 if (IS_ERR_MREF(mref)) {
1454 /*
1455 * If the file does not exist, transaction logging is disabled,
1456 * just return success.
1457 */
1458 if (MREF_ERR(mref) == -ENOENT) {
1459 ntfs_debug("$UsnJrnl not present. Volume does not "
1460 "have transaction logging enabled.");
1461 not_enabled:
1462 /*
1463 * No need to try to stamp the transaction log if
1464 * transaction logging is not enabled.
1465 */
1466 NVolSetUsnJrnlStamped(vol);
1467 return true;
1468 }
1469 /* A real error occurred. */
1470 ntfs_error(vol->sb, "Failed to find inode number for "
1471 "$UsnJrnl.");
1472 return false;
1473 }
1474 /* We do not care for the type of match that was found. */
1475 kfree(name);
1476 /* Get the inode. */
1477 tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1478 if (IS_ERR(tmp_ino) || unlikely(is_bad_inode(tmp_ino))) {
1479 if (!IS_ERR(tmp_ino))
1480 iput(tmp_ino);
1481 ntfs_error(vol->sb, "Failed to load $UsnJrnl.");
1482 return false;
1483 }
1484 vol->usnjrnl_ino = tmp_ino;
1485 /*
1486 * If the transaction log is in the process of being deleted, we can
1487 * ignore it.
1488 */
1489 if (unlikely(vol->vol_flags & VOLUME_DELETE_USN_UNDERWAY)) {
1490 ntfs_debug("$UsnJrnl in the process of being disabled. "
1491 "Volume does not have transaction logging "
1492 "enabled.");
1493 goto not_enabled;
1494 }
1495 /* Get the $DATA/$Max attribute. */
1496 tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, Max, 4);
1497 if (IS_ERR(tmp_ino)) {
1498 ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$Max "
1499 "attribute.");
1500 return false;
1501 }
1502 vol->usnjrnl_max_ino = tmp_ino;
1503 if (unlikely(i_size_read(tmp_ino) < sizeof(USN_HEADER))) {
1504 ntfs_error(vol->sb, "Found corrupt $UsnJrnl/$DATA/$Max "
1505 "attribute (size is 0x%llx but should be at "
1506 "least 0x%zx bytes).", i_size_read(tmp_ino),
1507 sizeof(USN_HEADER));
1508 return false;
1509 }
1510 /* Get the $DATA/$J attribute. */
1511 tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, J, 2);
1512 if (IS_ERR(tmp_ino)) {
1513 ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$J "
1514 "attribute.");
1515 return false;
1516 }
1517 vol->usnjrnl_j_ino = tmp_ino;
1518 /* Verify $J is non-resident and sparse. */
1519 tmp_ni = NTFS_I(vol->usnjrnl_j_ino);
1520 if (unlikely(!NInoNonResident(tmp_ni) || !NInoSparse(tmp_ni))) {
1521 ntfs_error(vol->sb, "$UsnJrnl/$DATA/$J attribute is resident "
1522 "and/or not sparse.");
1523 return false;
1524 }
1525 /* Read the USN_HEADER from $DATA/$Max. */
1526 page = ntfs_map_page(vol->usnjrnl_max_ino->i_mapping, 0);
1527 if (IS_ERR(page)) {
1528 ntfs_error(vol->sb, "Failed to read from $UsnJrnl/$DATA/$Max "
1529 "attribute.");
1530 return false;
1531 }
1532 uh = (USN_HEADER*)page_address(page);
1533 /* Sanity check the $Max. */
1534 if (unlikely(sle64_to_cpu(uh->allocation_delta) >
1535 sle64_to_cpu(uh->maximum_size))) {
1536 ntfs_error(vol->sb, "Allocation delta (0x%llx) exceeds "
1537 "maximum size (0x%llx). $UsnJrnl is corrupt.",
1538 (long long)sle64_to_cpu(uh->allocation_delta),
1539 (long long)sle64_to_cpu(uh->maximum_size));
1540 ntfs_unmap_page(page);
1541 return false;
1542 }
1543 /*
1544 * If the transaction log has been stamped and nothing has been written
1545 * to it since, we do not need to stamp it.
1546 */
1547 if (unlikely(sle64_to_cpu(uh->lowest_valid_usn) >=
1548 i_size_read(vol->usnjrnl_j_ino))) {
1549 if (likely(sle64_to_cpu(uh->lowest_valid_usn) ==
1550 i_size_read(vol->usnjrnl_j_ino))) {
1551 ntfs_unmap_page(page);
1552 ntfs_debug("$UsnJrnl is enabled but nothing has been "
1553 "logged since it was last stamped. "
1554 "Treating this as if the volume does "
1555 "not have transaction logging "
1556 "enabled.");
1557 goto not_enabled;
1558 }
1559 ntfs_error(vol->sb, "$UsnJrnl has lowest valid usn (0x%llx) "
1560 "which is out of bounds (0x%llx). $UsnJrnl "
1561 "is corrupt.",
1562 (long long)sle64_to_cpu(uh->lowest_valid_usn),
1563 i_size_read(vol->usnjrnl_j_ino));
1564 ntfs_unmap_page(page);
1565 return false;
1566 }
1567 ntfs_unmap_page(page);
1568 ntfs_debug("Done.");
1569 return true;
1570 }
1571
1572 /**
1573 * load_and_init_attrdef - load the attribute definitions table for a volume
1574 * @vol: ntfs super block describing device whose attrdef to load
1575 *
1576 * Return 'true' on success or 'false' on error.
1577 */
load_and_init_attrdef(ntfs_volume * vol)1578 static bool load_and_init_attrdef(ntfs_volume *vol)
1579 {
1580 loff_t i_size;
1581 struct super_block *sb = vol->sb;
1582 struct inode *ino;
1583 struct page *page;
1584 pgoff_t index, max_index;
1585 unsigned int size;
1586
1587 ntfs_debug("Entering.");
1588 /* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */
1589 ino = ntfs_iget(sb, FILE_AttrDef);
1590 if (IS_ERR(ino) || is_bad_inode(ino)) {
1591 if (!IS_ERR(ino))
1592 iput(ino);
1593 goto failed;
1594 }
1595 NInoSetSparseDisabled(NTFS_I(ino));
1596 /* The size of FILE_AttrDef must be above 0 and fit inside 31 bits. */
1597 i_size = i_size_read(ino);
1598 if (i_size <= 0 || i_size > 0x7fffffff)
1599 goto iput_failed;
1600 vol->attrdef = (ATTR_DEF*)ntfs_malloc_nofs(i_size);
1601 if (!vol->attrdef)
1602 goto iput_failed;
1603 index = 0;
1604 max_index = i_size >> PAGE_SHIFT;
1605 size = PAGE_SIZE;
1606 while (index < max_index) {
1607 /* Read the attrdef table and copy it into the linear buffer. */
1608 read_partial_attrdef_page:
1609 page = ntfs_map_page(ino->i_mapping, index);
1610 if (IS_ERR(page))
1611 goto free_iput_failed;
1612 memcpy((u8*)vol->attrdef + (index++ << PAGE_SHIFT),
1613 page_address(page), size);
1614 ntfs_unmap_page(page);
1615 };
1616 if (size == PAGE_SIZE) {
1617 size = i_size & ~PAGE_MASK;
1618 if (size)
1619 goto read_partial_attrdef_page;
1620 }
1621 vol->attrdef_size = i_size;
1622 ntfs_debug("Read %llu bytes from $AttrDef.", i_size);
1623 iput(ino);
1624 return true;
1625 free_iput_failed:
1626 ntfs_free(vol->attrdef);
1627 vol->attrdef = NULL;
1628 iput_failed:
1629 iput(ino);
1630 failed:
1631 ntfs_error(sb, "Failed to initialize attribute definition table.");
1632 return false;
1633 }
1634
1635 #endif /* NTFS_RW */
1636
1637 /**
1638 * load_and_init_upcase - load the upcase table for an ntfs volume
1639 * @vol: ntfs super block describing device whose upcase to load
1640 *
1641 * Return 'true' on success or 'false' on error.
1642 */
load_and_init_upcase(ntfs_volume * vol)1643 static bool load_and_init_upcase(ntfs_volume *vol)
1644 {
1645 loff_t i_size;
1646 struct super_block *sb = vol->sb;
1647 struct inode *ino;
1648 struct page *page;
1649 pgoff_t index, max_index;
1650 unsigned int size;
1651 int i, max;
1652
1653 ntfs_debug("Entering.");
1654 /* Read upcase table and setup vol->upcase and vol->upcase_len. */
1655 ino = ntfs_iget(sb, FILE_UpCase);
1656 if (IS_ERR(ino) || is_bad_inode(ino)) {
1657 if (!IS_ERR(ino))
1658 iput(ino);
1659 goto upcase_failed;
1660 }
1661 /*
1662 * The upcase size must not be above 64k Unicode characters, must not
1663 * be zero and must be a multiple of sizeof(ntfschar).
1664 */
1665 i_size = i_size_read(ino);
1666 if (!i_size || i_size & (sizeof(ntfschar) - 1) ||
1667 i_size > 64ULL * 1024 * sizeof(ntfschar))
1668 goto iput_upcase_failed;
1669 vol->upcase = (ntfschar*)ntfs_malloc_nofs(i_size);
1670 if (!vol->upcase)
1671 goto iput_upcase_failed;
1672 index = 0;
1673 max_index = i_size >> PAGE_SHIFT;
1674 size = PAGE_SIZE;
1675 while (index < max_index) {
1676 /* Read the upcase table and copy it into the linear buffer. */
1677 read_partial_upcase_page:
1678 page = ntfs_map_page(ino->i_mapping, index);
1679 if (IS_ERR(page))
1680 goto iput_upcase_failed;
1681 memcpy((char*)vol->upcase + (index++ << PAGE_SHIFT),
1682 page_address(page), size);
1683 ntfs_unmap_page(page);
1684 };
1685 if (size == PAGE_SIZE) {
1686 size = i_size & ~PAGE_MASK;
1687 if (size)
1688 goto read_partial_upcase_page;
1689 }
1690 vol->upcase_len = i_size >> UCHAR_T_SIZE_BITS;
1691 ntfs_debug("Read %llu bytes from $UpCase (expected %zu bytes).",
1692 i_size, 64 * 1024 * sizeof(ntfschar));
1693 iput(ino);
1694 mutex_lock(&ntfs_lock);
1695 if (!default_upcase) {
1696 ntfs_debug("Using volume specified $UpCase since default is "
1697 "not present.");
1698 mutex_unlock(&ntfs_lock);
1699 return true;
1700 }
1701 max = default_upcase_len;
1702 if (max > vol->upcase_len)
1703 max = vol->upcase_len;
1704 for (i = 0; i < max; i++)
1705 if (vol->upcase[i] != default_upcase[i])
1706 break;
1707 if (i == max) {
1708 ntfs_free(vol->upcase);
1709 vol->upcase = default_upcase;
1710 vol->upcase_len = max;
1711 ntfs_nr_upcase_users++;
1712 mutex_unlock(&ntfs_lock);
1713 ntfs_debug("Volume specified $UpCase matches default. Using "
1714 "default.");
1715 return true;
1716 }
1717 mutex_unlock(&ntfs_lock);
1718 ntfs_debug("Using volume specified $UpCase since it does not match "
1719 "the default.");
1720 return true;
1721 iput_upcase_failed:
1722 iput(ino);
1723 ntfs_free(vol->upcase);
1724 vol->upcase = NULL;
1725 upcase_failed:
1726 mutex_lock(&ntfs_lock);
1727 if (default_upcase) {
1728 vol->upcase = default_upcase;
1729 vol->upcase_len = default_upcase_len;
1730 ntfs_nr_upcase_users++;
1731 mutex_unlock(&ntfs_lock);
1732 ntfs_error(sb, "Failed to load $UpCase from the volume. Using "
1733 "default.");
1734 return true;
1735 }
1736 mutex_unlock(&ntfs_lock);
1737 ntfs_error(sb, "Failed to initialize upcase table.");
1738 return false;
1739 }
1740
1741 /*
1742 * The lcn and mft bitmap inodes are NTFS-internal inodes with
1743 * their own special locking rules:
1744 */
1745 static struct lock_class_key
1746 lcnbmp_runlist_lock_key, lcnbmp_mrec_lock_key,
1747 mftbmp_runlist_lock_key, mftbmp_mrec_lock_key;
1748
1749 /**
1750 * load_system_files - open the system files using normal functions
1751 * @vol: ntfs super block describing device whose system files to load
1752 *
1753 * Open the system files with normal access functions and complete setting up
1754 * the ntfs super block @vol.
1755 *
1756 * Return 'true' on success or 'false' on error.
1757 */
load_system_files(ntfs_volume * vol)1758 static bool load_system_files(ntfs_volume *vol)
1759 {
1760 struct super_block *sb = vol->sb;
1761 MFT_RECORD *m;
1762 VOLUME_INFORMATION *vi;
1763 ntfs_attr_search_ctx *ctx;
1764 #ifdef NTFS_RW
1765 RESTART_PAGE_HEADER *rp;
1766 int err;
1767 #endif /* NTFS_RW */
1768
1769 ntfs_debug("Entering.");
1770 #ifdef NTFS_RW
1771 /* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */
1772 if (!load_and_init_mft_mirror(vol) || !check_mft_mirror(vol)) {
1773 static const char *es1 = "Failed to load $MFTMirr";
1774 static const char *es2 = "$MFTMirr does not match $MFT";
1775 static const char *es3 = ". Run ntfsfix and/or chkdsk.";
1776
1777 /* If a read-write mount, convert it to a read-only mount. */
1778 if (!sb_rdonly(sb)) {
1779 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1780 ON_ERRORS_CONTINUE))) {
1781 ntfs_error(sb, "%s and neither on_errors="
1782 "continue nor on_errors="
1783 "remount-ro was specified%s",
1784 !vol->mftmirr_ino ? es1 : es2,
1785 es3);
1786 goto iput_mirr_err_out;
1787 }
1788 sb->s_flags |= SB_RDONLY;
1789 ntfs_error(sb, "%s. Mounting read-only%s",
1790 !vol->mftmirr_ino ? es1 : es2, es3);
1791 } else
1792 ntfs_warning(sb, "%s. Will not be able to remount "
1793 "read-write%s",
1794 !vol->mftmirr_ino ? es1 : es2, es3);
1795 /* This will prevent a read-write remount. */
1796 NVolSetErrors(vol);
1797 }
1798 #endif /* NTFS_RW */
1799 /* Get mft bitmap attribute inode. */
1800 vol->mftbmp_ino = ntfs_attr_iget(vol->mft_ino, AT_BITMAP, NULL, 0);
1801 if (IS_ERR(vol->mftbmp_ino)) {
1802 ntfs_error(sb, "Failed to load $MFT/$BITMAP attribute.");
1803 goto iput_mirr_err_out;
1804 }
1805 lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->runlist.lock,
1806 &mftbmp_runlist_lock_key);
1807 lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->mrec_lock,
1808 &mftbmp_mrec_lock_key);
1809 /* Read upcase table and setup @vol->upcase and @vol->upcase_len. */
1810 if (!load_and_init_upcase(vol))
1811 goto iput_mftbmp_err_out;
1812 #ifdef NTFS_RW
1813 /*
1814 * Read attribute definitions table and setup @vol->attrdef and
1815 * @vol->attrdef_size.
1816 */
1817 if (!load_and_init_attrdef(vol))
1818 goto iput_upcase_err_out;
1819 #endif /* NTFS_RW */
1820 /*
1821 * Get the cluster allocation bitmap inode and verify the size, no
1822 * need for any locking at this stage as we are already running
1823 * exclusively as we are mount in progress task.
1824 */
1825 vol->lcnbmp_ino = ntfs_iget(sb, FILE_Bitmap);
1826 if (IS_ERR(vol->lcnbmp_ino) || is_bad_inode(vol->lcnbmp_ino)) {
1827 if (!IS_ERR(vol->lcnbmp_ino))
1828 iput(vol->lcnbmp_ino);
1829 goto bitmap_failed;
1830 }
1831 lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->runlist.lock,
1832 &lcnbmp_runlist_lock_key);
1833 lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->mrec_lock,
1834 &lcnbmp_mrec_lock_key);
1835
1836 NInoSetSparseDisabled(NTFS_I(vol->lcnbmp_ino));
1837 if ((vol->nr_clusters + 7) >> 3 > i_size_read(vol->lcnbmp_ino)) {
1838 iput(vol->lcnbmp_ino);
1839 bitmap_failed:
1840 ntfs_error(sb, "Failed to load $Bitmap.");
1841 goto iput_attrdef_err_out;
1842 }
1843 /*
1844 * Get the volume inode and setup our cache of the volume flags and
1845 * version.
1846 */
1847 vol->vol_ino = ntfs_iget(sb, FILE_Volume);
1848 if (IS_ERR(vol->vol_ino) || is_bad_inode(vol->vol_ino)) {
1849 if (!IS_ERR(vol->vol_ino))
1850 iput(vol->vol_ino);
1851 volume_failed:
1852 ntfs_error(sb, "Failed to load $Volume.");
1853 goto iput_lcnbmp_err_out;
1854 }
1855 m = map_mft_record(NTFS_I(vol->vol_ino));
1856 if (IS_ERR(m)) {
1857 iput_volume_failed:
1858 iput(vol->vol_ino);
1859 goto volume_failed;
1860 }
1861 if (!(ctx = ntfs_attr_get_search_ctx(NTFS_I(vol->vol_ino), m))) {
1862 ntfs_error(sb, "Failed to get attribute search context.");
1863 goto get_ctx_vol_failed;
1864 }
1865 if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
1866 ctx) || ctx->attr->non_resident || ctx->attr->flags) {
1867 err_put_vol:
1868 ntfs_attr_put_search_ctx(ctx);
1869 get_ctx_vol_failed:
1870 unmap_mft_record(NTFS_I(vol->vol_ino));
1871 goto iput_volume_failed;
1872 }
1873 vi = (VOLUME_INFORMATION*)((char*)ctx->attr +
1874 le16_to_cpu(ctx->attr->data.resident.value_offset));
1875 /* Some bounds checks. */
1876 if ((u8*)vi < (u8*)ctx->attr || (u8*)vi +
1877 le32_to_cpu(ctx->attr->data.resident.value_length) >
1878 (u8*)ctx->attr + le32_to_cpu(ctx->attr->length))
1879 goto err_put_vol;
1880 /* Copy the volume flags and version to the ntfs_volume structure. */
1881 vol->vol_flags = vi->flags;
1882 vol->major_ver = vi->major_ver;
1883 vol->minor_ver = vi->minor_ver;
1884 ntfs_attr_put_search_ctx(ctx);
1885 unmap_mft_record(NTFS_I(vol->vol_ino));
1886 pr_info("volume version %i.%i.\n", vol->major_ver,
1887 vol->minor_ver);
1888 if (vol->major_ver < 3 && NVolSparseEnabled(vol)) {
1889 ntfs_warning(vol->sb, "Disabling sparse support due to NTFS "
1890 "volume version %i.%i (need at least version "
1891 "3.0).", vol->major_ver, vol->minor_ver);
1892 NVolClearSparseEnabled(vol);
1893 }
1894 #ifdef NTFS_RW
1895 /* Make sure that no unsupported volume flags are set. */
1896 if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
1897 static const char *es1a = "Volume is dirty";
1898 static const char *es1b = "Volume has been modified by chkdsk";
1899 static const char *es1c = "Volume has unsupported flags set";
1900 static const char *es2a = ". Run chkdsk and mount in Windows.";
1901 static const char *es2b = ". Mount in Windows.";
1902 const char *es1, *es2;
1903
1904 es2 = es2a;
1905 if (vol->vol_flags & VOLUME_IS_DIRTY)
1906 es1 = es1a;
1907 else if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
1908 es1 = es1b;
1909 es2 = es2b;
1910 } else {
1911 es1 = es1c;
1912 ntfs_warning(sb, "Unsupported volume flags 0x%x "
1913 "encountered.",
1914 (unsigned)le16_to_cpu(vol->vol_flags));
1915 }
1916 /* If a read-write mount, convert it to a read-only mount. */
1917 if (!sb_rdonly(sb)) {
1918 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1919 ON_ERRORS_CONTINUE))) {
1920 ntfs_error(sb, "%s and neither on_errors="
1921 "continue nor on_errors="
1922 "remount-ro was specified%s",
1923 es1, es2);
1924 goto iput_vol_err_out;
1925 }
1926 sb->s_flags |= SB_RDONLY;
1927 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
1928 } else
1929 ntfs_warning(sb, "%s. Will not be able to remount "
1930 "read-write%s", es1, es2);
1931 /*
1932 * Do not set NVolErrors() because ntfs_remount() re-checks the
1933 * flags which we need to do in case any flags have changed.
1934 */
1935 }
1936 /*
1937 * Get the inode for the logfile, check it and determine if the volume
1938 * was shutdown cleanly.
1939 */
1940 rp = NULL;
1941 if (!load_and_check_logfile(vol, &rp) ||
1942 !ntfs_is_logfile_clean(vol->logfile_ino, rp)) {
1943 static const char *es1a = "Failed to load $LogFile";
1944 static const char *es1b = "$LogFile is not clean";
1945 static const char *es2 = ". Mount in Windows.";
1946 const char *es1;
1947
1948 es1 = !vol->logfile_ino ? es1a : es1b;
1949 /* If a read-write mount, convert it to a read-only mount. */
1950 if (!sb_rdonly(sb)) {
1951 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1952 ON_ERRORS_CONTINUE))) {
1953 ntfs_error(sb, "%s and neither on_errors="
1954 "continue nor on_errors="
1955 "remount-ro was specified%s",
1956 es1, es2);
1957 if (vol->logfile_ino) {
1958 BUG_ON(!rp);
1959 ntfs_free(rp);
1960 }
1961 goto iput_logfile_err_out;
1962 }
1963 sb->s_flags |= SB_RDONLY;
1964 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
1965 } else
1966 ntfs_warning(sb, "%s. Will not be able to remount "
1967 "read-write%s", es1, es2);
1968 /* This will prevent a read-write remount. */
1969 NVolSetErrors(vol);
1970 }
1971 ntfs_free(rp);
1972 #endif /* NTFS_RW */
1973 /* Get the root directory inode so we can do path lookups. */
1974 vol->root_ino = ntfs_iget(sb, FILE_root);
1975 if (IS_ERR(vol->root_ino) || is_bad_inode(vol->root_ino)) {
1976 if (!IS_ERR(vol->root_ino))
1977 iput(vol->root_ino);
1978 ntfs_error(sb, "Failed to load root directory.");
1979 goto iput_logfile_err_out;
1980 }
1981 #ifdef NTFS_RW
1982 /*
1983 * Check if Windows is suspended to disk on the target volume. If it
1984 * is hibernated, we must not write *anything* to the disk so set
1985 * NVolErrors() without setting the dirty volume flag and mount
1986 * read-only. This will prevent read-write remounting and it will also
1987 * prevent all writes.
1988 */
1989 err = check_windows_hibernation_status(vol);
1990 if (unlikely(err)) {
1991 static const char *es1a = "Failed to determine if Windows is "
1992 "hibernated";
1993 static const char *es1b = "Windows is hibernated";
1994 static const char *es2 = ". Run chkdsk.";
1995 const char *es1;
1996
1997 es1 = err < 0 ? es1a : es1b;
1998 /* If a read-write mount, convert it to a read-only mount. */
1999 if (!sb_rdonly(sb)) {
2000 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2001 ON_ERRORS_CONTINUE))) {
2002 ntfs_error(sb, "%s and neither on_errors="
2003 "continue nor on_errors="
2004 "remount-ro was specified%s",
2005 es1, es2);
2006 goto iput_root_err_out;
2007 }
2008 sb->s_flags |= SB_RDONLY;
2009 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2010 } else
2011 ntfs_warning(sb, "%s. Will not be able to remount "
2012 "read-write%s", es1, es2);
2013 /* This will prevent a read-write remount. */
2014 NVolSetErrors(vol);
2015 }
2016 /* If (still) a read-write mount, mark the volume dirty. */
2017 if (!sb_rdonly(sb) && ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
2018 static const char *es1 = "Failed to set dirty bit in volume "
2019 "information flags";
2020 static const char *es2 = ". Run chkdsk.";
2021
2022 /* Convert to a read-only mount. */
2023 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2024 ON_ERRORS_CONTINUE))) {
2025 ntfs_error(sb, "%s and neither on_errors=continue nor "
2026 "on_errors=remount-ro was specified%s",
2027 es1, es2);
2028 goto iput_root_err_out;
2029 }
2030 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2031 sb->s_flags |= SB_RDONLY;
2032 /*
2033 * Do not set NVolErrors() because ntfs_remount() might manage
2034 * to set the dirty flag in which case all would be well.
2035 */
2036 }
2037 #if 0
2038 // TODO: Enable this code once we start modifying anything that is
2039 // different between NTFS 1.2 and 3.x...
2040 /*
2041 * If (still) a read-write mount, set the NT4 compatibility flag on
2042 * newer NTFS version volumes.
2043 */
2044 if (!(sb->s_flags & SB_RDONLY) && (vol->major_ver > 1) &&
2045 ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
2046 static const char *es1 = "Failed to set NT4 compatibility flag";
2047 static const char *es2 = ". Run chkdsk.";
2048
2049 /* Convert to a read-only mount. */
2050 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2051 ON_ERRORS_CONTINUE))) {
2052 ntfs_error(sb, "%s and neither on_errors=continue nor "
2053 "on_errors=remount-ro was specified%s",
2054 es1, es2);
2055 goto iput_root_err_out;
2056 }
2057 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2058 sb->s_flags |= SB_RDONLY;
2059 NVolSetErrors(vol);
2060 }
2061 #endif
2062 /* If (still) a read-write mount, empty the logfile. */
2063 if (!sb_rdonly(sb) && !ntfs_empty_logfile(vol->logfile_ino)) {
2064 static const char *es1 = "Failed to empty $LogFile";
2065 static const char *es2 = ". Mount in Windows.";
2066
2067 /* Convert to a read-only mount. */
2068 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2069 ON_ERRORS_CONTINUE))) {
2070 ntfs_error(sb, "%s and neither on_errors=continue nor "
2071 "on_errors=remount-ro was specified%s",
2072 es1, es2);
2073 goto iput_root_err_out;
2074 }
2075 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2076 sb->s_flags |= SB_RDONLY;
2077 NVolSetErrors(vol);
2078 }
2079 #endif /* NTFS_RW */
2080 /* If on NTFS versions before 3.0, we are done. */
2081 if (unlikely(vol->major_ver < 3))
2082 return true;
2083 /* NTFS 3.0+ specific initialization. */
2084 /* Get the security descriptors inode. */
2085 vol->secure_ino = ntfs_iget(sb, FILE_Secure);
2086 if (IS_ERR(vol->secure_ino) || is_bad_inode(vol->secure_ino)) {
2087 if (!IS_ERR(vol->secure_ino))
2088 iput(vol->secure_ino);
2089 ntfs_error(sb, "Failed to load $Secure.");
2090 goto iput_root_err_out;
2091 }
2092 // TODO: Initialize security.
2093 /* Get the extended system files' directory inode. */
2094 vol->extend_ino = ntfs_iget(sb, FILE_Extend);
2095 if (IS_ERR(vol->extend_ino) || is_bad_inode(vol->extend_ino) ||
2096 !S_ISDIR(vol->extend_ino->i_mode)) {
2097 if (!IS_ERR(vol->extend_ino))
2098 iput(vol->extend_ino);
2099 ntfs_error(sb, "Failed to load $Extend.");
2100 goto iput_sec_err_out;
2101 }
2102 #ifdef NTFS_RW
2103 /* Find the quota file, load it if present, and set it up. */
2104 if (!load_and_init_quota(vol)) {
2105 static const char *es1 = "Failed to load $Quota";
2106 static const char *es2 = ". Run chkdsk.";
2107
2108 /* If a read-write mount, convert it to a read-only mount. */
2109 if (!sb_rdonly(sb)) {
2110 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2111 ON_ERRORS_CONTINUE))) {
2112 ntfs_error(sb, "%s and neither on_errors="
2113 "continue nor on_errors="
2114 "remount-ro was specified%s",
2115 es1, es2);
2116 goto iput_quota_err_out;
2117 }
2118 sb->s_flags |= SB_RDONLY;
2119 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2120 } else
2121 ntfs_warning(sb, "%s. Will not be able to remount "
2122 "read-write%s", es1, es2);
2123 /* This will prevent a read-write remount. */
2124 NVolSetErrors(vol);
2125 }
2126 /* If (still) a read-write mount, mark the quotas out of date. */
2127 if (!sb_rdonly(sb) && !ntfs_mark_quotas_out_of_date(vol)) {
2128 static const char *es1 = "Failed to mark quotas out of date";
2129 static const char *es2 = ". Run chkdsk.";
2130
2131 /* Convert to a read-only mount. */
2132 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2133 ON_ERRORS_CONTINUE))) {
2134 ntfs_error(sb, "%s and neither on_errors=continue nor "
2135 "on_errors=remount-ro was specified%s",
2136 es1, es2);
2137 goto iput_quota_err_out;
2138 }
2139 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2140 sb->s_flags |= SB_RDONLY;
2141 NVolSetErrors(vol);
2142 }
2143 /*
2144 * Find the transaction log file ($UsnJrnl), load it if present, check
2145 * it, and set it up.
2146 */
2147 if (!load_and_init_usnjrnl(vol)) {
2148 static const char *es1 = "Failed to load $UsnJrnl";
2149 static const char *es2 = ". Run chkdsk.";
2150
2151 /* If a read-write mount, convert it to a read-only mount. */
2152 if (!sb_rdonly(sb)) {
2153 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2154 ON_ERRORS_CONTINUE))) {
2155 ntfs_error(sb, "%s and neither on_errors="
2156 "continue nor on_errors="
2157 "remount-ro was specified%s",
2158 es1, es2);
2159 goto iput_usnjrnl_err_out;
2160 }
2161 sb->s_flags |= SB_RDONLY;
2162 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2163 } else
2164 ntfs_warning(sb, "%s. Will not be able to remount "
2165 "read-write%s", es1, es2);
2166 /* This will prevent a read-write remount. */
2167 NVolSetErrors(vol);
2168 }
2169 /* If (still) a read-write mount, stamp the transaction log. */
2170 if (!sb_rdonly(sb) && !ntfs_stamp_usnjrnl(vol)) {
2171 static const char *es1 = "Failed to stamp transaction log "
2172 "($UsnJrnl)";
2173 static const char *es2 = ". Run chkdsk.";
2174
2175 /* Convert to a read-only mount. */
2176 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2177 ON_ERRORS_CONTINUE))) {
2178 ntfs_error(sb, "%s and neither on_errors=continue nor "
2179 "on_errors=remount-ro was specified%s",
2180 es1, es2);
2181 goto iput_usnjrnl_err_out;
2182 }
2183 ntfs_error(sb, "%s. Mounting read-only%s", es1, es2);
2184 sb->s_flags |= SB_RDONLY;
2185 NVolSetErrors(vol);
2186 }
2187 #endif /* NTFS_RW */
2188 return true;
2189 #ifdef NTFS_RW
2190 iput_usnjrnl_err_out:
2191 iput(vol->usnjrnl_j_ino);
2192 iput(vol->usnjrnl_max_ino);
2193 iput(vol->usnjrnl_ino);
2194 iput_quota_err_out:
2195 iput(vol->quota_q_ino);
2196 iput(vol->quota_ino);
2197 iput(vol->extend_ino);
2198 #endif /* NTFS_RW */
2199 iput_sec_err_out:
2200 iput(vol->secure_ino);
2201 iput_root_err_out:
2202 iput(vol->root_ino);
2203 iput_logfile_err_out:
2204 #ifdef NTFS_RW
2205 iput(vol->logfile_ino);
2206 iput_vol_err_out:
2207 #endif /* NTFS_RW */
2208 iput(vol->vol_ino);
2209 iput_lcnbmp_err_out:
2210 iput(vol->lcnbmp_ino);
2211 iput_attrdef_err_out:
2212 vol->attrdef_size = 0;
2213 if (vol->attrdef) {
2214 ntfs_free(vol->attrdef);
2215 vol->attrdef = NULL;
2216 }
2217 #ifdef NTFS_RW
2218 iput_upcase_err_out:
2219 #endif /* NTFS_RW */
2220 vol->upcase_len = 0;
2221 mutex_lock(&ntfs_lock);
2222 if (vol->upcase == default_upcase) {
2223 ntfs_nr_upcase_users--;
2224 vol->upcase = NULL;
2225 }
2226 mutex_unlock(&ntfs_lock);
2227 if (vol->upcase) {
2228 ntfs_free(vol->upcase);
2229 vol->upcase = NULL;
2230 }
2231 iput_mftbmp_err_out:
2232 iput(vol->mftbmp_ino);
2233 iput_mirr_err_out:
2234 #ifdef NTFS_RW
2235 iput(vol->mftmirr_ino);
2236 #endif /* NTFS_RW */
2237 return false;
2238 }
2239
2240 /**
2241 * ntfs_put_super - called by the vfs to unmount a volume
2242 * @sb: vfs superblock of volume to unmount
2243 *
2244 * ntfs_put_super() is called by the VFS (from fs/super.c::do_umount()) when
2245 * the volume is being unmounted (umount system call has been invoked) and it
2246 * releases all inodes and memory belonging to the NTFS specific part of the
2247 * super block.
2248 */
ntfs_put_super(struct super_block * sb)2249 static void ntfs_put_super(struct super_block *sb)
2250 {
2251 ntfs_volume *vol = NTFS_SB(sb);
2252
2253 ntfs_debug("Entering.");
2254
2255 #ifdef NTFS_RW
2256 /*
2257 * Commit all inodes while they are still open in case some of them
2258 * cause others to be dirtied.
2259 */
2260 ntfs_commit_inode(vol->vol_ino);
2261
2262 /* NTFS 3.0+ specific. */
2263 if (vol->major_ver >= 3) {
2264 if (vol->usnjrnl_j_ino)
2265 ntfs_commit_inode(vol->usnjrnl_j_ino);
2266 if (vol->usnjrnl_max_ino)
2267 ntfs_commit_inode(vol->usnjrnl_max_ino);
2268 if (vol->usnjrnl_ino)
2269 ntfs_commit_inode(vol->usnjrnl_ino);
2270 if (vol->quota_q_ino)
2271 ntfs_commit_inode(vol->quota_q_ino);
2272 if (vol->quota_ino)
2273 ntfs_commit_inode(vol->quota_ino);
2274 if (vol->extend_ino)
2275 ntfs_commit_inode(vol->extend_ino);
2276 if (vol->secure_ino)
2277 ntfs_commit_inode(vol->secure_ino);
2278 }
2279
2280 ntfs_commit_inode(vol->root_ino);
2281
2282 down_write(&vol->lcnbmp_lock);
2283 ntfs_commit_inode(vol->lcnbmp_ino);
2284 up_write(&vol->lcnbmp_lock);
2285
2286 down_write(&vol->mftbmp_lock);
2287 ntfs_commit_inode(vol->mftbmp_ino);
2288 up_write(&vol->mftbmp_lock);
2289
2290 if (vol->logfile_ino)
2291 ntfs_commit_inode(vol->logfile_ino);
2292
2293 if (vol->mftmirr_ino)
2294 ntfs_commit_inode(vol->mftmirr_ino);
2295 ntfs_commit_inode(vol->mft_ino);
2296
2297 /*
2298 * If a read-write mount and no volume errors have occurred, mark the
2299 * volume clean. Also, re-commit all affected inodes.
2300 */
2301 if (!sb_rdonly(sb)) {
2302 if (!NVolErrors(vol)) {
2303 if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
2304 ntfs_warning(sb, "Failed to clear dirty bit "
2305 "in volume information "
2306 "flags. Run chkdsk.");
2307 ntfs_commit_inode(vol->vol_ino);
2308 ntfs_commit_inode(vol->root_ino);
2309 if (vol->mftmirr_ino)
2310 ntfs_commit_inode(vol->mftmirr_ino);
2311 ntfs_commit_inode(vol->mft_ino);
2312 } else {
2313 ntfs_warning(sb, "Volume has errors. Leaving volume "
2314 "marked dirty. Run chkdsk.");
2315 }
2316 }
2317 #endif /* NTFS_RW */
2318
2319 iput(vol->vol_ino);
2320 vol->vol_ino = NULL;
2321
2322 /* NTFS 3.0+ specific clean up. */
2323 if (vol->major_ver >= 3) {
2324 #ifdef NTFS_RW
2325 if (vol->usnjrnl_j_ino) {
2326 iput(vol->usnjrnl_j_ino);
2327 vol->usnjrnl_j_ino = NULL;
2328 }
2329 if (vol->usnjrnl_max_ino) {
2330 iput(vol->usnjrnl_max_ino);
2331 vol->usnjrnl_max_ino = NULL;
2332 }
2333 if (vol->usnjrnl_ino) {
2334 iput(vol->usnjrnl_ino);
2335 vol->usnjrnl_ino = NULL;
2336 }
2337 if (vol->quota_q_ino) {
2338 iput(vol->quota_q_ino);
2339 vol->quota_q_ino = NULL;
2340 }
2341 if (vol->quota_ino) {
2342 iput(vol->quota_ino);
2343 vol->quota_ino = NULL;
2344 }
2345 #endif /* NTFS_RW */
2346 if (vol->extend_ino) {
2347 iput(vol->extend_ino);
2348 vol->extend_ino = NULL;
2349 }
2350 if (vol->secure_ino) {
2351 iput(vol->secure_ino);
2352 vol->secure_ino = NULL;
2353 }
2354 }
2355
2356 iput(vol->root_ino);
2357 vol->root_ino = NULL;
2358
2359 down_write(&vol->lcnbmp_lock);
2360 iput(vol->lcnbmp_ino);
2361 vol->lcnbmp_ino = NULL;
2362 up_write(&vol->lcnbmp_lock);
2363
2364 down_write(&vol->mftbmp_lock);
2365 iput(vol->mftbmp_ino);
2366 vol->mftbmp_ino = NULL;
2367 up_write(&vol->mftbmp_lock);
2368
2369 #ifdef NTFS_RW
2370 if (vol->logfile_ino) {
2371 iput(vol->logfile_ino);
2372 vol->logfile_ino = NULL;
2373 }
2374 if (vol->mftmirr_ino) {
2375 /* Re-commit the mft mirror and mft just in case. */
2376 ntfs_commit_inode(vol->mftmirr_ino);
2377 ntfs_commit_inode(vol->mft_ino);
2378 iput(vol->mftmirr_ino);
2379 vol->mftmirr_ino = NULL;
2380 }
2381 /*
2382 * We should have no dirty inodes left, due to
2383 * mft.c::ntfs_mft_writepage() cleaning all the dirty pages as
2384 * the underlying mft records are written out and cleaned.
2385 */
2386 ntfs_commit_inode(vol->mft_ino);
2387 write_inode_now(vol->mft_ino, 1);
2388 #endif /* NTFS_RW */
2389
2390 iput(vol->mft_ino);
2391 vol->mft_ino = NULL;
2392
2393 /* Throw away the table of attribute definitions. */
2394 vol->attrdef_size = 0;
2395 if (vol->attrdef) {
2396 ntfs_free(vol->attrdef);
2397 vol->attrdef = NULL;
2398 }
2399 vol->upcase_len = 0;
2400 /*
2401 * Destroy the global default upcase table if necessary. Also decrease
2402 * the number of upcase users if we are a user.
2403 */
2404 mutex_lock(&ntfs_lock);
2405 if (vol->upcase == default_upcase) {
2406 ntfs_nr_upcase_users--;
2407 vol->upcase = NULL;
2408 }
2409 if (!ntfs_nr_upcase_users && default_upcase) {
2410 ntfs_free(default_upcase);
2411 default_upcase = NULL;
2412 }
2413 if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
2414 free_compression_buffers();
2415 mutex_unlock(&ntfs_lock);
2416 if (vol->upcase) {
2417 ntfs_free(vol->upcase);
2418 vol->upcase = NULL;
2419 }
2420
2421 unload_nls(vol->nls_map);
2422
2423 sb->s_fs_info = NULL;
2424 kfree(vol);
2425 }
2426
2427 /**
2428 * get_nr_free_clusters - return the number of free clusters on a volume
2429 * @vol: ntfs volume for which to obtain free cluster count
2430 *
2431 * Calculate the number of free clusters on the mounted NTFS volume @vol. We
2432 * actually calculate the number of clusters in use instead because this
2433 * allows us to not care about partial pages as these will be just zero filled
2434 * and hence not be counted as allocated clusters.
2435 *
2436 * The only particularity is that clusters beyond the end of the logical ntfs
2437 * volume will be marked as allocated to prevent errors which means we have to
2438 * discount those at the end. This is important as the cluster bitmap always
2439 * has a size in multiples of 8 bytes, i.e. up to 63 clusters could be outside
2440 * the logical volume and marked in use when they are not as they do not exist.
2441 *
2442 * If any pages cannot be read we assume all clusters in the erroring pages are
2443 * in use. This means we return an underestimate on errors which is better than
2444 * an overestimate.
2445 */
get_nr_free_clusters(ntfs_volume * vol)2446 static s64 get_nr_free_clusters(ntfs_volume *vol)
2447 {
2448 s64 nr_free = vol->nr_clusters;
2449 struct address_space *mapping = vol->lcnbmp_ino->i_mapping;
2450 struct page *page;
2451 pgoff_t index, max_index;
2452
2453 ntfs_debug("Entering.");
2454 /* Serialize accesses to the cluster bitmap. */
2455 down_read(&vol->lcnbmp_lock);
2456 /*
2457 * Convert the number of bits into bytes rounded up, then convert into
2458 * multiples of PAGE_SIZE, rounding up so that if we have one
2459 * full and one partial page max_index = 2.
2460 */
2461 max_index = (((vol->nr_clusters + 7) >> 3) + PAGE_SIZE - 1) >>
2462 PAGE_SHIFT;
2463 /* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2464 ntfs_debug("Reading $Bitmap, max_index = 0x%lx, max_size = 0x%lx.",
2465 max_index, PAGE_SIZE / 4);
2466 for (index = 0; index < max_index; index++) {
2467 unsigned long *kaddr;
2468
2469 /*
2470 * Read the page from page cache, getting it from backing store
2471 * if necessary, and increment the use count.
2472 */
2473 page = read_mapping_page(mapping, index, NULL);
2474 /* Ignore pages which errored synchronously. */
2475 if (IS_ERR(page)) {
2476 ntfs_debug("read_mapping_page() error. Skipping "
2477 "page (index 0x%lx).", index);
2478 nr_free -= PAGE_SIZE * 8;
2479 continue;
2480 }
2481 kaddr = kmap_atomic(page);
2482 /*
2483 * Subtract the number of set bits. If this
2484 * is the last page and it is partial we don't really care as
2485 * it just means we do a little extra work but it won't affect
2486 * the result as all out of range bytes are set to zero by
2487 * ntfs_readpage().
2488 */
2489 nr_free -= bitmap_weight(kaddr,
2490 PAGE_SIZE * BITS_PER_BYTE);
2491 kunmap_atomic(kaddr);
2492 put_page(page);
2493 }
2494 ntfs_debug("Finished reading $Bitmap, last index = 0x%lx.", index - 1);
2495 /*
2496 * Fixup for eventual bits outside logical ntfs volume (see function
2497 * description above).
2498 */
2499 if (vol->nr_clusters & 63)
2500 nr_free += 64 - (vol->nr_clusters & 63);
2501 up_read(&vol->lcnbmp_lock);
2502 /* If errors occurred we may well have gone below zero, fix this. */
2503 if (nr_free < 0)
2504 nr_free = 0;
2505 ntfs_debug("Exiting.");
2506 return nr_free;
2507 }
2508
2509 /**
2510 * __get_nr_free_mft_records - return the number of free inodes on a volume
2511 * @vol: ntfs volume for which to obtain free inode count
2512 * @nr_free: number of mft records in filesystem
2513 * @max_index: maximum number of pages containing set bits
2514 *
2515 * Calculate the number of free mft records (inodes) on the mounted NTFS
2516 * volume @vol. We actually calculate the number of mft records in use instead
2517 * because this allows us to not care about partial pages as these will be just
2518 * zero filled and hence not be counted as allocated mft record.
2519 *
2520 * If any pages cannot be read we assume all mft records in the erroring pages
2521 * are in use. This means we return an underestimate on errors which is better
2522 * than an overestimate.
2523 *
2524 * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing.
2525 */
__get_nr_free_mft_records(ntfs_volume * vol,s64 nr_free,const pgoff_t max_index)2526 static unsigned long __get_nr_free_mft_records(ntfs_volume *vol,
2527 s64 nr_free, const pgoff_t max_index)
2528 {
2529 struct address_space *mapping = vol->mftbmp_ino->i_mapping;
2530 struct page *page;
2531 pgoff_t index;
2532
2533 ntfs_debug("Entering.");
2534 /* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2535 ntfs_debug("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = "
2536 "0x%lx.", max_index, PAGE_SIZE / 4);
2537 for (index = 0; index < max_index; index++) {
2538 unsigned long *kaddr;
2539
2540 /*
2541 * Read the page from page cache, getting it from backing store
2542 * if necessary, and increment the use count.
2543 */
2544 page = read_mapping_page(mapping, index, NULL);
2545 /* Ignore pages which errored synchronously. */
2546 if (IS_ERR(page)) {
2547 ntfs_debug("read_mapping_page() error. Skipping "
2548 "page (index 0x%lx).", index);
2549 nr_free -= PAGE_SIZE * 8;
2550 continue;
2551 }
2552 kaddr = kmap_atomic(page);
2553 /*
2554 * Subtract the number of set bits. If this
2555 * is the last page and it is partial we don't really care as
2556 * it just means we do a little extra work but it won't affect
2557 * the result as all out of range bytes are set to zero by
2558 * ntfs_readpage().
2559 */
2560 nr_free -= bitmap_weight(kaddr,
2561 PAGE_SIZE * BITS_PER_BYTE);
2562 kunmap_atomic(kaddr);
2563 put_page(page);
2564 }
2565 ntfs_debug("Finished reading $MFT/$BITMAP, last index = 0x%lx.",
2566 index - 1);
2567 /* If errors occurred we may well have gone below zero, fix this. */
2568 if (nr_free < 0)
2569 nr_free = 0;
2570 ntfs_debug("Exiting.");
2571 return nr_free;
2572 }
2573
2574 /**
2575 * ntfs_statfs - return information about mounted NTFS volume
2576 * @dentry: dentry from mounted volume
2577 * @sfs: statfs structure in which to return the information
2578 *
2579 * Return information about the mounted NTFS volume @dentry in the statfs structure
2580 * pointed to by @sfs (this is initialized with zeros before ntfs_statfs is
2581 * called). We interpret the values to be correct of the moment in time at
2582 * which we are called. Most values are variable otherwise and this isn't just
2583 * the free values but the totals as well. For example we can increase the
2584 * total number of file nodes if we run out and we can keep doing this until
2585 * there is no more space on the volume left at all.
2586 *
2587 * Called from vfs_statfs which is used to handle the statfs, fstatfs, and
2588 * ustat system calls.
2589 *
2590 * Return 0 on success or -errno on error.
2591 */
ntfs_statfs(struct dentry * dentry,struct kstatfs * sfs)2592 static int ntfs_statfs(struct dentry *dentry, struct kstatfs *sfs)
2593 {
2594 struct super_block *sb = dentry->d_sb;
2595 s64 size;
2596 ntfs_volume *vol = NTFS_SB(sb);
2597 ntfs_inode *mft_ni = NTFS_I(vol->mft_ino);
2598 pgoff_t max_index;
2599 unsigned long flags;
2600
2601 ntfs_debug("Entering.");
2602 /* Type of filesystem. */
2603 sfs->f_type = NTFS_SB_MAGIC;
2604 /* Optimal transfer block size. */
2605 sfs->f_bsize = PAGE_SIZE;
2606 /*
2607 * Total data blocks in filesystem in units of f_bsize and since
2608 * inodes are also stored in data blocs ($MFT is a file) this is just
2609 * the total clusters.
2610 */
2611 sfs->f_blocks = vol->nr_clusters << vol->cluster_size_bits >>
2612 PAGE_SHIFT;
2613 /* Free data blocks in filesystem in units of f_bsize. */
2614 size = get_nr_free_clusters(vol) << vol->cluster_size_bits >>
2615 PAGE_SHIFT;
2616 if (size < 0LL)
2617 size = 0LL;
2618 /* Free blocks avail to non-superuser, same as above on NTFS. */
2619 sfs->f_bavail = sfs->f_bfree = size;
2620 /* Serialize accesses to the inode bitmap. */
2621 down_read(&vol->mftbmp_lock);
2622 read_lock_irqsave(&mft_ni->size_lock, flags);
2623 size = i_size_read(vol->mft_ino) >> vol->mft_record_size_bits;
2624 /*
2625 * Convert the maximum number of set bits into bytes rounded up, then
2626 * convert into multiples of PAGE_SIZE, rounding up so that if we
2627 * have one full and one partial page max_index = 2.
2628 */
2629 max_index = ((((mft_ni->initialized_size >> vol->mft_record_size_bits)
2630 + 7) >> 3) + PAGE_SIZE - 1) >> PAGE_SHIFT;
2631 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2632 /* Number of inodes in filesystem (at this point in time). */
2633 sfs->f_files = size;
2634 /* Free inodes in fs (based on current total count). */
2635 sfs->f_ffree = __get_nr_free_mft_records(vol, size, max_index);
2636 up_read(&vol->mftbmp_lock);
2637 /*
2638 * File system id. This is extremely *nix flavour dependent and even
2639 * within Linux itself all fs do their own thing. I interpret this to
2640 * mean a unique id associated with the mounted fs and not the id
2641 * associated with the filesystem driver, the latter is already given
2642 * by the filesystem type in sfs->f_type. Thus we use the 64-bit
2643 * volume serial number splitting it into two 32-bit parts. We enter
2644 * the least significant 32-bits in f_fsid[0] and the most significant
2645 * 32-bits in f_fsid[1].
2646 */
2647 sfs->f_fsid = u64_to_fsid(vol->serial_no);
2648 /* Maximum length of filenames. */
2649 sfs->f_namelen = NTFS_MAX_NAME_LEN;
2650 return 0;
2651 }
2652
2653 #ifdef NTFS_RW
ntfs_write_inode(struct inode * vi,struct writeback_control * wbc)2654 static int ntfs_write_inode(struct inode *vi, struct writeback_control *wbc)
2655 {
2656 return __ntfs_write_inode(vi, wbc->sync_mode == WB_SYNC_ALL);
2657 }
2658 #endif
2659
2660 /**
2661 * The complete super operations.
2662 */
2663 static const struct super_operations ntfs_sops = {
2664 .alloc_inode = ntfs_alloc_big_inode, /* VFS: Allocate new inode. */
2665 .free_inode = ntfs_free_big_inode, /* VFS: Deallocate inode. */
2666 #ifdef NTFS_RW
2667 .write_inode = ntfs_write_inode, /* VFS: Write dirty inode to
2668 disk. */
2669 #endif /* NTFS_RW */
2670 .put_super = ntfs_put_super, /* Syscall: umount. */
2671 .statfs = ntfs_statfs, /* Syscall: statfs */
2672 .remount_fs = ntfs_remount, /* Syscall: mount -o remount. */
2673 .evict_inode = ntfs_evict_big_inode, /* VFS: Called when an inode is
2674 removed from memory. */
2675 .show_options = ntfs_show_options, /* Show mount options in
2676 proc. */
2677 };
2678
2679 /**
2680 * ntfs_fill_super - mount an ntfs filesystem
2681 * @sb: super block of ntfs filesystem to mount
2682 * @opt: string containing the mount options
2683 * @silent: silence error output
2684 *
2685 * ntfs_fill_super() is called by the VFS to mount the device described by @sb
2686 * with the mount otions in @data with the NTFS filesystem.
2687 *
2688 * If @silent is true, remain silent even if errors are detected. This is used
2689 * during bootup, when the kernel tries to mount the root filesystem with all
2690 * registered filesystems one after the other until one succeeds. This implies
2691 * that all filesystems except the correct one will quite correctly and
2692 * expectedly return an error, but nobody wants to see error messages when in
2693 * fact this is what is supposed to happen.
2694 *
2695 * NOTE: @sb->s_flags contains the mount options flags.
2696 */
ntfs_fill_super(struct super_block * sb,void * opt,const int silent)2697 static int ntfs_fill_super(struct super_block *sb, void *opt, const int silent)
2698 {
2699 ntfs_volume *vol;
2700 struct buffer_head *bh;
2701 struct inode *tmp_ino;
2702 int blocksize, result;
2703
2704 /*
2705 * We do a pretty difficult piece of bootstrap by reading the
2706 * MFT (and other metadata) from disk into memory. We'll only
2707 * release this metadata during umount, so the locking patterns
2708 * observed during bootstrap do not count. So turn off the
2709 * observation of locking patterns (strictly for this context
2710 * only) while mounting NTFS. [The validator is still active
2711 * otherwise, even for this context: it will for example record
2712 * lock class registrations.]
2713 */
2714 lockdep_off();
2715 ntfs_debug("Entering.");
2716 #ifndef NTFS_RW
2717 sb->s_flags |= SB_RDONLY;
2718 #endif /* ! NTFS_RW */
2719 /* Allocate a new ntfs_volume and place it in sb->s_fs_info. */
2720 sb->s_fs_info = kmalloc(sizeof(ntfs_volume), GFP_NOFS);
2721 vol = NTFS_SB(sb);
2722 if (!vol) {
2723 if (!silent)
2724 ntfs_error(sb, "Allocation of NTFS volume structure "
2725 "failed. Aborting mount...");
2726 lockdep_on();
2727 return -ENOMEM;
2728 }
2729 /* Initialize ntfs_volume structure. */
2730 *vol = (ntfs_volume) {
2731 .sb = sb,
2732 /*
2733 * Default is group and other don't have any access to files or
2734 * directories while owner has full access. Further, files by
2735 * default are not executable but directories are of course
2736 * browseable.
2737 */
2738 .fmask = 0177,
2739 .dmask = 0077,
2740 };
2741 init_rwsem(&vol->mftbmp_lock);
2742 init_rwsem(&vol->lcnbmp_lock);
2743
2744 /* By default, enable sparse support. */
2745 NVolSetSparseEnabled(vol);
2746
2747 /* Important to get the mount options dealt with now. */
2748 if (!parse_options(vol, (char*)opt))
2749 goto err_out_now;
2750
2751 /* We support sector sizes up to the PAGE_SIZE. */
2752 if (bdev_logical_block_size(sb->s_bdev) > PAGE_SIZE) {
2753 if (!silent)
2754 ntfs_error(sb, "Device has unsupported sector size "
2755 "(%i). The maximum supported sector "
2756 "size on this architecture is %lu "
2757 "bytes.",
2758 bdev_logical_block_size(sb->s_bdev),
2759 PAGE_SIZE);
2760 goto err_out_now;
2761 }
2762 /*
2763 * Setup the device access block size to NTFS_BLOCK_SIZE or the hard
2764 * sector size, whichever is bigger.
2765 */
2766 blocksize = sb_min_blocksize(sb, NTFS_BLOCK_SIZE);
2767 if (blocksize < NTFS_BLOCK_SIZE) {
2768 if (!silent)
2769 ntfs_error(sb, "Unable to set device block size.");
2770 goto err_out_now;
2771 }
2772 BUG_ON(blocksize != sb->s_blocksize);
2773 ntfs_debug("Set device block size to %i bytes (block size bits %i).",
2774 blocksize, sb->s_blocksize_bits);
2775 /* Determine the size of the device in units of block_size bytes. */
2776 vol->nr_blocks = sb_bdev_nr_blocks(sb);
2777 if (!vol->nr_blocks) {
2778 if (!silent)
2779 ntfs_error(sb, "Unable to determine device size.");
2780 goto err_out_now;
2781 }
2782 /* Read the boot sector and return unlocked buffer head to it. */
2783 if (!(bh = read_ntfs_boot_sector(sb, silent))) {
2784 if (!silent)
2785 ntfs_error(sb, "Not an NTFS volume.");
2786 goto err_out_now;
2787 }
2788 /*
2789 * Extract the data from the boot sector and setup the ntfs volume
2790 * using it.
2791 */
2792 result = parse_ntfs_boot_sector(vol, (NTFS_BOOT_SECTOR*)bh->b_data);
2793 brelse(bh);
2794 if (!result) {
2795 if (!silent)
2796 ntfs_error(sb, "Unsupported NTFS filesystem.");
2797 goto err_out_now;
2798 }
2799 /*
2800 * If the boot sector indicates a sector size bigger than the current
2801 * device block size, switch the device block size to the sector size.
2802 * TODO: It may be possible to support this case even when the set
2803 * below fails, we would just be breaking up the i/o for each sector
2804 * into multiple blocks for i/o purposes but otherwise it should just
2805 * work. However it is safer to leave disabled until someone hits this
2806 * error message and then we can get them to try it without the setting
2807 * so we know for sure that it works.
2808 */
2809 if (vol->sector_size > blocksize) {
2810 blocksize = sb_set_blocksize(sb, vol->sector_size);
2811 if (blocksize != vol->sector_size) {
2812 if (!silent)
2813 ntfs_error(sb, "Unable to set device block "
2814 "size to sector size (%i).",
2815 vol->sector_size);
2816 goto err_out_now;
2817 }
2818 BUG_ON(blocksize != sb->s_blocksize);
2819 vol->nr_blocks = sb_bdev_nr_blocks(sb);
2820 ntfs_debug("Changed device block size to %i bytes (block size "
2821 "bits %i) to match volume sector size.",
2822 blocksize, sb->s_blocksize_bits);
2823 }
2824 /* Initialize the cluster and mft allocators. */
2825 ntfs_setup_allocators(vol);
2826 /* Setup remaining fields in the super block. */
2827 sb->s_magic = NTFS_SB_MAGIC;
2828 /*
2829 * Ntfs allows 63 bits for the file size, i.e. correct would be:
2830 * sb->s_maxbytes = ~0ULL >> 1;
2831 * But the kernel uses a long as the page cache page index which on
2832 * 32-bit architectures is only 32-bits. MAX_LFS_FILESIZE is kernel
2833 * defined to the maximum the page cache page index can cope with
2834 * without overflowing the index or to 2^63 - 1, whichever is smaller.
2835 */
2836 sb->s_maxbytes = MAX_LFS_FILESIZE;
2837 /* Ntfs measures time in 100ns intervals. */
2838 sb->s_time_gran = 100;
2839 /*
2840 * Now load the metadata required for the page cache and our address
2841 * space operations to function. We do this by setting up a specialised
2842 * read_inode method and then just calling the normal iget() to obtain
2843 * the inode for $MFT which is sufficient to allow our normal inode
2844 * operations and associated address space operations to function.
2845 */
2846 sb->s_op = &ntfs_sops;
2847 tmp_ino = new_inode(sb);
2848 if (!tmp_ino) {
2849 if (!silent)
2850 ntfs_error(sb, "Failed to load essential metadata.");
2851 goto err_out_now;
2852 }
2853 tmp_ino->i_ino = FILE_MFT;
2854 insert_inode_hash(tmp_ino);
2855 if (ntfs_read_inode_mount(tmp_ino) < 0) {
2856 if (!silent)
2857 ntfs_error(sb, "Failed to load essential metadata.");
2858 goto iput_tmp_ino_err_out_now;
2859 }
2860 mutex_lock(&ntfs_lock);
2861 /*
2862 * The current mount is a compression user if the cluster size is
2863 * less than or equal 4kiB.
2864 */
2865 if (vol->cluster_size <= 4096 && !ntfs_nr_compression_users++) {
2866 result = allocate_compression_buffers();
2867 if (result) {
2868 ntfs_error(NULL, "Failed to allocate buffers "
2869 "for compression engine.");
2870 ntfs_nr_compression_users--;
2871 mutex_unlock(&ntfs_lock);
2872 goto iput_tmp_ino_err_out_now;
2873 }
2874 }
2875 /*
2876 * Generate the global default upcase table if necessary. Also
2877 * temporarily increment the number of upcase users to avoid race
2878 * conditions with concurrent (u)mounts.
2879 */
2880 if (!default_upcase)
2881 default_upcase = generate_default_upcase();
2882 ntfs_nr_upcase_users++;
2883 mutex_unlock(&ntfs_lock);
2884 /*
2885 * From now on, ignore @silent parameter. If we fail below this line,
2886 * it will be due to a corrupt fs or a system error, so we report it.
2887 */
2888 /*
2889 * Open the system files with normal access functions and complete
2890 * setting up the ntfs super block.
2891 */
2892 if (!load_system_files(vol)) {
2893 ntfs_error(sb, "Failed to load system files.");
2894 goto unl_upcase_iput_tmp_ino_err_out_now;
2895 }
2896
2897 /* We grab a reference, simulating an ntfs_iget(). */
2898 ihold(vol->root_ino);
2899 if ((sb->s_root = d_make_root(vol->root_ino))) {
2900 ntfs_debug("Exiting, status successful.");
2901 /* Release the default upcase if it has no users. */
2902 mutex_lock(&ntfs_lock);
2903 if (!--ntfs_nr_upcase_users && default_upcase) {
2904 ntfs_free(default_upcase);
2905 default_upcase = NULL;
2906 }
2907 mutex_unlock(&ntfs_lock);
2908 sb->s_export_op = &ntfs_export_ops;
2909 lockdep_on();
2910 return 0;
2911 }
2912 ntfs_error(sb, "Failed to allocate root directory.");
2913 /* Clean up after the successful load_system_files() call from above. */
2914 // TODO: Use ntfs_put_super() instead of repeating all this code...
2915 // FIXME: Should mark the volume clean as the error is most likely
2916 // -ENOMEM.
2917 iput(vol->vol_ino);
2918 vol->vol_ino = NULL;
2919 /* NTFS 3.0+ specific clean up. */
2920 if (vol->major_ver >= 3) {
2921 #ifdef NTFS_RW
2922 if (vol->usnjrnl_j_ino) {
2923 iput(vol->usnjrnl_j_ino);
2924 vol->usnjrnl_j_ino = NULL;
2925 }
2926 if (vol->usnjrnl_max_ino) {
2927 iput(vol->usnjrnl_max_ino);
2928 vol->usnjrnl_max_ino = NULL;
2929 }
2930 if (vol->usnjrnl_ino) {
2931 iput(vol->usnjrnl_ino);
2932 vol->usnjrnl_ino = NULL;
2933 }
2934 if (vol->quota_q_ino) {
2935 iput(vol->quota_q_ino);
2936 vol->quota_q_ino = NULL;
2937 }
2938 if (vol->quota_ino) {
2939 iput(vol->quota_ino);
2940 vol->quota_ino = NULL;
2941 }
2942 #endif /* NTFS_RW */
2943 if (vol->extend_ino) {
2944 iput(vol->extend_ino);
2945 vol->extend_ino = NULL;
2946 }
2947 if (vol->secure_ino) {
2948 iput(vol->secure_ino);
2949 vol->secure_ino = NULL;
2950 }
2951 }
2952 iput(vol->root_ino);
2953 vol->root_ino = NULL;
2954 iput(vol->lcnbmp_ino);
2955 vol->lcnbmp_ino = NULL;
2956 iput(vol->mftbmp_ino);
2957 vol->mftbmp_ino = NULL;
2958 #ifdef NTFS_RW
2959 if (vol->logfile_ino) {
2960 iput(vol->logfile_ino);
2961 vol->logfile_ino = NULL;
2962 }
2963 if (vol->mftmirr_ino) {
2964 iput(vol->mftmirr_ino);
2965 vol->mftmirr_ino = NULL;
2966 }
2967 #endif /* NTFS_RW */
2968 /* Throw away the table of attribute definitions. */
2969 vol->attrdef_size = 0;
2970 if (vol->attrdef) {
2971 ntfs_free(vol->attrdef);
2972 vol->attrdef = NULL;
2973 }
2974 vol->upcase_len = 0;
2975 mutex_lock(&ntfs_lock);
2976 if (vol->upcase == default_upcase) {
2977 ntfs_nr_upcase_users--;
2978 vol->upcase = NULL;
2979 }
2980 mutex_unlock(&ntfs_lock);
2981 if (vol->upcase) {
2982 ntfs_free(vol->upcase);
2983 vol->upcase = NULL;
2984 }
2985 if (vol->nls_map) {
2986 unload_nls(vol->nls_map);
2987 vol->nls_map = NULL;
2988 }
2989 /* Error exit code path. */
2990 unl_upcase_iput_tmp_ino_err_out_now:
2991 /*
2992 * Decrease the number of upcase users and destroy the global default
2993 * upcase table if necessary.
2994 */
2995 mutex_lock(&ntfs_lock);
2996 if (!--ntfs_nr_upcase_users && default_upcase) {
2997 ntfs_free(default_upcase);
2998 default_upcase = NULL;
2999 }
3000 if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
3001 free_compression_buffers();
3002 mutex_unlock(&ntfs_lock);
3003 iput_tmp_ino_err_out_now:
3004 iput(tmp_ino);
3005 if (vol->mft_ino && vol->mft_ino != tmp_ino)
3006 iput(vol->mft_ino);
3007 vol->mft_ino = NULL;
3008 /* Errors at this stage are irrelevant. */
3009 err_out_now:
3010 sb->s_fs_info = NULL;
3011 kfree(vol);
3012 ntfs_debug("Failed, returning -EINVAL.");
3013 lockdep_on();
3014 return -EINVAL;
3015 }
3016
3017 /*
3018 * This is a slab cache to optimize allocations and deallocations of Unicode
3019 * strings of the maximum length allowed by NTFS, which is NTFS_MAX_NAME_LEN
3020 * (255) Unicode characters + a terminating NULL Unicode character.
3021 */
3022 struct kmem_cache *ntfs_name_cache;
3023
3024 /* Slab caches for efficient allocation/deallocation of inodes. */
3025 struct kmem_cache *ntfs_inode_cache;
3026 struct kmem_cache *ntfs_big_inode_cache;
3027
3028 /* Init once constructor for the inode slab cache. */
ntfs_big_inode_init_once(void * foo)3029 static void ntfs_big_inode_init_once(void *foo)
3030 {
3031 ntfs_inode *ni = (ntfs_inode *)foo;
3032
3033 inode_init_once(VFS_I(ni));
3034 }
3035
3036 /*
3037 * Slab caches to optimize allocations and deallocations of attribute search
3038 * contexts and index contexts, respectively.
3039 */
3040 struct kmem_cache *ntfs_attr_ctx_cache;
3041 struct kmem_cache *ntfs_index_ctx_cache;
3042
3043 /* Driver wide mutex. */
3044 DEFINE_MUTEX(ntfs_lock);
3045
ntfs_mount(struct file_system_type * fs_type,int flags,const char * dev_name,void * data)3046 static struct dentry *ntfs_mount(struct file_system_type *fs_type,
3047 int flags, const char *dev_name, void *data)
3048 {
3049 return mount_bdev(fs_type, flags, dev_name, data, ntfs_fill_super);
3050 }
3051
3052 static struct file_system_type ntfs_fs_type = {
3053 .owner = THIS_MODULE,
3054 .name = "ntfs",
3055 .mount = ntfs_mount,
3056 .kill_sb = kill_block_super,
3057 .fs_flags = FS_REQUIRES_DEV,
3058 };
3059 MODULE_ALIAS_FS("ntfs");
3060
3061 /* Stable names for the slab caches. */
3062 static const char ntfs_index_ctx_cache_name[] = "ntfs_index_ctx_cache";
3063 static const char ntfs_attr_ctx_cache_name[] = "ntfs_attr_ctx_cache";
3064 static const char ntfs_name_cache_name[] = "ntfs_name_cache";
3065 static const char ntfs_inode_cache_name[] = "ntfs_inode_cache";
3066 static const char ntfs_big_inode_cache_name[] = "ntfs_big_inode_cache";
3067
init_ntfs_fs(void)3068 static int __init init_ntfs_fs(void)
3069 {
3070 int err = 0;
3071
3072 /* This may be ugly but it results in pretty output so who cares. (-8 */
3073 pr_info("driver " NTFS_VERSION " [Flags: R/"
3074 #ifdef NTFS_RW
3075 "W"
3076 #else
3077 "O"
3078 #endif
3079 #ifdef DEBUG
3080 " DEBUG"
3081 #endif
3082 #ifdef MODULE
3083 " MODULE"
3084 #endif
3085 "].\n");
3086
3087 ntfs_debug("Debug messages are enabled.");
3088
3089 ntfs_index_ctx_cache = kmem_cache_create(ntfs_index_ctx_cache_name,
3090 sizeof(ntfs_index_context), 0 /* offset */,
3091 SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3092 if (!ntfs_index_ctx_cache) {
3093 pr_crit("Failed to create %s!\n", ntfs_index_ctx_cache_name);
3094 goto ictx_err_out;
3095 }
3096 ntfs_attr_ctx_cache = kmem_cache_create(ntfs_attr_ctx_cache_name,
3097 sizeof(ntfs_attr_search_ctx), 0 /* offset */,
3098 SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3099 if (!ntfs_attr_ctx_cache) {
3100 pr_crit("NTFS: Failed to create %s!\n",
3101 ntfs_attr_ctx_cache_name);
3102 goto actx_err_out;
3103 }
3104
3105 ntfs_name_cache = kmem_cache_create(ntfs_name_cache_name,
3106 (NTFS_MAX_NAME_LEN+1) * sizeof(ntfschar), 0,
3107 SLAB_HWCACHE_ALIGN, NULL);
3108 if (!ntfs_name_cache) {
3109 pr_crit("Failed to create %s!\n", ntfs_name_cache_name);
3110 goto name_err_out;
3111 }
3112
3113 ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
3114 sizeof(ntfs_inode), 0,
3115 SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD, NULL);
3116 if (!ntfs_inode_cache) {
3117 pr_crit("Failed to create %s!\n", ntfs_inode_cache_name);
3118 goto inode_err_out;
3119 }
3120
3121 ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
3122 sizeof(big_ntfs_inode), 0,
3123 SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
3124 SLAB_ACCOUNT, ntfs_big_inode_init_once);
3125 if (!ntfs_big_inode_cache) {
3126 pr_crit("Failed to create %s!\n", ntfs_big_inode_cache_name);
3127 goto big_inode_err_out;
3128 }
3129
3130 /* Register the ntfs sysctls. */
3131 err = ntfs_sysctl(1);
3132 if (err) {
3133 pr_crit("Failed to register NTFS sysctls!\n");
3134 goto sysctl_err_out;
3135 }
3136
3137 err = register_filesystem(&ntfs_fs_type);
3138 if (!err) {
3139 ntfs_debug("NTFS driver registered successfully.");
3140 return 0; /* Success! */
3141 }
3142 pr_crit("Failed to register NTFS filesystem driver!\n");
3143
3144 /* Unregister the ntfs sysctls. */
3145 ntfs_sysctl(0);
3146 sysctl_err_out:
3147 kmem_cache_destroy(ntfs_big_inode_cache);
3148 big_inode_err_out:
3149 kmem_cache_destroy(ntfs_inode_cache);
3150 inode_err_out:
3151 kmem_cache_destroy(ntfs_name_cache);
3152 name_err_out:
3153 kmem_cache_destroy(ntfs_attr_ctx_cache);
3154 actx_err_out:
3155 kmem_cache_destroy(ntfs_index_ctx_cache);
3156 ictx_err_out:
3157 if (!err) {
3158 pr_crit("Aborting NTFS filesystem driver registration...\n");
3159 err = -ENOMEM;
3160 }
3161 return err;
3162 }
3163
exit_ntfs_fs(void)3164 static void __exit exit_ntfs_fs(void)
3165 {
3166 ntfs_debug("Unregistering NTFS driver.");
3167
3168 unregister_filesystem(&ntfs_fs_type);
3169
3170 /*
3171 * Make sure all delayed rcu free inodes are flushed before we
3172 * destroy cache.
3173 */
3174 rcu_barrier();
3175 kmem_cache_destroy(ntfs_big_inode_cache);
3176 kmem_cache_destroy(ntfs_inode_cache);
3177 kmem_cache_destroy(ntfs_name_cache);
3178 kmem_cache_destroy(ntfs_attr_ctx_cache);
3179 kmem_cache_destroy(ntfs_index_ctx_cache);
3180 /* Unregister the ntfs sysctls. */
3181 ntfs_sysctl(0);
3182 }
3183
3184 MODULE_AUTHOR("Anton Altaparmakov <anton@tuxera.com>");
3185 MODULE_DESCRIPTION("NTFS 1.2/3.x driver - Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc.");
3186 MODULE_VERSION(NTFS_VERSION);
3187 MODULE_LICENSE("GPL");
3188 #ifdef DEBUG
3189 module_param(debug_msgs, bint, 0);
3190 MODULE_PARM_DESC(debug_msgs, "Enable debug messages.");
3191 #endif
3192
3193 module_init(init_ntfs_fs)
3194 module_exit(exit_ntfs_fs)
3195