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