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