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