Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * super.c - NTFS kernel super block handling. Part of the Linux-NTFS project.
0004  *
0005  * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
0006  * Copyright (c) 2001,2002 Richard Russon
0007  */
0008 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0009 
0010 #include <linux/stddef.h>
0011 #include <linux/init.h>
0012 #include <linux/slab.h>
0013 #include <linux/string.h>
0014 #include <linux/spinlock.h>
0015 #include <linux/blkdev.h>   /* For bdev_logical_block_size(). */
0016 #include <linux/backing-dev.h>
0017 #include <linux/buffer_head.h>
0018 #include <linux/vfs.h>
0019 #include <linux/moduleparam.h>
0020 #include <linux/bitmap.h>
0021 
0022 #include "sysctl.h"
0023 #include "logfile.h"
0024 #include "quota.h"
0025 #include "usnjrnl.h"
0026 #include "dir.h"
0027 #include "debug.h"
0028 #include "index.h"
0029 #include "inode.h"
0030 #include "aops.h"
0031 #include "layout.h"
0032 #include "malloc.h"
0033 #include "ntfs.h"
0034 
0035 /* Number of mounted filesystems which have compression enabled. */
0036 static unsigned long ntfs_nr_compression_users;
0037 
0038 /* A global default upcase table and a corresponding reference count. */
0039 static ntfschar *default_upcase;
0040 static unsigned long ntfs_nr_upcase_users;
0041 
0042 /* Error constants/strings used in inode.c::ntfs_show_options(). */
0043 typedef enum {
0044     /* One of these must be present, default is ON_ERRORS_CONTINUE. */
0045     ON_ERRORS_PANIC         = 0x01,
0046     ON_ERRORS_REMOUNT_RO        = 0x02,
0047     ON_ERRORS_CONTINUE      = 0x04,
0048     /* Optional, can be combined with any of the above. */
0049     ON_ERRORS_RECOVER       = 0x10,
0050 } ON_ERRORS_ACTIONS;
0051 
0052 const option_t on_errors_arr[] = {
0053     { ON_ERRORS_PANIC,  "panic" },
0054     { ON_ERRORS_REMOUNT_RO, "remount-ro", },
0055     { ON_ERRORS_CONTINUE,   "continue", },
0056     { ON_ERRORS_RECOVER,    "recover" },
0057     { 0,            NULL }
0058 };
0059 
0060 /**
0061  * simple_getbool -
0062  *
0063  * Copied from old ntfs driver (which copied from vfat driver).
0064  */
0065 static int simple_getbool(char *s, bool *setval)
0066 {
0067     if (s) {
0068         if (!strcmp(s, "1") || !strcmp(s, "yes") || !strcmp(s, "true"))
0069             *setval = true;
0070         else if (!strcmp(s, "0") || !strcmp(s, "no") ||
0071                             !strcmp(s, "false"))
0072             *setval = false;
0073         else
0074             return 0;
0075     } else
0076         *setval = true;
0077     return 1;
0078 }
0079 
0080 /**
0081  * parse_options - parse the (re)mount options
0082  * @vol:    ntfs volume
0083  * @opt:    string containing the (re)mount options
0084  *
0085  * Parse the recognized options in @opt for the ntfs volume described by @vol.
0086  */
0087 static bool parse_options(ntfs_volume *vol, char *opt)
0088 {
0089     char *p, *v, *ov;
0090     static char *utf8 = "utf8";
0091     int errors = 0, sloppy = 0;
0092     kuid_t uid = INVALID_UID;
0093     kgid_t gid = INVALID_GID;
0094     umode_t fmask = (umode_t)-1, dmask = (umode_t)-1;
0095     int mft_zone_multiplier = -1, on_errors = -1;
0096     int show_sys_files = -1, case_sensitive = -1, disable_sparse = -1;
0097     struct nls_table *nls_map = NULL, *old_nls;
0098 
0099     /* I am lazy... (-8 */
0100 #define NTFS_GETOPT_WITH_DEFAULT(option, variable, default_value)   \
0101     if (!strcmp(p, option)) {                   \
0102         if (!v || !*v)                      \
0103             variable = default_value;           \
0104         else {                          \
0105             variable = simple_strtoul(ov = v, &v, 0);   \
0106             if (*v)                     \
0107                 goto needs_val;             \
0108         }                           \
0109     }
0110 #define NTFS_GETOPT(option, variable)                   \
0111     if (!strcmp(p, option)) {                   \
0112         if (!v || !*v)                      \
0113             goto needs_arg;                 \
0114         variable = simple_strtoul(ov = v, &v, 0);       \
0115         if (*v)                         \
0116             goto needs_val;                 \
0117     }
0118 #define NTFS_GETOPT_UID(option, variable)               \
0119     if (!strcmp(p, option)) {                   \
0120         uid_t uid_value;                    \
0121         if (!v || !*v)                      \
0122             goto needs_arg;                 \
0123         uid_value = simple_strtoul(ov = v, &v, 0);      \
0124         if (*v)                         \
0125             goto needs_val;                 \
0126         variable = make_kuid(current_user_ns(), uid_value); \
0127         if (!uid_valid(variable))               \
0128             goto needs_val;                 \
0129     }
0130 #define NTFS_GETOPT_GID(option, variable)               \
0131     if (!strcmp(p, option)) {                   \
0132         gid_t gid_value;                    \
0133         if (!v || !*v)                      \
0134             goto needs_arg;                 \
0135         gid_value = simple_strtoul(ov = v, &v, 0);      \
0136         if (*v)                         \
0137             goto needs_val;                 \
0138         variable = make_kgid(current_user_ns(), gid_value); \
0139         if (!gid_valid(variable))               \
0140             goto needs_val;                 \
0141     }
0142 #define NTFS_GETOPT_OCTAL(option, variable)             \
0143     if (!strcmp(p, option)) {                   \
0144         if (!v || !*v)                      \
0145             goto needs_arg;                 \
0146         variable = simple_strtoul(ov = v, &v, 8);       \
0147         if (*v)                         \
0148             goto needs_val;                 \
0149     }
0150 #define NTFS_GETOPT_BOOL(option, variable)              \
0151     if (!strcmp(p, option)) {                   \
0152         bool val;                       \
0153         if (!simple_getbool(v, &val))               \
0154             goto needs_bool;                \
0155         variable = val;                     \
0156     }
0157 #define NTFS_GETOPT_OPTIONS_ARRAY(option, variable, opt_array)      \
0158     if (!strcmp(p, option)) {                   \
0159         int _i;                         \
0160         if (!v || !*v)                      \
0161             goto needs_arg;                 \
0162         ov = v;                         \
0163         if (variable == -1)                 \
0164             variable = 0;                   \
0165         for (_i = 0; opt_array[_i].str && *opt_array[_i].str; _i++) \
0166             if (!strcmp(opt_array[_i].str, v)) {        \
0167                 variable |= opt_array[_i].val;      \
0168                 break;                  \
0169             }                       \
0170         if (!opt_array[_i].str || !*opt_array[_i].str)      \
0171             goto needs_val;                 \
0172     }
0173     if (!opt || !*opt)
0174         goto no_mount_options;
0175     ntfs_debug("Entering with mount options string: %s", opt);
0176     while ((p = strsep(&opt, ","))) {
0177         if ((v = strchr(p, '=')))
0178             *v++ = 0;
0179         NTFS_GETOPT_UID("uid", uid)
0180         else NTFS_GETOPT_GID("gid", gid)
0181         else NTFS_GETOPT_OCTAL("umask", fmask = dmask)
0182         else NTFS_GETOPT_OCTAL("fmask", fmask)
0183         else NTFS_GETOPT_OCTAL("dmask", dmask)
0184         else NTFS_GETOPT("mft_zone_multiplier", mft_zone_multiplier)
0185         else NTFS_GETOPT_WITH_DEFAULT("sloppy", sloppy, true)
0186         else NTFS_GETOPT_BOOL("show_sys_files", show_sys_files)
0187         else NTFS_GETOPT_BOOL("case_sensitive", case_sensitive)
0188         else NTFS_GETOPT_BOOL("disable_sparse", disable_sparse)
0189         else NTFS_GETOPT_OPTIONS_ARRAY("errors", on_errors,
0190                 on_errors_arr)
0191         else if (!strcmp(p, "posix") || !strcmp(p, "show_inodes"))
0192             ntfs_warning(vol->sb, "Ignoring obsolete option %s.",
0193                     p);
0194         else if (!strcmp(p, "nls") || !strcmp(p, "iocharset")) {
0195             if (!strcmp(p, "iocharset"))
0196                 ntfs_warning(vol->sb, "Option iocharset is "
0197                         "deprecated. Please use "
0198                         "option nls=<charsetname> in "
0199                         "the future.");
0200             if (!v || !*v)
0201                 goto needs_arg;
0202 use_utf8:
0203             old_nls = nls_map;
0204             nls_map = load_nls(v);
0205             if (!nls_map) {
0206                 if (!old_nls) {
0207                     ntfs_error(vol->sb, "NLS character set "
0208                             "%s not found.", v);
0209                     return false;
0210                 }
0211                 ntfs_error(vol->sb, "NLS character set %s not "
0212                         "found. Using previous one %s.",
0213                         v, old_nls->charset);
0214                 nls_map = old_nls;
0215             } else /* nls_map */ {
0216                 unload_nls(old_nls);
0217             }
0218         } else if (!strcmp(p, "utf8")) {
0219             bool val = false;
0220             ntfs_warning(vol->sb, "Option utf8 is no longer "
0221                    "supported, using option nls=utf8. Please "
0222                    "use option nls=utf8 in the future and "
0223                    "make sure utf8 is compiled either as a "
0224                    "module or into the kernel.");
0225             if (!v || !*v)
0226                 val = true;
0227             else if (!simple_getbool(v, &val))
0228                 goto needs_bool;
0229             if (val) {
0230                 v = utf8;
0231                 goto use_utf8;
0232             }
0233         } else {
0234             ntfs_error(vol->sb, "Unrecognized mount option %s.", p);
0235             if (errors < INT_MAX)
0236                 errors++;
0237         }
0238 #undef NTFS_GETOPT_OPTIONS_ARRAY
0239 #undef NTFS_GETOPT_BOOL
0240 #undef NTFS_GETOPT
0241 #undef NTFS_GETOPT_WITH_DEFAULT
0242     }
0243 no_mount_options:
0244     if (errors && !sloppy)
0245         return false;
0246     if (sloppy)
0247         ntfs_warning(vol->sb, "Sloppy option given. Ignoring "
0248                 "unrecognized mount option(s) and continuing.");
0249     /* Keep this first! */
0250     if (on_errors != -1) {
0251         if (!on_errors) {
0252             ntfs_error(vol->sb, "Invalid errors option argument "
0253                     "or bug in options parser.");
0254             return false;
0255         }
0256     }
0257     if (nls_map) {
0258         if (vol->nls_map && vol->nls_map != nls_map) {
0259             ntfs_error(vol->sb, "Cannot change NLS character set "
0260                     "on remount.");
0261             return false;
0262         } /* else (!vol->nls_map) */
0263         ntfs_debug("Using NLS character set %s.", nls_map->charset);
0264         vol->nls_map = nls_map;
0265     } else /* (!nls_map) */ {
0266         if (!vol->nls_map) {
0267             vol->nls_map = load_nls_default();
0268             if (!vol->nls_map) {
0269                 ntfs_error(vol->sb, "Failed to load default "
0270                         "NLS character set.");
0271                 return false;
0272             }
0273             ntfs_debug("Using default NLS character set (%s).",
0274                     vol->nls_map->charset);
0275         }
0276     }
0277     if (mft_zone_multiplier != -1) {
0278         if (vol->mft_zone_multiplier && vol->mft_zone_multiplier !=
0279                 mft_zone_multiplier) {
0280             ntfs_error(vol->sb, "Cannot change mft_zone_multiplier "
0281                     "on remount.");
0282             return false;
0283         }
0284         if (mft_zone_multiplier < 1 || mft_zone_multiplier > 4) {
0285             ntfs_error(vol->sb, "Invalid mft_zone_multiplier. "
0286                     "Using default value, i.e. 1.");
0287             mft_zone_multiplier = 1;
0288         }
0289         vol->mft_zone_multiplier = mft_zone_multiplier;
0290     }
0291     if (!vol->mft_zone_multiplier)
0292         vol->mft_zone_multiplier = 1;
0293     if (on_errors != -1)
0294         vol->on_errors = on_errors;
0295     if (!vol->on_errors || vol->on_errors == ON_ERRORS_RECOVER)
0296         vol->on_errors |= ON_ERRORS_CONTINUE;
0297     if (uid_valid(uid))
0298         vol->uid = uid;
0299     if (gid_valid(gid))
0300         vol->gid = gid;
0301     if (fmask != (umode_t)-1)
0302         vol->fmask = fmask;
0303     if (dmask != (umode_t)-1)
0304         vol->dmask = dmask;
0305     if (show_sys_files != -1) {
0306         if (show_sys_files)
0307             NVolSetShowSystemFiles(vol);
0308         else
0309             NVolClearShowSystemFiles(vol);
0310     }
0311     if (case_sensitive != -1) {
0312         if (case_sensitive)
0313             NVolSetCaseSensitive(vol);
0314         else
0315             NVolClearCaseSensitive(vol);
0316     }
0317     if (disable_sparse != -1) {
0318         if (disable_sparse)
0319             NVolClearSparseEnabled(vol);
0320         else {
0321             if (!NVolSparseEnabled(vol) &&
0322                     vol->major_ver && vol->major_ver < 3)
0323                 ntfs_warning(vol->sb, "Not enabling sparse "
0324                         "support due to NTFS volume "
0325                         "version %i.%i (need at least "
0326                         "version 3.0).", vol->major_ver,
0327                         vol->minor_ver);
0328             else
0329                 NVolSetSparseEnabled(vol);
0330         }
0331     }
0332     return true;
0333 needs_arg:
0334     ntfs_error(vol->sb, "The %s option requires an argument.", p);
0335     return false;
0336 needs_bool:
0337     ntfs_error(vol->sb, "The %s option requires a boolean argument.", p);
0338     return false;
0339 needs_val:
0340     ntfs_error(vol->sb, "Invalid %s option argument: %s", p, ov);
0341     return false;
0342 }
0343 
0344 #ifdef NTFS_RW
0345 
0346 /**
0347  * ntfs_write_volume_flags - write new flags to the volume information flags
0348  * @vol:    ntfs volume on which to modify the flags
0349  * @flags:  new flags value for the volume information flags
0350  *
0351  * Internal function.  You probably want to use ntfs_{set,clear}_volume_flags()
0352  * instead (see below).
0353  *
0354  * Replace the volume information flags on the volume @vol with the value
0355  * supplied in @flags.  Note, this overwrites the volume information flags, so
0356  * make sure to combine the flags you want to modify with the old flags and use
0357  * the result when calling ntfs_write_volume_flags().
0358  *
0359  * Return 0 on success and -errno on error.
0360  */
0361 static int ntfs_write_volume_flags(ntfs_volume *vol, const VOLUME_FLAGS flags)
0362 {
0363     ntfs_inode *ni = NTFS_I(vol->vol_ino);
0364     MFT_RECORD *m;
0365     VOLUME_INFORMATION *vi;
0366     ntfs_attr_search_ctx *ctx;
0367     int err;
0368 
0369     ntfs_debug("Entering, old flags = 0x%x, new flags = 0x%x.",
0370             le16_to_cpu(vol->vol_flags), le16_to_cpu(flags));
0371     if (vol->vol_flags == flags)
0372         goto done;
0373     BUG_ON(!ni);
0374     m = map_mft_record(ni);
0375     if (IS_ERR(m)) {
0376         err = PTR_ERR(m);
0377         goto err_out;
0378     }
0379     ctx = ntfs_attr_get_search_ctx(ni, m);
0380     if (!ctx) {
0381         err = -ENOMEM;
0382         goto put_unm_err_out;
0383     }
0384     err = ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
0385             ctx);
0386     if (err)
0387         goto put_unm_err_out;
0388     vi = (VOLUME_INFORMATION*)((u8*)ctx->attr +
0389             le16_to_cpu(ctx->attr->data.resident.value_offset));
0390     vol->vol_flags = vi->flags = flags;
0391     flush_dcache_mft_record_page(ctx->ntfs_ino);
0392     mark_mft_record_dirty(ctx->ntfs_ino);
0393     ntfs_attr_put_search_ctx(ctx);
0394     unmap_mft_record(ni);
0395 done:
0396     ntfs_debug("Done.");
0397     return 0;
0398 put_unm_err_out:
0399     if (ctx)
0400         ntfs_attr_put_search_ctx(ctx);
0401     unmap_mft_record(ni);
0402 err_out:
0403     ntfs_error(vol->sb, "Failed with error code %i.", -err);
0404     return err;
0405 }
0406 
0407 /**
0408  * ntfs_set_volume_flags - set bits in the volume information flags
0409  * @vol:    ntfs volume on which to modify the flags
0410  * @flags:  flags to set on the volume
0411  *
0412  * Set the bits in @flags in the volume information flags on the volume @vol.
0413  *
0414  * Return 0 on success and -errno on error.
0415  */
0416 static inline int ntfs_set_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
0417 {
0418     flags &= VOLUME_FLAGS_MASK;
0419     return ntfs_write_volume_flags(vol, vol->vol_flags | flags);
0420 }
0421 
0422 /**
0423  * ntfs_clear_volume_flags - clear bits in the volume information flags
0424  * @vol:    ntfs volume on which to modify the flags
0425  * @flags:  flags to clear on the volume
0426  *
0427  * Clear the bits in @flags in the volume information flags on the volume @vol.
0428  *
0429  * Return 0 on success and -errno on error.
0430  */
0431 static inline int ntfs_clear_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
0432 {
0433     flags &= VOLUME_FLAGS_MASK;
0434     flags = vol->vol_flags & cpu_to_le16(~le16_to_cpu(flags));
0435     return ntfs_write_volume_flags(vol, flags);
0436 }
0437 
0438 #endif /* NTFS_RW */
0439 
0440 /**
0441  * ntfs_remount - change the mount options of a mounted ntfs filesystem
0442  * @sb:     superblock of mounted ntfs filesystem
0443  * @flags:  remount flags
0444  * @opt:    remount options string
0445  *
0446  * Change the mount options of an already mounted ntfs filesystem.
0447  *
0448  * NOTE:  The VFS sets the @sb->s_flags remount flags to @flags after
0449  * ntfs_remount() returns successfully (i.e. returns 0).  Otherwise,
0450  * @sb->s_flags are not changed.
0451  */
0452 static int ntfs_remount(struct super_block *sb, int *flags, char *opt)
0453 {
0454     ntfs_volume *vol = NTFS_SB(sb);
0455 
0456     ntfs_debug("Entering with remount options string: %s", opt);
0457 
0458     sync_filesystem(sb);
0459 
0460 #ifndef NTFS_RW
0461     /* For read-only compiled driver, enforce read-only flag. */
0462     *flags |= SB_RDONLY;
0463 #else /* NTFS_RW */
0464     /*
0465      * For the read-write compiled driver, if we are remounting read-write,
0466      * make sure there are no volume errors and that no unsupported volume
0467      * flags are set.  Also, empty the logfile journal as it would become
0468      * stale as soon as something is written to the volume and mark the
0469      * volume dirty so that chkdsk is run if the volume is not umounted
0470      * cleanly.  Finally, mark the quotas out of date so Windows rescans
0471      * the volume on boot and updates them.
0472      *
0473      * When remounting read-only, mark the volume clean if no volume errors
0474      * have occurred.
0475      */
0476     if (sb_rdonly(sb) && !(*flags & SB_RDONLY)) {
0477         static const char *es = ".  Cannot remount read-write.";
0478 
0479         /* Remounting read-write. */
0480         if (NVolErrors(vol)) {
0481             ntfs_error(sb, "Volume has errors and is read-only%s",
0482                     es);
0483             return -EROFS;
0484         }
0485         if (vol->vol_flags & VOLUME_IS_DIRTY) {
0486             ntfs_error(sb, "Volume is dirty and read-only%s", es);
0487             return -EROFS;
0488         }
0489         if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
0490             ntfs_error(sb, "Volume has been modified by chkdsk "
0491                     "and is read-only%s", es);
0492             return -EROFS;
0493         }
0494         if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
0495             ntfs_error(sb, "Volume has unsupported flags set "
0496                     "(0x%x) and is read-only%s",
0497                     (unsigned)le16_to_cpu(vol->vol_flags),
0498                     es);
0499             return -EROFS;
0500         }
0501         if (ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
0502             ntfs_error(sb, "Failed to set dirty bit in volume "
0503                     "information flags%s", es);
0504             return -EROFS;
0505         }
0506 #if 0
0507         // TODO: Enable this code once we start modifying anything that
0508         //   is different between NTFS 1.2 and 3.x...
0509         /* Set NT4 compatibility flag on newer NTFS version volumes. */
0510         if ((vol->major_ver > 1)) {
0511             if (ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
0512                 ntfs_error(sb, "Failed to set NT4 "
0513                         "compatibility flag%s", es);
0514                 NVolSetErrors(vol);
0515                 return -EROFS;
0516             }
0517         }
0518 #endif
0519         if (!ntfs_empty_logfile(vol->logfile_ino)) {
0520             ntfs_error(sb, "Failed to empty journal $LogFile%s",
0521                     es);
0522             NVolSetErrors(vol);
0523             return -EROFS;
0524         }
0525         if (!ntfs_mark_quotas_out_of_date(vol)) {
0526             ntfs_error(sb, "Failed to mark quotas out of date%s",
0527                     es);
0528             NVolSetErrors(vol);
0529             return -EROFS;
0530         }
0531         if (!ntfs_stamp_usnjrnl(vol)) {
0532             ntfs_error(sb, "Failed to stamp transaction log "
0533                     "($UsnJrnl)%s", es);
0534             NVolSetErrors(vol);
0535             return -EROFS;
0536         }
0537     } else if (!sb_rdonly(sb) && (*flags & SB_RDONLY)) {
0538         /* Remounting read-only. */
0539         if (!NVolErrors(vol)) {
0540             if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
0541                 ntfs_warning(sb, "Failed to clear dirty bit "
0542                         "in volume information "
0543                         "flags.  Run chkdsk.");
0544         }
0545     }
0546 #endif /* NTFS_RW */
0547 
0548     // TODO: Deal with *flags.
0549 
0550     if (!parse_options(vol, opt))
0551         return -EINVAL;
0552 
0553     ntfs_debug("Done.");
0554     return 0;
0555 }
0556 
0557 /**
0558  * is_boot_sector_ntfs - check whether a boot sector is a valid NTFS boot sector
0559  * @sb:     Super block of the device to which @b belongs.
0560  * @b:      Boot sector of device @sb to check.
0561  * @silent: If 'true', all output will be silenced.
0562  *
0563  * is_boot_sector_ntfs() checks whether the boot sector @b is a valid NTFS boot
0564  * sector. Returns 'true' if it is valid and 'false' if not.
0565  *
0566  * @sb is only needed for warning/error output, i.e. it can be NULL when silent
0567  * is 'true'.
0568  */
0569 static bool is_boot_sector_ntfs(const struct super_block *sb,
0570         const NTFS_BOOT_SECTOR *b, const bool silent)
0571 {
0572     /*
0573      * Check that checksum == sum of u32 values from b to the checksum
0574      * field.  If checksum is zero, no checking is done.  We will work when
0575      * the checksum test fails, since some utilities update the boot sector
0576      * ignoring the checksum which leaves the checksum out-of-date.  We
0577      * report a warning if this is the case.
0578      */
0579     if ((void*)b < (void*)&b->checksum && b->checksum && !silent) {
0580         le32 *u;
0581         u32 i;
0582 
0583         for (i = 0, u = (le32*)b; u < (le32*)(&b->checksum); ++u)
0584             i += le32_to_cpup(u);
0585         if (le32_to_cpu(b->checksum) != i)
0586             ntfs_warning(sb, "Invalid boot sector checksum.");
0587     }
0588     /* Check OEMidentifier is "NTFS    " */
0589     if (b->oem_id != magicNTFS)
0590         goto not_ntfs;
0591     /* Check bytes per sector value is between 256 and 4096. */
0592     if (le16_to_cpu(b->bpb.bytes_per_sector) < 0x100 ||
0593             le16_to_cpu(b->bpb.bytes_per_sector) > 0x1000)
0594         goto not_ntfs;
0595     /* Check sectors per cluster value is valid. */
0596     switch (b->bpb.sectors_per_cluster) {
0597     case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128:
0598         break;
0599     default:
0600         goto not_ntfs;
0601     }
0602     /* Check the cluster size is not above the maximum (64kiB). */
0603     if ((u32)le16_to_cpu(b->bpb.bytes_per_sector) *
0604             b->bpb.sectors_per_cluster > NTFS_MAX_CLUSTER_SIZE)
0605         goto not_ntfs;
0606     /* Check reserved/unused fields are really zero. */
0607     if (le16_to_cpu(b->bpb.reserved_sectors) ||
0608             le16_to_cpu(b->bpb.root_entries) ||
0609             le16_to_cpu(b->bpb.sectors) ||
0610             le16_to_cpu(b->bpb.sectors_per_fat) ||
0611             le32_to_cpu(b->bpb.large_sectors) || b->bpb.fats)
0612         goto not_ntfs;
0613     /* Check clusters per file mft record value is valid. */
0614     if ((u8)b->clusters_per_mft_record < 0xe1 ||
0615             (u8)b->clusters_per_mft_record > 0xf7)
0616         switch (b->clusters_per_mft_record) {
0617         case 1: case 2: case 4: case 8: case 16: case 32: case 64:
0618             break;
0619         default:
0620             goto not_ntfs;
0621         }
0622     /* Check clusters per index block value is valid. */
0623     if ((u8)b->clusters_per_index_record < 0xe1 ||
0624             (u8)b->clusters_per_index_record > 0xf7)
0625         switch (b->clusters_per_index_record) {
0626         case 1: case 2: case 4: case 8: case 16: case 32: case 64:
0627             break;
0628         default:
0629             goto not_ntfs;
0630         }
0631     /*
0632      * Check for valid end of sector marker. We will work without it, but
0633      * many BIOSes will refuse to boot from a bootsector if the magic is
0634      * incorrect, so we emit a warning.
0635      */
0636     if (!silent && b->end_of_sector_marker != cpu_to_le16(0xaa55))
0637         ntfs_warning(sb, "Invalid end of sector marker.");
0638     return true;
0639 not_ntfs:
0640     return false;
0641 }
0642 
0643 /**
0644  * read_ntfs_boot_sector - read the NTFS boot sector of a device
0645  * @sb:     super block of device to read the boot sector from
0646  * @silent: if true, suppress all output
0647  *
0648  * Reads the boot sector from the device and validates it. If that fails, tries
0649  * to read the backup boot sector, first from the end of the device a-la NT4 and
0650  * later and then from the middle of the device a-la NT3.51 and before.
0651  *
0652  * If a valid boot sector is found but it is not the primary boot sector, we
0653  * repair the primary boot sector silently (unless the device is read-only or
0654  * the primary boot sector is not accessible).
0655  *
0656  * NOTE: To call this function, @sb must have the fields s_dev, the ntfs super
0657  * block (u.ntfs_sb), nr_blocks and the device flags (s_flags) initialized
0658  * to their respective values.
0659  *
0660  * Return the unlocked buffer head containing the boot sector or NULL on error.
0661  */
0662 static struct buffer_head *read_ntfs_boot_sector(struct super_block *sb,
0663         const int silent)
0664 {
0665     const char *read_err_str = "Unable to read %s boot sector.";
0666     struct buffer_head *bh_primary, *bh_backup;
0667     sector_t nr_blocks = NTFS_SB(sb)->nr_blocks;
0668 
0669     /* Try to read primary boot sector. */
0670     if ((bh_primary = sb_bread(sb, 0))) {
0671         if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
0672                 bh_primary->b_data, silent))
0673             return bh_primary;
0674         if (!silent)
0675             ntfs_error(sb, "Primary boot sector is invalid.");
0676     } else if (!silent)
0677         ntfs_error(sb, read_err_str, "primary");
0678     if (!(NTFS_SB(sb)->on_errors & ON_ERRORS_RECOVER)) {
0679         if (bh_primary)
0680             brelse(bh_primary);
0681         if (!silent)
0682             ntfs_error(sb, "Mount option errors=recover not used. "
0683                     "Aborting without trying to recover.");
0684         return NULL;
0685     }
0686     /* Try to read NT4+ backup boot sector. */
0687     if ((bh_backup = sb_bread(sb, nr_blocks - 1))) {
0688         if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
0689                 bh_backup->b_data, silent))
0690             goto hotfix_primary_boot_sector;
0691         brelse(bh_backup);
0692     } else if (!silent)
0693         ntfs_error(sb, read_err_str, "backup");
0694     /* Try to read NT3.51- backup boot sector. */
0695     if ((bh_backup = sb_bread(sb, nr_blocks >> 1))) {
0696         if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
0697                 bh_backup->b_data, silent))
0698             goto hotfix_primary_boot_sector;
0699         if (!silent)
0700             ntfs_error(sb, "Could not find a valid backup boot "
0701                     "sector.");
0702         brelse(bh_backup);
0703     } else if (!silent)
0704         ntfs_error(sb, read_err_str, "backup");
0705     /* We failed. Cleanup and return. */
0706     if (bh_primary)
0707         brelse(bh_primary);
0708     return NULL;
0709 hotfix_primary_boot_sector:
0710     if (bh_primary) {
0711         /*
0712          * If we managed to read sector zero and the volume is not
0713          * read-only, copy the found, valid backup boot sector to the
0714          * primary boot sector.  Note we only copy the actual boot
0715          * sector structure, not the actual whole device sector as that
0716          * may be bigger and would potentially damage the $Boot system
0717          * file (FIXME: Would be nice to know if the backup boot sector
0718          * on a large sector device contains the whole boot loader or
0719          * just the first 512 bytes).
0720          */
0721         if (!sb_rdonly(sb)) {
0722             ntfs_warning(sb, "Hot-fix: Recovering invalid primary "
0723                     "boot sector from backup copy.");
0724             memcpy(bh_primary->b_data, bh_backup->b_data,
0725                     NTFS_BLOCK_SIZE);
0726             mark_buffer_dirty(bh_primary);
0727             sync_dirty_buffer(bh_primary);
0728             if (buffer_uptodate(bh_primary)) {
0729                 brelse(bh_backup);
0730                 return bh_primary;
0731             }
0732             ntfs_error(sb, "Hot-fix: Device write error while "
0733                     "recovering primary boot sector.");
0734         } else {
0735             ntfs_warning(sb, "Hot-fix: Recovery of primary boot "
0736                     "sector failed: Read-only mount.");
0737         }
0738         brelse(bh_primary);
0739     }
0740     ntfs_warning(sb, "Using backup boot sector.");
0741     return bh_backup;
0742 }
0743 
0744 /**
0745  * parse_ntfs_boot_sector - parse the boot sector and store the data in @vol
0746  * @vol:    volume structure to initialise with data from boot sector
0747  * @b:      boot sector to parse
0748  *
0749  * Parse the ntfs boot sector @b and store all imporant information therein in
0750  * the ntfs super block @vol.  Return 'true' on success and 'false' on error.
0751  */
0752 static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)
0753 {
0754     unsigned int sectors_per_cluster_bits, nr_hidden_sects;
0755     int clusters_per_mft_record, clusters_per_index_record;
0756     s64 ll;
0757 
0758     vol->sector_size = le16_to_cpu(b->bpb.bytes_per_sector);
0759     vol->sector_size_bits = ffs(vol->sector_size) - 1;
0760     ntfs_debug("vol->sector_size = %i (0x%x)", vol->sector_size,
0761             vol->sector_size);
0762     ntfs_debug("vol->sector_size_bits = %i (0x%x)", vol->sector_size_bits,
0763             vol->sector_size_bits);
0764     if (vol->sector_size < vol->sb->s_blocksize) {
0765         ntfs_error(vol->sb, "Sector size (%i) is smaller than the "
0766                 "device block size (%lu).  This is not "
0767                 "supported.  Sorry.", vol->sector_size,
0768                 vol->sb->s_blocksize);
0769         return false;
0770     }
0771     ntfs_debug("sectors_per_cluster = 0x%x", b->bpb.sectors_per_cluster);
0772     sectors_per_cluster_bits = ffs(b->bpb.sectors_per_cluster) - 1;
0773     ntfs_debug("sectors_per_cluster_bits = 0x%x",
0774             sectors_per_cluster_bits);
0775     nr_hidden_sects = le32_to_cpu(b->bpb.hidden_sectors);
0776     ntfs_debug("number of hidden sectors = 0x%x", nr_hidden_sects);
0777     vol->cluster_size = vol->sector_size << sectors_per_cluster_bits;
0778     vol->cluster_size_mask = vol->cluster_size - 1;
0779     vol->cluster_size_bits = ffs(vol->cluster_size) - 1;
0780     ntfs_debug("vol->cluster_size = %i (0x%x)", vol->cluster_size,
0781             vol->cluster_size);
0782     ntfs_debug("vol->cluster_size_mask = 0x%x", vol->cluster_size_mask);
0783     ntfs_debug("vol->cluster_size_bits = %i", vol->cluster_size_bits);
0784     if (vol->cluster_size < vol->sector_size) {
0785         ntfs_error(vol->sb, "Cluster size (%i) is smaller than the "
0786                 "sector size (%i).  This is not supported.  "
0787                 "Sorry.", vol->cluster_size, vol->sector_size);
0788         return false;
0789     }
0790     clusters_per_mft_record = b->clusters_per_mft_record;
0791     ntfs_debug("clusters_per_mft_record = %i (0x%x)",
0792             clusters_per_mft_record, clusters_per_mft_record);
0793     if (clusters_per_mft_record > 0)
0794         vol->mft_record_size = vol->cluster_size <<
0795                 (ffs(clusters_per_mft_record) - 1);
0796     else
0797         /*
0798          * When mft_record_size < cluster_size, clusters_per_mft_record
0799          * = -log2(mft_record_size) bytes. mft_record_size normaly is
0800          * 1024 bytes, which is encoded as 0xF6 (-10 in decimal).
0801          */
0802         vol->mft_record_size = 1 << -clusters_per_mft_record;
0803     vol->mft_record_size_mask = vol->mft_record_size - 1;
0804     vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1;
0805     ntfs_debug("vol->mft_record_size = %i (0x%x)", vol->mft_record_size,
0806             vol->mft_record_size);
0807     ntfs_debug("vol->mft_record_size_mask = 0x%x",
0808             vol->mft_record_size_mask);
0809     ntfs_debug("vol->mft_record_size_bits = %i (0x%x)",
0810             vol->mft_record_size_bits, vol->mft_record_size_bits);
0811     /*
0812      * We cannot support mft record sizes above the PAGE_SIZE since
0813      * we store $MFT/$DATA, the table of mft records in the page cache.
0814      */
0815     if (vol->mft_record_size > PAGE_SIZE) {
0816         ntfs_error(vol->sb, "Mft record size (%i) exceeds the "
0817                 "PAGE_SIZE on your system (%lu).  "
0818                 "This is not supported.  Sorry.",
0819                 vol->mft_record_size, PAGE_SIZE);
0820         return false;
0821     }
0822     /* We cannot support mft record sizes below the sector size. */
0823     if (vol->mft_record_size < vol->sector_size) {
0824         ntfs_error(vol->sb, "Mft record size (%i) is smaller than the "
0825                 "sector size (%i).  This is not supported.  "
0826                 "Sorry.", vol->mft_record_size,
0827                 vol->sector_size);
0828         return false;
0829     }
0830     clusters_per_index_record = b->clusters_per_index_record;
0831     ntfs_debug("clusters_per_index_record = %i (0x%x)",
0832             clusters_per_index_record, clusters_per_index_record);
0833     if (clusters_per_index_record > 0)
0834         vol->index_record_size = vol->cluster_size <<
0835                 (ffs(clusters_per_index_record) - 1);
0836     else
0837         /*
0838          * When index_record_size < cluster_size,
0839          * clusters_per_index_record = -log2(index_record_size) bytes.
0840          * index_record_size normaly equals 4096 bytes, which is
0841          * encoded as 0xF4 (-12 in decimal).
0842          */
0843         vol->index_record_size = 1 << -clusters_per_index_record;
0844     vol->index_record_size_mask = vol->index_record_size - 1;
0845     vol->index_record_size_bits = ffs(vol->index_record_size) - 1;
0846     ntfs_debug("vol->index_record_size = %i (0x%x)",
0847             vol->index_record_size, vol->index_record_size);
0848     ntfs_debug("vol->index_record_size_mask = 0x%x",
0849             vol->index_record_size_mask);
0850     ntfs_debug("vol->index_record_size_bits = %i (0x%x)",
0851             vol->index_record_size_bits,
0852             vol->index_record_size_bits);
0853     /* We cannot support index record sizes below the sector size. */
0854     if (vol->index_record_size < vol->sector_size) {
0855         ntfs_error(vol->sb, "Index record size (%i) is smaller than "
0856                 "the sector size (%i).  This is not "
0857                 "supported.  Sorry.", vol->index_record_size,
0858                 vol->sector_size);
0859         return false;
0860     }
0861     /*
0862      * Get the size of the volume in clusters and check for 64-bit-ness.
0863      * Windows currently only uses 32 bits to save the clusters so we do
0864      * the same as it is much faster on 32-bit CPUs.
0865      */
0866     ll = sle64_to_cpu(b->number_of_sectors) >> sectors_per_cluster_bits;
0867     if ((u64)ll >= 1ULL << 32) {
0868         ntfs_error(vol->sb, "Cannot handle 64-bit clusters.  Sorry.");
0869         return false;
0870     }
0871     vol->nr_clusters = ll;
0872     ntfs_debug("vol->nr_clusters = 0x%llx", (long long)vol->nr_clusters);
0873     /*
0874      * On an architecture where unsigned long is 32-bits, we restrict the
0875      * volume size to 2TiB (2^41). On a 64-bit architecture, the compiler
0876      * will hopefully optimize the whole check away.
0877      */
0878     if (sizeof(unsigned long) < 8) {
0879         if ((ll << vol->cluster_size_bits) >= (1ULL << 41)) {
0880             ntfs_error(vol->sb, "Volume size (%lluTiB) is too "
0881                     "large for this architecture.  "
0882                     "Maximum supported is 2TiB.  Sorry.",
0883                     (unsigned long long)ll >> (40 -
0884                     vol->cluster_size_bits));
0885             return false;
0886         }
0887     }
0888     ll = sle64_to_cpu(b->mft_lcn);
0889     if (ll >= vol->nr_clusters) {
0890         ntfs_error(vol->sb, "MFT LCN (%lli, 0x%llx) is beyond end of "
0891                 "volume.  Weird.", (unsigned long long)ll,
0892                 (unsigned long long)ll);
0893         return false;
0894     }
0895     vol->mft_lcn = ll;
0896     ntfs_debug("vol->mft_lcn = 0x%llx", (long long)vol->mft_lcn);
0897     ll = sle64_to_cpu(b->mftmirr_lcn);
0898     if (ll >= vol->nr_clusters) {
0899         ntfs_error(vol->sb, "MFTMirr LCN (%lli, 0x%llx) is beyond end "
0900                 "of volume.  Weird.", (unsigned long long)ll,
0901                 (unsigned long long)ll);
0902         return false;
0903     }
0904     vol->mftmirr_lcn = ll;
0905     ntfs_debug("vol->mftmirr_lcn = 0x%llx", (long long)vol->mftmirr_lcn);
0906 #ifdef NTFS_RW
0907     /*
0908      * Work out the size of the mft mirror in number of mft records. If the
0909      * cluster size is less than or equal to the size taken by four mft
0910      * records, the mft mirror stores the first four mft records. If the
0911      * cluster size is bigger than the size taken by four mft records, the
0912      * mft mirror contains as many mft records as will fit into one
0913      * cluster.
0914      */
0915     if (vol->cluster_size <= (4 << vol->mft_record_size_bits))
0916         vol->mftmirr_size = 4;
0917     else
0918         vol->mftmirr_size = vol->cluster_size >>
0919                 vol->mft_record_size_bits;
0920     ntfs_debug("vol->mftmirr_size = %i", vol->mftmirr_size);
0921 #endif /* NTFS_RW */
0922     vol->serial_no = le64_to_cpu(b->volume_serial_number);
0923     ntfs_debug("vol->serial_no = 0x%llx",
0924             (unsigned long long)vol->serial_no);
0925     return true;
0926 }
0927 
0928 /**
0929  * ntfs_setup_allocators - initialize the cluster and mft allocators
0930  * @vol:    volume structure for which to setup the allocators
0931  *
0932  * Setup the cluster (lcn) and mft allocators to the starting values.
0933  */
0934 static void ntfs_setup_allocators(ntfs_volume *vol)
0935 {
0936 #ifdef NTFS_RW
0937     LCN mft_zone_size, mft_lcn;
0938 #endif /* NTFS_RW */
0939 
0940     ntfs_debug("vol->mft_zone_multiplier = 0x%x",
0941             vol->mft_zone_multiplier);
0942 #ifdef NTFS_RW
0943     /* Determine the size of the MFT zone. */
0944     mft_zone_size = vol->nr_clusters;
0945     switch (vol->mft_zone_multiplier) {  /* % of volume size in clusters */
0946     case 4:
0947         mft_zone_size >>= 1;            /* 50%   */
0948         break;
0949     case 3:
0950         mft_zone_size = (mft_zone_size +
0951                 (mft_zone_size >> 1)) >> 2; /* 37.5% */
0952         break;
0953     case 2:
0954         mft_zone_size >>= 2;            /* 25%   */
0955         break;
0956     /* case 1: */
0957     default:
0958         mft_zone_size >>= 3;            /* 12.5% */
0959         break;
0960     }
0961     /* Setup the mft zone. */
0962     vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
0963     ntfs_debug("vol->mft_zone_pos = 0x%llx",
0964             (unsigned long long)vol->mft_zone_pos);
0965     /*
0966      * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
0967      * source) and if the actual mft_lcn is in the expected place or even
0968      * further to the front of the volume, extend the mft_zone to cover the
0969      * beginning of the volume as well.  This is in order to protect the
0970      * area reserved for the mft bitmap as well within the mft_zone itself.
0971      * On non-standard volumes we do not protect it as the overhead would
0972      * be higher than the speed increase we would get by doing it.
0973      */
0974     mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size;
0975     if (mft_lcn * vol->cluster_size < 16 * 1024)
0976         mft_lcn = (16 * 1024 + vol->cluster_size - 1) /
0977                 vol->cluster_size;
0978     if (vol->mft_zone_start <= mft_lcn)
0979         vol->mft_zone_start = 0;
0980     ntfs_debug("vol->mft_zone_start = 0x%llx",
0981             (unsigned long long)vol->mft_zone_start);
0982     /*
0983      * Need to cap the mft zone on non-standard volumes so that it does
0984      * not point outside the boundaries of the volume.  We do this by
0985      * halving the zone size until we are inside the volume.
0986      */
0987     vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
0988     while (vol->mft_zone_end >= vol->nr_clusters) {
0989         mft_zone_size >>= 1;
0990         vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
0991     }
0992     ntfs_debug("vol->mft_zone_end = 0x%llx",
0993             (unsigned long long)vol->mft_zone_end);
0994     /*
0995      * Set the current position within each data zone to the start of the
0996      * respective zone.
0997      */
0998     vol->data1_zone_pos = vol->mft_zone_end;
0999     ntfs_debug("vol->data1_zone_pos = 0x%llx",
1000             (unsigned long long)vol->data1_zone_pos);
1001     vol->data2_zone_pos = 0;
1002     ntfs_debug("vol->data2_zone_pos = 0x%llx",
1003             (unsigned long long)vol->data2_zone_pos);
1004 
1005     /* Set the mft data allocation position to mft record 24. */
1006     vol->mft_data_pos = 24;
1007     ntfs_debug("vol->mft_data_pos = 0x%llx",
1008             (unsigned long long)vol->mft_data_pos);
1009 #endif /* NTFS_RW */
1010 }
1011 
1012 #ifdef NTFS_RW
1013 
1014 /**
1015  * load_and_init_mft_mirror - load and setup the mft mirror inode for a volume
1016  * @vol:    ntfs super block describing device whose mft mirror to load
1017  *
1018  * Return 'true' on success or 'false' on error.
1019  */
1020 static bool load_and_init_mft_mirror(ntfs_volume *vol)
1021 {
1022     struct inode *tmp_ino;
1023     ntfs_inode *tmp_ni;
1024 
1025     ntfs_debug("Entering.");
1026     /* Get mft mirror inode. */
1027     tmp_ino = ntfs_iget(vol->sb, FILE_MFTMirr);
1028     if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1029         if (!IS_ERR(tmp_ino))
1030             iput(tmp_ino);
1031         /* Caller will display error message. */
1032         return false;
1033     }
1034     /*
1035      * Re-initialize some specifics about $MFTMirr's inode as
1036      * ntfs_read_inode() will have set up the default ones.
1037      */
1038     /* Set uid and gid to root. */
1039     tmp_ino->i_uid = GLOBAL_ROOT_UID;
1040     tmp_ino->i_gid = GLOBAL_ROOT_GID;
1041     /* Regular file.  No access for anyone. */
1042     tmp_ino->i_mode = S_IFREG;
1043     /* No VFS initiated operations allowed for $MFTMirr. */
1044     tmp_ino->i_op = &ntfs_empty_inode_ops;
1045     tmp_ino->i_fop = &ntfs_empty_file_ops;
1046     /* Put in our special address space operations. */
1047     tmp_ino->i_mapping->a_ops = &ntfs_mst_aops;
1048     tmp_ni = NTFS_I(tmp_ino);
1049     /* The $MFTMirr, like the $MFT is multi sector transfer protected. */
1050     NInoSetMstProtected(tmp_ni);
1051     NInoSetSparseDisabled(tmp_ni);
1052     /*
1053      * Set up our little cheat allowing us to reuse the async read io
1054      * completion handler for directories.
1055      */
1056     tmp_ni->itype.index.block_size = vol->mft_record_size;
1057     tmp_ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1058     vol->mftmirr_ino = tmp_ino;
1059     ntfs_debug("Done.");
1060     return true;
1061 }
1062 
1063 /**
1064  * check_mft_mirror - compare contents of the mft mirror with the mft
1065  * @vol:    ntfs super block describing device whose mft mirror to check
1066  *
1067  * Return 'true' on success or 'false' on error.
1068  *
1069  * Note, this function also results in the mft mirror runlist being completely
1070  * mapped into memory.  The mft mirror write code requires this and will BUG()
1071  * should it find an unmapped runlist element.
1072  */
1073 static bool check_mft_mirror(ntfs_volume *vol)
1074 {
1075     struct super_block *sb = vol->sb;
1076     ntfs_inode *mirr_ni;
1077     struct page *mft_page, *mirr_page;
1078     u8 *kmft, *kmirr;
1079     runlist_element *rl, rl2[2];
1080     pgoff_t index;
1081     int mrecs_per_page, i;
1082 
1083     ntfs_debug("Entering.");
1084     /* Compare contents of $MFT and $MFTMirr. */
1085     mrecs_per_page = PAGE_SIZE / vol->mft_record_size;
1086     BUG_ON(!mrecs_per_page);
1087     BUG_ON(!vol->mftmirr_size);
1088     mft_page = mirr_page = NULL;
1089     kmft = kmirr = NULL;
1090     index = i = 0;
1091     do {
1092         u32 bytes;
1093 
1094         /* Switch pages if necessary. */
1095         if (!(i % mrecs_per_page)) {
1096             if (index) {
1097                 ntfs_unmap_page(mft_page);
1098                 ntfs_unmap_page(mirr_page);
1099             }
1100             /* Get the $MFT page. */
1101             mft_page = ntfs_map_page(vol->mft_ino->i_mapping,
1102                     index);
1103             if (IS_ERR(mft_page)) {
1104                 ntfs_error(sb, "Failed to read $MFT.");
1105                 return false;
1106             }
1107             kmft = page_address(mft_page);
1108             /* Get the $MFTMirr page. */
1109             mirr_page = ntfs_map_page(vol->mftmirr_ino->i_mapping,
1110                     index);
1111             if (IS_ERR(mirr_page)) {
1112                 ntfs_error(sb, "Failed to read $MFTMirr.");
1113                 goto mft_unmap_out;
1114             }
1115             kmirr = page_address(mirr_page);
1116             ++index;
1117         }
1118         /* Do not check the record if it is not in use. */
1119         if (((MFT_RECORD*)kmft)->flags & MFT_RECORD_IN_USE) {
1120             /* Make sure the record is ok. */
1121             if (ntfs_is_baad_recordp((le32*)kmft)) {
1122                 ntfs_error(sb, "Incomplete multi sector "
1123                         "transfer detected in mft "
1124                         "record %i.", i);
1125 mm_unmap_out:
1126                 ntfs_unmap_page(mirr_page);
1127 mft_unmap_out:
1128                 ntfs_unmap_page(mft_page);
1129                 return false;
1130             }
1131         }
1132         /* Do not check the mirror record if it is not in use. */
1133         if (((MFT_RECORD*)kmirr)->flags & MFT_RECORD_IN_USE) {
1134             if (ntfs_is_baad_recordp((le32*)kmirr)) {
1135                 ntfs_error(sb, "Incomplete multi sector "
1136                         "transfer detected in mft "
1137                         "mirror record %i.", i);
1138                 goto mm_unmap_out;
1139             }
1140         }
1141         /* Get the amount of data in the current record. */
1142         bytes = le32_to_cpu(((MFT_RECORD*)kmft)->bytes_in_use);
1143         if (bytes < sizeof(MFT_RECORD_OLD) ||
1144                 bytes > vol->mft_record_size ||
1145                 ntfs_is_baad_recordp((le32*)kmft)) {
1146             bytes = le32_to_cpu(((MFT_RECORD*)kmirr)->bytes_in_use);
1147             if (bytes < sizeof(MFT_RECORD_OLD) ||
1148                     bytes > vol->mft_record_size ||
1149                     ntfs_is_baad_recordp((le32*)kmirr))
1150                 bytes = vol->mft_record_size;
1151         }
1152         /* Compare the two records. */
1153         if (memcmp(kmft, kmirr, bytes)) {
1154             ntfs_error(sb, "$MFT and $MFTMirr (record %i) do not "
1155                     "match.  Run ntfsfix or chkdsk.", i);
1156             goto mm_unmap_out;
1157         }
1158         kmft += vol->mft_record_size;
1159         kmirr += vol->mft_record_size;
1160     } while (++i < vol->mftmirr_size);
1161     /* Release the last pages. */
1162     ntfs_unmap_page(mft_page);
1163     ntfs_unmap_page(mirr_page);
1164 
1165     /* Construct the mft mirror runlist by hand. */
1166     rl2[0].vcn = 0;
1167     rl2[0].lcn = vol->mftmirr_lcn;
1168     rl2[0].length = (vol->mftmirr_size * vol->mft_record_size +
1169             vol->cluster_size - 1) / vol->cluster_size;
1170     rl2[1].vcn = rl2[0].length;
1171     rl2[1].lcn = LCN_ENOENT;
1172     rl2[1].length = 0;
1173     /*
1174      * Because we have just read all of the mft mirror, we know we have
1175      * mapped the full runlist for it.
1176      */
1177     mirr_ni = NTFS_I(vol->mftmirr_ino);
1178     down_read(&mirr_ni->runlist.lock);
1179     rl = mirr_ni->runlist.rl;
1180     /* Compare the two runlists.  They must be identical. */
1181     i = 0;
1182     do {
1183         if (rl2[i].vcn != rl[i].vcn || rl2[i].lcn != rl[i].lcn ||
1184                 rl2[i].length != rl[i].length) {
1185             ntfs_error(sb, "$MFTMirr location mismatch.  "
1186                     "Run chkdsk.");
1187             up_read(&mirr_ni->runlist.lock);
1188             return false;
1189         }
1190     } while (rl2[i++].length);
1191     up_read(&mirr_ni->runlist.lock);
1192     ntfs_debug("Done.");
1193     return true;
1194 }
1195 
1196 /**
1197  * load_and_check_logfile - load and check the logfile inode for a volume
1198  * @vol:    ntfs super block describing device whose logfile to load
1199  *
1200  * Return 'true' on success or 'false' on error.
1201  */
1202 static bool load_and_check_logfile(ntfs_volume *vol,
1203         RESTART_PAGE_HEADER **rp)
1204 {
1205     struct inode *tmp_ino;
1206 
1207     ntfs_debug("Entering.");
1208     tmp_ino = ntfs_iget(vol->sb, FILE_LogFile);
1209     if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1210         if (!IS_ERR(tmp_ino))
1211             iput(tmp_ino);
1212         /* Caller will display error message. */
1213         return false;
1214     }
1215     if (!ntfs_check_logfile(tmp_ino, rp)) {
1216         iput(tmp_ino);
1217         /* ntfs_check_logfile() will have displayed error output. */
1218         return false;
1219     }
1220     NInoSetSparseDisabled(NTFS_I(tmp_ino));
1221     vol->logfile_ino = tmp_ino;
1222     ntfs_debug("Done.");
1223     return true;
1224 }
1225 
1226 #define NTFS_HIBERFIL_HEADER_SIZE   4096
1227 
1228 /**
1229  * check_windows_hibernation_status - check if Windows is suspended on a volume
1230  * @vol:    ntfs super block of device to check
1231  *
1232  * Check if Windows is hibernated on the ntfs volume @vol.  This is done by
1233  * looking for the file hiberfil.sys in the root directory of the volume.  If
1234  * the file is not present Windows is definitely not suspended.
1235  *
1236  * If hiberfil.sys exists and is less than 4kiB in size it means Windows is
1237  * definitely suspended (this volume is not the system volume).  Caveat:  on a
1238  * system with many volumes it is possible that the < 4kiB check is bogus but
1239  * for now this should do fine.
1240  *
1241  * If hiberfil.sys exists and is larger than 4kiB in size, we need to read the
1242  * hiberfil header (which is the first 4kiB).  If this begins with "hibr",
1243  * Windows is definitely suspended.  If it is completely full of zeroes,
1244  * Windows is definitely not hibernated.  Any other case is treated as if
1245  * Windows is suspended.  This caters for the above mentioned caveat of a
1246  * system with many volumes where no "hibr" magic would be present and there is
1247  * no zero header.
1248  *
1249  * Return 0 if Windows is not hibernated on the volume, >0 if Windows is
1250  * hibernated on the volume, and -errno on error.
1251  */
1252 static int check_windows_hibernation_status(ntfs_volume *vol)
1253 {
1254     MFT_REF mref;
1255     struct inode *vi;
1256     struct page *page;
1257     u32 *kaddr, *kend;
1258     ntfs_name *name = NULL;
1259     int ret = 1;
1260     static const ntfschar hiberfil[13] = { cpu_to_le16('h'),
1261             cpu_to_le16('i'), cpu_to_le16('b'),
1262             cpu_to_le16('e'), cpu_to_le16('r'),
1263             cpu_to_le16('f'), cpu_to_le16('i'),
1264             cpu_to_le16('l'), cpu_to_le16('.'),
1265             cpu_to_le16('s'), cpu_to_le16('y'),
1266             cpu_to_le16('s'), 0 };
1267 
1268     ntfs_debug("Entering.");
1269     /*
1270      * Find the inode number for the hibernation file by looking up the
1271      * filename hiberfil.sys in the root directory.
1272      */
1273     inode_lock(vol->root_ino);
1274     mref = ntfs_lookup_inode_by_name(NTFS_I(vol->root_ino), hiberfil, 12,
1275             &name);
1276     inode_unlock(vol->root_ino);
1277     if (IS_ERR_MREF(mref)) {
1278         ret = MREF_ERR(mref);
1279         /* If the file does not exist, Windows is not hibernated. */
1280         if (ret == -ENOENT) {
1281             ntfs_debug("hiberfil.sys not present.  Windows is not "
1282                     "hibernated on the volume.");
1283             return 0;
1284         }
1285         /* A real error occurred. */
1286         ntfs_error(vol->sb, "Failed to find inode number for "
1287                 "hiberfil.sys.");
1288         return ret;
1289     }
1290     /* We do not care for the type of match that was found. */
1291     kfree(name);
1292     /* Get the inode. */
1293     vi = ntfs_iget(vol->sb, MREF(mref));
1294     if (IS_ERR(vi) || is_bad_inode(vi)) {
1295         if (!IS_ERR(vi))
1296             iput(vi);
1297         ntfs_error(vol->sb, "Failed to load hiberfil.sys.");
1298         return IS_ERR(vi) ? PTR_ERR(vi) : -EIO;
1299     }
1300     if (unlikely(i_size_read(vi) < NTFS_HIBERFIL_HEADER_SIZE)) {
1301         ntfs_debug("hiberfil.sys is smaller than 4kiB (0x%llx).  "
1302                 "Windows is hibernated on the volume.  This "
1303                 "is not the system volume.", i_size_read(vi));
1304         goto iput_out;
1305     }
1306     page = ntfs_map_page(vi->i_mapping, 0);
1307     if (IS_ERR(page)) {
1308         ntfs_error(vol->sb, "Failed to read from hiberfil.sys.");
1309         ret = PTR_ERR(page);
1310         goto iput_out;
1311     }
1312     kaddr = (u32*)page_address(page);
1313     if (*(le32*)kaddr == cpu_to_le32(0x72626968)/*'hibr'*/) {
1314         ntfs_debug("Magic \"hibr\" found in hiberfil.sys.  Windows is "
1315                 "hibernated on the volume.  This is the "
1316                 "system volume.");
1317         goto unm_iput_out;
1318     }
1319     kend = kaddr + NTFS_HIBERFIL_HEADER_SIZE/sizeof(*kaddr);
1320     do {
1321         if (unlikely(*kaddr)) {
1322             ntfs_debug("hiberfil.sys is larger than 4kiB "
1323                     "(0x%llx), does not contain the "
1324                     "\"hibr\" magic, and does not have a "
1325                     "zero header.  Windows is hibernated "
1326                     "on the volume.  This is not the "
1327                     "system volume.", i_size_read(vi));
1328             goto unm_iput_out;
1329         }
1330     } while (++kaddr < kend);
1331     ntfs_debug("hiberfil.sys contains a zero header.  Windows is not "
1332             "hibernated on the volume.  This is the system "
1333             "volume.");
1334     ret = 0;
1335 unm_iput_out:
1336     ntfs_unmap_page(page);
1337 iput_out:
1338     iput(vi);
1339     return ret;
1340 }
1341 
1342 /**
1343  * load_and_init_quota - load and setup the quota file for a volume if present
1344  * @vol:    ntfs super block describing device whose quota file to load
1345  *
1346  * Return 'true' on success or 'false' on error.  If $Quota is not present, we
1347  * leave vol->quota_ino as NULL and return success.
1348  */
1349 static bool load_and_init_quota(ntfs_volume *vol)
1350 {
1351     MFT_REF mref;
1352     struct inode *tmp_ino;
1353     ntfs_name *name = NULL;
1354     static const ntfschar Quota[7] = { cpu_to_le16('$'),
1355             cpu_to_le16('Q'), cpu_to_le16('u'),
1356             cpu_to_le16('o'), cpu_to_le16('t'),
1357             cpu_to_le16('a'), 0 };
1358     static ntfschar Q[3] = { cpu_to_le16('$'),
1359             cpu_to_le16('Q'), 0 };
1360 
1361     ntfs_debug("Entering.");
1362     /*
1363      * Find the inode number for the quota file by looking up the filename
1364      * $Quota in the extended system files directory $Extend.
1365      */
1366     inode_lock(vol->extend_ino);
1367     mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), Quota, 6,
1368             &name);
1369     inode_unlock(vol->extend_ino);
1370     if (IS_ERR_MREF(mref)) {
1371         /*
1372          * If the file does not exist, quotas are disabled and have
1373          * never been enabled on this volume, just return success.
1374          */
1375         if (MREF_ERR(mref) == -ENOENT) {
1376             ntfs_debug("$Quota not present.  Volume does not have "
1377                     "quotas enabled.");
1378             /*
1379              * No need to try to set quotas out of date if they are
1380              * not enabled.
1381              */
1382             NVolSetQuotaOutOfDate(vol);
1383             return true;
1384         }
1385         /* A real error occurred. */
1386         ntfs_error(vol->sb, "Failed to find inode number for $Quota.");
1387         return false;
1388     }
1389     /* We do not care for the type of match that was found. */
1390     kfree(name);
1391     /* Get the inode. */
1392     tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1393     if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1394         if (!IS_ERR(tmp_ino))
1395             iput(tmp_ino);
1396         ntfs_error(vol->sb, "Failed to load $Quota.");
1397         return false;
1398     }
1399     vol->quota_ino = tmp_ino;
1400     /* Get the $Q index allocation attribute. */
1401     tmp_ino = ntfs_index_iget(vol->quota_ino, Q, 2);
1402     if (IS_ERR(tmp_ino)) {
1403         ntfs_error(vol->sb, "Failed to load $Quota/$Q index.");
1404         return false;
1405     }
1406     vol->quota_q_ino = tmp_ino;
1407     ntfs_debug("Done.");
1408     return true;
1409 }
1410 
1411 /**
1412  * load_and_init_usnjrnl - load and setup the transaction log if present
1413  * @vol:    ntfs super block describing device whose usnjrnl file to load
1414  *
1415  * Return 'true' on success or 'false' on error.
1416  *
1417  * If $UsnJrnl is not present or in the process of being disabled, we set
1418  * NVolUsnJrnlStamped() and return success.
1419  *
1420  * If the $UsnJrnl $DATA/$J attribute has a size equal to the lowest valid usn,
1421  * i.e. transaction logging has only just been enabled or the journal has been
1422  * stamped and nothing has been logged since, we also set NVolUsnJrnlStamped()
1423  * and return success.
1424  */
1425 static bool load_and_init_usnjrnl(ntfs_volume *vol)
1426 {
1427     MFT_REF mref;
1428     struct inode *tmp_ino;
1429     ntfs_inode *tmp_ni;
1430     struct page *page;
1431     ntfs_name *name = NULL;
1432     USN_HEADER *uh;
1433     static const ntfschar UsnJrnl[9] = { cpu_to_le16('$'),
1434             cpu_to_le16('U'), cpu_to_le16('s'),
1435             cpu_to_le16('n'), cpu_to_le16('J'),
1436             cpu_to_le16('r'), cpu_to_le16('n'),
1437             cpu_to_le16('l'), 0 };
1438     static ntfschar Max[5] = { cpu_to_le16('$'),
1439             cpu_to_le16('M'), cpu_to_le16('a'),
1440             cpu_to_le16('x'), 0 };
1441     static ntfschar J[3] = { cpu_to_le16('$'),
1442             cpu_to_le16('J'), 0 };
1443 
1444     ntfs_debug("Entering.");
1445     /*
1446      * Find the inode number for the transaction log file by looking up the
1447      * filename $UsnJrnl in the extended system files directory $Extend.
1448      */
1449     inode_lock(vol->extend_ino);
1450     mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), UsnJrnl, 8,
1451             &name);
1452     inode_unlock(vol->extend_ino);
1453     if (IS_ERR_MREF(mref)) {
1454         /*
1455          * If the file does not exist, transaction logging is disabled,
1456          * just return success.
1457          */
1458         if (MREF_ERR(mref) == -ENOENT) {
1459             ntfs_debug("$UsnJrnl not present.  Volume does not "
1460                     "have transaction logging enabled.");
1461 not_enabled:
1462             /*
1463              * No need to try to stamp the transaction log if
1464              * transaction logging is not enabled.
1465              */
1466             NVolSetUsnJrnlStamped(vol);
1467             return true;
1468         }
1469         /* A real error occurred. */
1470         ntfs_error(vol->sb, "Failed to find inode number for "
1471                 "$UsnJrnl.");
1472         return false;
1473     }
1474     /* We do not care for the type of match that was found. */
1475     kfree(name);
1476     /* Get the inode. */
1477     tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1478     if (IS_ERR(tmp_ino) || unlikely(is_bad_inode(tmp_ino))) {
1479         if (!IS_ERR(tmp_ino))
1480             iput(tmp_ino);
1481         ntfs_error(vol->sb, "Failed to load $UsnJrnl.");
1482         return false;
1483     }
1484     vol->usnjrnl_ino = tmp_ino;
1485     /*
1486      * If the transaction log is in the process of being deleted, we can
1487      * ignore it.
1488      */
1489     if (unlikely(vol->vol_flags & VOLUME_DELETE_USN_UNDERWAY)) {
1490         ntfs_debug("$UsnJrnl in the process of being disabled.  "
1491                 "Volume does not have transaction logging "
1492                 "enabled.");
1493         goto not_enabled;
1494     }
1495     /* Get the $DATA/$Max attribute. */
1496     tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, Max, 4);
1497     if (IS_ERR(tmp_ino)) {
1498         ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$Max "
1499                 "attribute.");
1500         return false;
1501     }
1502     vol->usnjrnl_max_ino = tmp_ino;
1503     if (unlikely(i_size_read(tmp_ino) < sizeof(USN_HEADER))) {
1504         ntfs_error(vol->sb, "Found corrupt $UsnJrnl/$DATA/$Max "
1505                 "attribute (size is 0x%llx but should be at "
1506                 "least 0x%zx bytes).", i_size_read(tmp_ino),
1507                 sizeof(USN_HEADER));
1508         return false;
1509     }
1510     /* Get the $DATA/$J attribute. */
1511     tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, J, 2);
1512     if (IS_ERR(tmp_ino)) {
1513         ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$J "
1514                 "attribute.");
1515         return false;
1516     }
1517     vol->usnjrnl_j_ino = tmp_ino;
1518     /* Verify $J is non-resident and sparse. */
1519     tmp_ni = NTFS_I(vol->usnjrnl_j_ino);
1520     if (unlikely(!NInoNonResident(tmp_ni) || !NInoSparse(tmp_ni))) {
1521         ntfs_error(vol->sb, "$UsnJrnl/$DATA/$J attribute is resident "
1522                 "and/or not sparse.");
1523         return false;
1524     }
1525     /* Read the USN_HEADER from $DATA/$Max. */
1526     page = ntfs_map_page(vol->usnjrnl_max_ino->i_mapping, 0);
1527     if (IS_ERR(page)) {
1528         ntfs_error(vol->sb, "Failed to read from $UsnJrnl/$DATA/$Max "
1529                 "attribute.");
1530         return false;
1531     }
1532     uh = (USN_HEADER*)page_address(page);
1533     /* Sanity check the $Max. */
1534     if (unlikely(sle64_to_cpu(uh->allocation_delta) >
1535             sle64_to_cpu(uh->maximum_size))) {
1536         ntfs_error(vol->sb, "Allocation delta (0x%llx) exceeds "
1537                 "maximum size (0x%llx).  $UsnJrnl is corrupt.",
1538                 (long long)sle64_to_cpu(uh->allocation_delta),
1539                 (long long)sle64_to_cpu(uh->maximum_size));
1540         ntfs_unmap_page(page);
1541         return false;
1542     }
1543     /*
1544      * If the transaction log has been stamped and nothing has been written
1545      * to it since, we do not need to stamp it.
1546      */
1547     if (unlikely(sle64_to_cpu(uh->lowest_valid_usn) >=
1548             i_size_read(vol->usnjrnl_j_ino))) {
1549         if (likely(sle64_to_cpu(uh->lowest_valid_usn) ==
1550                 i_size_read(vol->usnjrnl_j_ino))) {
1551             ntfs_unmap_page(page);
1552             ntfs_debug("$UsnJrnl is enabled but nothing has been "
1553                     "logged since it was last stamped.  "
1554                     "Treating this as if the volume does "
1555                     "not have transaction logging "
1556                     "enabled.");
1557             goto not_enabled;
1558         }
1559         ntfs_error(vol->sb, "$UsnJrnl has lowest valid usn (0x%llx) "
1560                 "which is out of bounds (0x%llx).  $UsnJrnl "
1561                 "is corrupt.",
1562                 (long long)sle64_to_cpu(uh->lowest_valid_usn),
1563                 i_size_read(vol->usnjrnl_j_ino));
1564         ntfs_unmap_page(page);
1565         return false;
1566     }
1567     ntfs_unmap_page(page);
1568     ntfs_debug("Done.");
1569     return true;
1570 }
1571 
1572 /**
1573  * load_and_init_attrdef - load the attribute definitions table for a volume
1574  * @vol:    ntfs super block describing device whose attrdef to load
1575  *
1576  * Return 'true' on success or 'false' on error.
1577  */
1578 static bool load_and_init_attrdef(ntfs_volume *vol)
1579 {
1580     loff_t i_size;
1581     struct super_block *sb = vol->sb;
1582     struct inode *ino;
1583     struct page *page;
1584     pgoff_t index, max_index;
1585     unsigned int size;
1586 
1587     ntfs_debug("Entering.");
1588     /* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */
1589     ino = ntfs_iget(sb, FILE_AttrDef);
1590     if (IS_ERR(ino) || is_bad_inode(ino)) {
1591         if (!IS_ERR(ino))
1592             iput(ino);
1593         goto failed;
1594     }
1595     NInoSetSparseDisabled(NTFS_I(ino));
1596     /* The size of FILE_AttrDef must be above 0 and fit inside 31 bits. */
1597     i_size = i_size_read(ino);
1598     if (i_size <= 0 || i_size > 0x7fffffff)
1599         goto iput_failed;
1600     vol->attrdef = (ATTR_DEF*)ntfs_malloc_nofs(i_size);
1601     if (!vol->attrdef)
1602         goto iput_failed;
1603     index = 0;
1604     max_index = i_size >> PAGE_SHIFT;
1605     size = PAGE_SIZE;
1606     while (index < max_index) {
1607         /* Read the attrdef table and copy it into the linear buffer. */
1608 read_partial_attrdef_page:
1609         page = ntfs_map_page(ino->i_mapping, index);
1610         if (IS_ERR(page))
1611             goto free_iput_failed;
1612         memcpy((u8*)vol->attrdef + (index++ << PAGE_SHIFT),
1613                 page_address(page), size);
1614         ntfs_unmap_page(page);
1615     };
1616     if (size == PAGE_SIZE) {
1617         size = i_size & ~PAGE_MASK;
1618         if (size)
1619             goto read_partial_attrdef_page;
1620     }
1621     vol->attrdef_size = i_size;
1622     ntfs_debug("Read %llu bytes from $AttrDef.", i_size);
1623     iput(ino);
1624     return true;
1625 free_iput_failed:
1626     ntfs_free(vol->attrdef);
1627     vol->attrdef = NULL;
1628 iput_failed:
1629     iput(ino);
1630 failed:
1631     ntfs_error(sb, "Failed to initialize attribute definition table.");
1632     return false;
1633 }
1634 
1635 #endif /* NTFS_RW */
1636 
1637 /**
1638  * load_and_init_upcase - load the upcase table for an ntfs volume
1639  * @vol:    ntfs super block describing device whose upcase to load
1640  *
1641  * Return 'true' on success or 'false' on error.
1642  */
1643 static bool load_and_init_upcase(ntfs_volume *vol)
1644 {
1645     loff_t i_size;
1646     struct super_block *sb = vol->sb;
1647     struct inode *ino;
1648     struct page *page;
1649     pgoff_t index, max_index;
1650     unsigned int size;
1651     int i, max;
1652 
1653     ntfs_debug("Entering.");
1654     /* Read upcase table and setup vol->upcase and vol->upcase_len. */
1655     ino = ntfs_iget(sb, FILE_UpCase);
1656     if (IS_ERR(ino) || is_bad_inode(ino)) {
1657         if (!IS_ERR(ino))
1658             iput(ino);
1659         goto upcase_failed;
1660     }
1661     /*
1662      * The upcase size must not be above 64k Unicode characters, must not
1663      * be zero and must be a multiple of sizeof(ntfschar).
1664      */
1665     i_size = i_size_read(ino);
1666     if (!i_size || i_size & (sizeof(ntfschar) - 1) ||
1667             i_size > 64ULL * 1024 * sizeof(ntfschar))
1668         goto iput_upcase_failed;
1669     vol->upcase = (ntfschar*)ntfs_malloc_nofs(i_size);
1670     if (!vol->upcase)
1671         goto iput_upcase_failed;
1672     index = 0;
1673     max_index = i_size >> PAGE_SHIFT;
1674     size = PAGE_SIZE;
1675     while (index < max_index) {
1676         /* Read the upcase table and copy it into the linear buffer. */
1677 read_partial_upcase_page:
1678         page = ntfs_map_page(ino->i_mapping, index);
1679         if (IS_ERR(page))
1680             goto iput_upcase_failed;
1681         memcpy((char*)vol->upcase + (index++ << PAGE_SHIFT),
1682                 page_address(page), size);
1683         ntfs_unmap_page(page);
1684     };
1685     if (size == PAGE_SIZE) {
1686         size = i_size & ~PAGE_MASK;
1687         if (size)
1688             goto read_partial_upcase_page;
1689     }
1690     vol->upcase_len = i_size >> UCHAR_T_SIZE_BITS;
1691     ntfs_debug("Read %llu bytes from $UpCase (expected %zu bytes).",
1692             i_size, 64 * 1024 * sizeof(ntfschar));
1693     iput(ino);
1694     mutex_lock(&ntfs_lock);
1695     if (!default_upcase) {
1696         ntfs_debug("Using volume specified $UpCase since default is "
1697                 "not present.");
1698         mutex_unlock(&ntfs_lock);
1699         return true;
1700     }
1701     max = default_upcase_len;
1702     if (max > vol->upcase_len)
1703         max = vol->upcase_len;
1704     for (i = 0; i < max; i++)
1705         if (vol->upcase[i] != default_upcase[i])
1706             break;
1707     if (i == max) {
1708         ntfs_free(vol->upcase);
1709         vol->upcase = default_upcase;
1710         vol->upcase_len = max;
1711         ntfs_nr_upcase_users++;
1712         mutex_unlock(&ntfs_lock);
1713         ntfs_debug("Volume specified $UpCase matches default. Using "
1714                 "default.");
1715         return true;
1716     }
1717     mutex_unlock(&ntfs_lock);
1718     ntfs_debug("Using volume specified $UpCase since it does not match "
1719             "the default.");
1720     return true;
1721 iput_upcase_failed:
1722     iput(ino);
1723     ntfs_free(vol->upcase);
1724     vol->upcase = NULL;
1725 upcase_failed:
1726     mutex_lock(&ntfs_lock);
1727     if (default_upcase) {
1728         vol->upcase = default_upcase;
1729         vol->upcase_len = default_upcase_len;
1730         ntfs_nr_upcase_users++;
1731         mutex_unlock(&ntfs_lock);
1732         ntfs_error(sb, "Failed to load $UpCase from the volume. Using "
1733                 "default.");
1734         return true;
1735     }
1736     mutex_unlock(&ntfs_lock);
1737     ntfs_error(sb, "Failed to initialize upcase table.");
1738     return false;
1739 }
1740 
1741 /*
1742  * The lcn and mft bitmap inodes are NTFS-internal inodes with
1743  * their own special locking rules:
1744  */
1745 static struct lock_class_key
1746     lcnbmp_runlist_lock_key, lcnbmp_mrec_lock_key,
1747     mftbmp_runlist_lock_key, mftbmp_mrec_lock_key;
1748 
1749 /**
1750  * load_system_files - open the system files using normal functions
1751  * @vol:    ntfs super block describing device whose system files to load
1752  *
1753  * Open the system files with normal access functions and complete setting up
1754  * the ntfs super block @vol.
1755  *
1756  * Return 'true' on success or 'false' on error.
1757  */
1758 static bool load_system_files(ntfs_volume *vol)
1759 {
1760     struct super_block *sb = vol->sb;
1761     MFT_RECORD *m;
1762     VOLUME_INFORMATION *vi;
1763     ntfs_attr_search_ctx *ctx;
1764 #ifdef NTFS_RW
1765     RESTART_PAGE_HEADER *rp;
1766     int err;
1767 #endif /* NTFS_RW */
1768 
1769     ntfs_debug("Entering.");
1770 #ifdef NTFS_RW
1771     /* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */
1772     if (!load_and_init_mft_mirror(vol) || !check_mft_mirror(vol)) {
1773         static const char *es1 = "Failed to load $MFTMirr";
1774         static const char *es2 = "$MFTMirr does not match $MFT";
1775         static const char *es3 = ".  Run ntfsfix and/or chkdsk.";
1776 
1777         /* If a read-write mount, convert it to a read-only mount. */
1778         if (!sb_rdonly(sb)) {
1779             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1780                     ON_ERRORS_CONTINUE))) {
1781                 ntfs_error(sb, "%s and neither on_errors="
1782                         "continue nor on_errors="
1783                         "remount-ro was specified%s",
1784                         !vol->mftmirr_ino ? es1 : es2,
1785                         es3);
1786                 goto iput_mirr_err_out;
1787             }
1788             sb->s_flags |= SB_RDONLY;
1789             ntfs_error(sb, "%s.  Mounting read-only%s",
1790                     !vol->mftmirr_ino ? es1 : es2, es3);
1791         } else
1792             ntfs_warning(sb, "%s.  Will not be able to remount "
1793                     "read-write%s",
1794                     !vol->mftmirr_ino ? es1 : es2, es3);
1795         /* This will prevent a read-write remount. */
1796         NVolSetErrors(vol);
1797     }
1798 #endif /* NTFS_RW */
1799     /* Get mft bitmap attribute inode. */
1800     vol->mftbmp_ino = ntfs_attr_iget(vol->mft_ino, AT_BITMAP, NULL, 0);
1801     if (IS_ERR(vol->mftbmp_ino)) {
1802         ntfs_error(sb, "Failed to load $MFT/$BITMAP attribute.");
1803         goto iput_mirr_err_out;
1804     }
1805     lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->runlist.lock,
1806                &mftbmp_runlist_lock_key);
1807     lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->mrec_lock,
1808                &mftbmp_mrec_lock_key);
1809     /* Read upcase table and setup @vol->upcase and @vol->upcase_len. */
1810     if (!load_and_init_upcase(vol))
1811         goto iput_mftbmp_err_out;
1812 #ifdef NTFS_RW
1813     /*
1814      * Read attribute definitions table and setup @vol->attrdef and
1815      * @vol->attrdef_size.
1816      */
1817     if (!load_and_init_attrdef(vol))
1818         goto iput_upcase_err_out;
1819 #endif /* NTFS_RW */
1820     /*
1821      * Get the cluster allocation bitmap inode and verify the size, no
1822      * need for any locking at this stage as we are already running
1823      * exclusively as we are mount in progress task.
1824      */
1825     vol->lcnbmp_ino = ntfs_iget(sb, FILE_Bitmap);
1826     if (IS_ERR(vol->lcnbmp_ino) || is_bad_inode(vol->lcnbmp_ino)) {
1827         if (!IS_ERR(vol->lcnbmp_ino))
1828             iput(vol->lcnbmp_ino);
1829         goto bitmap_failed;
1830     }
1831     lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->runlist.lock,
1832                &lcnbmp_runlist_lock_key);
1833     lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->mrec_lock,
1834                &lcnbmp_mrec_lock_key);
1835 
1836     NInoSetSparseDisabled(NTFS_I(vol->lcnbmp_ino));
1837     if ((vol->nr_clusters + 7) >> 3 > i_size_read(vol->lcnbmp_ino)) {
1838         iput(vol->lcnbmp_ino);
1839 bitmap_failed:
1840         ntfs_error(sb, "Failed to load $Bitmap.");
1841         goto iput_attrdef_err_out;
1842     }
1843     /*
1844      * Get the volume inode and setup our cache of the volume flags and
1845      * version.
1846      */
1847     vol->vol_ino = ntfs_iget(sb, FILE_Volume);
1848     if (IS_ERR(vol->vol_ino) || is_bad_inode(vol->vol_ino)) {
1849         if (!IS_ERR(vol->vol_ino))
1850             iput(vol->vol_ino);
1851 volume_failed:
1852         ntfs_error(sb, "Failed to load $Volume.");
1853         goto iput_lcnbmp_err_out;
1854     }
1855     m = map_mft_record(NTFS_I(vol->vol_ino));
1856     if (IS_ERR(m)) {
1857 iput_volume_failed:
1858         iput(vol->vol_ino);
1859         goto volume_failed;
1860     }
1861     if (!(ctx = ntfs_attr_get_search_ctx(NTFS_I(vol->vol_ino), m))) {
1862         ntfs_error(sb, "Failed to get attribute search context.");
1863         goto get_ctx_vol_failed;
1864     }
1865     if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
1866             ctx) || ctx->attr->non_resident || ctx->attr->flags) {
1867 err_put_vol:
1868         ntfs_attr_put_search_ctx(ctx);
1869 get_ctx_vol_failed:
1870         unmap_mft_record(NTFS_I(vol->vol_ino));
1871         goto iput_volume_failed;
1872     }
1873     vi = (VOLUME_INFORMATION*)((char*)ctx->attr +
1874             le16_to_cpu(ctx->attr->data.resident.value_offset));
1875     /* Some bounds checks. */
1876     if ((u8*)vi < (u8*)ctx->attr || (u8*)vi +
1877             le32_to_cpu(ctx->attr->data.resident.value_length) >
1878             (u8*)ctx->attr + le32_to_cpu(ctx->attr->length))
1879         goto err_put_vol;
1880     /* Copy the volume flags and version to the ntfs_volume structure. */
1881     vol->vol_flags = vi->flags;
1882     vol->major_ver = vi->major_ver;
1883     vol->minor_ver = vi->minor_ver;
1884     ntfs_attr_put_search_ctx(ctx);
1885     unmap_mft_record(NTFS_I(vol->vol_ino));
1886     pr_info("volume version %i.%i.\n", vol->major_ver,
1887             vol->minor_ver);
1888     if (vol->major_ver < 3 && NVolSparseEnabled(vol)) {
1889         ntfs_warning(vol->sb, "Disabling sparse support due to NTFS "
1890                 "volume version %i.%i (need at least version "
1891                 "3.0).", vol->major_ver, vol->minor_ver);
1892         NVolClearSparseEnabled(vol);
1893     }
1894 #ifdef NTFS_RW
1895     /* Make sure that no unsupported volume flags are set. */
1896     if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
1897         static const char *es1a = "Volume is dirty";
1898         static const char *es1b = "Volume has been modified by chkdsk";
1899         static const char *es1c = "Volume has unsupported flags set";
1900         static const char *es2a = ".  Run chkdsk and mount in Windows.";
1901         static const char *es2b = ".  Mount in Windows.";
1902         const char *es1, *es2;
1903 
1904         es2 = es2a;
1905         if (vol->vol_flags & VOLUME_IS_DIRTY)
1906             es1 = es1a;
1907         else if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
1908             es1 = es1b;
1909             es2 = es2b;
1910         } else {
1911             es1 = es1c;
1912             ntfs_warning(sb, "Unsupported volume flags 0x%x "
1913                     "encountered.",
1914                     (unsigned)le16_to_cpu(vol->vol_flags));
1915         }
1916         /* If a read-write mount, convert it to a read-only mount. */
1917         if (!sb_rdonly(sb)) {
1918             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1919                     ON_ERRORS_CONTINUE))) {
1920                 ntfs_error(sb, "%s and neither on_errors="
1921                         "continue nor on_errors="
1922                         "remount-ro was specified%s",
1923                         es1, es2);
1924                 goto iput_vol_err_out;
1925             }
1926             sb->s_flags |= SB_RDONLY;
1927             ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1928         } else
1929             ntfs_warning(sb, "%s.  Will not be able to remount "
1930                     "read-write%s", es1, es2);
1931         /*
1932          * Do not set NVolErrors() because ntfs_remount() re-checks the
1933          * flags which we need to do in case any flags have changed.
1934          */
1935     }
1936     /*
1937      * Get the inode for the logfile, check it and determine if the volume
1938      * was shutdown cleanly.
1939      */
1940     rp = NULL;
1941     if (!load_and_check_logfile(vol, &rp) ||
1942             !ntfs_is_logfile_clean(vol->logfile_ino, rp)) {
1943         static const char *es1a = "Failed to load $LogFile";
1944         static const char *es1b = "$LogFile is not clean";
1945         static const char *es2 = ".  Mount in Windows.";
1946         const char *es1;
1947 
1948         es1 = !vol->logfile_ino ? es1a : es1b;
1949         /* If a read-write mount, convert it to a read-only mount. */
1950         if (!sb_rdonly(sb)) {
1951             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1952                     ON_ERRORS_CONTINUE))) {
1953                 ntfs_error(sb, "%s and neither on_errors="
1954                         "continue nor on_errors="
1955                         "remount-ro was specified%s",
1956                         es1, es2);
1957                 if (vol->logfile_ino) {
1958                     BUG_ON(!rp);
1959                     ntfs_free(rp);
1960                 }
1961                 goto iput_logfile_err_out;
1962             }
1963             sb->s_flags |= SB_RDONLY;
1964             ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1965         } else
1966             ntfs_warning(sb, "%s.  Will not be able to remount "
1967                     "read-write%s", es1, es2);
1968         /* This will prevent a read-write remount. */
1969         NVolSetErrors(vol);
1970     }
1971     ntfs_free(rp);
1972 #endif /* NTFS_RW */
1973     /* Get the root directory inode so we can do path lookups. */
1974     vol->root_ino = ntfs_iget(sb, FILE_root);
1975     if (IS_ERR(vol->root_ino) || is_bad_inode(vol->root_ino)) {
1976         if (!IS_ERR(vol->root_ino))
1977             iput(vol->root_ino);
1978         ntfs_error(sb, "Failed to load root directory.");
1979         goto iput_logfile_err_out;
1980     }
1981 #ifdef NTFS_RW
1982     /*
1983      * Check if Windows is suspended to disk on the target volume.  If it
1984      * is hibernated, we must not write *anything* to the disk so set
1985      * NVolErrors() without setting the dirty volume flag and mount
1986      * read-only.  This will prevent read-write remounting and it will also
1987      * prevent all writes.
1988      */
1989     err = check_windows_hibernation_status(vol);
1990     if (unlikely(err)) {
1991         static const char *es1a = "Failed to determine if Windows is "
1992                 "hibernated";
1993         static const char *es1b = "Windows is hibernated";
1994         static const char *es2 = ".  Run chkdsk.";
1995         const char *es1;
1996 
1997         es1 = err < 0 ? es1a : es1b;
1998         /* If a read-write mount, convert it to a read-only mount. */
1999         if (!sb_rdonly(sb)) {
2000             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2001                     ON_ERRORS_CONTINUE))) {
2002                 ntfs_error(sb, "%s and neither on_errors="
2003                         "continue nor on_errors="
2004                         "remount-ro was specified%s",
2005                         es1, es2);
2006                 goto iput_root_err_out;
2007             }
2008             sb->s_flags |= SB_RDONLY;
2009             ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2010         } else
2011             ntfs_warning(sb, "%s.  Will not be able to remount "
2012                     "read-write%s", es1, es2);
2013         /* This will prevent a read-write remount. */
2014         NVolSetErrors(vol);
2015     }
2016     /* If (still) a read-write mount, mark the volume dirty. */
2017     if (!sb_rdonly(sb) && ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
2018         static const char *es1 = "Failed to set dirty bit in volume "
2019                 "information flags";
2020         static const char *es2 = ".  Run chkdsk.";
2021 
2022         /* Convert to a read-only mount. */
2023         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2024                 ON_ERRORS_CONTINUE))) {
2025             ntfs_error(sb, "%s and neither on_errors=continue nor "
2026                     "on_errors=remount-ro was specified%s",
2027                     es1, es2);
2028             goto iput_root_err_out;
2029         }
2030         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2031         sb->s_flags |= SB_RDONLY;
2032         /*
2033          * Do not set NVolErrors() because ntfs_remount() might manage
2034          * to set the dirty flag in which case all would be well.
2035          */
2036     }
2037 #if 0
2038     // TODO: Enable this code once we start modifying anything that is
2039     //   different between NTFS 1.2 and 3.x...
2040     /*
2041      * If (still) a read-write mount, set the NT4 compatibility flag on
2042      * newer NTFS version volumes.
2043      */
2044     if (!(sb->s_flags & SB_RDONLY) && (vol->major_ver > 1) &&
2045             ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
2046         static const char *es1 = "Failed to set NT4 compatibility flag";
2047         static const char *es2 = ".  Run chkdsk.";
2048 
2049         /* Convert to a read-only mount. */
2050         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2051                 ON_ERRORS_CONTINUE))) {
2052             ntfs_error(sb, "%s and neither on_errors=continue nor "
2053                     "on_errors=remount-ro was specified%s",
2054                     es1, es2);
2055             goto iput_root_err_out;
2056         }
2057         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2058         sb->s_flags |= SB_RDONLY;
2059         NVolSetErrors(vol);
2060     }
2061 #endif
2062     /* If (still) a read-write mount, empty the logfile. */
2063     if (!sb_rdonly(sb) && !ntfs_empty_logfile(vol->logfile_ino)) {
2064         static const char *es1 = "Failed to empty $LogFile";
2065         static const char *es2 = ".  Mount in Windows.";
2066 
2067         /* Convert to a read-only mount. */
2068         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2069                 ON_ERRORS_CONTINUE))) {
2070             ntfs_error(sb, "%s and neither on_errors=continue nor "
2071                     "on_errors=remount-ro was specified%s",
2072                     es1, es2);
2073             goto iput_root_err_out;
2074         }
2075         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2076         sb->s_flags |= SB_RDONLY;
2077         NVolSetErrors(vol);
2078     }
2079 #endif /* NTFS_RW */
2080     /* If on NTFS versions before 3.0, we are done. */
2081     if (unlikely(vol->major_ver < 3))
2082         return true;
2083     /* NTFS 3.0+ specific initialization. */
2084     /* Get the security descriptors inode. */
2085     vol->secure_ino = ntfs_iget(sb, FILE_Secure);
2086     if (IS_ERR(vol->secure_ino) || is_bad_inode(vol->secure_ino)) {
2087         if (!IS_ERR(vol->secure_ino))
2088             iput(vol->secure_ino);
2089         ntfs_error(sb, "Failed to load $Secure.");
2090         goto iput_root_err_out;
2091     }
2092     // TODO: Initialize security.
2093     /* Get the extended system files' directory inode. */
2094     vol->extend_ino = ntfs_iget(sb, FILE_Extend);
2095     if (IS_ERR(vol->extend_ino) || is_bad_inode(vol->extend_ino) ||
2096         !S_ISDIR(vol->extend_ino->i_mode)) {
2097         if (!IS_ERR(vol->extend_ino))
2098             iput(vol->extend_ino);
2099         ntfs_error(sb, "Failed to load $Extend.");
2100         goto iput_sec_err_out;
2101     }
2102 #ifdef NTFS_RW
2103     /* Find the quota file, load it if present, and set it up. */
2104     if (!load_and_init_quota(vol)) {
2105         static const char *es1 = "Failed to load $Quota";
2106         static const char *es2 = ".  Run chkdsk.";
2107 
2108         /* If a read-write mount, convert it to a read-only mount. */
2109         if (!sb_rdonly(sb)) {
2110             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2111                     ON_ERRORS_CONTINUE))) {
2112                 ntfs_error(sb, "%s and neither on_errors="
2113                         "continue nor on_errors="
2114                         "remount-ro was specified%s",
2115                         es1, es2);
2116                 goto iput_quota_err_out;
2117             }
2118             sb->s_flags |= SB_RDONLY;
2119             ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2120         } else
2121             ntfs_warning(sb, "%s.  Will not be able to remount "
2122                     "read-write%s", es1, es2);
2123         /* This will prevent a read-write remount. */
2124         NVolSetErrors(vol);
2125     }
2126     /* If (still) a read-write mount, mark the quotas out of date. */
2127     if (!sb_rdonly(sb) && !ntfs_mark_quotas_out_of_date(vol)) {
2128         static const char *es1 = "Failed to mark quotas out of date";
2129         static const char *es2 = ".  Run chkdsk.";
2130 
2131         /* Convert to a read-only mount. */
2132         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2133                 ON_ERRORS_CONTINUE))) {
2134             ntfs_error(sb, "%s and neither on_errors=continue nor "
2135                     "on_errors=remount-ro was specified%s",
2136                     es1, es2);
2137             goto iput_quota_err_out;
2138         }
2139         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2140         sb->s_flags |= SB_RDONLY;
2141         NVolSetErrors(vol);
2142     }
2143     /*
2144      * Find the transaction log file ($UsnJrnl), load it if present, check
2145      * it, and set it up.
2146      */
2147     if (!load_and_init_usnjrnl(vol)) {
2148         static const char *es1 = "Failed to load $UsnJrnl";
2149         static const char *es2 = ".  Run chkdsk.";
2150 
2151         /* If a read-write mount, convert it to a read-only mount. */
2152         if (!sb_rdonly(sb)) {
2153             if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2154                     ON_ERRORS_CONTINUE))) {
2155                 ntfs_error(sb, "%s and neither on_errors="
2156                         "continue nor on_errors="
2157                         "remount-ro was specified%s",
2158                         es1, es2);
2159                 goto iput_usnjrnl_err_out;
2160             }
2161             sb->s_flags |= SB_RDONLY;
2162             ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2163         } else
2164             ntfs_warning(sb, "%s.  Will not be able to remount "
2165                     "read-write%s", es1, es2);
2166         /* This will prevent a read-write remount. */
2167         NVolSetErrors(vol);
2168     }
2169     /* If (still) a read-write mount, stamp the transaction log. */
2170     if (!sb_rdonly(sb) && !ntfs_stamp_usnjrnl(vol)) {
2171         static const char *es1 = "Failed to stamp transaction log "
2172                 "($UsnJrnl)";
2173         static const char *es2 = ".  Run chkdsk.";
2174 
2175         /* Convert to a read-only mount. */
2176         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
2177                 ON_ERRORS_CONTINUE))) {
2178             ntfs_error(sb, "%s and neither on_errors=continue nor "
2179                     "on_errors=remount-ro was specified%s",
2180                     es1, es2);
2181             goto iput_usnjrnl_err_out;
2182         }
2183         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
2184         sb->s_flags |= SB_RDONLY;
2185         NVolSetErrors(vol);
2186     }
2187 #endif /* NTFS_RW */
2188     return true;
2189 #ifdef NTFS_RW
2190 iput_usnjrnl_err_out:
2191     iput(vol->usnjrnl_j_ino);
2192     iput(vol->usnjrnl_max_ino);
2193     iput(vol->usnjrnl_ino);
2194 iput_quota_err_out:
2195     iput(vol->quota_q_ino);
2196     iput(vol->quota_ino);
2197     iput(vol->extend_ino);
2198 #endif /* NTFS_RW */
2199 iput_sec_err_out:
2200     iput(vol->secure_ino);
2201 iput_root_err_out:
2202     iput(vol->root_ino);
2203 iput_logfile_err_out:
2204 #ifdef NTFS_RW
2205     iput(vol->logfile_ino);
2206 iput_vol_err_out:
2207 #endif /* NTFS_RW */
2208     iput(vol->vol_ino);
2209 iput_lcnbmp_err_out:
2210     iput(vol->lcnbmp_ino);
2211 iput_attrdef_err_out:
2212     vol->attrdef_size = 0;
2213     if (vol->attrdef) {
2214         ntfs_free(vol->attrdef);
2215         vol->attrdef = NULL;
2216     }
2217 #ifdef NTFS_RW
2218 iput_upcase_err_out:
2219 #endif /* NTFS_RW */
2220     vol->upcase_len = 0;
2221     mutex_lock(&ntfs_lock);
2222     if (vol->upcase == default_upcase) {
2223         ntfs_nr_upcase_users--;
2224         vol->upcase = NULL;
2225     }
2226     mutex_unlock(&ntfs_lock);
2227     if (vol->upcase) {
2228         ntfs_free(vol->upcase);
2229         vol->upcase = NULL;
2230     }
2231 iput_mftbmp_err_out:
2232     iput(vol->mftbmp_ino);
2233 iput_mirr_err_out:
2234 #ifdef NTFS_RW
2235     iput(vol->mftmirr_ino);
2236 #endif /* NTFS_RW */
2237     return false;
2238 }
2239 
2240 /**
2241  * ntfs_put_super - called by the vfs to unmount a volume
2242  * @sb:     vfs superblock of volume to unmount
2243  *
2244  * ntfs_put_super() is called by the VFS (from fs/super.c::do_umount()) when
2245  * the volume is being unmounted (umount system call has been invoked) and it
2246  * releases all inodes and memory belonging to the NTFS specific part of the
2247  * super block.
2248  */
2249 static void ntfs_put_super(struct super_block *sb)
2250 {
2251     ntfs_volume *vol = NTFS_SB(sb);
2252 
2253     ntfs_debug("Entering.");
2254 
2255 #ifdef NTFS_RW
2256     /*
2257      * Commit all inodes while they are still open in case some of them
2258      * cause others to be dirtied.
2259      */
2260     ntfs_commit_inode(vol->vol_ino);
2261 
2262     /* NTFS 3.0+ specific. */
2263     if (vol->major_ver >= 3) {
2264         if (vol->usnjrnl_j_ino)
2265             ntfs_commit_inode(vol->usnjrnl_j_ino);
2266         if (vol->usnjrnl_max_ino)
2267             ntfs_commit_inode(vol->usnjrnl_max_ino);
2268         if (vol->usnjrnl_ino)
2269             ntfs_commit_inode(vol->usnjrnl_ino);
2270         if (vol->quota_q_ino)
2271             ntfs_commit_inode(vol->quota_q_ino);
2272         if (vol->quota_ino)
2273             ntfs_commit_inode(vol->quota_ino);
2274         if (vol->extend_ino)
2275             ntfs_commit_inode(vol->extend_ino);
2276         if (vol->secure_ino)
2277             ntfs_commit_inode(vol->secure_ino);
2278     }
2279 
2280     ntfs_commit_inode(vol->root_ino);
2281 
2282     down_write(&vol->lcnbmp_lock);
2283     ntfs_commit_inode(vol->lcnbmp_ino);
2284     up_write(&vol->lcnbmp_lock);
2285 
2286     down_write(&vol->mftbmp_lock);
2287     ntfs_commit_inode(vol->mftbmp_ino);
2288     up_write(&vol->mftbmp_lock);
2289 
2290     if (vol->logfile_ino)
2291         ntfs_commit_inode(vol->logfile_ino);
2292 
2293     if (vol->mftmirr_ino)
2294         ntfs_commit_inode(vol->mftmirr_ino);
2295     ntfs_commit_inode(vol->mft_ino);
2296 
2297     /*
2298      * If a read-write mount and no volume errors have occurred, mark the
2299      * volume clean.  Also, re-commit all affected inodes.
2300      */
2301     if (!sb_rdonly(sb)) {
2302         if (!NVolErrors(vol)) {
2303             if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
2304                 ntfs_warning(sb, "Failed to clear dirty bit "
2305                         "in volume information "
2306                         "flags.  Run chkdsk.");
2307             ntfs_commit_inode(vol->vol_ino);
2308             ntfs_commit_inode(vol->root_ino);
2309             if (vol->mftmirr_ino)
2310                 ntfs_commit_inode(vol->mftmirr_ino);
2311             ntfs_commit_inode(vol->mft_ino);
2312         } else {
2313             ntfs_warning(sb, "Volume has errors.  Leaving volume "
2314                     "marked dirty.  Run chkdsk.");
2315         }
2316     }
2317 #endif /* NTFS_RW */
2318 
2319     iput(vol->vol_ino);
2320     vol->vol_ino = NULL;
2321 
2322     /* NTFS 3.0+ specific clean up. */
2323     if (vol->major_ver >= 3) {
2324 #ifdef NTFS_RW
2325         if (vol->usnjrnl_j_ino) {
2326             iput(vol->usnjrnl_j_ino);
2327             vol->usnjrnl_j_ino = NULL;
2328         }
2329         if (vol->usnjrnl_max_ino) {
2330             iput(vol->usnjrnl_max_ino);
2331             vol->usnjrnl_max_ino = NULL;
2332         }
2333         if (vol->usnjrnl_ino) {
2334             iput(vol->usnjrnl_ino);
2335             vol->usnjrnl_ino = NULL;
2336         }
2337         if (vol->quota_q_ino) {
2338             iput(vol->quota_q_ino);
2339             vol->quota_q_ino = NULL;
2340         }
2341         if (vol->quota_ino) {
2342             iput(vol->quota_ino);
2343             vol->quota_ino = NULL;
2344         }
2345 #endif /* NTFS_RW */
2346         if (vol->extend_ino) {
2347             iput(vol->extend_ino);
2348             vol->extend_ino = NULL;
2349         }
2350         if (vol->secure_ino) {
2351             iput(vol->secure_ino);
2352             vol->secure_ino = NULL;
2353         }
2354     }
2355 
2356     iput(vol->root_ino);
2357     vol->root_ino = NULL;
2358 
2359     down_write(&vol->lcnbmp_lock);
2360     iput(vol->lcnbmp_ino);
2361     vol->lcnbmp_ino = NULL;
2362     up_write(&vol->lcnbmp_lock);
2363 
2364     down_write(&vol->mftbmp_lock);
2365     iput(vol->mftbmp_ino);
2366     vol->mftbmp_ino = NULL;
2367     up_write(&vol->mftbmp_lock);
2368 
2369 #ifdef NTFS_RW
2370     if (vol->logfile_ino) {
2371         iput(vol->logfile_ino);
2372         vol->logfile_ino = NULL;
2373     }
2374     if (vol->mftmirr_ino) {
2375         /* Re-commit the mft mirror and mft just in case. */
2376         ntfs_commit_inode(vol->mftmirr_ino);
2377         ntfs_commit_inode(vol->mft_ino);
2378         iput(vol->mftmirr_ino);
2379         vol->mftmirr_ino = NULL;
2380     }
2381     /*
2382      * We should have no dirty inodes left, due to
2383      * mft.c::ntfs_mft_writepage() cleaning all the dirty pages as
2384      * the underlying mft records are written out and cleaned.
2385      */
2386     ntfs_commit_inode(vol->mft_ino);
2387     write_inode_now(vol->mft_ino, 1);
2388 #endif /* NTFS_RW */
2389 
2390     iput(vol->mft_ino);
2391     vol->mft_ino = NULL;
2392 
2393     /* Throw away the table of attribute definitions. */
2394     vol->attrdef_size = 0;
2395     if (vol->attrdef) {
2396         ntfs_free(vol->attrdef);
2397         vol->attrdef = NULL;
2398     }
2399     vol->upcase_len = 0;
2400     /*
2401      * Destroy the global default upcase table if necessary.  Also decrease
2402      * the number of upcase users if we are a user.
2403      */
2404     mutex_lock(&ntfs_lock);
2405     if (vol->upcase == default_upcase) {
2406         ntfs_nr_upcase_users--;
2407         vol->upcase = NULL;
2408     }
2409     if (!ntfs_nr_upcase_users && default_upcase) {
2410         ntfs_free(default_upcase);
2411         default_upcase = NULL;
2412     }
2413     if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
2414         free_compression_buffers();
2415     mutex_unlock(&ntfs_lock);
2416     if (vol->upcase) {
2417         ntfs_free(vol->upcase);
2418         vol->upcase = NULL;
2419     }
2420 
2421     unload_nls(vol->nls_map);
2422 
2423     sb->s_fs_info = NULL;
2424     kfree(vol);
2425 }
2426 
2427 /**
2428  * get_nr_free_clusters - return the number of free clusters on a volume
2429  * @vol:    ntfs volume for which to obtain free cluster count
2430  *
2431  * Calculate the number of free clusters on the mounted NTFS volume @vol. We
2432  * actually calculate the number of clusters in use instead because this
2433  * allows us to not care about partial pages as these will be just zero filled
2434  * and hence not be counted as allocated clusters.
2435  *
2436  * The only particularity is that clusters beyond the end of the logical ntfs
2437  * volume will be marked as allocated to prevent errors which means we have to
2438  * discount those at the end. This is important as the cluster bitmap always
2439  * has a size in multiples of 8 bytes, i.e. up to 63 clusters could be outside
2440  * the logical volume and marked in use when they are not as they do not exist.
2441  *
2442  * If any pages cannot be read we assume all clusters in the erroring pages are
2443  * in use. This means we return an underestimate on errors which is better than
2444  * an overestimate.
2445  */
2446 static s64 get_nr_free_clusters(ntfs_volume *vol)
2447 {
2448     s64 nr_free = vol->nr_clusters;
2449     struct address_space *mapping = vol->lcnbmp_ino->i_mapping;
2450     struct page *page;
2451     pgoff_t index, max_index;
2452 
2453     ntfs_debug("Entering.");
2454     /* Serialize accesses to the cluster bitmap. */
2455     down_read(&vol->lcnbmp_lock);
2456     /*
2457      * Convert the number of bits into bytes rounded up, then convert into
2458      * multiples of PAGE_SIZE, rounding up so that if we have one
2459      * full and one partial page max_index = 2.
2460      */
2461     max_index = (((vol->nr_clusters + 7) >> 3) + PAGE_SIZE - 1) >>
2462             PAGE_SHIFT;
2463     /* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2464     ntfs_debug("Reading $Bitmap, max_index = 0x%lx, max_size = 0x%lx.",
2465             max_index, PAGE_SIZE / 4);
2466     for (index = 0; index < max_index; index++) {
2467         unsigned long *kaddr;
2468 
2469         /*
2470          * Read the page from page cache, getting it from backing store
2471          * if necessary, and increment the use count.
2472          */
2473         page = read_mapping_page(mapping, index, NULL);
2474         /* Ignore pages which errored synchronously. */
2475         if (IS_ERR(page)) {
2476             ntfs_debug("read_mapping_page() error. Skipping "
2477                     "page (index 0x%lx).", index);
2478             nr_free -= PAGE_SIZE * 8;
2479             continue;
2480         }
2481         kaddr = kmap_atomic(page);
2482         /*
2483          * Subtract the number of set bits. If this
2484          * is the last page and it is partial we don't really care as
2485          * it just means we do a little extra work but it won't affect
2486          * the result as all out of range bytes are set to zero by
2487          * ntfs_readpage().
2488          */
2489         nr_free -= bitmap_weight(kaddr,
2490                     PAGE_SIZE * BITS_PER_BYTE);
2491         kunmap_atomic(kaddr);
2492         put_page(page);
2493     }
2494     ntfs_debug("Finished reading $Bitmap, last index = 0x%lx.", index - 1);
2495     /*
2496      * Fixup for eventual bits outside logical ntfs volume (see function
2497      * description above).
2498      */
2499     if (vol->nr_clusters & 63)
2500         nr_free += 64 - (vol->nr_clusters & 63);
2501     up_read(&vol->lcnbmp_lock);
2502     /* If errors occurred we may well have gone below zero, fix this. */
2503     if (nr_free < 0)
2504         nr_free = 0;
2505     ntfs_debug("Exiting.");
2506     return nr_free;
2507 }
2508 
2509 /**
2510  * __get_nr_free_mft_records - return the number of free inodes on a volume
2511  * @vol:    ntfs volume for which to obtain free inode count
2512  * @nr_free:    number of mft records in filesystem
2513  * @max_index:  maximum number of pages containing set bits
2514  *
2515  * Calculate the number of free mft records (inodes) on the mounted NTFS
2516  * volume @vol. We actually calculate the number of mft records in use instead
2517  * because this allows us to not care about partial pages as these will be just
2518  * zero filled and hence not be counted as allocated mft record.
2519  *
2520  * If any pages cannot be read we assume all mft records in the erroring pages
2521  * are in use. This means we return an underestimate on errors which is better
2522  * than an overestimate.
2523  *
2524  * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing.
2525  */
2526 static unsigned long __get_nr_free_mft_records(ntfs_volume *vol,
2527         s64 nr_free, const pgoff_t max_index)
2528 {
2529     struct address_space *mapping = vol->mftbmp_ino->i_mapping;
2530     struct page *page;
2531     pgoff_t index;
2532 
2533     ntfs_debug("Entering.");
2534     /* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2535     ntfs_debug("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = "
2536             "0x%lx.", max_index, PAGE_SIZE / 4);
2537     for (index = 0; index < max_index; index++) {
2538         unsigned long *kaddr;
2539 
2540         /*
2541          * Read the page from page cache, getting it from backing store
2542          * if necessary, and increment the use count.
2543          */
2544         page = read_mapping_page(mapping, index, NULL);
2545         /* Ignore pages which errored synchronously. */
2546         if (IS_ERR(page)) {
2547             ntfs_debug("read_mapping_page() error. Skipping "
2548                     "page (index 0x%lx).", index);
2549             nr_free -= PAGE_SIZE * 8;
2550             continue;
2551         }
2552         kaddr = kmap_atomic(page);
2553         /*
2554          * Subtract the number of set bits. If this
2555          * is the last page and it is partial we don't really care as
2556          * it just means we do a little extra work but it won't affect
2557          * the result as all out of range bytes are set to zero by
2558          * ntfs_readpage().
2559          */
2560         nr_free -= bitmap_weight(kaddr,
2561                     PAGE_SIZE * BITS_PER_BYTE);
2562         kunmap_atomic(kaddr);
2563         put_page(page);
2564     }
2565     ntfs_debug("Finished reading $MFT/$BITMAP, last index = 0x%lx.",
2566             index - 1);
2567     /* If errors occurred we may well have gone below zero, fix this. */
2568     if (nr_free < 0)
2569         nr_free = 0;
2570     ntfs_debug("Exiting.");
2571     return nr_free;
2572 }
2573 
2574 /**
2575  * ntfs_statfs - return information about mounted NTFS volume
2576  * @dentry: dentry from mounted volume
2577  * @sfs:    statfs structure in which to return the information
2578  *
2579  * Return information about the mounted NTFS volume @dentry in the statfs structure
2580  * pointed to by @sfs (this is initialized with zeros before ntfs_statfs is
2581  * called). We interpret the values to be correct of the moment in time at
2582  * which we are called. Most values are variable otherwise and this isn't just
2583  * the free values but the totals as well. For example we can increase the
2584  * total number of file nodes if we run out and we can keep doing this until
2585  * there is no more space on the volume left at all.
2586  *
2587  * Called from vfs_statfs which is used to handle the statfs, fstatfs, and
2588  * ustat system calls.
2589  *
2590  * Return 0 on success or -errno on error.
2591  */
2592 static int ntfs_statfs(struct dentry *dentry, struct kstatfs *sfs)
2593 {
2594     struct super_block *sb = dentry->d_sb;
2595     s64 size;
2596     ntfs_volume *vol = NTFS_SB(sb);
2597     ntfs_inode *mft_ni = NTFS_I(vol->mft_ino);
2598     pgoff_t max_index;
2599     unsigned long flags;
2600 
2601     ntfs_debug("Entering.");
2602     /* Type of filesystem. */
2603     sfs->f_type   = NTFS_SB_MAGIC;
2604     /* Optimal transfer block size. */
2605     sfs->f_bsize  = PAGE_SIZE;
2606     /*
2607      * Total data blocks in filesystem in units of f_bsize and since
2608      * inodes are also stored in data blocs ($MFT is a file) this is just
2609      * the total clusters.
2610      */
2611     sfs->f_blocks = vol->nr_clusters << vol->cluster_size_bits >>
2612                 PAGE_SHIFT;
2613     /* Free data blocks in filesystem in units of f_bsize. */
2614     size          = get_nr_free_clusters(vol) << vol->cluster_size_bits >>
2615                 PAGE_SHIFT;
2616     if (size < 0LL)
2617         size = 0LL;
2618     /* Free blocks avail to non-superuser, same as above on NTFS. */
2619     sfs->f_bavail = sfs->f_bfree = size;
2620     /* Serialize accesses to the inode bitmap. */
2621     down_read(&vol->mftbmp_lock);
2622     read_lock_irqsave(&mft_ni->size_lock, flags);
2623     size = i_size_read(vol->mft_ino) >> vol->mft_record_size_bits;
2624     /*
2625      * Convert the maximum number of set bits into bytes rounded up, then
2626      * convert into multiples of PAGE_SIZE, rounding up so that if we
2627      * have one full and one partial page max_index = 2.
2628      */
2629     max_index = ((((mft_ni->initialized_size >> vol->mft_record_size_bits)
2630             + 7) >> 3) + PAGE_SIZE - 1) >> PAGE_SHIFT;
2631     read_unlock_irqrestore(&mft_ni->size_lock, flags);
2632     /* Number of inodes in filesystem (at this point in time). */
2633     sfs->f_files = size;
2634     /* Free inodes in fs (based on current total count). */
2635     sfs->f_ffree = __get_nr_free_mft_records(vol, size, max_index);
2636     up_read(&vol->mftbmp_lock);
2637     /*
2638      * File system id. This is extremely *nix flavour dependent and even
2639      * within Linux itself all fs do their own thing. I interpret this to
2640      * mean a unique id associated with the mounted fs and not the id
2641      * associated with the filesystem driver, the latter is already given
2642      * by the filesystem type in sfs->f_type. Thus we use the 64-bit
2643      * volume serial number splitting it into two 32-bit parts. We enter
2644      * the least significant 32-bits in f_fsid[0] and the most significant
2645      * 32-bits in f_fsid[1].
2646      */
2647     sfs->f_fsid = u64_to_fsid(vol->serial_no);
2648     /* Maximum length of filenames. */
2649     sfs->f_namelen     = NTFS_MAX_NAME_LEN;
2650     return 0;
2651 }
2652 
2653 #ifdef NTFS_RW
2654 static int ntfs_write_inode(struct inode *vi, struct writeback_control *wbc)
2655 {
2656     return __ntfs_write_inode(vi, wbc->sync_mode == WB_SYNC_ALL);
2657 }
2658 #endif
2659 
2660 /**
2661  * The complete super operations.
2662  */
2663 static const struct super_operations ntfs_sops = {
2664     .alloc_inode    = ntfs_alloc_big_inode,   /* VFS: Allocate new inode. */
2665     .free_inode = ntfs_free_big_inode, /* VFS: Deallocate inode. */
2666 #ifdef NTFS_RW
2667     .write_inode    = ntfs_write_inode, /* VFS: Write dirty inode to
2668                            disk. */
2669 #endif /* NTFS_RW */
2670     .put_super  = ntfs_put_super,   /* Syscall: umount. */
2671     .statfs     = ntfs_statfs,      /* Syscall: statfs */
2672     .remount_fs = ntfs_remount,     /* Syscall: mount -o remount. */
2673     .evict_inode    = ntfs_evict_big_inode, /* VFS: Called when an inode is
2674                            removed from memory. */
2675     .show_options   = ntfs_show_options,    /* Show mount options in
2676                            proc. */
2677 };
2678 
2679 /**
2680  * ntfs_fill_super - mount an ntfs filesystem
2681  * @sb:     super block of ntfs filesystem to mount
2682  * @opt:    string containing the mount options
2683  * @silent: silence error output
2684  *
2685  * ntfs_fill_super() is called by the VFS to mount the device described by @sb
2686  * with the mount otions in @data with the NTFS filesystem.
2687  *
2688  * If @silent is true, remain silent even if errors are detected. This is used
2689  * during bootup, when the kernel tries to mount the root filesystem with all
2690  * registered filesystems one after the other until one succeeds. This implies
2691  * that all filesystems except the correct one will quite correctly and
2692  * expectedly return an error, but nobody wants to see error messages when in
2693  * fact this is what is supposed to happen.
2694  *
2695  * NOTE: @sb->s_flags contains the mount options flags.
2696  */
2697 static int ntfs_fill_super(struct super_block *sb, void *opt, const int silent)
2698 {
2699     ntfs_volume *vol;
2700     struct buffer_head *bh;
2701     struct inode *tmp_ino;
2702     int blocksize, result;
2703 
2704     /*
2705      * We do a pretty difficult piece of bootstrap by reading the
2706      * MFT (and other metadata) from disk into memory. We'll only
2707      * release this metadata during umount, so the locking patterns
2708      * observed during bootstrap do not count. So turn off the
2709      * observation of locking patterns (strictly for this context
2710      * only) while mounting NTFS. [The validator is still active
2711      * otherwise, even for this context: it will for example record
2712      * lock class registrations.]
2713      */
2714     lockdep_off();
2715     ntfs_debug("Entering.");
2716 #ifndef NTFS_RW
2717     sb->s_flags |= SB_RDONLY;
2718 #endif /* ! NTFS_RW */
2719     /* Allocate a new ntfs_volume and place it in sb->s_fs_info. */
2720     sb->s_fs_info = kmalloc(sizeof(ntfs_volume), GFP_NOFS);
2721     vol = NTFS_SB(sb);
2722     if (!vol) {
2723         if (!silent)
2724             ntfs_error(sb, "Allocation of NTFS volume structure "
2725                     "failed. Aborting mount...");
2726         lockdep_on();
2727         return -ENOMEM;
2728     }
2729     /* Initialize ntfs_volume structure. */
2730     *vol = (ntfs_volume) {
2731         .sb = sb,
2732         /*
2733          * Default is group and other don't have any access to files or
2734          * directories while owner has full access. Further, files by
2735          * default are not executable but directories are of course
2736          * browseable.
2737          */
2738         .fmask = 0177,
2739         .dmask = 0077,
2740     };
2741     init_rwsem(&vol->mftbmp_lock);
2742     init_rwsem(&vol->lcnbmp_lock);
2743 
2744     /* By default, enable sparse support. */
2745     NVolSetSparseEnabled(vol);
2746 
2747     /* Important to get the mount options dealt with now. */
2748     if (!parse_options(vol, (char*)opt))
2749         goto err_out_now;
2750 
2751     /* We support sector sizes up to the PAGE_SIZE. */
2752     if (bdev_logical_block_size(sb->s_bdev) > PAGE_SIZE) {
2753         if (!silent)
2754             ntfs_error(sb, "Device has unsupported sector size "
2755                     "(%i).  The maximum supported sector "
2756                     "size on this architecture is %lu "
2757                     "bytes.",
2758                     bdev_logical_block_size(sb->s_bdev),
2759                     PAGE_SIZE);
2760         goto err_out_now;
2761     }
2762     /*
2763      * Setup the device access block size to NTFS_BLOCK_SIZE or the hard
2764      * sector size, whichever is bigger.
2765      */
2766     blocksize = sb_min_blocksize(sb, NTFS_BLOCK_SIZE);
2767     if (blocksize < NTFS_BLOCK_SIZE) {
2768         if (!silent)
2769             ntfs_error(sb, "Unable to set device block size.");
2770         goto err_out_now;
2771     }
2772     BUG_ON(blocksize != sb->s_blocksize);
2773     ntfs_debug("Set device block size to %i bytes (block size bits %i).",
2774             blocksize, sb->s_blocksize_bits);
2775     /* Determine the size of the device in units of block_size bytes. */
2776     vol->nr_blocks = sb_bdev_nr_blocks(sb);
2777     if (!vol->nr_blocks) {
2778         if (!silent)
2779             ntfs_error(sb, "Unable to determine device size.");
2780         goto err_out_now;
2781     }
2782     /* Read the boot sector and return unlocked buffer head to it. */
2783     if (!(bh = read_ntfs_boot_sector(sb, silent))) {
2784         if (!silent)
2785             ntfs_error(sb, "Not an NTFS volume.");
2786         goto err_out_now;
2787     }
2788     /*
2789      * Extract the data from the boot sector and setup the ntfs volume
2790      * using it.
2791      */
2792     result = parse_ntfs_boot_sector(vol, (NTFS_BOOT_SECTOR*)bh->b_data);
2793     brelse(bh);
2794     if (!result) {
2795         if (!silent)
2796             ntfs_error(sb, "Unsupported NTFS filesystem.");
2797         goto err_out_now;
2798     }
2799     /*
2800      * If the boot sector indicates a sector size bigger than the current
2801      * device block size, switch the device block size to the sector size.
2802      * TODO: It may be possible to support this case even when the set
2803      * below fails, we would just be breaking up the i/o for each sector
2804      * into multiple blocks for i/o purposes but otherwise it should just
2805      * work.  However it is safer to leave disabled until someone hits this
2806      * error message and then we can get them to try it without the setting
2807      * so we know for sure that it works.
2808      */
2809     if (vol->sector_size > blocksize) {
2810         blocksize = sb_set_blocksize(sb, vol->sector_size);
2811         if (blocksize != vol->sector_size) {
2812             if (!silent)
2813                 ntfs_error(sb, "Unable to set device block "
2814                         "size to sector size (%i).",
2815                         vol->sector_size);
2816             goto err_out_now;
2817         }
2818         BUG_ON(blocksize != sb->s_blocksize);
2819         vol->nr_blocks = sb_bdev_nr_blocks(sb);
2820         ntfs_debug("Changed device block size to %i bytes (block size "
2821                 "bits %i) to match volume sector size.",
2822                 blocksize, sb->s_blocksize_bits);
2823     }
2824     /* Initialize the cluster and mft allocators. */
2825     ntfs_setup_allocators(vol);
2826     /* Setup remaining fields in the super block. */
2827     sb->s_magic = NTFS_SB_MAGIC;
2828     /*
2829      * Ntfs allows 63 bits for the file size, i.e. correct would be:
2830      *  sb->s_maxbytes = ~0ULL >> 1;
2831      * But the kernel uses a long as the page cache page index which on
2832      * 32-bit architectures is only 32-bits. MAX_LFS_FILESIZE is kernel
2833      * defined to the maximum the page cache page index can cope with
2834      * without overflowing the index or to 2^63 - 1, whichever is smaller.
2835      */
2836     sb->s_maxbytes = MAX_LFS_FILESIZE;
2837     /* Ntfs measures time in 100ns intervals. */
2838     sb->s_time_gran = 100;
2839     /*
2840      * Now load the metadata required for the page cache and our address
2841      * space operations to function. We do this by setting up a specialised
2842      * read_inode method and then just calling the normal iget() to obtain
2843      * the inode for $MFT which is sufficient to allow our normal inode
2844      * operations and associated address space operations to function.
2845      */
2846     sb->s_op = &ntfs_sops;
2847     tmp_ino = new_inode(sb);
2848     if (!tmp_ino) {
2849         if (!silent)
2850             ntfs_error(sb, "Failed to load essential metadata.");
2851         goto err_out_now;
2852     }
2853     tmp_ino->i_ino = FILE_MFT;
2854     insert_inode_hash(tmp_ino);
2855     if (ntfs_read_inode_mount(tmp_ino) < 0) {
2856         if (!silent)
2857             ntfs_error(sb, "Failed to load essential metadata.");
2858         goto iput_tmp_ino_err_out_now;
2859     }
2860     mutex_lock(&ntfs_lock);
2861     /*
2862      * The current mount is a compression user if the cluster size is
2863      * less than or equal 4kiB.
2864      */
2865     if (vol->cluster_size <= 4096 && !ntfs_nr_compression_users++) {
2866         result = allocate_compression_buffers();
2867         if (result) {
2868             ntfs_error(NULL, "Failed to allocate buffers "
2869                     "for compression engine.");
2870             ntfs_nr_compression_users--;
2871             mutex_unlock(&ntfs_lock);
2872             goto iput_tmp_ino_err_out_now;
2873         }
2874     }
2875     /*
2876      * Generate the global default upcase table if necessary.  Also
2877      * temporarily increment the number of upcase users to avoid race
2878      * conditions with concurrent (u)mounts.
2879      */
2880     if (!default_upcase)
2881         default_upcase = generate_default_upcase();
2882     ntfs_nr_upcase_users++;
2883     mutex_unlock(&ntfs_lock);
2884     /*
2885      * From now on, ignore @silent parameter. If we fail below this line,
2886      * it will be due to a corrupt fs or a system error, so we report it.
2887      */
2888     /*
2889      * Open the system files with normal access functions and complete
2890      * setting up the ntfs super block.
2891      */
2892     if (!load_system_files(vol)) {
2893         ntfs_error(sb, "Failed to load system files.");
2894         goto unl_upcase_iput_tmp_ino_err_out_now;
2895     }
2896 
2897     /* We grab a reference, simulating an ntfs_iget(). */
2898     ihold(vol->root_ino);
2899     if ((sb->s_root = d_make_root(vol->root_ino))) {
2900         ntfs_debug("Exiting, status successful.");
2901         /* Release the default upcase if it has no users. */
2902         mutex_lock(&ntfs_lock);
2903         if (!--ntfs_nr_upcase_users && default_upcase) {
2904             ntfs_free(default_upcase);
2905             default_upcase = NULL;
2906         }
2907         mutex_unlock(&ntfs_lock);
2908         sb->s_export_op = &ntfs_export_ops;
2909         lockdep_on();
2910         return 0;
2911     }
2912     ntfs_error(sb, "Failed to allocate root directory.");
2913     /* Clean up after the successful load_system_files() call from above. */
2914     // TODO: Use ntfs_put_super() instead of repeating all this code...
2915     // FIXME: Should mark the volume clean as the error is most likely
2916     //    -ENOMEM.
2917     iput(vol->vol_ino);
2918     vol->vol_ino = NULL;
2919     /* NTFS 3.0+ specific clean up. */
2920     if (vol->major_ver >= 3) {
2921 #ifdef NTFS_RW
2922         if (vol->usnjrnl_j_ino) {
2923             iput(vol->usnjrnl_j_ino);
2924             vol->usnjrnl_j_ino = NULL;
2925         }
2926         if (vol->usnjrnl_max_ino) {
2927             iput(vol->usnjrnl_max_ino);
2928             vol->usnjrnl_max_ino = NULL;
2929         }
2930         if (vol->usnjrnl_ino) {
2931             iput(vol->usnjrnl_ino);
2932             vol->usnjrnl_ino = NULL;
2933         }
2934         if (vol->quota_q_ino) {
2935             iput(vol->quota_q_ino);
2936             vol->quota_q_ino = NULL;
2937         }
2938         if (vol->quota_ino) {
2939             iput(vol->quota_ino);
2940             vol->quota_ino = NULL;
2941         }
2942 #endif /* NTFS_RW */
2943         if (vol->extend_ino) {
2944             iput(vol->extend_ino);
2945             vol->extend_ino = NULL;
2946         }
2947         if (vol->secure_ino) {
2948             iput(vol->secure_ino);
2949             vol->secure_ino = NULL;
2950         }
2951     }
2952     iput(vol->root_ino);
2953     vol->root_ino = NULL;
2954     iput(vol->lcnbmp_ino);
2955     vol->lcnbmp_ino = NULL;
2956     iput(vol->mftbmp_ino);
2957     vol->mftbmp_ino = NULL;
2958 #ifdef NTFS_RW
2959     if (vol->logfile_ino) {
2960         iput(vol->logfile_ino);
2961         vol->logfile_ino = NULL;
2962     }
2963     if (vol->mftmirr_ino) {
2964         iput(vol->mftmirr_ino);
2965         vol->mftmirr_ino = NULL;
2966     }
2967 #endif /* NTFS_RW */
2968     /* Throw away the table of attribute definitions. */
2969     vol->attrdef_size = 0;
2970     if (vol->attrdef) {
2971         ntfs_free(vol->attrdef);
2972         vol->attrdef = NULL;
2973     }
2974     vol->upcase_len = 0;
2975     mutex_lock(&ntfs_lock);
2976     if (vol->upcase == default_upcase) {
2977         ntfs_nr_upcase_users--;
2978         vol->upcase = NULL;
2979     }
2980     mutex_unlock(&ntfs_lock);
2981     if (vol->upcase) {
2982         ntfs_free(vol->upcase);
2983         vol->upcase = NULL;
2984     }
2985     if (vol->nls_map) {
2986         unload_nls(vol->nls_map);
2987         vol->nls_map = NULL;
2988     }
2989     /* Error exit code path. */
2990 unl_upcase_iput_tmp_ino_err_out_now:
2991     /*
2992      * Decrease the number of upcase users and destroy the global default
2993      * upcase table if necessary.
2994      */
2995     mutex_lock(&ntfs_lock);
2996     if (!--ntfs_nr_upcase_users && default_upcase) {
2997         ntfs_free(default_upcase);
2998         default_upcase = NULL;
2999     }
3000     if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
3001         free_compression_buffers();
3002     mutex_unlock(&ntfs_lock);
3003 iput_tmp_ino_err_out_now:
3004     iput(tmp_ino);
3005     if (vol->mft_ino && vol->mft_ino != tmp_ino)
3006         iput(vol->mft_ino);
3007     vol->mft_ino = NULL;
3008     /* Errors at this stage are irrelevant. */
3009 err_out_now:
3010     sb->s_fs_info = NULL;
3011     kfree(vol);
3012     ntfs_debug("Failed, returning -EINVAL.");
3013     lockdep_on();
3014     return -EINVAL;
3015 }
3016 
3017 /*
3018  * This is a slab cache to optimize allocations and deallocations of Unicode
3019  * strings of the maximum length allowed by NTFS, which is NTFS_MAX_NAME_LEN
3020  * (255) Unicode characters + a terminating NULL Unicode character.
3021  */
3022 struct kmem_cache *ntfs_name_cache;
3023 
3024 /* Slab caches for efficient allocation/deallocation of inodes. */
3025 struct kmem_cache *ntfs_inode_cache;
3026 struct kmem_cache *ntfs_big_inode_cache;
3027 
3028 /* Init once constructor for the inode slab cache. */
3029 static void ntfs_big_inode_init_once(void *foo)
3030 {
3031     ntfs_inode *ni = (ntfs_inode *)foo;
3032 
3033     inode_init_once(VFS_I(ni));
3034 }
3035 
3036 /*
3037  * Slab caches to optimize allocations and deallocations of attribute search
3038  * contexts and index contexts, respectively.
3039  */
3040 struct kmem_cache *ntfs_attr_ctx_cache;
3041 struct kmem_cache *ntfs_index_ctx_cache;
3042 
3043 /* Driver wide mutex. */
3044 DEFINE_MUTEX(ntfs_lock);
3045 
3046 static struct dentry *ntfs_mount(struct file_system_type *fs_type,
3047     int flags, const char *dev_name, void *data)
3048 {
3049     return mount_bdev(fs_type, flags, dev_name, data, ntfs_fill_super);
3050 }
3051 
3052 static struct file_system_type ntfs_fs_type = {
3053     .owner      = THIS_MODULE,
3054     .name       = "ntfs",
3055     .mount      = ntfs_mount,
3056     .kill_sb    = kill_block_super,
3057     .fs_flags   = FS_REQUIRES_DEV,
3058 };
3059 MODULE_ALIAS_FS("ntfs");
3060 
3061 /* Stable names for the slab caches. */
3062 static const char ntfs_index_ctx_cache_name[] = "ntfs_index_ctx_cache";
3063 static const char ntfs_attr_ctx_cache_name[] = "ntfs_attr_ctx_cache";
3064 static const char ntfs_name_cache_name[] = "ntfs_name_cache";
3065 static const char ntfs_inode_cache_name[] = "ntfs_inode_cache";
3066 static const char ntfs_big_inode_cache_name[] = "ntfs_big_inode_cache";
3067 
3068 static int __init init_ntfs_fs(void)
3069 {
3070     int err = 0;
3071 
3072     /* This may be ugly but it results in pretty output so who cares. (-8 */
3073     pr_info("driver " NTFS_VERSION " [Flags: R/"
3074 #ifdef NTFS_RW
3075             "W"
3076 #else
3077             "O"
3078 #endif
3079 #ifdef DEBUG
3080             " DEBUG"
3081 #endif
3082 #ifdef MODULE
3083             " MODULE"
3084 #endif
3085             "].\n");
3086 
3087     ntfs_debug("Debug messages are enabled.");
3088 
3089     ntfs_index_ctx_cache = kmem_cache_create(ntfs_index_ctx_cache_name,
3090             sizeof(ntfs_index_context), 0 /* offset */,
3091             SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3092     if (!ntfs_index_ctx_cache) {
3093         pr_crit("Failed to create %s!\n", ntfs_index_ctx_cache_name);
3094         goto ictx_err_out;
3095     }
3096     ntfs_attr_ctx_cache = kmem_cache_create(ntfs_attr_ctx_cache_name,
3097             sizeof(ntfs_attr_search_ctx), 0 /* offset */,
3098             SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3099     if (!ntfs_attr_ctx_cache) {
3100         pr_crit("NTFS: Failed to create %s!\n",
3101             ntfs_attr_ctx_cache_name);
3102         goto actx_err_out;
3103     }
3104 
3105     ntfs_name_cache = kmem_cache_create(ntfs_name_cache_name,
3106             (NTFS_MAX_NAME_LEN+1) * sizeof(ntfschar), 0,
3107             SLAB_HWCACHE_ALIGN, NULL);
3108     if (!ntfs_name_cache) {
3109         pr_crit("Failed to create %s!\n", ntfs_name_cache_name);
3110         goto name_err_out;
3111     }
3112 
3113     ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
3114             sizeof(ntfs_inode), 0,
3115             SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD, NULL);
3116     if (!ntfs_inode_cache) {
3117         pr_crit("Failed to create %s!\n", ntfs_inode_cache_name);
3118         goto inode_err_out;
3119     }
3120 
3121     ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
3122             sizeof(big_ntfs_inode), 0,
3123             SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
3124             SLAB_ACCOUNT, ntfs_big_inode_init_once);
3125     if (!ntfs_big_inode_cache) {
3126         pr_crit("Failed to create %s!\n", ntfs_big_inode_cache_name);
3127         goto big_inode_err_out;
3128     }
3129 
3130     /* Register the ntfs sysctls. */
3131     err = ntfs_sysctl(1);
3132     if (err) {
3133         pr_crit("Failed to register NTFS sysctls!\n");
3134         goto sysctl_err_out;
3135     }
3136 
3137     err = register_filesystem(&ntfs_fs_type);
3138     if (!err) {
3139         ntfs_debug("NTFS driver registered successfully.");
3140         return 0; /* Success! */
3141     }
3142     pr_crit("Failed to register NTFS filesystem driver!\n");
3143 
3144     /* Unregister the ntfs sysctls. */
3145     ntfs_sysctl(0);
3146 sysctl_err_out:
3147     kmem_cache_destroy(ntfs_big_inode_cache);
3148 big_inode_err_out:
3149     kmem_cache_destroy(ntfs_inode_cache);
3150 inode_err_out:
3151     kmem_cache_destroy(ntfs_name_cache);
3152 name_err_out:
3153     kmem_cache_destroy(ntfs_attr_ctx_cache);
3154 actx_err_out:
3155     kmem_cache_destroy(ntfs_index_ctx_cache);
3156 ictx_err_out:
3157     if (!err) {
3158         pr_crit("Aborting NTFS filesystem driver registration...\n");
3159         err = -ENOMEM;
3160     }
3161     return err;
3162 }
3163 
3164 static void __exit exit_ntfs_fs(void)
3165 {
3166     ntfs_debug("Unregistering NTFS driver.");
3167 
3168     unregister_filesystem(&ntfs_fs_type);
3169 
3170     /*
3171      * Make sure all delayed rcu free inodes are flushed before we
3172      * destroy cache.
3173      */
3174     rcu_barrier();
3175     kmem_cache_destroy(ntfs_big_inode_cache);
3176     kmem_cache_destroy(ntfs_inode_cache);
3177     kmem_cache_destroy(ntfs_name_cache);
3178     kmem_cache_destroy(ntfs_attr_ctx_cache);
3179     kmem_cache_destroy(ntfs_index_ctx_cache);
3180     /* Unregister the ntfs sysctls. */
3181     ntfs_sysctl(0);
3182 }
3183 
3184 MODULE_AUTHOR("Anton Altaparmakov <anton@tuxera.com>");
3185 MODULE_DESCRIPTION("NTFS 1.2/3.x driver - Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc.");
3186 MODULE_VERSION(NTFS_VERSION);
3187 MODULE_LICENSE("GPL");
3188 #ifdef DEBUG
3189 module_param(debug_msgs, bint, 0);
3190 MODULE_PARM_DESC(debug_msgs, "Enable debug messages.");
3191 #endif
3192 
3193 module_init(init_ntfs_fs)
3194 module_exit(exit_ntfs_fs)