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