]> Pileus Git - ~andy/linux/blob - fs/ntfs/super.c
NTFS: Fix a bug in address space operations error recovery code paths where
[~andy/linux] / 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 /**
1160  * load_and_init_quota - load and setup the quota file for a volume if present
1161  * @vol:        ntfs super block describing device whose quota file to load
1162  *
1163  * Return TRUE on success or FALSE on error.  If $Quota is not present, we
1164  * leave vol->quota_ino as NULL and return success.
1165  */
1166 static BOOL load_and_init_quota(ntfs_volume *vol)
1167 {
1168         MFT_REF mref;
1169         struct inode *tmp_ino;
1170         ntfs_name *name = NULL;
1171         static const ntfschar Quota[7] = { const_cpu_to_le16('$'),
1172                         const_cpu_to_le16('Q'), const_cpu_to_le16('u'),
1173                         const_cpu_to_le16('o'), const_cpu_to_le16('t'),
1174                         const_cpu_to_le16('a'), 0 };
1175         static ntfschar Q[3] = { const_cpu_to_le16('$'),
1176                         const_cpu_to_le16('Q'), 0 };
1177
1178         ntfs_debug("Entering.");
1179         /*
1180          * Find the inode number for the quota file by looking up the filename
1181          * $Quota in the extended system files directory $Extend.
1182          */
1183         down(&vol->extend_ino->i_sem);
1184         mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), Quota, 6,
1185                         &name);
1186         up(&vol->extend_ino->i_sem);
1187         if (IS_ERR_MREF(mref)) {
1188                 /*
1189                  * If the file does not exist, quotas are disabled and have
1190                  * never been enabled on this volume, just return success.
1191                  */
1192                 if (MREF_ERR(mref) == -ENOENT) {
1193                         ntfs_debug("$Quota not present.  Volume does not have "
1194                                         "quotas enabled.");
1195                         /*
1196                          * No need to try to set quotas out of date if they are
1197                          * not enabled.
1198                          */
1199                         NVolSetQuotaOutOfDate(vol);
1200                         return TRUE;
1201                 }
1202                 /* A real error occured. */
1203                 ntfs_error(vol->sb, "Failed to find inode number for $Quota.");
1204                 return FALSE;
1205         }
1206         /* We do not care for the type of match that was found. */
1207         kfree(name);
1208         /* Get the inode. */
1209         tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1210         if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
1211                 if (!IS_ERR(tmp_ino))
1212                         iput(tmp_ino);
1213                 ntfs_error(vol->sb, "Failed to load $Quota.");
1214                 return FALSE;
1215         }
1216         vol->quota_ino = tmp_ino;
1217         /* Get the $Q index allocation attribute. */
1218         tmp_ino = ntfs_index_iget(vol->quota_ino, Q, 2);
1219         if (IS_ERR(tmp_ino)) {
1220                 ntfs_error(vol->sb, "Failed to load $Quota/$Q index.");
1221                 return FALSE;
1222         }
1223         vol->quota_q_ino = tmp_ino;
1224         ntfs_debug("Done.");
1225         return TRUE;
1226 }
1227
1228 /**
1229  * load_and_init_usnjrnl - load and setup the transaction log if present
1230  * @vol:        ntfs super block describing device whose usnjrnl file to load
1231  *
1232  * Return TRUE on success or FALSE on error.
1233  *
1234  * If $UsnJrnl is not present or in the process of being disabled, we set
1235  * NVolUsnJrnlStamped() and return success.
1236  *
1237  * If the $UsnJrnl $DATA/$J attribute has a size equal to the lowest valid usn,
1238  * i.e. transaction logging has only just been enabled or the journal has been
1239  * stamped and nothing has been logged since, we also set NVolUsnJrnlStamped()
1240  * and return success.
1241  */
1242 static BOOL load_and_init_usnjrnl(ntfs_volume *vol)
1243 {
1244         MFT_REF mref;
1245         struct inode *tmp_ino;
1246         ntfs_inode *tmp_ni;
1247         struct page *page;
1248         ntfs_name *name = NULL;
1249         USN_HEADER *uh;
1250         static const ntfschar UsnJrnl[9] = { const_cpu_to_le16('$'),
1251                         const_cpu_to_le16('U'), const_cpu_to_le16('s'),
1252                         const_cpu_to_le16('n'), const_cpu_to_le16('J'),
1253                         const_cpu_to_le16('r'), const_cpu_to_le16('n'),
1254                         const_cpu_to_le16('l'), 0 };
1255         static ntfschar Max[5] = { const_cpu_to_le16('$'),
1256                         const_cpu_to_le16('M'), const_cpu_to_le16('a'),
1257                         const_cpu_to_le16('x'), 0 };
1258         static ntfschar J[3] = { const_cpu_to_le16('$'),
1259                         const_cpu_to_le16('J'), 0 };
1260
1261         ntfs_debug("Entering.");
1262         /*
1263          * Find the inode number for the transaction log file by looking up the
1264          * filename $UsnJrnl in the extended system files directory $Extend.
1265          */
1266         down(&vol->extend_ino->i_sem);
1267         mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), UsnJrnl, 8,
1268                         &name);
1269         up(&vol->extend_ino->i_sem);
1270         if (IS_ERR_MREF(mref)) {
1271                 /*
1272                  * If the file does not exist, transaction logging is disabled,
1273                  * just return success.
1274                  */
1275                 if (MREF_ERR(mref) == -ENOENT) {
1276                         ntfs_debug("$UsnJrnl not present.  Volume does not "
1277                                         "have transaction logging enabled.");
1278 not_enabled:
1279                         /*
1280                          * No need to try to stamp the transaction log if
1281                          * transaction logging is not enabled.
1282                          */
1283                         NVolSetUsnJrnlStamped(vol);
1284                         return TRUE;
1285                 }
1286                 /* A real error occured. */
1287                 ntfs_error(vol->sb, "Failed to find inode number for "
1288                                 "$UsnJrnl.");
1289                 return FALSE;
1290         }
1291         /* We do not care for the type of match that was found. */
1292         kfree(name);
1293         /* Get the inode. */
1294         tmp_ino = ntfs_iget(vol->sb, MREF(mref));
1295         if (unlikely(IS_ERR(tmp_ino) || is_bad_inode(tmp_ino))) {
1296                 if (!IS_ERR(tmp_ino))
1297                         iput(tmp_ino);
1298                 ntfs_error(vol->sb, "Failed to load $UsnJrnl.");
1299                 return FALSE;
1300         }
1301         vol->usnjrnl_ino = tmp_ino;
1302         /*
1303          * If the transaction log is in the process of being deleted, we can
1304          * ignore it.
1305          */
1306         if (unlikely(vol->vol_flags & VOLUME_DELETE_USN_UNDERWAY)) {
1307                 ntfs_debug("$UsnJrnl in the process of being disabled.  "
1308                                 "Volume does not have transaction logging "
1309                                 "enabled.");
1310                 goto not_enabled;
1311         }
1312         /* Get the $DATA/$Max attribute. */
1313         tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, Max, 4);
1314         if (IS_ERR(tmp_ino)) {
1315                 ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$Max "
1316                                 "attribute.");
1317                 return FALSE;
1318         }
1319         vol->usnjrnl_max_ino = tmp_ino;
1320         if (unlikely(i_size_read(tmp_ino) < sizeof(USN_HEADER))) {
1321                 ntfs_error(vol->sb, "Found corrupt $UsnJrnl/$DATA/$Max "
1322                                 "attribute (size is 0x%llx but should be at "
1323                                 "least 0x%x bytes).", i_size_read(tmp_ino),
1324                                 sizeof(USN_HEADER));
1325                 return FALSE;
1326         }
1327         /* Get the $DATA/$J attribute. */
1328         tmp_ino = ntfs_attr_iget(vol->usnjrnl_ino, AT_DATA, J, 2);
1329         if (IS_ERR(tmp_ino)) {
1330                 ntfs_error(vol->sb, "Failed to load $UsnJrnl/$DATA/$J "
1331                                 "attribute.");
1332                 return FALSE;
1333         }
1334         vol->usnjrnl_j_ino = tmp_ino;
1335         /* Verify $J is non-resident and sparse. */
1336         tmp_ni = NTFS_I(vol->usnjrnl_j_ino);
1337         if (unlikely(!NInoNonResident(tmp_ni) || !NInoSparse(tmp_ni))) {
1338                 ntfs_error(vol->sb, "$UsnJrnl/$DATA/$J attribute is resident "
1339                                 "and/or not sparse.");
1340                 return FALSE;
1341         }
1342         /* Read the USN_HEADER from $DATA/$Max. */
1343         page = ntfs_map_page(vol->usnjrnl_max_ino->i_mapping, 0);
1344         if (IS_ERR(page)) {
1345                 ntfs_error(vol->sb, "Failed to read from $UsnJrnl/$DATA/$Max "
1346                                 "attribute.");
1347                 return FALSE;
1348         }
1349         uh = (USN_HEADER*)page_address(page);
1350         /* Sanity check the $Max. */
1351         if (unlikely(sle64_to_cpu(uh->allocation_delta) >
1352                         sle64_to_cpu(uh->maximum_size))) {
1353                 ntfs_error(vol->sb, "Allocation delta (0x%llx) exceeds "
1354                                 "maximum size (0x%llx).  $UsnJrnl is corrupt.",
1355                                 (long long)sle64_to_cpu(uh->allocation_delta),
1356                                 (long long)sle64_to_cpu(uh->maximum_size));
1357                 ntfs_unmap_page(page);
1358                 return FALSE;
1359         }
1360         /*
1361          * If the transaction log has been stamped and nothing has been written
1362          * to it since, we do not need to stamp it.
1363          */
1364         if (unlikely(sle64_to_cpu(uh->lowest_valid_usn) >=
1365                         i_size_read(vol->usnjrnl_j_ino))) {
1366                 if (likely(sle64_to_cpu(uh->lowest_valid_usn) ==
1367                                 i_size_read(vol->usnjrnl_j_ino))) {
1368                         ntfs_unmap_page(page);
1369                         ntfs_debug("$UsnJrnl is enabled but nothing has been "
1370                                         "logged since it was last stamped.  "
1371                                         "Treating this as if the volume does "
1372                                         "not have transaction logging "
1373                                         "enabled.");
1374                         goto not_enabled;
1375                 }
1376                 ntfs_error(vol->sb, "$UsnJrnl has lowest valid usn (0x%llx) "
1377                                 "which is out of bounds (0x%llx).  $UsnJrnl "
1378                                 "is corrupt.",
1379                                 (long long)sle64_to_cpu(uh->lowest_valid_usn),
1380                                 i_size_read(vol->usnjrnl_j_ino));
1381                 ntfs_unmap_page(page);
1382                 return FALSE;
1383         }
1384         ntfs_unmap_page(page);
1385         ntfs_debug("Done.");
1386         return TRUE;
1387 }
1388
1389 /**
1390  * load_and_init_attrdef - load the attribute definitions table for a volume
1391  * @vol:        ntfs super block describing device whose attrdef to load
1392  *
1393  * Return TRUE on success or FALSE on error.
1394  */
1395 static BOOL load_and_init_attrdef(ntfs_volume *vol)
1396 {
1397         loff_t i_size;
1398         struct super_block *sb = vol->sb;
1399         struct inode *ino;
1400         struct page *page;
1401         pgoff_t index, max_index;
1402         unsigned int size;
1403
1404         ntfs_debug("Entering.");
1405         /* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */
1406         ino = ntfs_iget(sb, FILE_AttrDef);
1407         if (IS_ERR(ino) || is_bad_inode(ino)) {
1408                 if (!IS_ERR(ino))
1409                         iput(ino);
1410                 goto failed;
1411         }
1412         NInoSetSparseDisabled(NTFS_I(ino));
1413         /* The size of FILE_AttrDef must be above 0 and fit inside 31 bits. */
1414         i_size = i_size_read(ino);
1415         if (i_size <= 0 || i_size > 0x7fffffff)
1416                 goto iput_failed;
1417         vol->attrdef = (ATTR_DEF*)ntfs_malloc_nofs(i_size);
1418         if (!vol->attrdef)
1419                 goto iput_failed;
1420         index = 0;
1421         max_index = i_size >> PAGE_CACHE_SHIFT;
1422         size = PAGE_CACHE_SIZE;
1423         while (index < max_index) {
1424                 /* Read the attrdef table and copy it into the linear buffer. */
1425 read_partial_attrdef_page:
1426                 page = ntfs_map_page(ino->i_mapping, index);
1427                 if (IS_ERR(page))
1428                         goto free_iput_failed;
1429                 memcpy((u8*)vol->attrdef + (index++ << PAGE_CACHE_SHIFT),
1430                                 page_address(page), size);
1431                 ntfs_unmap_page(page);
1432         };
1433         if (size == PAGE_CACHE_SIZE) {
1434                 size = i_size & ~PAGE_CACHE_MASK;
1435                 if (size)
1436                         goto read_partial_attrdef_page;
1437         }
1438         vol->attrdef_size = i_size;
1439         ntfs_debug("Read %llu bytes from $AttrDef.", i_size);
1440         iput(ino);
1441         return TRUE;
1442 free_iput_failed:
1443         ntfs_free(vol->attrdef);
1444         vol->attrdef = NULL;
1445 iput_failed:
1446         iput(ino);
1447 failed:
1448         ntfs_error(sb, "Failed to initialize attribute definition table.");
1449         return FALSE;
1450 }
1451
1452 #endif /* NTFS_RW */
1453
1454 /**
1455  * load_and_init_upcase - load the upcase table for an ntfs volume
1456  * @vol:        ntfs super block describing device whose upcase to load
1457  *
1458  * Return TRUE on success or FALSE on error.
1459  */
1460 static BOOL load_and_init_upcase(ntfs_volume *vol)
1461 {
1462         loff_t i_size;
1463         struct super_block *sb = vol->sb;
1464         struct inode *ino;
1465         struct page *page;
1466         pgoff_t index, max_index;
1467         unsigned int size;
1468         int i, max;
1469
1470         ntfs_debug("Entering.");
1471         /* Read upcase table and setup vol->upcase and vol->upcase_len. */
1472         ino = ntfs_iget(sb, FILE_UpCase);
1473         if (IS_ERR(ino) || is_bad_inode(ino)) {
1474                 if (!IS_ERR(ino))
1475                         iput(ino);
1476                 goto upcase_failed;
1477         }
1478         /*
1479          * The upcase size must not be above 64k Unicode characters, must not
1480          * be zero and must be a multiple of sizeof(ntfschar).
1481          */
1482         i_size = i_size_read(ino);
1483         if (!i_size || i_size & (sizeof(ntfschar) - 1) ||
1484                         i_size > 64ULL * 1024 * sizeof(ntfschar))
1485                 goto iput_upcase_failed;
1486         vol->upcase = (ntfschar*)ntfs_malloc_nofs(i_size);
1487         if (!vol->upcase)
1488                 goto iput_upcase_failed;
1489         index = 0;
1490         max_index = i_size >> PAGE_CACHE_SHIFT;
1491         size = PAGE_CACHE_SIZE;
1492         while (index < max_index) {
1493                 /* Read the upcase table and copy it into the linear buffer. */
1494 read_partial_upcase_page:
1495                 page = ntfs_map_page(ino->i_mapping, index);
1496                 if (IS_ERR(page))
1497                         goto iput_upcase_failed;
1498                 memcpy((char*)vol->upcase + (index++ << PAGE_CACHE_SHIFT),
1499                                 page_address(page), size);
1500                 ntfs_unmap_page(page);
1501         };
1502         if (size == PAGE_CACHE_SIZE) {
1503                 size = i_size & ~PAGE_CACHE_MASK;
1504                 if (size)
1505                         goto read_partial_upcase_page;
1506         }
1507         vol->upcase_len = i_size >> UCHAR_T_SIZE_BITS;
1508         ntfs_debug("Read %llu bytes from $UpCase (expected %zu bytes).",
1509                         i_size, 64 * 1024 * sizeof(ntfschar));
1510         iput(ino);
1511         down(&ntfs_lock);
1512         if (!default_upcase) {
1513                 ntfs_debug("Using volume specified $UpCase since default is "
1514                                 "not present.");
1515                 up(&ntfs_lock);
1516                 return TRUE;
1517         }
1518         max = default_upcase_len;
1519         if (max > vol->upcase_len)
1520                 max = vol->upcase_len;
1521         for (i = 0; i < max; i++)
1522                 if (vol->upcase[i] != default_upcase[i])
1523                         break;
1524         if (i == max) {
1525                 ntfs_free(vol->upcase);
1526                 vol->upcase = default_upcase;
1527                 vol->upcase_len = max;
1528                 ntfs_nr_upcase_users++;
1529                 up(&ntfs_lock);
1530                 ntfs_debug("Volume specified $UpCase matches default. Using "
1531                                 "default.");
1532                 return TRUE;
1533         }
1534         up(&ntfs_lock);
1535         ntfs_debug("Using volume specified $UpCase since it does not match "
1536                         "the default.");
1537         return TRUE;
1538 iput_upcase_failed:
1539         iput(ino);
1540         ntfs_free(vol->upcase);
1541         vol->upcase = NULL;
1542 upcase_failed:
1543         down(&ntfs_lock);
1544         if (default_upcase) {
1545                 vol->upcase = default_upcase;
1546                 vol->upcase_len = default_upcase_len;
1547                 ntfs_nr_upcase_users++;
1548                 up(&ntfs_lock);
1549                 ntfs_error(sb, "Failed to load $UpCase from the volume. Using "
1550                                 "default.");
1551                 return TRUE;
1552         }
1553         up(&ntfs_lock);
1554         ntfs_error(sb, "Failed to initialize upcase table.");
1555         return FALSE;
1556 }
1557
1558 /**
1559  * load_system_files - open the system files using normal functions
1560  * @vol:        ntfs super block describing device whose system files to load
1561  *
1562  * Open the system files with normal access functions and complete setting up
1563  * the ntfs super block @vol.
1564  *
1565  * Return TRUE on success or FALSE on error.
1566  */
1567 static BOOL load_system_files(ntfs_volume *vol)
1568 {
1569         struct super_block *sb = vol->sb;
1570         MFT_RECORD *m;
1571         VOLUME_INFORMATION *vi;
1572         ntfs_attr_search_ctx *ctx;
1573
1574         ntfs_debug("Entering.");
1575 #ifdef NTFS_RW
1576         /* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */
1577         if (!load_and_init_mft_mirror(vol) || !check_mft_mirror(vol)) {
1578                 static const char *es1 = "Failed to load $MFTMirr";
1579                 static const char *es2 = "$MFTMirr does not match $MFT";
1580                 static const char *es3 = ".  Run ntfsfix and/or chkdsk.";
1581
1582                 /* If a read-write mount, convert it to a read-only mount. */
1583                 if (!(sb->s_flags & MS_RDONLY)) {
1584                         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1585                                         ON_ERRORS_CONTINUE))) {
1586                                 ntfs_error(sb, "%s and neither on_errors="
1587                                                 "continue nor on_errors="
1588                                                 "remount-ro was specified%s",
1589                                                 !vol->mftmirr_ino ? es1 : es2,
1590                                                 es3);
1591                                 goto iput_mirr_err_out;
1592                         }
1593                         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1594                         ntfs_error(sb, "%s.  Mounting read-only%s",
1595                                         !vol->mftmirr_ino ? es1 : es2, es3);
1596                 } else
1597                         ntfs_warning(sb, "%s.  Will not be able to remount "
1598                                         "read-write%s",
1599                                         !vol->mftmirr_ino ? es1 : es2, es3);
1600                 /* This will prevent a read-write remount. */
1601                 NVolSetErrors(vol);
1602         }
1603 #endif /* NTFS_RW */
1604         /* Get mft bitmap attribute inode. */
1605         vol->mftbmp_ino = ntfs_attr_iget(vol->mft_ino, AT_BITMAP, NULL, 0);
1606         if (IS_ERR(vol->mftbmp_ino)) {
1607                 ntfs_error(sb, "Failed to load $MFT/$BITMAP attribute.");
1608                 goto iput_mirr_err_out;
1609         }
1610         /* Read upcase table and setup @vol->upcase and @vol->upcase_len. */
1611         if (!load_and_init_upcase(vol))
1612                 goto iput_mftbmp_err_out;
1613 #ifdef NTFS_RW
1614         /*
1615          * Read attribute definitions table and setup @vol->attrdef and
1616          * @vol->attrdef_size.
1617          */
1618         if (!load_and_init_attrdef(vol))
1619                 goto iput_upcase_err_out;
1620 #endif /* NTFS_RW */
1621         /*
1622          * Get the cluster allocation bitmap inode and verify the size, no
1623          * need for any locking at this stage as we are already running
1624          * exclusively as we are mount in progress task.
1625          */
1626         vol->lcnbmp_ino = ntfs_iget(sb, FILE_Bitmap);
1627         if (IS_ERR(vol->lcnbmp_ino) || is_bad_inode(vol->lcnbmp_ino)) {
1628                 if (!IS_ERR(vol->lcnbmp_ino))
1629                         iput(vol->lcnbmp_ino);
1630                 goto bitmap_failed;
1631         }
1632         NInoSetSparseDisabled(NTFS_I(vol->lcnbmp_ino));
1633         if ((vol->nr_clusters + 7) >> 3 > i_size_read(vol->lcnbmp_ino)) {
1634                 iput(vol->lcnbmp_ino);
1635 bitmap_failed:
1636                 ntfs_error(sb, "Failed to load $Bitmap.");
1637                 goto iput_attrdef_err_out;
1638         }
1639         /*
1640          * Get the volume inode and setup our cache of the volume flags and
1641          * version.
1642          */
1643         vol->vol_ino = ntfs_iget(sb, FILE_Volume);
1644         if (IS_ERR(vol->vol_ino) || is_bad_inode(vol->vol_ino)) {
1645                 if (!IS_ERR(vol->vol_ino))
1646                         iput(vol->vol_ino);
1647 volume_failed:
1648                 ntfs_error(sb, "Failed to load $Volume.");
1649                 goto iput_lcnbmp_err_out;
1650         }
1651         m = map_mft_record(NTFS_I(vol->vol_ino));
1652         if (IS_ERR(m)) {
1653 iput_volume_failed:
1654                 iput(vol->vol_ino);
1655                 goto volume_failed;
1656         }
1657         if (!(ctx = ntfs_attr_get_search_ctx(NTFS_I(vol->vol_ino), m))) {
1658                 ntfs_error(sb, "Failed to get attribute search context.");
1659                 goto get_ctx_vol_failed;
1660         }
1661         if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
1662                         ctx) || ctx->attr->non_resident || ctx->attr->flags) {
1663 err_put_vol:
1664                 ntfs_attr_put_search_ctx(ctx);
1665 get_ctx_vol_failed:
1666                 unmap_mft_record(NTFS_I(vol->vol_ino));
1667                 goto iput_volume_failed;
1668         }
1669         vi = (VOLUME_INFORMATION*)((char*)ctx->attr +
1670                         le16_to_cpu(ctx->attr->data.resident.value_offset));
1671         /* Some bounds checks. */
1672         if ((u8*)vi < (u8*)ctx->attr || (u8*)vi +
1673                         le32_to_cpu(ctx->attr->data.resident.value_length) >
1674                         (u8*)ctx->attr + le32_to_cpu(ctx->attr->length))
1675                 goto err_put_vol;
1676         /* Copy the volume flags and version to the ntfs_volume structure. */
1677         vol->vol_flags = vi->flags;
1678         vol->major_ver = vi->major_ver;
1679         vol->minor_ver = vi->minor_ver;
1680         ntfs_attr_put_search_ctx(ctx);
1681         unmap_mft_record(NTFS_I(vol->vol_ino));
1682         printk(KERN_INFO "NTFS volume version %i.%i.\n", vol->major_ver,
1683                         vol->minor_ver);
1684         if (vol->major_ver < 3 && NVolSparseEnabled(vol)) {
1685                 ntfs_warning(vol->sb, "Disabling sparse support due to NTFS "
1686                                 "volume version %i.%i (need at least version "
1687                                 "3.0).", vol->major_ver, vol->minor_ver);
1688                 NVolClearSparseEnabled(vol);
1689         }
1690 #ifdef NTFS_RW
1691         /* Make sure that no unsupported volume flags are set. */
1692         if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
1693                 static const char *es1a = "Volume is dirty";
1694                 static const char *es1b = "Volume has unsupported flags set";
1695                 static const char *es2 = ".  Run chkdsk and mount in Windows.";
1696                 const char *es1;
1697                 
1698                 es1 = vol->vol_flags & VOLUME_IS_DIRTY ? es1a : es1b;
1699                 /* If a read-write mount, convert it to a read-only mount. */
1700                 if (!(sb->s_flags & MS_RDONLY)) {
1701                         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1702                                         ON_ERRORS_CONTINUE))) {
1703                                 ntfs_error(sb, "%s and neither on_errors="
1704                                                 "continue nor on_errors="
1705                                                 "remount-ro was specified%s",
1706                                                 es1, es2);
1707                                 goto iput_vol_err_out;
1708                         }
1709                         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1710                         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1711                 } else
1712                         ntfs_warning(sb, "%s.  Will not be able to remount "
1713                                         "read-write%s", es1, es2);
1714                 /*
1715                  * Do not set NVolErrors() because ntfs_remount() re-checks the
1716                  * flags which we need to do in case any flags have changed.
1717                  */
1718         }
1719         /*
1720          * Get the inode for the logfile, check it and determine if the volume
1721          * was shutdown cleanly.
1722          */
1723         if (!load_and_check_logfile(vol) ||
1724                         !ntfs_is_logfile_clean(vol->logfile_ino)) {
1725                 static const char *es1a = "Failed to load $LogFile";
1726                 static const char *es1b = "$LogFile is not clean";
1727                 static const char *es2 = ".  Mount in Windows.";
1728                 const char *es1;
1729
1730                 es1 = !vol->logfile_ino ? es1a : es1b;
1731                 /* If a read-write mount, convert it to a read-only mount. */
1732                 if (!(sb->s_flags & MS_RDONLY)) {
1733                         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1734                                         ON_ERRORS_CONTINUE))) {
1735                                 ntfs_error(sb, "%s and neither on_errors="
1736                                                 "continue nor on_errors="
1737                                                 "remount-ro was specified%s",
1738                                                 es1, es2);
1739                                 goto iput_logfile_err_out;
1740                         }
1741                         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1742                         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1743                 } else
1744                         ntfs_warning(sb, "%s.  Will not be able to remount "
1745                                         "read-write%s", es1, es2);
1746                 /* This will prevent a read-write remount. */
1747                 NVolSetErrors(vol);
1748         }
1749         /* If (still) a read-write mount, mark the volume dirty. */
1750         if (!(sb->s_flags & MS_RDONLY) &&
1751                         ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
1752                 static const char *es1 = "Failed to set dirty bit in volume "
1753                                 "information flags";
1754                 static const char *es2 = ".  Run chkdsk.";
1755
1756                 /* Convert to a read-only mount. */
1757                 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1758                                 ON_ERRORS_CONTINUE))) {
1759                         ntfs_error(sb, "%s and neither on_errors=continue nor "
1760                                         "on_errors=remount-ro was specified%s",
1761                                         es1, es2);
1762                         goto iput_logfile_err_out;
1763                 }
1764                 ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1765                 sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1766                 /*
1767                  * Do not set NVolErrors() because ntfs_remount() might manage
1768                  * to set the dirty flag in which case all would be well.
1769                  */
1770         }
1771 #if 0
1772         // TODO: Enable this code once we start modifying anything that is
1773         //       different between NTFS 1.2 and 3.x...
1774         /*
1775          * If (still) a read-write mount, set the NT4 compatibility flag on
1776          * newer NTFS version volumes.
1777          */
1778         if (!(sb->s_flags & MS_RDONLY) && (vol->major_ver > 1) &&
1779                         ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
1780                 static const char *es1 = "Failed to set NT4 compatibility flag";
1781                 static const char *es2 = ".  Run chkdsk.";
1782
1783                 /* Convert to a read-only mount. */
1784                 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1785                                 ON_ERRORS_CONTINUE))) {
1786                         ntfs_error(sb, "%s and neither on_errors=continue nor "
1787                                         "on_errors=remount-ro was specified%s",
1788                                         es1, es2);
1789                         goto iput_logfile_err_out;
1790                 }
1791                 ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1792                 sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1793                 NVolSetErrors(vol);
1794         }
1795 #endif
1796         /* If (still) a read-write mount, empty the logfile. */
1797         if (!(sb->s_flags & MS_RDONLY) &&
1798                         !ntfs_empty_logfile(vol->logfile_ino)) {
1799                 static const char *es1 = "Failed to empty $LogFile";
1800                 static const char *es2 = ".  Mount in Windows.";
1801
1802                 /* Convert to a read-only mount. */
1803                 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1804                                 ON_ERRORS_CONTINUE))) {
1805                         ntfs_error(sb, "%s and neither on_errors=continue nor "
1806                                         "on_errors=remount-ro was specified%s",
1807                                         es1, es2);
1808                         goto iput_logfile_err_out;
1809                 }
1810                 ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1811                 sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1812                 NVolSetErrors(vol);
1813         }
1814 #endif /* NTFS_RW */
1815         /* Get the root directory inode. */
1816         vol->root_ino = ntfs_iget(sb, FILE_root);
1817         if (IS_ERR(vol->root_ino) || is_bad_inode(vol->root_ino)) {
1818                 if (!IS_ERR(vol->root_ino))
1819                         iput(vol->root_ino);
1820                 ntfs_error(sb, "Failed to load root directory.");
1821                 goto iput_logfile_err_out;
1822         }
1823         /* If on NTFS versions before 3.0, we are done. */
1824         if (unlikely(vol->major_ver < 3))
1825                 return TRUE;
1826         /* NTFS 3.0+ specific initialization. */
1827         /* Get the security descriptors inode. */
1828         vol->secure_ino = ntfs_iget(sb, FILE_Secure);
1829         if (IS_ERR(vol->secure_ino) || is_bad_inode(vol->secure_ino)) {
1830                 if (!IS_ERR(vol->secure_ino))
1831                         iput(vol->secure_ino);
1832                 ntfs_error(sb, "Failed to load $Secure.");
1833                 goto iput_root_err_out;
1834         }
1835         // TODO: Initialize security.
1836         /* Get the extended system files' directory inode. */
1837         vol->extend_ino = ntfs_iget(sb, FILE_Extend);
1838         if (IS_ERR(vol->extend_ino) || is_bad_inode(vol->extend_ino)) {
1839                 if (!IS_ERR(vol->extend_ino))
1840                         iput(vol->extend_ino);
1841                 ntfs_error(sb, "Failed to load $Extend.");
1842                 goto iput_sec_err_out;
1843         }
1844 #ifdef NTFS_RW
1845         /* Find the quota file, load it if present, and set it up. */
1846         if (!load_and_init_quota(vol)) {
1847                 static const char *es1 = "Failed to load $Quota";
1848                 static const char *es2 = ".  Run chkdsk.";
1849
1850                 /* If a read-write mount, convert it to a read-only mount. */
1851                 if (!(sb->s_flags & MS_RDONLY)) {
1852                         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1853                                         ON_ERRORS_CONTINUE))) {
1854                                 ntfs_error(sb, "%s and neither on_errors="
1855                                                 "continue nor on_errors="
1856                                                 "remount-ro was specified%s",
1857                                                 es1, es2);
1858                                 goto iput_quota_err_out;
1859                         }
1860                         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1861                         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1862                 } else
1863                         ntfs_warning(sb, "%s.  Will not be able to remount "
1864                                         "read-write%s", es1, es2);
1865                 /* This will prevent a read-write remount. */
1866                 NVolSetErrors(vol);
1867         }
1868         /* If (still) a read-write mount, mark the quotas out of date. */
1869         if (!(sb->s_flags & MS_RDONLY) &&
1870                         !ntfs_mark_quotas_out_of_date(vol)) {
1871                 static const char *es1 = "Failed to mark quotas out of date";
1872                 static const char *es2 = ".  Run chkdsk.";
1873
1874                 /* Convert to a read-only mount. */
1875                 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1876                                 ON_ERRORS_CONTINUE))) {
1877                         ntfs_error(sb, "%s and neither on_errors=continue nor "
1878                                         "on_errors=remount-ro was specified%s",
1879                                         es1, es2);
1880                         goto iput_quota_err_out;
1881                 }
1882                 ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1883                 sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1884                 NVolSetErrors(vol);
1885         }
1886         /*
1887          * Find the transaction log file ($UsnJrnl), load it if present, check
1888          * it, and set it up.
1889          */
1890         if (!load_and_init_usnjrnl(vol)) {
1891                 static const char *es1 = "Failed to load $UsnJrnl";
1892                 static const char *es2 = ".  Run chkdsk.";
1893
1894                 /* If a read-write mount, convert it to a read-only mount. */
1895                 if (!(sb->s_flags & MS_RDONLY)) {
1896                         if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1897                                         ON_ERRORS_CONTINUE))) {
1898                                 ntfs_error(sb, "%s and neither on_errors="
1899                                                 "continue nor on_errors="
1900                                                 "remount-ro was specified%s",
1901                                                 es1, es2);
1902                                 goto iput_usnjrnl_err_out;
1903                         }
1904                         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1905                         ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1906                 } else
1907                         ntfs_warning(sb, "%s.  Will not be able to remount "
1908                                         "read-write%s", es1, es2);
1909                 /* This will prevent a read-write remount. */
1910                 NVolSetErrors(vol);
1911         }
1912         /* If (still) a read-write mount, stamp the transaction log. */
1913         if (!(sb->s_flags & MS_RDONLY) && !ntfs_stamp_usnjrnl(vol)) {
1914                 static const char *es1 = "Failed to stamp transaction log "
1915                                 "($UsnJrnl)";
1916                 static const char *es2 = ".  Run chkdsk.";
1917
1918                 /* Convert to a read-only mount. */
1919                 if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
1920                                 ON_ERRORS_CONTINUE))) {
1921                         ntfs_error(sb, "%s and neither on_errors=continue nor "
1922                                         "on_errors=remount-ro was specified%s",
1923                                         es1, es2);
1924                         goto iput_usnjrnl_err_out;
1925                 }
1926                 ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1927                 sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1928                 NVolSetErrors(vol);
1929         }
1930 #endif /* NTFS_RW */
1931         return TRUE;
1932 #ifdef NTFS_RW
1933 iput_usnjrnl_err_out:
1934         if (vol->usnjrnl_j_ino)
1935                 iput(vol->usnjrnl_j_ino);
1936         if (vol->usnjrnl_max_ino)
1937                 iput(vol->usnjrnl_max_ino);
1938         if (vol->usnjrnl_ino)
1939                 iput(vol->usnjrnl_ino);
1940 iput_quota_err_out:
1941         if (vol->quota_q_ino)
1942                 iput(vol->quota_q_ino);
1943         if (vol->quota_ino)
1944                 iput(vol->quota_ino);
1945         iput(vol->extend_ino);
1946 #endif /* NTFS_RW */
1947 iput_sec_err_out:
1948         iput(vol->secure_ino);
1949 iput_root_err_out:
1950         iput(vol->root_ino);
1951 iput_logfile_err_out:
1952 #ifdef NTFS_RW
1953         if (vol->logfile_ino)
1954                 iput(vol->logfile_ino);
1955 iput_vol_err_out:
1956 #endif /* NTFS_RW */
1957         iput(vol->vol_ino);
1958 iput_lcnbmp_err_out:
1959         iput(vol->lcnbmp_ino);
1960 iput_attrdef_err_out:
1961         vol->attrdef_size = 0;
1962         if (vol->attrdef) {
1963                 ntfs_free(vol->attrdef);
1964                 vol->attrdef = NULL;
1965         }
1966 #ifdef NTFS_RW
1967 iput_upcase_err_out:
1968 #endif /* NTFS_RW */
1969         vol->upcase_len = 0;
1970         down(&ntfs_lock);
1971         if (vol->upcase == default_upcase) {
1972                 ntfs_nr_upcase_users--;
1973                 vol->upcase = NULL;
1974         }
1975         up(&ntfs_lock);
1976         if (vol->upcase) {
1977                 ntfs_free(vol->upcase);
1978                 vol->upcase = NULL;
1979         }
1980 iput_mftbmp_err_out:
1981         iput(vol->mftbmp_ino);
1982 iput_mirr_err_out:
1983 #ifdef NTFS_RW
1984         if (vol->mftmirr_ino)
1985                 iput(vol->mftmirr_ino);
1986 #endif /* NTFS_RW */
1987         return FALSE;
1988 }
1989
1990 /**
1991  * ntfs_put_super - called by the vfs to unmount a volume
1992  * @sb:         vfs superblock of volume to unmount
1993  *
1994  * ntfs_put_super() is called by the VFS (from fs/super.c::do_umount()) when
1995  * the volume is being unmounted (umount system call has been invoked) and it
1996  * releases all inodes and memory belonging to the NTFS specific part of the
1997  * super block.
1998  */
1999 static void ntfs_put_super(struct super_block *sb)
2000 {
2001         ntfs_volume *vol = NTFS_SB(sb);
2002
2003         ntfs_debug("Entering.");
2004 #ifdef NTFS_RW
2005         /*
2006          * Commit all inodes while they are still open in case some of them
2007          * cause others to be dirtied.
2008          */
2009         ntfs_commit_inode(vol->vol_ino);
2010
2011         /* NTFS 3.0+ specific. */
2012         if (vol->major_ver >= 3) {
2013                 if (vol->usnjrnl_j_ino)
2014                         ntfs_commit_inode(vol->usnjrnl_j_ino);
2015                 if (vol->usnjrnl_max_ino)
2016                         ntfs_commit_inode(vol->usnjrnl_max_ino);
2017                 if (vol->usnjrnl_ino)
2018                         ntfs_commit_inode(vol->usnjrnl_ino);
2019                 if (vol->quota_q_ino)
2020                         ntfs_commit_inode(vol->quota_q_ino);
2021                 if (vol->quota_ino)
2022                         ntfs_commit_inode(vol->quota_ino);
2023                 if (vol->extend_ino)
2024                         ntfs_commit_inode(vol->extend_ino);
2025                 if (vol->secure_ino)
2026                         ntfs_commit_inode(vol->secure_ino);
2027         }
2028
2029         ntfs_commit_inode(vol->root_ino);
2030
2031         down_write(&vol->lcnbmp_lock);
2032         ntfs_commit_inode(vol->lcnbmp_ino);
2033         up_write(&vol->lcnbmp_lock);
2034
2035         down_write(&vol->mftbmp_lock);
2036         ntfs_commit_inode(vol->mftbmp_ino);
2037         up_write(&vol->mftbmp_lock);
2038
2039         if (vol->logfile_ino)
2040                 ntfs_commit_inode(vol->logfile_ino);
2041
2042         if (vol->mftmirr_ino)
2043                 ntfs_commit_inode(vol->mftmirr_ino);
2044         ntfs_commit_inode(vol->mft_ino);
2045
2046         /*
2047          * If a read-write mount and no volume errors have occured, mark the
2048          * volume clean.  Also, re-commit all affected inodes.
2049          */
2050         if (!(sb->s_flags & MS_RDONLY)) {
2051                 if (!NVolErrors(vol)) {
2052                         if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
2053                                 ntfs_warning(sb, "Failed to clear dirty bit "
2054                                                 "in volume information "
2055                                                 "flags.  Run chkdsk.");
2056                         ntfs_commit_inode(vol->vol_ino);
2057                         ntfs_commit_inode(vol->root_ino);
2058                         if (vol->mftmirr_ino)
2059                                 ntfs_commit_inode(vol->mftmirr_ino);
2060                         ntfs_commit_inode(vol->mft_ino);
2061                 } else {
2062                         ntfs_warning(sb, "Volume has errors.  Leaving volume "
2063                                         "marked dirty.  Run chkdsk.");
2064                 }
2065         }
2066 #endif /* NTFS_RW */
2067
2068         iput(vol->vol_ino);
2069         vol->vol_ino = NULL;
2070
2071         /* NTFS 3.0+ specific clean up. */
2072         if (vol->major_ver >= 3) {
2073 #ifdef NTFS_RW
2074                 if (vol->usnjrnl_j_ino) {
2075                         iput(vol->usnjrnl_j_ino);
2076                         vol->usnjrnl_j_ino = NULL;
2077                 }
2078                 if (vol->usnjrnl_max_ino) {
2079                         iput(vol->usnjrnl_max_ino);
2080                         vol->usnjrnl_max_ino = NULL;
2081                 }
2082                 if (vol->usnjrnl_ino) {
2083                         iput(vol->usnjrnl_ino);
2084                         vol->usnjrnl_ino = NULL;
2085                 }
2086                 if (vol->quota_q_ino) {
2087                         iput(vol->quota_q_ino);
2088                         vol->quota_q_ino = NULL;
2089                 }
2090                 if (vol->quota_ino) {
2091                         iput(vol->quota_ino);
2092                         vol->quota_ino = NULL;
2093                 }
2094 #endif /* NTFS_RW */
2095                 if (vol->extend_ino) {
2096                         iput(vol->extend_ino);
2097                         vol->extend_ino = NULL;
2098                 }
2099                 if (vol->secure_ino) {
2100                         iput(vol->secure_ino);
2101                         vol->secure_ino = NULL;
2102                 }
2103         }
2104
2105         iput(vol->root_ino);
2106         vol->root_ino = NULL;
2107
2108         down_write(&vol->lcnbmp_lock);
2109         iput(vol->lcnbmp_ino);
2110         vol->lcnbmp_ino = NULL;
2111         up_write(&vol->lcnbmp_lock);
2112
2113         down_write(&vol->mftbmp_lock);
2114         iput(vol->mftbmp_ino);
2115         vol->mftbmp_ino = NULL;
2116         up_write(&vol->mftbmp_lock);
2117
2118 #ifdef NTFS_RW
2119         if (vol->logfile_ino) {
2120                 iput(vol->logfile_ino);
2121                 vol->logfile_ino = NULL;
2122         }
2123         if (vol->mftmirr_ino) {
2124                 /* Re-commit the mft mirror and mft just in case. */
2125                 ntfs_commit_inode(vol->mftmirr_ino);
2126                 ntfs_commit_inode(vol->mft_ino);
2127                 iput(vol->mftmirr_ino);
2128                 vol->mftmirr_ino = NULL;
2129         }
2130         /*
2131          * If any dirty inodes are left, throw away all mft data page cache
2132          * pages to allow a clean umount.  This should never happen any more
2133          * due to mft.c::ntfs_mft_writepage() cleaning all the dirty pages as
2134          * the underlying mft records are written out and cleaned.  If it does,
2135          * happen anyway, we want to know...
2136          */
2137         ntfs_commit_inode(vol->mft_ino);
2138         write_inode_now(vol->mft_ino, 1);
2139         if (!list_empty(&sb->s_dirty)) {
2140                 const char *s1, *s2;
2141
2142                 down(&vol->mft_ino->i_sem);
2143                 truncate_inode_pages(vol->mft_ino->i_mapping, 0);
2144                 up(&vol->mft_ino->i_sem);
2145                 write_inode_now(vol->mft_ino, 1);
2146                 if (!list_empty(&sb->s_dirty)) {
2147                         static const char *_s1 = "inodes";
2148                         static const char *_s2 = "";
2149                         s1 = _s1;
2150                         s2 = _s2;
2151                 } else {
2152                         static const char *_s1 = "mft pages";
2153                         static const char *_s2 = "They have been thrown "
2154                                         "away.  ";
2155                         s1 = _s1;
2156                         s2 = _s2;
2157                 }
2158                 ntfs_error(sb, "Dirty %s found at umount time.  %sYou should "
2159                                 "run chkdsk.  Please email "
2160                                 "linux-ntfs-dev@lists.sourceforge.net and say "
2161                                 "that you saw this message.  Thank you.", s1,
2162                                 s2);
2163         }
2164 #endif /* NTFS_RW */
2165
2166         iput(vol->mft_ino);
2167         vol->mft_ino = NULL;
2168
2169         /* Throw away the table of attribute definitions. */
2170         vol->attrdef_size = 0;
2171         if (vol->attrdef) {
2172                 ntfs_free(vol->attrdef);
2173                 vol->attrdef = NULL;
2174         }
2175         vol->upcase_len = 0;
2176         /*
2177          * Destroy the global default upcase table if necessary.  Also decrease
2178          * the number of upcase users if we are a user.
2179          */
2180         down(&ntfs_lock);
2181         if (vol->upcase == default_upcase) {
2182                 ntfs_nr_upcase_users--;
2183                 vol->upcase = NULL;
2184         }
2185         if (!ntfs_nr_upcase_users && default_upcase) {
2186                 ntfs_free(default_upcase);
2187                 default_upcase = NULL;
2188         }
2189         if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
2190                 free_compression_buffers();
2191         up(&ntfs_lock);
2192         if (vol->upcase) {
2193                 ntfs_free(vol->upcase);
2194                 vol->upcase = NULL;
2195         }
2196         if (vol->nls_map) {
2197                 unload_nls(vol->nls_map);
2198                 vol->nls_map = NULL;
2199         }
2200         sb->s_fs_info = NULL;
2201         kfree(vol);
2202         return;
2203 }
2204
2205 /**
2206  * get_nr_free_clusters - return the number of free clusters on a volume
2207  * @vol:        ntfs volume for which to obtain free cluster count
2208  *
2209  * Calculate the number of free clusters on the mounted NTFS volume @vol. We
2210  * actually calculate the number of clusters in use instead because this
2211  * allows us to not care about partial pages as these will be just zero filled
2212  * and hence not be counted as allocated clusters.
2213  *
2214  * The only particularity is that clusters beyond the end of the logical ntfs
2215  * volume will be marked as allocated to prevent errors which means we have to
2216  * discount those at the end. This is important as the cluster bitmap always
2217  * has a size in multiples of 8 bytes, i.e. up to 63 clusters could be outside
2218  * the logical volume and marked in use when they are not as they do not exist.
2219  *
2220  * If any pages cannot be read we assume all clusters in the erroring pages are
2221  * in use. This means we return an underestimate on errors which is better than
2222  * an overestimate.
2223  */
2224 static s64 get_nr_free_clusters(ntfs_volume *vol)
2225 {
2226         s64 nr_free = vol->nr_clusters;
2227         u32 *kaddr;
2228         struct address_space *mapping = vol->lcnbmp_ino->i_mapping;
2229         filler_t *readpage = (filler_t*)mapping->a_ops->readpage;
2230         struct page *page;
2231         pgoff_t index, max_index;
2232
2233         ntfs_debug("Entering.");
2234         /* Serialize accesses to the cluster bitmap. */
2235         down_read(&vol->lcnbmp_lock);
2236         /*
2237          * Convert the number of bits into bytes rounded up, then convert into
2238          * multiples of PAGE_CACHE_SIZE, rounding up so that if we have one
2239          * full and one partial page max_index = 2.
2240          */
2241         max_index = (((vol->nr_clusters + 7) >> 3) + PAGE_CACHE_SIZE - 1) >>
2242                         PAGE_CACHE_SHIFT;
2243         /* Use multiples of 4 bytes, thus max_size is PAGE_CACHE_SIZE / 4. */
2244         ntfs_debug("Reading $Bitmap, max_index = 0x%lx, max_size = 0x%lx.",
2245                         max_index, PAGE_CACHE_SIZE / 4);
2246         for (index = 0; index < max_index; index++) {
2247                 unsigned int i;
2248                 /*
2249                  * Read the page from page cache, getting it from backing store
2250                  * if necessary, and increment the use count.
2251                  */
2252                 page = read_cache_page(mapping, index, (filler_t*)readpage,
2253                                 NULL);
2254                 /* Ignore pages which errored synchronously. */
2255                 if (IS_ERR(page)) {
2256                         ntfs_debug("Sync read_cache_page() error. Skipping "
2257                                         "page (index 0x%lx).", index);
2258                         nr_free -= PAGE_CACHE_SIZE * 8;
2259                         continue;
2260                 }
2261                 wait_on_page_locked(page);
2262                 /* Ignore pages which errored asynchronously. */
2263                 if (!PageUptodate(page)) {
2264                         ntfs_debug("Async read_cache_page() error. Skipping "
2265                                         "page (index 0x%lx).", index);
2266                         page_cache_release(page);
2267                         nr_free -= PAGE_CACHE_SIZE * 8;
2268                         continue;
2269                 }
2270                 kaddr = (u32*)kmap_atomic(page, KM_USER0);
2271                 /*
2272                  * For each 4 bytes, subtract the number of set bits. If this
2273                  * is the last page and it is partial we don't really care as
2274                  * it just means we do a little extra work but it won't affect
2275                  * the result as all out of range bytes are set to zero by
2276                  * ntfs_readpage().
2277                  */
2278                 for (i = 0; i < PAGE_CACHE_SIZE / 4; i++)
2279                         nr_free -= (s64)hweight32(kaddr[i]);
2280                 kunmap_atomic(kaddr, KM_USER0);
2281                 page_cache_release(page);
2282         }
2283         ntfs_debug("Finished reading $Bitmap, last index = 0x%lx.", index - 1);
2284         /*
2285          * Fixup for eventual bits outside logical ntfs volume (see function
2286          * description above).
2287          */
2288         if (vol->nr_clusters & 63)
2289                 nr_free += 64 - (vol->nr_clusters & 63);
2290         up_read(&vol->lcnbmp_lock);
2291         /* If errors occured we may well have gone below zero, fix this. */
2292         if (nr_free < 0)
2293                 nr_free = 0;
2294         ntfs_debug("Exiting.");
2295         return nr_free;
2296 }
2297
2298 /**
2299  * __get_nr_free_mft_records - return the number of free inodes on a volume
2300  * @vol:        ntfs volume for which to obtain free inode count
2301  * @nr_free:    number of mft records in filesystem
2302  * @max_index:  maximum number of pages containing set bits
2303  *
2304  * Calculate the number of free mft records (inodes) on the mounted NTFS
2305  * volume @vol. We actually calculate the number of mft records in use instead
2306  * because this allows us to not care about partial pages as these will be just
2307  * zero filled and hence not be counted as allocated mft record.
2308  *
2309  * If any pages cannot be read we assume all mft records in the erroring pages
2310  * are in use. This means we return an underestimate on errors which is better
2311  * than an overestimate.
2312  *
2313  * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing.
2314  */
2315 static unsigned long __get_nr_free_mft_records(ntfs_volume *vol,
2316                 s64 nr_free, const pgoff_t max_index)
2317 {
2318         u32 *kaddr;
2319         struct address_space *mapping = vol->mftbmp_ino->i_mapping;
2320         filler_t *readpage = (filler_t*)mapping->a_ops->readpage;
2321         struct page *page;
2322         pgoff_t index;
2323
2324         ntfs_debug("Entering.");
2325         /* Use multiples of 4 bytes, thus max_size is PAGE_CACHE_SIZE / 4. */
2326         ntfs_debug("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = "
2327                         "0x%lx.", max_index, PAGE_CACHE_SIZE / 4);
2328         for (index = 0; index < max_index; index++) {
2329                 unsigned int i;
2330                 /*
2331                  * Read the page from page cache, getting it from backing store
2332                  * if necessary, and increment the use count.
2333                  */
2334                 page = read_cache_page(mapping, index, (filler_t*)readpage,
2335                                 NULL);
2336                 /* Ignore pages which errored synchronously. */
2337                 if (IS_ERR(page)) {
2338                         ntfs_debug("Sync read_cache_page() error. Skipping "
2339                                         "page (index 0x%lx).", index);
2340                         nr_free -= PAGE_CACHE_SIZE * 8;
2341                         continue;
2342                 }
2343                 wait_on_page_locked(page);
2344                 /* Ignore pages which errored asynchronously. */
2345                 if (!PageUptodate(page)) {
2346                         ntfs_debug("Async read_cache_page() error. Skipping "
2347                                         "page (index 0x%lx).", index);
2348                         page_cache_release(page);
2349                         nr_free -= PAGE_CACHE_SIZE * 8;
2350                         continue;
2351                 }
2352                 kaddr = (u32*)kmap_atomic(page, KM_USER0);
2353                 /*
2354                  * For each 4 bytes, subtract the number of set bits. If this
2355                  * is the last page and it is partial we don't really care as
2356                  * it just means we do a little extra work but it won't affect
2357                  * the result as all out of range bytes are set to zero by
2358                  * ntfs_readpage().
2359                  */
2360                 for (i = 0; i < PAGE_CACHE_SIZE / 4; i++)
2361                         nr_free -= (s64)hweight32(kaddr[i]);
2362                 kunmap_atomic(kaddr, KM_USER0);
2363                 page_cache_release(page);
2364         }
2365         ntfs_debug("Finished reading $MFT/$BITMAP, last index = 0x%lx.",
2366                         index - 1);
2367         /* If errors occured we may well have gone below zero, fix this. */
2368         if (nr_free < 0)
2369                 nr_free = 0;
2370         ntfs_debug("Exiting.");
2371         return nr_free;
2372 }
2373
2374 /**
2375  * ntfs_statfs - return information about mounted NTFS volume
2376  * @sb:         super block of mounted volume
2377  * @sfs:        statfs structure in which to return the information
2378  *
2379  * Return information about the mounted NTFS volume @sb in the statfs structure
2380  * pointed to by @sfs (this is initialized with zeros before ntfs_statfs is
2381  * called). We interpret the values to be correct of the moment in time at
2382  * which we are called. Most values are variable otherwise and this isn't just
2383  * the free values but the totals as well. For example we can increase the
2384  * total number of file nodes if we run out and we can keep doing this until
2385  * there is no more space on the volume left at all.
2386  *
2387  * Called from vfs_statfs which is used to handle the statfs, fstatfs, and
2388  * ustat system calls.
2389  *
2390  * Return 0 on success or -errno on error.
2391  */
2392 static int ntfs_statfs(struct super_block *sb, struct kstatfs *sfs)
2393 {
2394         s64 size;
2395         ntfs_volume *vol = NTFS_SB(sb);
2396         ntfs_inode *mft_ni = NTFS_I(vol->mft_ino);
2397         pgoff_t max_index;
2398         unsigned long flags;
2399
2400         ntfs_debug("Entering.");
2401         /* Type of filesystem. */
2402         sfs->f_type   = NTFS_SB_MAGIC;
2403         /* Optimal transfer block size. */
2404         sfs->f_bsize  = PAGE_CACHE_SIZE;
2405         /*
2406          * Total data blocks in filesystem in units of f_bsize and since
2407          * inodes are also stored in data blocs ($MFT is a file) this is just
2408          * the total clusters.
2409          */
2410         sfs->f_blocks = vol->nr_clusters << vol->cluster_size_bits >>
2411                                 PAGE_CACHE_SHIFT;
2412         /* Free data blocks in filesystem in units of f_bsize. */
2413         size          = get_nr_free_clusters(vol) << vol->cluster_size_bits >>
2414                                 PAGE_CACHE_SHIFT;
2415         if (size < 0LL)
2416                 size = 0LL;
2417         /* Free blocks avail to non-superuser, same as above on NTFS. */
2418         sfs->f_bavail = sfs->f_bfree = size;
2419         /* Serialize accesses to the inode bitmap. */
2420         down_read(&vol->mftbmp_lock);
2421         read_lock_irqsave(&mft_ni->size_lock, flags);
2422         size = i_size_read(vol->mft_ino) >> vol->mft_record_size_bits;
2423         /*
2424          * Convert the maximum number of set bits into bytes rounded up, then
2425          * convert into multiples of PAGE_CACHE_SIZE, rounding up so that if we
2426          * have one full and one partial page max_index = 2.
2427          */
2428         max_index = ((((mft_ni->initialized_size >> vol->mft_record_size_bits)
2429                         + 7) >> 3) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
2430         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2431         /* Number of inodes in filesystem (at this point in time). */
2432         sfs->f_files = size;
2433         /* Free inodes in fs (based on current total count). */
2434         sfs->f_ffree = __get_nr_free_mft_records(vol, size, max_index);
2435         up_read(&vol->mftbmp_lock);
2436         /*
2437          * File system id. This is extremely *nix flavour dependent and even
2438          * within Linux itself all fs do their own thing. I interpret this to
2439          * mean a unique id associated with the mounted fs and not the id
2440          * associated with the filesystem driver, the latter is already given
2441          * by the filesystem type in sfs->f_type. Thus we use the 64-bit
2442          * volume serial number splitting it into two 32-bit parts. We enter
2443          * the least significant 32-bits in f_fsid[0] and the most significant
2444          * 32-bits in f_fsid[1].
2445          */
2446         sfs->f_fsid.val[0] = vol->serial_no & 0xffffffff;
2447         sfs->f_fsid.val[1] = (vol->serial_no >> 32) & 0xffffffff;
2448         /* Maximum length of filenames. */
2449         sfs->f_namelen     = NTFS_MAX_NAME_LEN;
2450         return 0;
2451 }
2452
2453 /**
2454  * The complete super operations.
2455  */
2456 static struct super_operations ntfs_sops = {
2457         .alloc_inode    = ntfs_alloc_big_inode,   /* VFS: Allocate new inode. */
2458         .destroy_inode  = ntfs_destroy_big_inode, /* VFS: Deallocate inode. */
2459         .put_inode      = ntfs_put_inode,         /* VFS: Called just before
2460                                                      the inode reference count
2461                                                      is decreased. */
2462 #ifdef NTFS_RW
2463         //.dirty_inode  = NULL,                 /* VFS: Called from
2464         //                                         __mark_inode_dirty(). */
2465         .write_inode    = ntfs_write_inode,     /* VFS: Write dirty inode to
2466                                                    disk. */
2467         //.drop_inode   = NULL,                 /* VFS: Called just after the
2468         //                                         inode reference count has
2469         //                                         been decreased to zero.
2470         //                                         NOTE: The inode lock is
2471         //                                         held. See fs/inode.c::
2472         //                                         generic_drop_inode(). */
2473         //.delete_inode = NULL,                 /* VFS: Delete inode from disk.
2474         //                                         Called when i_count becomes
2475         //                                         0 and i_nlink is also 0. */
2476         //.write_super  = NULL,                 /* Flush dirty super block to
2477         //                                         disk. */
2478         //.sync_fs      = NULL,                 /* ? */
2479         //.write_super_lockfs   = NULL,         /* ? */
2480         //.unlockfs     = NULL,                 /* ? */
2481 #endif /* NTFS_RW */
2482         .put_super      = ntfs_put_super,       /* Syscall: umount. */
2483         .statfs         = ntfs_statfs,          /* Syscall: statfs */
2484         .remount_fs     = ntfs_remount,         /* Syscall: mount -o remount. */
2485         .clear_inode    = ntfs_clear_big_inode, /* VFS: Called when an inode is
2486                                                    removed from memory. */
2487         //.umount_begin = NULL,                 /* Forced umount. */
2488         .show_options   = ntfs_show_options,    /* Show mount options in
2489                                                    proc. */
2490 };
2491
2492 /**
2493  * ntfs_fill_super - mount an ntfs filesystem
2494  * @sb:         super block of ntfs filesystem to mount
2495  * @opt:        string containing the mount options
2496  * @silent:     silence error output
2497  *
2498  * ntfs_fill_super() is called by the VFS to mount the device described by @sb
2499  * with the mount otions in @data with the NTFS filesystem.
2500  *
2501  * If @silent is true, remain silent even if errors are detected. This is used
2502  * during bootup, when the kernel tries to mount the root filesystem with all
2503  * registered filesystems one after the other until one succeeds. This implies
2504  * that all filesystems except the correct one will quite correctly and
2505  * expectedly return an error, but nobody wants to see error messages when in
2506  * fact this is what is supposed to happen.
2507  *
2508  * NOTE: @sb->s_flags contains the mount options flags.
2509  */
2510 static int ntfs_fill_super(struct super_block *sb, void *opt, const int silent)
2511 {
2512         ntfs_volume *vol;
2513         struct buffer_head *bh;
2514         struct inode *tmp_ino;
2515         int result;
2516
2517         ntfs_debug("Entering.");
2518 #ifndef NTFS_RW
2519         sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
2520 #endif /* ! NTFS_RW */
2521         /* Allocate a new ntfs_volume and place it in sb->s_fs_info. */
2522         sb->s_fs_info = kmalloc(sizeof(ntfs_volume), GFP_NOFS);
2523         vol = NTFS_SB(sb);
2524         if (!vol) {
2525                 if (!silent)
2526                         ntfs_error(sb, "Allocation of NTFS volume structure "
2527                                         "failed. Aborting mount...");
2528                 return -ENOMEM;
2529         }
2530         /* Initialize ntfs_volume structure. */
2531         *vol = (ntfs_volume) {
2532                 .sb = sb,
2533                 /*
2534                  * Default is group and other don't have any access to files or
2535                  * directories while owner has full access. Further, files by
2536                  * default are not executable but directories are of course
2537                  * browseable.
2538                  */
2539                 .fmask = 0177,
2540                 .dmask = 0077,
2541         };
2542         init_rwsem(&vol->mftbmp_lock);
2543         init_rwsem(&vol->lcnbmp_lock);
2544
2545         unlock_kernel();
2546
2547         /* By default, enable sparse support. */
2548         NVolSetSparseEnabled(vol);
2549
2550         /* Important to get the mount options dealt with now. */
2551         if (!parse_options(vol, (char*)opt))
2552                 goto err_out_now;
2553
2554         /*
2555          * TODO: Fail safety check. In the future we should really be able to
2556          * cope with this being the case, but for now just bail out.
2557          */
2558         if (bdev_hardsect_size(sb->s_bdev) > NTFS_BLOCK_SIZE) {
2559                 if (!silent)
2560                         ntfs_error(sb, "Device has unsupported hardsect_size.");
2561                 goto err_out_now;
2562         }
2563
2564         /* Setup the device access block size to NTFS_BLOCK_SIZE. */
2565         if (sb_set_blocksize(sb, NTFS_BLOCK_SIZE) != NTFS_BLOCK_SIZE) {
2566                 if (!silent)
2567                         ntfs_error(sb, "Unable to set block size.");
2568                 goto err_out_now;
2569         }
2570
2571         /* Get the size of the device in units of NTFS_BLOCK_SIZE bytes. */
2572         vol->nr_blocks = i_size_read(sb->s_bdev->bd_inode) >>
2573                         NTFS_BLOCK_SIZE_BITS;
2574
2575         /* Read the boot sector and return unlocked buffer head to it. */
2576         if (!(bh = read_ntfs_boot_sector(sb, silent))) {
2577                 if (!silent)
2578                         ntfs_error(sb, "Not an NTFS volume.");
2579                 goto err_out_now;
2580         }
2581
2582         /*
2583          * Extract the data from the boot sector and setup the ntfs super block
2584          * using it.
2585          */
2586         result = parse_ntfs_boot_sector(vol, (NTFS_BOOT_SECTOR*)bh->b_data);
2587
2588         /* Initialize the cluster and mft allocators. */
2589         ntfs_setup_allocators(vol);
2590
2591         brelse(bh);
2592
2593         if (!result) {
2594                 if (!silent)
2595                         ntfs_error(sb, "Unsupported NTFS filesystem.");
2596                 goto err_out_now;
2597         }
2598
2599         /*
2600          * TODO: When we start coping with sector sizes different from
2601          * NTFS_BLOCK_SIZE, we now probably need to set the blocksize of the
2602          * device (probably to NTFS_BLOCK_SIZE).
2603          */
2604
2605         /* Setup remaining fields in the super block. */
2606         sb->s_magic = NTFS_SB_MAGIC;
2607
2608         /*
2609          * Ntfs allows 63 bits for the file size, i.e. correct would be:
2610          *      sb->s_maxbytes = ~0ULL >> 1;
2611          * But the kernel uses a long as the page cache page index which on
2612          * 32-bit architectures is only 32-bits. MAX_LFS_FILESIZE is kernel
2613          * defined to the maximum the page cache page index can cope with
2614          * without overflowing the index or to 2^63 - 1, whichever is smaller.
2615          */
2616         sb->s_maxbytes = MAX_LFS_FILESIZE;
2617
2618         sb->s_time_gran = 100;
2619
2620         /*
2621          * Now load the metadata required for the page cache and our address
2622          * space operations to function. We do this by setting up a specialised
2623          * read_inode method and then just calling the normal iget() to obtain
2624          * the inode for $MFT which is sufficient to allow our normal inode
2625          * operations and associated address space operations to function.
2626          */
2627         sb->s_op = &ntfs_sops;
2628         tmp_ino = new_inode(sb);
2629         if (!tmp_ino) {
2630                 if (!silent)
2631                         ntfs_error(sb, "Failed to load essential metadata.");
2632                 goto err_out_now;
2633         }
2634         tmp_ino->i_ino = FILE_MFT;
2635         insert_inode_hash(tmp_ino);
2636         if (ntfs_read_inode_mount(tmp_ino) < 0) {
2637                 if (!silent)
2638                         ntfs_error(sb, "Failed to load essential metadata.");
2639                 goto iput_tmp_ino_err_out_now;
2640         }
2641         down(&ntfs_lock);
2642         /*
2643          * The current mount is a compression user if the cluster size is
2644          * less than or equal 4kiB.
2645          */
2646         if (vol->cluster_size <= 4096 && !ntfs_nr_compression_users++) {
2647                 result = allocate_compression_buffers();
2648                 if (result) {
2649                         ntfs_error(NULL, "Failed to allocate buffers "
2650                                         "for compression engine.");
2651                         ntfs_nr_compression_users--;
2652                         up(&ntfs_lock);
2653                         goto iput_tmp_ino_err_out_now;
2654                 }
2655         }
2656         /*
2657          * Generate the global default upcase table if necessary.  Also
2658          * temporarily increment the number of upcase users to avoid race
2659          * conditions with concurrent (u)mounts.
2660          */
2661         if (!default_upcase)
2662                 default_upcase = generate_default_upcase();
2663         ntfs_nr_upcase_users++;
2664         up(&ntfs_lock);
2665         /*
2666          * From now on, ignore @silent parameter. If we fail below this line,
2667          * it will be due to a corrupt fs or a system error, so we report it.
2668          */
2669         /*
2670          * Open the system files with normal access functions and complete
2671          * setting up the ntfs super block.
2672          */
2673         if (!load_system_files(vol)) {
2674                 ntfs_error(sb, "Failed to load system files.");
2675                 goto unl_upcase_iput_tmp_ino_err_out_now;
2676         }
2677         if ((sb->s_root = d_alloc_root(vol->root_ino))) {
2678                 /* We increment i_count simulating an ntfs_iget(). */
2679                 atomic_inc(&vol->root_ino->i_count);
2680                 ntfs_debug("Exiting, status successful.");
2681                 /* Release the default upcase if it has no users. */
2682                 down(&ntfs_lock);
2683                 if (!--ntfs_nr_upcase_users && default_upcase) {
2684                         ntfs_free(default_upcase);
2685                         default_upcase = NULL;
2686                 }
2687                 up(&ntfs_lock);
2688                 sb->s_export_op = &ntfs_export_ops;
2689                 lock_kernel();
2690                 return 0;
2691         }
2692         ntfs_error(sb, "Failed to allocate root directory.");
2693         /* Clean up after the successful load_system_files() call from above. */
2694         // TODO: Use ntfs_put_super() instead of repeating all this code...
2695         // FIXME: Should mark the volume clean as the error is most likely
2696         //        -ENOMEM.
2697         iput(vol->vol_ino);
2698         vol->vol_ino = NULL;
2699         /* NTFS 3.0+ specific clean up. */
2700         if (vol->major_ver >= 3) {
2701 #ifdef NTFS_RW
2702                 if (vol->usnjrnl_j_ino) {
2703                         iput(vol->usnjrnl_j_ino);
2704                         vol->usnjrnl_j_ino = NULL;
2705                 }
2706                 if (vol->usnjrnl_max_ino) {
2707                         iput(vol->usnjrnl_max_ino);
2708                         vol->usnjrnl_max_ino = NULL;
2709                 }
2710                 if (vol->usnjrnl_ino) {
2711                         iput(vol->usnjrnl_ino);
2712                         vol->usnjrnl_ino = NULL;
2713                 }
2714                 if (vol->quota_q_ino) {
2715                         iput(vol->quota_q_ino);
2716                         vol->quota_q_ino = NULL;
2717                 }
2718                 if (vol->quota_ino) {
2719                         iput(vol->quota_ino);
2720                         vol->quota_ino = NULL;
2721                 }
2722 #endif /* NTFS_RW */
2723                 if (vol->extend_ino) {
2724                         iput(vol->extend_ino);
2725                         vol->extend_ino = NULL;
2726                 }
2727                 if (vol->secure_ino) {
2728                         iput(vol->secure_ino);
2729                         vol->secure_ino = NULL;
2730                 }
2731         }
2732         iput(vol->root_ino);
2733         vol->root_ino = NULL;
2734         iput(vol->lcnbmp_ino);
2735         vol->lcnbmp_ino = NULL;
2736         iput(vol->mftbmp_ino);
2737         vol->mftbmp_ino = NULL;
2738 #ifdef NTFS_RW
2739         if (vol->logfile_ino) {
2740                 iput(vol->logfile_ino);
2741                 vol->logfile_ino = NULL;
2742         }
2743         if (vol->mftmirr_ino) {
2744                 iput(vol->mftmirr_ino);
2745                 vol->mftmirr_ino = NULL;
2746         }
2747 #endif /* NTFS_RW */
2748         /* Throw away the table of attribute definitions. */
2749         vol->attrdef_size = 0;
2750         if (vol->attrdef) {
2751                 ntfs_free(vol->attrdef);
2752                 vol->attrdef = NULL;
2753         }
2754         vol->upcase_len = 0;
2755         down(&ntfs_lock);
2756         if (vol->upcase == default_upcase) {
2757                 ntfs_nr_upcase_users--;
2758                 vol->upcase = NULL;
2759         }
2760         up(&ntfs_lock);
2761         if (vol->upcase) {
2762                 ntfs_free(vol->upcase);
2763                 vol->upcase = NULL;
2764         }
2765         if (vol->nls_map) {
2766                 unload_nls(vol->nls_map);
2767                 vol->nls_map = NULL;
2768         }
2769         /* Error exit code path. */
2770 unl_upcase_iput_tmp_ino_err_out_now:
2771         /*
2772          * Decrease the number of upcase users and destroy the global default
2773          * upcase table if necessary.
2774          */
2775         down(&ntfs_lock);
2776         if (!--ntfs_nr_upcase_users && default_upcase) {
2777                 ntfs_free(default_upcase);
2778                 default_upcase = NULL;
2779         }
2780         if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
2781                 free_compression_buffers();
2782         up(&ntfs_lock);
2783 iput_tmp_ino_err_out_now:
2784         iput(tmp_ino);
2785         if (vol->mft_ino && vol->mft_ino != tmp_ino)
2786                 iput(vol->mft_ino);
2787         vol->mft_ino = NULL;
2788         /*
2789          * This is needed to get ntfs_clear_extent_inode() called for each
2790          * inode we have ever called ntfs_iget()/iput() on, otherwise we A)
2791          * leak resources and B) a subsequent mount fails automatically due to
2792          * ntfs_iget() never calling down into our ntfs_read_locked_inode()
2793          * method again... FIXME: Do we need to do this twice now because of
2794          * attribute inodes? I think not, so leave as is for now... (AIA)
2795          */
2796         if (invalidate_inodes(sb)) {
2797                 ntfs_error(sb, "Busy inodes left. This is most likely a NTFS "
2798                                 "driver bug.");
2799                 /* Copied from fs/super.c. I just love this message. (-; */
2800                 printk("NTFS: Busy inodes after umount. Self-destruct in 5 "
2801                                 "seconds.  Have a nice day...\n");
2802         }
2803         /* Errors at this stage are irrelevant. */
2804 err_out_now:
2805         lock_kernel();
2806         sb->s_fs_info = NULL;
2807         kfree(vol);
2808         ntfs_debug("Failed, returning -EINVAL.");
2809         return -EINVAL;
2810 }
2811
2812 /*
2813  * This is a slab cache to optimize allocations and deallocations of Unicode
2814  * strings of the maximum length allowed by NTFS, which is NTFS_MAX_NAME_LEN
2815  * (255) Unicode characters + a terminating NULL Unicode character.
2816  */
2817 kmem_cache_t *ntfs_name_cache;
2818
2819 /* Slab caches for efficient allocation/deallocation of inodes. */
2820 kmem_cache_t *ntfs_inode_cache;
2821 kmem_cache_t *ntfs_big_inode_cache;
2822
2823 /* Init once constructor for the inode slab cache. */
2824 static void ntfs_big_inode_init_once(void *foo, kmem_cache_t *cachep,
2825                 unsigned long flags)
2826 {
2827         ntfs_inode *ni = (ntfs_inode *)foo;
2828
2829         if ((flags & (SLAB_CTOR_VERIFY|SLAB_CTOR_CONSTRUCTOR)) ==
2830                         SLAB_CTOR_CONSTRUCTOR)
2831                 inode_init_once(VFS_I(ni));
2832 }
2833
2834 /*
2835  * Slab caches to optimize allocations and deallocations of attribute search
2836  * contexts and index contexts, respectively.
2837  */
2838 kmem_cache_t *ntfs_attr_ctx_cache;
2839 kmem_cache_t *ntfs_index_ctx_cache;
2840
2841 /* Driver wide semaphore. */
2842 DECLARE_MUTEX(ntfs_lock);
2843
2844 static struct super_block *ntfs_get_sb(struct file_system_type *fs_type,
2845         int flags, const char *dev_name, void *data)
2846 {
2847         return get_sb_bdev(fs_type, flags, dev_name, data, ntfs_fill_super);
2848 }
2849
2850 static struct file_system_type ntfs_fs_type = {
2851         .owner          = THIS_MODULE,
2852         .name           = "ntfs",
2853         .get_sb         = ntfs_get_sb,
2854         .kill_sb        = kill_block_super,
2855         .fs_flags       = FS_REQUIRES_DEV,
2856 };
2857
2858 /* Stable names for the slab caches. */
2859 static const char ntfs_index_ctx_cache_name[] = "ntfs_index_ctx_cache";
2860 static const char ntfs_attr_ctx_cache_name[] = "ntfs_attr_ctx_cache";
2861 static const char ntfs_name_cache_name[] = "ntfs_name_cache";
2862 static const char ntfs_inode_cache_name[] = "ntfs_inode_cache";
2863 static const char ntfs_big_inode_cache_name[] = "ntfs_big_inode_cache";
2864
2865 static int __init init_ntfs_fs(void)
2866 {
2867         int err = 0;
2868
2869         /* This may be ugly but it results in pretty output so who cares. (-8 */
2870         printk(KERN_INFO "NTFS driver " NTFS_VERSION " [Flags: R/"
2871 #ifdef NTFS_RW
2872                         "W"
2873 #else
2874                         "O"
2875 #endif
2876 #ifdef DEBUG
2877                         " DEBUG"
2878 #endif
2879 #ifdef MODULE
2880                         " MODULE"
2881 #endif
2882                         "].\n");
2883
2884         ntfs_debug("Debug messages are enabled.");
2885
2886         ntfs_index_ctx_cache = kmem_cache_create(ntfs_index_ctx_cache_name,
2887                         sizeof(ntfs_index_context), 0 /* offset */,
2888                         SLAB_HWCACHE_ALIGN, NULL /* ctor */, NULL /* dtor */);
2889         if (!ntfs_index_ctx_cache) {
2890                 printk(KERN_CRIT "NTFS: Failed to create %s!\n",
2891                                 ntfs_index_ctx_cache_name);
2892                 goto ictx_err_out;
2893         }
2894         ntfs_attr_ctx_cache = kmem_cache_create(ntfs_attr_ctx_cache_name,
2895                         sizeof(ntfs_attr_search_ctx), 0 /* offset */,
2896                         SLAB_HWCACHE_ALIGN, NULL /* ctor */, NULL /* dtor */);
2897         if (!ntfs_attr_ctx_cache) {
2898                 printk(KERN_CRIT "NTFS: Failed to create %s!\n",
2899                                 ntfs_attr_ctx_cache_name);
2900                 goto actx_err_out;
2901         }
2902
2903         ntfs_name_cache = kmem_cache_create(ntfs_name_cache_name,
2904                         (NTFS_MAX_NAME_LEN+1) * sizeof(ntfschar), 0,
2905                         SLAB_HWCACHE_ALIGN, NULL, NULL);
2906         if (!ntfs_name_cache) {
2907                 printk(KERN_CRIT "NTFS: Failed to create %s!\n",
2908                                 ntfs_name_cache_name);
2909                 goto name_err_out;
2910         }
2911
2912         ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
2913                         sizeof(ntfs_inode), 0,
2914                         SLAB_RECLAIM_ACCOUNT, NULL, NULL);
2915         if (!ntfs_inode_cache) {
2916                 printk(KERN_CRIT "NTFS: Failed to create %s!\n",
2917                                 ntfs_inode_cache_name);
2918                 goto inode_err_out;
2919         }
2920
2921         ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
2922                         sizeof(big_ntfs_inode), 0,
2923                         SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT,
2924                         ntfs_big_inode_init_once, NULL);
2925         if (!ntfs_big_inode_cache) {
2926                 printk(KERN_CRIT "NTFS: Failed to create %s!\n",
2927                                 ntfs_big_inode_cache_name);
2928                 goto big_inode_err_out;
2929         }
2930
2931         /* Register the ntfs sysctls. */
2932         err = ntfs_sysctl(1);
2933         if (err) {
2934                 printk(KERN_CRIT "NTFS: Failed to register NTFS sysctls!\n");
2935                 goto sysctl_err_out;
2936         }
2937
2938         err = register_filesystem(&ntfs_fs_type);
2939         if (!err) {
2940                 ntfs_debug("NTFS driver registered successfully.");
2941                 return 0; /* Success! */
2942         }
2943         printk(KERN_CRIT "NTFS: Failed to register NTFS filesystem driver!\n");
2944
2945 sysctl_err_out:
2946         kmem_cache_destroy(ntfs_big_inode_cache);
2947 big_inode_err_out:
2948         kmem_cache_destroy(ntfs_inode_cache);
2949 inode_err_out:
2950         kmem_cache_destroy(ntfs_name_cache);
2951 name_err_out:
2952         kmem_cache_destroy(ntfs_attr_ctx_cache);
2953 actx_err_out:
2954         kmem_cache_destroy(ntfs_index_ctx_cache);
2955 ictx_err_out:
2956         if (!err) {
2957                 printk(KERN_CRIT "NTFS: Aborting NTFS filesystem driver "
2958                                 "registration...\n");
2959                 err = -ENOMEM;
2960         }
2961         return err;
2962 }
2963
2964 static void __exit exit_ntfs_fs(void)
2965 {
2966         int err = 0;
2967
2968         ntfs_debug("Unregistering NTFS driver.");
2969
2970         unregister_filesystem(&ntfs_fs_type);
2971
2972         if (kmem_cache_destroy(ntfs_big_inode_cache) && (err = 1))
2973                 printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
2974                                 ntfs_big_inode_cache_name);
2975         if (kmem_cache_destroy(ntfs_inode_cache) && (err = 1))
2976                 printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
2977                                 ntfs_inode_cache_name);
2978         if (kmem_cache_destroy(ntfs_name_cache) && (err = 1))
2979                 printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
2980                                 ntfs_name_cache_name);
2981         if (kmem_cache_destroy(ntfs_attr_ctx_cache) && (err = 1))
2982                 printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
2983                                 ntfs_attr_ctx_cache_name);
2984         if (kmem_cache_destroy(ntfs_index_ctx_cache) && (err = 1))
2985                 printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
2986                                 ntfs_index_ctx_cache_name);
2987         if (err)
2988                 printk(KERN_CRIT "NTFS: This causes memory to leak! There is "
2989                                 "probably a BUG in the driver! Please report "
2990                                 "you saw this message to "
2991                                 "linux-ntfs-dev@lists.sourceforge.net\n");
2992         /* Unregister the ntfs sysctls. */
2993         ntfs_sysctl(0);
2994 }
2995
2996 MODULE_AUTHOR("Anton Altaparmakov <aia21@cantab.net>");
2997 MODULE_DESCRIPTION("NTFS 1.2/3.x driver - Copyright (c) 2001-2005 Anton Altaparmakov");
2998 MODULE_VERSION(NTFS_VERSION);
2999 MODULE_LICENSE("GPL");
3000 #ifdef DEBUG
3001 module_param(debug_msgs, bool, 0);
3002 MODULE_PARM_DESC(debug_msgs, "Enable debug messages.");
3003 #endif
3004
3005 module_init(init_ntfs_fs)
3006 module_exit(exit_ntfs_fs)