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