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