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