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