super.c 85 KB
Newer Older
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1 2 3
/*
 * super.c - NTFS kernel super block handling. Part of the Linux-NTFS project.
 *
4
 * Copyright (c) 2001-2004 Anton Altaparmakov
Anton Altaparmakov's avatar
Anton Altaparmakov committed
5
 * Copyright (c) 2001,2002 Richard Russon
Anton Altaparmakov's avatar
Anton Altaparmakov committed
6 7 8 9 10 11
 *
 * This program/include file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
12 13
 * This program/include file is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
Anton Altaparmakov's avatar
Anton Altaparmakov committed
14 15 16 17
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * 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
Anton Altaparmakov's avatar
Anton Altaparmakov committed
19 20 21 22 23 24 25 26
 * distribution in the file COPYING); if not, write to the Free Software
 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/spinlock.h>
27
#include <linux/blkdev.h>	/* For bdev_hardsect_size(). */
28
#include <linux/backing-dev.h>
29
#include <linux/buffer_head.h>
30
#include <linux/vfs.h>
31
#include <linux/moduleparam.h>
32
#include <linux/smp_lock.h>
Anton Altaparmakov's avatar
Anton Altaparmakov committed
33 34 35

#include "ntfs.h"
#include "sysctl.h"
36
#include "logfile.h"
37 38
#include "quota.h"
#include "dir.h"
39
#include "index.h"
Anton Altaparmakov's avatar
Anton Altaparmakov committed
40 41

/* Number of mounted file systems which have compression enabled. */
42
static unsigned long ntfs_nr_compression_users;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
43 44 45

/* Error constants/strings used in inode.c::ntfs_show_options(). */
typedef enum {
46
	/* One of these must be present, default is ON_ERRORS_CONTINUE. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
47 48 49
	ON_ERRORS_PANIC			= 0x01,
	ON_ERRORS_REMOUNT_RO		= 0x02,
	ON_ERRORS_CONTINUE		= 0x04,
50
	/* Optional, can be combined with any of the above. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
51 52 53 54
	ON_ERRORS_RECOVER		= 0x10,
} ON_ERRORS_ACTIONS;

const option_t on_errors_arr[] = {
55 56 57 58 59
	{ ON_ERRORS_PANIC,	"panic" },
	{ ON_ERRORS_REMOUNT_RO,	"remount-ro", },
	{ ON_ERRORS_CONTINUE,	"continue", },
	{ ON_ERRORS_RECOVER,	"recover" },
	{ 0,			NULL }
Anton Altaparmakov's avatar
Anton Altaparmakov committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
};

/**
 * simple_getbool -
 *
 * Copied from old ntfs driver (which copied from vfat driver).
 */
static int simple_getbool(char *s, BOOL *setval)
{
	if (s) {
		if (!strcmp(s, "1") || !strcmp(s, "yes") || !strcmp(s, "true"))
			*setval = TRUE;
		else if (!strcmp(s, "0") || !strcmp(s, "no") ||
							!strcmp(s, "false"))
			*setval = FALSE;
		else
			return 0;
	} else
		*setval = TRUE;
	return 1;
}

/**
 * parse_options - parse the (re)mount options
 * @vol:	ntfs volume
 * @opt:	string containing the (re)mount options
 *
 * Parse the recognized options in @opt for the ntfs volume described by @vol.
 */
static BOOL parse_options(ntfs_volume *vol, char *opt)
{
	char *p, *v, *ov;
	static char *utf8 = "utf8";
	int errors = 0, sloppy = 0;
	uid_t uid = (uid_t)-1;
	gid_t gid = (gid_t)-1;
	mode_t fmask = (mode_t)-1, dmask = (mode_t)-1;
97 98
	int mft_zone_multiplier = -1, on_errors = -1;
	int show_sys_files = -1, case_sensitive = -1;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
99 100 101 102 103 104 105 106 107 108 109 110
	struct nls_table *nls_map = NULL, *old_nls;

	/* I am lazy... (-8 */
#define NTFS_GETOPT_WITH_DEFAULT(option, variable, default_value)	\
	if (!strcmp(p, option)) {					\
		if (!v || !*v)						\
			variable = default_value;			\
		else {							\
			variable = simple_strtoul(ov = v, &v, 0);	\
			if (*v)						\
				goto needs_val;				\
		}							\
111
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
112 113 114 115 116 117 118
#define NTFS_GETOPT(option, variable)					\
	if (!strcmp(p, option)) {					\
		if (!v || !*v)						\
			goto needs_arg;					\
		variable = simple_strtoul(ov = v, &v, 0);		\
		if (*v)							\
			goto needs_val;					\
119
	}
120 121 122 123 124 125
#define NTFS_GETOPT_BOOL(option, variable)				\
	if (!strcmp(p, option)) {					\
		BOOL val;						\
		if (!simple_getbool(v, &val))				\
			goto needs_bool;				\
		variable = val;						\
126
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
#define NTFS_GETOPT_OPTIONS_ARRAY(option, variable, opt_array)		\
	if (!strcmp(p, option)) {					\
		int _i;							\
		if (!v || !*v)						\
			goto needs_arg;					\
		ov = v;							\
		if (variable == -1)					\
			variable = 0;					\
		for (_i = 0; opt_array[_i].str && *opt_array[_i].str; _i++) \
			if (!strcmp(opt_array[_i].str, v)) {		\
				variable |= opt_array[_i].val;		\
				break;					\
			}						\
		if (!opt_array[_i].str || !*opt_array[_i].str)		\
			goto needs_val;					\
	}
	if (!opt || !*opt)
		goto no_mount_options;
145
	ntfs_debug("Entering with mount options string: %s", opt);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
146 147 148 149 150 151 152 153 154
	while ((p = strsep(&opt, ","))) {
		if ((v = strchr(p, '=')))
			*v++ = '\0';
		NTFS_GETOPT("uid", uid)
		else NTFS_GETOPT("gid", gid)
		else NTFS_GETOPT("umask", fmask = dmask)
		else NTFS_GETOPT("fmask", fmask)
		else NTFS_GETOPT("dmask", dmask)
		else NTFS_GETOPT("mft_zone_multiplier", mft_zone_multiplier)
155 156 157
		else NTFS_GETOPT_WITH_DEFAULT("sloppy", sloppy, TRUE)
		else NTFS_GETOPT_BOOL("show_sys_files", show_sys_files)
		else NTFS_GETOPT_BOOL("case_sensitive", case_sensitive)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
158 159
		else NTFS_GETOPT_OPTIONS_ARRAY("errors", on_errors,
				on_errors_arr)
160 161 162 163
		else if (!strcmp(p, "posix") || !strcmp(p, "show_inodes"))
			ntfs_warning(vol->sb, "Ignoring obsolete option %s.",
					p);
		else if (!strcmp(p, "nls") || !strcmp(p, "iocharset")) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
			if (!strcmp(p, "iocharset"))
				ntfs_warning(vol->sb, "Option iocharset is "
						"deprecated. Please use "
						"option nls=<charsetname> in "
						"the future.");
			if (!v || !*v)
				goto needs_arg;
use_utf8:
			old_nls = nls_map;
			nls_map = load_nls(v);
			if (!nls_map) {
				if (!old_nls) {
					ntfs_error(vol->sb, "NLS character set "
							"%s not found.", v);
					return FALSE;
				}
				ntfs_error(vol->sb, "NLS character set %s not "
						"found. Using previous one %s.",
						v, old_nls->charset);
				nls_map = old_nls;
			} else /* nls_map */ {
				if (old_nls)
					unload_nls(old_nls);
			}
		} else if (!strcmp(p, "utf8")) {
			BOOL val = FALSE;
			ntfs_warning(vol->sb, "Option utf8 is no longer "
				   "supported, using option nls=utf8. Please "
				   "use option nls=utf8 in the future and "
				   "make sure utf8 is compiled either as a "
				   "module or into the kernel.");
			if (!v || !*v)
				val = TRUE;
			else if (!simple_getbool(v, &val))
				goto needs_bool;
			if (val) {
				v = utf8;
				goto use_utf8;
			}
		} else {
			ntfs_error(vol->sb, "Unrecognized mount option %s.", p);
			if (errors < INT_MAX)
				errors++;
		}
#undef NTFS_GETOPT_OPTIONS_ARRAY
209
#undef NTFS_GETOPT_BOOL
Anton Altaparmakov's avatar
Anton Altaparmakov committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
#undef NTFS_GETOPT
#undef NTFS_GETOPT_WITH_DEFAULT
	}
no_mount_options:
	if (errors && !sloppy)
		return FALSE;
	if (sloppy)
		ntfs_warning(vol->sb, "Sloppy option given. Ignoring "
				"unrecognized mount option(s) and continuing.");
	/* Keep this first! */
	if (on_errors != -1) {
		if (!on_errors) {
			ntfs_error(vol->sb, "Invalid errors option argument "
					"or bug in options parser.");
			return FALSE;
		}
	}
	if (nls_map) {
228
		if (vol->nls_map && vol->nls_map != nls_map) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
			ntfs_error(vol->sb, "Cannot change NLS character set "
					"on remount.");
			return FALSE;
		} /* else (!vol->nls_map) */
		ntfs_debug("Using NLS character set %s.", nls_map->charset);
		vol->nls_map = nls_map;
	} else /* (!nls_map) */ {
		if (!vol->nls_map) {
			vol->nls_map = load_nls_default();
			if (!vol->nls_map) {
				ntfs_error(vol->sb, "Failed to load default "
						"NLS character set.");
				return FALSE;
			}
			ntfs_debug("Using default NLS character set (%s).",
					vol->nls_map->charset);
		}
	}
	if (mft_zone_multiplier != -1) {
		if (vol->mft_zone_multiplier && vol->mft_zone_multiplier !=
				mft_zone_multiplier) {
			ntfs_error(vol->sb, "Cannot change mft_zone_multiplier "
					"on remount.");
			return FALSE;
		}
		if (mft_zone_multiplier < 1 || mft_zone_multiplier > 4) {
			ntfs_error(vol->sb, "Invalid mft_zone_multiplier. "
					"Using default value, i.e. 1.");
			mft_zone_multiplier = 1;
		}
		vol->mft_zone_multiplier = mft_zone_multiplier;
260 261
	}
	if (!vol->mft_zone_multiplier)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
262 263 264
		vol->mft_zone_multiplier = 1;
	if (on_errors != -1)
		vol->on_errors = on_errors;
265 266
	if (!vol->on_errors || vol->on_errors == ON_ERRORS_RECOVER)
		vol->on_errors |= ON_ERRORS_CONTINUE;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
267 268 269 270 271 272 273 274
	if (uid != (uid_t)-1)
		vol->uid = uid;
	if (gid != (gid_t)-1)
		vol->gid = gid;
	if (fmask != (mode_t)-1)
		vol->fmask = fmask;
	if (dmask != (mode_t)-1)
		vol->dmask = dmask;
275 276 277 278 279 280 281 282 283 284 285 286
	if (show_sys_files != -1) {
		if (show_sys_files)
			NVolSetShowSystemFiles(vol);
		else
			NVolClearShowSystemFiles(vol);
	}
	if (case_sensitive != -1) {
		if (case_sensitive)
			NVolSetCaseSensitive(vol);
		else
			NVolClearCaseSensitive(vol);
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
287 288 289 290 291 292 293 294 295 296 297 298
	return TRUE;
needs_arg:
	ntfs_error(vol->sb, "The %s option requires an argument.", p);
	return FALSE;
needs_bool:
	ntfs_error(vol->sb, "The %s option requires a boolean argument.", p);
	return FALSE;
needs_val:
	ntfs_error(vol->sb, "Invalid %s option argument: %s", p, ov);
	return FALSE;
}

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
#ifdef NTFS_RW

/**
 * ntfs_write_volume_flags - write new flags to the volume information flags
 * @vol:	ntfs volume on which to modify the flags
 * @flags:	new flags value for the volume information flags
 *
 * Internal function.  You probably want to use ntfs_{set,clear}_volume_flags()
 * instead (see below).
 *
 * Replace the volume information flags on the volume @vol with the value
 * supplied in @flags.  Note, this overwrites the volume information flags, so
 * make sure to combine the flags you want to modify with the old flags and use
 * the result when calling ntfs_write_volume_flags().
 *
 * Return 0 on success and -errno on error.
 */
static int ntfs_write_volume_flags(ntfs_volume *vol, const VOLUME_FLAGS flags)
{
	ntfs_inode *ni = NTFS_I(vol->vol_ino);
	MFT_RECORD *m;
	VOLUME_INFORMATION *vi;
	attr_search_context *ctx;
	int err;

	ntfs_debug("Entering, old flags = 0x%x, new flags = 0x%x.",
			vol->vol_flags, flags);
	if (vol->vol_flags == flags)
		goto done;
	BUG_ON(!ni);
	m = map_mft_record(ni);
	if (IS_ERR(m)) {
		err = PTR_ERR(m);
		goto err_out;
	}
	ctx = get_attr_search_ctx(ni, m);
	if (!ctx) {
		err = -ENOMEM;
		goto put_unm_err_out;
	}
	if (!lookup_attr(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0, ctx)) {
		err = -EIO;
		goto put_unm_err_out;
	}
	vi = (VOLUME_INFORMATION*)((u8*)ctx->attr +
			le16_to_cpu(ctx->attr->data.resident.value_offset));
	vol->vol_flags = vi->flags = flags;
	flush_dcache_mft_record_page(ctx->ntfs_ino);
	mark_mft_record_dirty(ctx->ntfs_ino);
	put_attr_search_ctx(ctx);
	unmap_mft_record(ni);
done:
	ntfs_debug("Done.");
	return 0;
put_unm_err_out:
	if (ctx)
		put_attr_search_ctx(ctx);
	unmap_mft_record(ni);
err_out:
	ntfs_error(vol->sb, "Failed with error code %i.", -err);
	return err;
}

/**
 * ntfs_set_volume_flags - set bits in the volume information flags
 * @vol:	ntfs volume on which to modify the flags
 * @flags:	flags to set on the volume
 *
 * Set the bits in @flags in the volume information flags on the volume @vol.
 *
 * Return 0 on success and -errno on error.
 */
static inline int ntfs_set_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
{
	flags &= VOLUME_FLAGS_MASK;
	return ntfs_write_volume_flags(vol, vol->vol_flags | flags);
}

/**
 * ntfs_clear_volume_flags - clear bits in the volume information flags
 * @vol:	ntfs volume on which to modify the flags
 * @flags:	flags to clear on the volume
 *
 * Clear the bits in @flags in the volume information flags on the volume @vol.
 *
 * Return 0 on success and -errno on error.
 */
static inline int ntfs_clear_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)
{
	flags &= VOLUME_FLAGS_MASK;
	return ntfs_write_volume_flags(vol, vol->vol_flags & ~flags);
}

#endif /* NTFS_RW */

Anton Altaparmakov's avatar
Anton Altaparmakov committed
394 395 396 397 398 399 400 401
/**
 * ntfs_remount - change the mount options of a mounted ntfs filesystem
 * @sb:		superblock of mounted ntfs filesystem
 * @flags:	remount flags
 * @opt:	remount options string
 *
 * Change the mount options of an already mounted ntfs filesystem.
 *
402 403
 * NOTE:  The VFS sets the @sb->s_flags remount flags to @flags after
 * ntfs_remount() returns successfully (i.e. returns 0).  Otherwise,
Anton Altaparmakov's avatar
Anton Altaparmakov committed
404 405 406 407 408 409
 * @sb->s_flags are not changed.
 */
static int ntfs_remount(struct super_block *sb, int *flags, char *opt)
{
	ntfs_volume *vol = NTFS_SB(sb);

410
	ntfs_debug("Entering with remount options string: %s", opt);
411 412 413
#ifndef NTFS_RW
	/* For read-only compiled driver, enforce all read-only flags. */
	*flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
414
#else /* NTFS_RW */
415 416
	/*
	 * For the read-write compiled driver, if we are remounting read-write,
417 418
	 * make sure there are no volume errors and that no unsupported volume
	 * flags are set.  Also, empty the logfile journal as it would become
419 420
	 * stale as soon as something is written to the volume and mark the
	 * volume dirty so that chkdsk is run if the volume is not umounted
421 422
	 * cleanly.  Finally, mark the quotas out of date so Windows rescans
	 * the volume on boot and updates them.
423 424 425
	 *
	 * When remounting read-only, mark the volume clean if no volume errors
	 * have occured.
426 427
	 */
	if ((sb->s_flags & MS_RDONLY) && !(*flags & MS_RDONLY)) {
428 429
		static const char *es = ".  Cannot remount read-write.";

430
		/* Remounting read-write. */
431
		if (NVolErrors(vol)) {
432 433 434 435
			ntfs_error(sb, "Volume has errors and is read-only%s",
					es);
			return -EROFS;
		}
436 437 438 439
		if (vol->vol_flags & VOLUME_IS_DIRTY) {
			ntfs_error(sb, "Volume is dirty and read-only%s", es);
			return -EROFS;
		}
440 441 442 443 444
		if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
			ntfs_error(sb, "Volume has unsupported flags set and "
					"is read-only%s", es);
			return -EROFS;
		}
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
		if (ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
			ntfs_error(sb, "Failed to set dirty bit in volume "
					"information flags%s", es);
			return -EROFS;
		}
#if 0
		// TODO: Enable this code once we start modifying anything that
		//	 is different between NTFS 1.2 and 3.x...
		/* Set NT4 compatibility flag on newer NTFS version volumes. */
		if ((vol->major_ver > 1)) {
			if (ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
				ntfs_error(sb, "Failed to set NT4 "
						"compatibility flag%s", es);
				NVolSetErrors(vol);
				return -EROFS;
			}
		}
#endif
463 464 465 466
		if (!ntfs_empty_logfile(vol->logfile_ino)) {
			ntfs_error(sb, "Failed to empty journal $LogFile%s",
					es);
			NVolSetErrors(vol);
467 468
			return -EROFS;
		}
469 470 471 472 473 474
		if (!ntfs_mark_quotas_out_of_date(vol)) {
			ntfs_error(sb, "Failed to mark quotas out of date%s",
					es);
			NVolSetErrors(vol);
			return -EROFS;
		}
475 476 477 478 479 480 481 482
	} else if (!(sb->s_flags & MS_RDONLY) && (*flags & MS_RDONLY)) {
		/* Remounting read-only. */
		if (!NVolErrors(vol)) {
			if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
				ntfs_warning(sb, "Failed to clear dirty bit "
						"in volume information "
						"flags.  Run chkdsk.");
		}
483
	}
484
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
485 486 487 488 489

	// TODO: Deal with *flags.

	if (!parse_options(vol, opt))
		return -EINVAL;
490
	ntfs_debug("Done.");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	return 0;
}

/**
 * is_boot_sector_ntfs - check whether a boot sector is a valid NTFS boot sector
 * @sb:		Super block of the device to which @b belongs.
 * @b:		Boot sector of device @sb to check.
 * @silent:	If TRUE, all output will be silenced.
 *
 * is_boot_sector_ntfs() checks whether the boot sector @b is a valid NTFS boot
 * sector. Returns TRUE if it is valid and FALSE if not.
 *
 * @sb is only needed for warning/error output, i.e. it can be NULL when silent
 * is TRUE.
 */
static BOOL is_boot_sector_ntfs(const struct super_block *sb,
		const NTFS_BOOT_SECTOR *b, const BOOL silent)
{
	/*
	 * Check that checksum == sum of u32 values from b to the checksum
	 * field. If checksum is zero, no checking is done.
	 */
	if ((void*)b < (void*)&b->checksum && b->checksum) {
		u32 i, *u;
		for (i = 0, u = (u32*)b; u < (u32*)(&b->checksum); ++u)
			i += le32_to_cpup(u);
		if (le32_to_cpu(b->checksum) != i)
			goto not_ntfs;
	}
	/* Check OEMidentifier is "NTFS    " */
	if (b->oem_id != magicNTFS)
		goto not_ntfs;
	/* Check bytes per sector value is between 256 and 4096. */
	if (le16_to_cpu(b->bpb.bytes_per_sector) <  0x100 ||
			le16_to_cpu(b->bpb.bytes_per_sector) > 0x1000)
		goto not_ntfs;
	/* Check sectors per cluster value is valid. */
	switch (b->bpb.sectors_per_cluster) {
	case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128:
		break;
	default:
		goto not_ntfs;
	}
	/* Check the cluster size is not above 65536 bytes. */
	if ((u32)le16_to_cpu(b->bpb.bytes_per_sector) *
			b->bpb.sectors_per_cluster > 0x10000)
		goto not_ntfs;
	/* Check reserved/unused fields are really zero. */
	if (le16_to_cpu(b->bpb.reserved_sectors) ||
			le16_to_cpu(b->bpb.root_entries) ||
			le16_to_cpu(b->bpb.sectors) ||
			le16_to_cpu(b->bpb.sectors_per_fat) ||
			le32_to_cpu(b->bpb.large_sectors) || b->bpb.fats)
		goto not_ntfs;
	/* Check clusters per file mft record value is valid. */
546
	if ((u8)b->clusters_per_mft_record < 0xe1 ||
Anton Altaparmakov's avatar
Anton Altaparmakov committed
547 548 549 550 551 552 553 554
			(u8)b->clusters_per_mft_record > 0xf7)
		switch (b->clusters_per_mft_record) {
		case 1: case 2: case 4: case 8: case 16: case 32: case 64:
			break;
		default:
			goto not_ntfs;
		}
	/* Check clusters per index block value is valid. */
555
	if ((u8)b->clusters_per_index_record < 0xe1 ||
Anton Altaparmakov's avatar
Anton Altaparmakov committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
			(u8)b->clusters_per_index_record > 0xf7)
		switch (b->clusters_per_index_record) {
		case 1: case 2: case 4: case 8: case 16: case 32: case 64:
			break;
		default:
			goto not_ntfs;
		}
	/*
	 * Check for valid end of sector marker. We will work without it, but
	 * many BIOSes will refuse to boot from a bootsector if the magic is
	 * incorrect, so we emit a warning.
	 */
	if (!silent && b->end_of_sector_marker != cpu_to_le16(0xaa55))
		ntfs_warning(sb, "Invalid end of sector marker.");
	return TRUE;
not_ntfs:
	return FALSE;
}

/**
576
 * read_ntfs_boot_sector - read the NTFS boot sector of a device
Anton Altaparmakov's avatar
Anton Altaparmakov committed
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
 * @sb:		super block of device to read the boot sector from
 * @silent:	if true, suppress all output
 *
 * Reads the boot sector from the device and validates it. If that fails, tries
 * to read the backup boot sector, first from the end of the device a-la NT4 and
 * later and then from the middle of the device a-la NT3.51 and before.
 *
 * If a valid boot sector is found but it is not the primary boot sector, we
 * repair the primary boot sector silently (unless the device is read-only or
 * the primary boot sector is not accessible).
 *
 * NOTE: To call this function, @sb must have the fields s_dev, the ntfs super
 * block (u.ntfs_sb), nr_blocks and the device flags (s_flags) initialized
 * to their respective values.
 *
 * Return the unlocked buffer head containing the boot sector or NULL on error.
 */
static struct buffer_head *read_ntfs_boot_sector(struct super_block *sb,
		const int silent)
{
	const char *read_err_str = "Unable to read %s boot sector.";
	struct buffer_head *bh_primary, *bh_backup;
	long nr_blocks = NTFS_SB(sb)->nr_blocks;

	/* Try to read primary boot sector. */
	if ((bh_primary = sb_bread(sb, 0))) {
		if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
				bh_primary->b_data, silent))
			return bh_primary;
		if (!silent)
			ntfs_error(sb, "Primary boot sector is invalid.");
	} else if (!silent)
		ntfs_error(sb, read_err_str, "primary");
610
	if (!(NTFS_SB(sb)->on_errors & ON_ERRORS_RECOVER)) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
		if (bh_primary)
			brelse(bh_primary);
		if (!silent)
			ntfs_error(sb, "Mount option errors=recover not used. "
					"Aborting without trying to recover.");
		return NULL;
	}
	/* Try to read NT4+ backup boot sector. */
	if ((bh_backup = sb_bread(sb, nr_blocks - 1))) {
		if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
				bh_backup->b_data, silent))
			goto hotfix_primary_boot_sector;
		brelse(bh_backup);
	} else if (!silent)
		ntfs_error(sb, read_err_str, "backup");
	/* Try to read NT3.51- backup boot sector. */
	if ((bh_backup = sb_bread(sb, nr_blocks >> 1))) {
		if (is_boot_sector_ntfs(sb, (NTFS_BOOT_SECTOR*)
				bh_backup->b_data, silent))
			goto hotfix_primary_boot_sector;
		if (!silent)
			ntfs_error(sb, "Could not find a valid backup boot "
					"sector.");
		brelse(bh_backup);
	} else if (!silent)
		ntfs_error(sb, read_err_str, "backup");
	/* We failed. Cleanup and return. */
	if (bh_primary)
		brelse(bh_primary);
	return NULL;
hotfix_primary_boot_sector:
	if (bh_primary) {
		/*
		 * If we managed to read sector zero and the volume is not
		 * read-only, copy the found, valid backup boot sector to the
		 * primary boot sector.
		 */
		if (!(sb->s_flags & MS_RDONLY)) {
			ntfs_warning(sb, "Hot-fix: Recovering invalid primary "
					"boot sector from backup copy.");
			memcpy(bh_primary->b_data, bh_backup->b_data,
					sb->s_blocksize);
			mark_buffer_dirty(bh_primary);
654
			sync_dirty_buffer(bh_primary);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
			if (buffer_uptodate(bh_primary)) {
				brelse(bh_backup);
				return bh_primary;
			}
			ntfs_error(sb, "Hot-fix: Device write error while "
					"recovering primary boot sector.");
		} else {
			ntfs_warning(sb, "Hot-fix: Recovery of primary boot "
					"sector failed: Read-only mount.");
		}
		brelse(bh_primary);
	}
	ntfs_warning(sb, "Using backup boot sector.");
	return bh_backup;
}

/**
 * parse_ntfs_boot_sector - parse the boot sector and store the data in @vol
 * @vol:	volume structure to initialise with data from boot sector
 * @b:		boot sector to parse
675
 *
Anton Altaparmakov's avatar
Anton Altaparmakov committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
 * Parse the ntfs boot sector @b and store all imporant information therein in
 * the ntfs super block @vol. Return TRUE on success and FALSE on error.
 */
static BOOL parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)
{
	unsigned int sectors_per_cluster_bits, nr_hidden_sects;
	int clusters_per_mft_record, clusters_per_index_record;
	s64 ll;

	vol->sector_size = le16_to_cpu(b->bpb.bytes_per_sector);
	vol->sector_size_bits = ffs(vol->sector_size) - 1;
	ntfs_debug("vol->sector_size = %i (0x%x)", vol->sector_size,
			vol->sector_size);
	ntfs_debug("vol->sector_size_bits = %i (0x%x)", vol->sector_size_bits,
			vol->sector_size_bits);
	if (vol->sector_size != vol->sb->s_blocksize)
		ntfs_warning(vol->sb, "The boot sector indicates a sector size "
				"different from the device sector size.");
	ntfs_debug("sectors_per_cluster = 0x%x", b->bpb.sectors_per_cluster);
	sectors_per_cluster_bits = ffs(b->bpb.sectors_per_cluster) - 1;
	ntfs_debug("sectors_per_cluster_bits = 0x%x",
			sectors_per_cluster_bits);
	nr_hidden_sects = le32_to_cpu(b->bpb.hidden_sectors);
	ntfs_debug("number of hidden sectors = 0x%x", nr_hidden_sects);
	vol->cluster_size = vol->sector_size << sectors_per_cluster_bits;
	vol->cluster_size_mask = vol->cluster_size - 1;
	vol->cluster_size_bits = ffs(vol->cluster_size) - 1;
	ntfs_debug("vol->cluster_size = %i (0x%x)", vol->cluster_size,
			vol->cluster_size);
	ntfs_debug("vol->cluster_size_mask = 0x%x", vol->cluster_size_mask);
	ntfs_debug("vol->cluster_size_bits = %i (0x%x)",
			vol->cluster_size_bits, vol->cluster_size_bits);
	if (vol->sector_size > vol->cluster_size) {
		ntfs_error(vol->sb, "Sector sizes above the cluster size are "
				"not supported. Sorry.");
		return FALSE;
	}
	if (vol->sb->s_blocksize > vol->cluster_size) {
		ntfs_error(vol->sb, "Cluster sizes smaller than the device "
				"sector size are not supported. Sorry.");
		return FALSE;
	}
	clusters_per_mft_record = b->clusters_per_mft_record;
	ntfs_debug("clusters_per_mft_record = %i (0x%x)",
			clusters_per_mft_record, clusters_per_mft_record);
	if (clusters_per_mft_record > 0)
		vol->mft_record_size = vol->cluster_size <<
				(ffs(clusters_per_mft_record) - 1);
	else
		/*
		 * When mft_record_size < cluster_size, clusters_per_mft_record
		 * = -log2(mft_record_size) bytes. mft_record_size normaly is
		 * 1024 bytes, which is encoded as 0xF6 (-10 in decimal).
		 */
		vol->mft_record_size = 1 << -clusters_per_mft_record;
	vol->mft_record_size_mask = vol->mft_record_size - 1;
	vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1;
	ntfs_debug("vol->mft_record_size = %i (0x%x)", vol->mft_record_size,
			vol->mft_record_size);
	ntfs_debug("vol->mft_record_size_mask = 0x%x",
			vol->mft_record_size_mask);
	ntfs_debug("vol->mft_record_size_bits = %i (0x%x)",
738
			vol->mft_record_size_bits, vol->mft_record_size_bits);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
739 740
	clusters_per_index_record = b->clusters_per_index_record;
	ntfs_debug("clusters_per_index_record = %i (0x%x)",
741
			clusters_per_index_record, clusters_per_index_record);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755
	if (clusters_per_index_record > 0)
		vol->index_record_size = vol->cluster_size <<
				(ffs(clusters_per_index_record) - 1);
	else
		/*
		 * When index_record_size < cluster_size,
		 * clusters_per_index_record = -log2(index_record_size) bytes.
		 * index_record_size normaly equals 4096 bytes, which is
		 * encoded as 0xF4 (-12 in decimal).
		 */
		vol->index_record_size = 1 << -clusters_per_index_record;
	vol->index_record_size_mask = vol->index_record_size - 1;
	vol->index_record_size_bits = ffs(vol->index_record_size) - 1;
	ntfs_debug("vol->index_record_size = %i (0x%x)",
756
			vol->index_record_size, vol->index_record_size);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
757 758 759 760 761 762 763 764 765 766 767
	ntfs_debug("vol->index_record_size_mask = 0x%x",
			vol->index_record_size_mask);
	ntfs_debug("vol->index_record_size_bits = %i (0x%x)",
			vol->index_record_size_bits,
			vol->index_record_size_bits);
	/*
	 * Get the size of the volume in clusters and check for 64-bit-ness.
	 * Windows currently only uses 32 bits to save the clusters so we do
	 * the same as it is much faster on 32-bit CPUs.
	 */
	ll = sle64_to_cpu(b->number_of_sectors) >> sectors_per_cluster_bits;
768
	if ((u64)ll >= 1ULL << 32) {
769
		ntfs_error(vol->sb, "Cannot handle 64-bit clusters. Sorry.");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
770 771
		return FALSE;
	}
772
	vol->nr_clusters = ll;
773
	ntfs_debug("vol->nr_clusters = 0x%llx", (long long)vol->nr_clusters);
774 775 776 777 778 779 780
	/*
	 * On an architecture where unsigned long is 32-bits, we restrict the
	 * volume size to 2TiB (2^41). On a 64-bit architecture, the compiler
	 * will hopefully optimize the whole check away.
	 */
	if (sizeof(unsigned long) < 8) {
		if ((ll << vol->cluster_size_bits) >= (1ULL << 41)) {
781 782
			ntfs_error(vol->sb, "Volume size (%lluTiB) is too "
					"large for this architecture. Maximum "
783
					"supported is 2TiB. Sorry.",
784 785
					(unsigned long long)ll >> (40 -
					vol->cluster_size_bits));
786 787 788
			return FALSE;
		}
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
789
	ll = sle64_to_cpu(b->mft_lcn);
790
	if (ll >= vol->nr_clusters) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
791 792 793 794
		ntfs_error(vol->sb, "MFT LCN is beyond end of volume. Weird.");
		return FALSE;
	}
	vol->mft_lcn = ll;
795
	ntfs_debug("vol->mft_lcn = 0x%llx", (long long)vol->mft_lcn);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
796
	ll = sle64_to_cpu(b->mftmirr_lcn);
797
	if (ll >= vol->nr_clusters) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
798 799 800 801 802
		ntfs_error(vol->sb, "MFTMirr LCN is beyond end of volume. "
				"Weird.");
		return FALSE;
	}
	vol->mftmirr_lcn = ll;
803
	ntfs_debug("vol->mftmirr_lcn = 0x%llx", (long long)vol->mftmirr_lcn);
804
#ifdef NTFS_RW
805 806 807 808 809 810 811 812 813 814 815 816 817 818
	/*
	 * Work out the size of the mft mirror in number of mft records. If the
	 * cluster size is less than or equal to the size taken by four mft
	 * records, the mft mirror stores the first four mft records. If the
	 * cluster size is bigger than the size taken by four mft records, the
	 * mft mirror contains as many mft records as will fit into one
	 * cluster.
	 */
	if (vol->cluster_size <= (4 << vol->mft_record_size_bits))
		vol->mftmirr_size = 4;
	else
		vol->mftmirr_size = vol->cluster_size >>
				vol->mft_record_size_bits;
	ntfs_debug("vol->mftmirr_size = %i", vol->mftmirr_size);
819
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
820
	vol->serial_no = le64_to_cpu(b->volume_serial_number);
821
	ntfs_debug("vol->serial_no = 0x%llx",
Anton Altaparmakov's avatar
Anton Altaparmakov committed
822
			(unsigned long long)vol->serial_no);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
	return TRUE;
}

/**
 * setup_lcn_allocator - initialize the cluster allocator
 * @vol:	volume structure for which to setup the lcn allocator
 *
 * Setup the cluster (lcn) allocator to the starting values.
 */
static void setup_lcn_allocator(ntfs_volume *vol)
{
#ifdef NTFS_RW
	LCN mft_zone_size, mft_lcn;
#endif /* NTFS_RW */

	ntfs_debug("vol->mft_zone_multiplier = 0x%x",
			vol->mft_zone_multiplier);
#ifdef NTFS_RW
	/* Determine the size of the MFT zone. */
	mft_zone_size = vol->nr_clusters;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
843 844
	switch (vol->mft_zone_multiplier) {  /* % of volume size in clusters */
	case 4:
845
		mft_zone_size >>= 1;			/* 50%   */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
846 847
		break;
	case 3:
848 849
		mft_zone_size = (mft_zone_size +
				(mft_zone_size >> 1)) >> 2;	/* 37.5% */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
850 851
		break;
	case 2:
852
		mft_zone_size >>= 2;			/* 25%   */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
853
		break;
854
	/* case 1: */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
855
	default:
856
		mft_zone_size >>= 3;			/* 12.5% */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
857 858
		break;
	}
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
	/* Setup the mft zone. */
	vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
	ntfs_debug("vol->mft_zone_pos = 0x%llx",
			(unsigned long long)vol->mft_zone_pos);
	/*
	 * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
	 * source) and if the actual mft_lcn is in the expected place or even
	 * further to the front of the volume, extend the mft_zone to cover the
	 * beginning of the volume as well.  This is in order to protect the
	 * area reserved for the mft bitmap as well within the mft_zone itself.
	 * On non-standard volumes we do not protect it as the overhead would
	 * be higher than the speed increase we would get by doing it.
	 */
	mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size;
	if (mft_lcn * vol->cluster_size < 16 * 1024)
		mft_lcn = (16 * 1024 + vol->cluster_size - 1) /
				vol->cluster_size;
	if (vol->mft_zone_start <= mft_lcn)
		vol->mft_zone_start = 0;
878
	ntfs_debug("vol->mft_zone_start = 0x%llx",
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
			(unsigned long long)vol->mft_zone_start);
	/*
	 * Need to cap the mft zone on non-standard volumes so that it does
	 * not point outside the boundaries of the volume.  We do this by
	 * halving the zone size until we are inside the volume.
	 */
	vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
	while (vol->mft_zone_end >= vol->nr_clusters) {
		mft_zone_size >>= 1;
		vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
	}
	ntfs_debug("vol->mft_zone_end = 0x%llx",
			(unsigned long long)vol->mft_zone_end);
	/*
	 * Set the current position within each data zone to the start of the
	 * respective zone.
	 */
	vol->data1_zone_pos = vol->mft_zone_end;
	ntfs_debug("vol->data1_zone_pos = 0x%llx",
			(unsigned long long)vol->data1_zone_pos);
	vol->data2_zone_pos = 0;
	ntfs_debug("vol->data2_zone_pos = 0x%llx",
			(unsigned long long)vol->data2_zone_pos);
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
903 904
}

905 906 907 908 909 910 911 912 913 914 915 916 917
#ifdef NTFS_RW

/**
 * load_and_init_mft_mirror - load and setup the mft mirror inode for a volume
 * @vol:	ntfs super block describing device whose mft mirror to load
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL load_and_init_mft_mirror(ntfs_volume *vol)
{
	struct inode *tmp_ino;
	ntfs_inode *tmp_ni;

918
	ntfs_debug("Entering.");
919 920 921 922 923
	/* Get mft mirror inode. */
	tmp_ino = ntfs_iget(vol->sb, FILE_MFTMirr);
	if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
		if (!IS_ERR(tmp_ino))
			iput(tmp_ino);
924
		/* Caller will display error message. */
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
		return FALSE;
	}
	/*
	 * Re-initialize some specifics about $MFTMirr's inode as
	 * ntfs_read_inode() will have set up the default ones.
	 */
	/* Set uid and gid to root. */
	tmp_ino->i_uid = tmp_ino->i_gid = 0;
	/* Regular file.  No access for anyone. */
	tmp_ino->i_mode = S_IFREG;
	/* No VFS initiated operations allowed for $MFTMirr. */
	tmp_ino->i_op = &ntfs_empty_inode_ops;
	tmp_ino->i_fop = &ntfs_empty_file_ops;
	/* Put back our special address space operations. */
	tmp_ino->i_mapping->a_ops = &ntfs_mft_aops;
	tmp_ni = NTFS_I(tmp_ino);
	/* The $MFTMirr, like the $MFT is multi sector transfer protected. */
	NInoSetMstProtected(tmp_ni);
	/*
944
	 * Set up our little cheat allowing us to reuse the async read io
945 946 947 948 949
	 * completion handler for directories.
	 */
	tmp_ni->itype.index.block_size = vol->mft_record_size;
	tmp_ni->itype.index.block_size_bits = vol->mft_record_size_bits;
	vol->mftmirr_ino = tmp_ino;
950
	ntfs_debug("Done.");
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
	return TRUE;
}

/**
 * check_mft_mirror - compare contents of the mft mirror with the mft
 * @vol:	ntfs super block describing device whose mft mirror to check
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL check_mft_mirror(ntfs_volume *vol)
{
	unsigned long index;
	struct super_block *sb = vol->sb;
	ntfs_inode *mirr_ni;
	struct page *mft_page, *mirr_page;
	u8 *kmft, *kmirr;
967
	runlist_element *rl, rl2[2];
968 969
	int mrecs_per_page, i;

970
	ntfs_debug("Entering.");
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
	/* Compare contents of $MFT and $MFTMirr. */
	mrecs_per_page = PAGE_CACHE_SIZE / vol->mft_record_size;
	BUG_ON(!mrecs_per_page);
	BUG_ON(!vol->mftmirr_size);
	mft_page = mirr_page = NULL;
	kmft = kmirr = NULL;
	index = i = 0;
	do {
		u32 bytes;

		/* Switch pages if necessary. */
		if (!(i % mrecs_per_page)) {
			if (index) {
				ntfs_unmap_page(mft_page);
				ntfs_unmap_page(mirr_page);
			}
			/* Get the $MFT page. */
			mft_page = ntfs_map_page(vol->mft_ino->i_mapping,
					index);
			if (IS_ERR(mft_page)) {
				ntfs_error(sb, "Failed to read $MFT.");
				return FALSE;
			}
			kmft = page_address(mft_page);
			/* Get the $MFTMirr page. */
			mirr_page = ntfs_map_page(vol->mftmirr_ino->i_mapping,
					index);
			if (IS_ERR(mirr_page)) {
				ntfs_error(sb, "Failed to read $MFTMirr.");
				goto mft_unmap_out;
			}
			kmirr = page_address(mirr_page);
			++index;
		}
		/* Make sure the record is ok. */
1006
		if (ntfs_is_baad_recordp(kmft)) {
1007 1008 1009 1010 1011 1012 1013 1014
			ntfs_error(sb, "Incomplete multi sector transfer "
					"detected in mft record %i.", i);
mm_unmap_out:
			ntfs_unmap_page(mirr_page);
mft_unmap_out:
			ntfs_unmap_page(mft_page);
			return FALSE;
		}
1015
		if (ntfs_is_baad_recordp(kmirr)) {
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
			ntfs_error(sb, "Incomplete multi sector transfer "
					"detected in mft mirror record %i.", i);
			goto mm_unmap_out;
		}
		/* Get the amount of data in the current record. */
		bytes = le32_to_cpu(((MFT_RECORD*)kmft)->bytes_in_use);
		if (!bytes || bytes > vol->mft_record_size) {
			bytes = le32_to_cpu(((MFT_RECORD*)kmirr)->bytes_in_use);
			if (!bytes || bytes > vol->mft_record_size)
				bytes = vol->mft_record_size;
		}
		/* Compare the two records. */
		if (memcmp(kmft, kmirr, bytes)) {
			ntfs_error(sb, "$MFT and $MFTMirr (record %i) do not "
1030
					"match.  Run ntfsfix or chkdsk.", i);
1031 1032 1033 1034 1035 1036 1037 1038 1039
			goto mm_unmap_out;
		}
		kmft += vol->mft_record_size;
		kmirr += vol->mft_record_size;
	} while (++i < vol->mftmirr_size);
	/* Release the last pages. */
	ntfs_unmap_page(mft_page);
	ntfs_unmap_page(mirr_page);

1040
	/* Construct the mft mirror runlist by hand. */
1041 1042 1043 1044 1045 1046 1047 1048 1049
	rl2[0].vcn = 0;
	rl2[0].lcn = vol->mftmirr_lcn;
	rl2[0].length = (vol->mftmirr_size * vol->mft_record_size +
			vol->cluster_size - 1) / vol->cluster_size;
	rl2[1].vcn = rl2[0].length;
	rl2[1].lcn = LCN_ENOENT;
	rl2[1].length = 0;
	/*
	 * Because we have just read all of the mft mirror, we know we have
1050
	 * mapped the full runlist for it.
1051 1052
	 */
	mirr_ni = NTFS_I(vol->mftmirr_ino);
1053 1054
	down_read(&mirr_ni->runlist.lock);
	rl = mirr_ni->runlist.rl;
1055
	/* Compare the two runlists.  They must be identical. */
1056 1057 1058 1059
	i = 0;
	do {
		if (rl2[i].vcn != rl[i].vcn || rl2[i].lcn != rl[i].lcn ||
				rl2[i].length != rl[i].length) {
1060
			ntfs_error(sb, "$MFTMirr location mismatch.  "
1061
					"Run chkdsk.");
1062
			up_read(&mirr_ni->runlist.lock);
1063 1064 1065
			return FALSE;
		}
	} while (rl2[i++].length);
1066
	up_read(&mirr_ni->runlist.lock);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	ntfs_debug("Done.");
	return TRUE;
}

/**
 * load_and_check_logfile - load and check the logfile inode for a volume
 * @vol:	ntfs super block describing device whose logfile to load
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL load_and_check_logfile(ntfs_volume *vol)
{
	struct inode *tmp_ino;

	ntfs_debug("Entering.");
	tmp_ino = ntfs_iget(vol->sb, FILE_LogFile);
	if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
		if (!IS_ERR(tmp_ino))
			iput(tmp_ino);
		/* Caller will display error message. */
		return FALSE;
	}
	if (!ntfs_check_logfile(tmp_ino)) {
		iput(tmp_ino);
		/* ntfs_check_logfile() will have displayed error output. */
		return FALSE;
	}
	vol->logfile_ino = tmp_ino;
	ntfs_debug("Done.");
1096 1097 1098
	return TRUE;
}

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
/**
 * load_and_init_quota - load and setup the quota file for a volume if present
 * @vol:	ntfs super block describing device whose quota file to load
 *
 * Return TRUE on success or FALSE on error.  If $Quota is not present, we
 * leave vol->quota_ino as NULL and return success.
 */
static BOOL load_and_init_quota(ntfs_volume *vol)
{
	MFT_REF mref;
	struct inode *tmp_ino;
	ntfs_name *name = NULL;
	static const ntfschar Quota[7] = { const_cpu_to_le16('$'),
			const_cpu_to_le16('Q'), const_cpu_to_le16('u'),
			const_cpu_to_le16('o'), const_cpu_to_le16('t'),
			const_cpu_to_le16('a'), const_cpu_to_le16(0) };
	static ntfschar Q[3] = { const_cpu_to_le16('$'),
			const_cpu_to_le16('Q'), const_cpu_to_le16(0) };

	ntfs_debug("Entering.");
	/*
	 * Find the inode number for the quota file by looking up the filename
	 * $Quota in the extended system files directory $Extend.
	 */
	down(&vol->extend_ino->i_sem);
	mref = ntfs_lookup_inode_by_name(NTFS_I(vol->extend_ino), Quota, 6,
			&name);
	up(&vol->extend_ino->i_sem);
	if (IS_ERR_MREF(mref)) {
		/*
		 * If the file does not exist, quotas are disabled and have
		 * never been enabled on this volume, just return success.
		 */
		if (MREF_ERR(mref) == -ENOENT) {
			ntfs_debug("$Quota not present.  Volume does not have "
					"quotas enabled.");
			/*
			 * No need to try to set quotas out of date if they are
			 * not enabled.
			 */
			NVolSetQuotaOutOfDate(vol);
			return TRUE;
		}
		/* A real error occured. */
		ntfs_error(vol->sb, "Failed to find inode number for $Quota.");
		return FALSE;
	}
	/* We do not care for the type of match that was found. */
	if (name)
		kfree(name);
	/* Get the inode. */
	tmp_ino = ntfs_iget(vol->sb, MREF(mref));
	if (IS_ERR(tmp_ino) || is_bad_inode(tmp_ino)) {
		if (!IS_ERR(tmp_ino))
			iput(tmp_ino);
		ntfs_error(vol->sb, "Failed to load $Quota.");
		return FALSE;
	}
	vol->quota_ino = tmp_ino;
	/* Get the $Q index allocation attribute. */
	tmp_ino = ntfs_index_iget(vol->quota_ino, Q, 2);
	if (IS_ERR(tmp_ino)) {
		ntfs_error(vol->sb, "Failed to load $Quota/$Q index.");
		return FALSE;
	}
	vol->quota_q_ino = tmp_ino;
	ntfs_debug("Done.");
	return TRUE;
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
/**
 * load_and_init_attrdef - load the attribute definitions table for a volume
 * @vol:	ntfs super block describing device whose attrdef to load
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL load_and_init_attrdef(ntfs_volume *vol)
{
	struct super_block *sb = vol->sb;
	struct inode *ino;
	struct page *page;
	unsigned long index, max_index;
	unsigned int size;

	ntfs_debug("Entering.");
	/* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */
	ino = ntfs_iget(sb, FILE_AttrDef);
	if (IS_ERR(ino) || is_bad_inode(ino)) {
		if (!IS_ERR(ino))
			iput(ino);
		goto failed;
	}
	/* The size of FILE_AttrDef must be above 0 and fit inside 31 bits. */
	if (!ino->i_size || ino->i_size > 0x7fffffff)
		goto iput_failed;
	vol->attrdef = (ATTR_DEF*)ntfs_malloc_nofs(ino->i_size);
	if (!vol->attrdef)
		goto iput_failed;
	index = 0;
	max_index = ino->i_size >> PAGE_CACHE_SHIFT;
	size = PAGE_CACHE_SIZE;
	while (index < max_index) {
		/* Read the attrdef table and copy it into the linear buffer. */
read_partial_attrdef_page:
		page = ntfs_map_page(ino->i_mapping, index);
		if (IS_ERR(page))
			goto free_iput_failed;
		memcpy((u8*)vol->attrdef + (index++ << PAGE_CACHE_SHIFT),
				page_address(page), size);
		ntfs_unmap_page(page);
	};
	if (size == PAGE_CACHE_SIZE) {
		size = ino->i_size & ~PAGE_CACHE_MASK;
		if (size)
			goto read_partial_attrdef_page;
	}
	vol->attrdef_size = ino->i_size;
	ntfs_debug("Read %llu bytes from $AttrDef.", ino->i_size);
	iput(ino);
	return TRUE;
free_iput_failed:
	ntfs_free(vol->attrdef);
	vol->attrdef = NULL;
iput_failed:
	iput(ino);
failed:
	ntfs_error(sb, "Failed to initialize attribute definition table.");
	return FALSE;
}

1229 1230
#endif /* NTFS_RW */

Anton Altaparmakov's avatar
Anton Altaparmakov committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
/**
 * load_and_init_upcase - load the upcase table for an ntfs volume
 * @vol:	ntfs super block describing device whose upcase to load
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL load_and_init_upcase(ntfs_volume *vol)
{
	struct super_block *sb = vol->sb;
	struct inode *ino;
	struct page *page;
	unsigned long index, max_index;
	unsigned int size;
	int i, max;

	ntfs_debug("Entering.");
	/* Read upcase table and setup vol->upcase and vol->upcase_len. */
1248 1249 1250
	ino = ntfs_iget(sb, FILE_UpCase);
	if (IS_ERR(ino) || is_bad_inode(ino)) {
		if (!IS_ERR(ino))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1251 1252 1253 1254 1255
			iput(ino);
		goto upcase_failed;
	}
	/*
	 * The upcase size must not be above 64k Unicode characters, must not
1256
	 * be zero and must be a multiple of sizeof(ntfschar).
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1257
	 */
1258 1259
	if (!ino->i_size || ino->i_size & (sizeof(ntfschar) - 1) ||
			ino->i_size > 64ULL * 1024 * sizeof(ntfschar))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1260
		goto iput_upcase_failed;
1261
	vol->upcase = (ntfschar*)ntfs_malloc_nofs(ino->i_size);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	if (!vol->upcase)
		goto iput_upcase_failed;
	index = 0;
	max_index = ino->i_size >> PAGE_CACHE_SHIFT;
	size = PAGE_CACHE_SIZE;
	while (index < max_index) {
		/* Read the upcase table and copy it into the linear buffer. */
read_partial_upcase_page:
		page = ntfs_map_page(ino->i_mapping, index);
		if (IS_ERR(page))
			goto iput_upcase_failed;
		memcpy((char*)vol->upcase + (index++ << PAGE_CACHE_SHIFT),
				page_address(page), size);
		ntfs_unmap_page(page);
	};
	if (size == PAGE_CACHE_SIZE) {
		size = ino->i_size & ~PAGE_CACHE_MASK;
		if (size)
			goto read_partial_upcase_page;
	}
	vol->upcase_len = ino->i_size >> UCHAR_T_SIZE_BITS;
1283
	ntfs_debug("Read %llu bytes from $UpCase (expected %zu bytes).",
1284
			ino->i_size, 64 * 1024 * sizeof(ntfschar));
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
	iput(ino);
	down(&ntfs_lock);
	if (!default_upcase) {
		ntfs_debug("Using volume specified $UpCase since default is "
				"not present.");
		up(&ntfs_lock);
		return TRUE;
	}
	max = default_upcase_len;
	if (max > vol->upcase_len)
		max = vol->upcase_len;
	for (i = 0; i < max; i++)
		if (vol->upcase[i] != default_upcase[i])
			break;
	if (i == max) {
		ntfs_free(vol->upcase);
		vol->upcase = default_upcase;
		vol->upcase_len = max;
		ntfs_nr_upcase_users++;
		up(&ntfs_lock);
		ntfs_debug("Volume specified $UpCase matches default. Using "
				"default.");
		return TRUE;
	}
	up(&ntfs_lock);
	ntfs_debug("Using volume specified $UpCase since it does not match "
			"the default.");
	return TRUE;
iput_upcase_failed:
	iput(ino);
	ntfs_free(vol->upcase);
	vol->upcase = NULL;
upcase_failed:
	down(&ntfs_lock);
	if (default_upcase) {
		vol->upcase = default_upcase;
		vol->upcase_len = default_upcase_len;
		ntfs_nr_upcase_users++;
		up(&ntfs_lock);
		ntfs_error(sb, "Failed to load $UpCase from the volume. Using "
				"default.");
		return TRUE;
	}
	up(&ntfs_lock);
1329
	ntfs_error(sb, "Failed to initialize upcase table.");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
	return FALSE;
}

/**
 * load_system_files - open the system files using normal functions
 * @vol:	ntfs super block describing device whose system files to load
 *
 * Open the system files with normal access functions and complete setting up
 * the ntfs super block @vol.
 *
 * Return TRUE on success or FALSE on error.
 */
static BOOL load_system_files(ntfs_volume *vol)
{
	struct super_block *sb = vol->sb;
	MFT_RECORD *m;
	VOLUME_INFORMATION *vi;
	attr_search_context *ctx;

	ntfs_debug("Entering.");
1350 1351 1352 1353 1354 1355
#ifdef NTFS_RW
	/* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */
	if (!load_and_init_mft_mirror(vol) || !check_mft_mirror(vol)) {
		static const char *es1 = "Failed to load $MFTMirr";
		static const char *es2 = "$MFTMirr does not match $MFT";
		static const char *es3 = ".  Run ntfsfix and/or chkdsk.";
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1356

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
		/* If a read-write mount, convert it to a read-only mount. */
		if (!(sb->s_flags & MS_RDONLY)) {
			if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
					ON_ERRORS_CONTINUE))) {
				ntfs_error(sb, "%s and neither on_errors="
						"continue nor on_errors="
						"remount-ro was specified%s",
						!vol->mftmirr_ino ? es1 : es2,
						es3);
				goto iput_mirr_err_out;
			}
			sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
			ntfs_error(sb, "%s.  Mounting read-only%s",
					!vol->mftmirr_ino ? es1 : es2, es3);
		} else
			ntfs_warning(sb, "%s.  Will not be able to remount "
					"read-write%s",
					!vol->mftmirr_ino ? es1 : es2, es3);
		/* This will prevent a read-write remount. */
		NVolSetErrors(vol);
	}
#endif /* NTFS_RW */
1379 1380 1381 1382
	/* Get mft bitmap attribute inode. */
	vol->mftbmp_ino = ntfs_attr_iget(vol->mft_ino, AT_BITMAP, NULL, 0);
	if (IS_ERR(vol->mftbmp_ino)) {
		ntfs_error(sb, "Failed to load $MFT/$BITMAP attribute.");
1383
		goto iput_mirr_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1384
	}
1385
	/* Read upcase table and setup @vol->upcase and @vol->upcase_len. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1386
	if (!load_and_init_upcase(vol))
1387
		goto iput_mftbmp_err_out;
1388 1389 1390 1391 1392 1393 1394 1395
#ifdef NTFS_RW
	/*
	 * Read attribute definitions table and setup @vol->attrdef and
	 * @vol->attrdef_size.
	 */
	if (!load_and_init_attrdef(vol))
		goto iput_upcase_err_out;
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1396 1397 1398 1399 1400
	/*
	 * Get the cluster allocation bitmap inode and verify the size, no
	 * need for any locking at this stage as we are already running
	 * exclusively as we are mount in progress task.
	 */
1401 1402 1403
	vol->lcnbmp_ino = ntfs_iget(sb, FILE_Bitmap);
	if (IS_ERR(vol->lcnbmp_ino) || is_bad_inode(vol->lcnbmp_ino)) {
		if (!IS_ERR(vol->lcnbmp_ino))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1404 1405 1406
			iput(vol->lcnbmp_ino);
		goto bitmap_failed;
	}
1407
	if ((vol->nr_clusters + 7) >> 3 > vol->lcnbmp_ino->i_size) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1408 1409 1410
		iput(vol->lcnbmp_ino);
bitmap_failed:
		ntfs_error(sb, "Failed to load $Bitmap.");
1411
		goto iput_attrdef_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1412 1413 1414 1415 1416
	}
	/*
	 * Get the volume inode and setup our cache of the volume flags and
	 * version.
	 */
1417 1418 1419
	vol->vol_ino = ntfs_iget(sb, FILE_Volume);
	if (IS_ERR(vol->vol_ino) || is_bad_inode(vol->vol_ino)) {
		if (!IS_ERR(vol->vol_ino))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1420 1421 1422
			iput(vol->vol_ino);
volume_failed:
		ntfs_error(sb, "Failed to load $Volume.");
1423
		goto iput_lcnbmp_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1424
	}
1425
	m = map_mft_record(NTFS_I(vol->vol_ino));
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1426 1427 1428 1429 1430
	if (IS_ERR(m)) {
iput_volume_failed:
		iput(vol->vol_ino);
		goto volume_failed;
	}
1431
	if (!(ctx = get_attr_search_ctx(NTFS_I(vol->vol_ino), m))) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1432 1433 1434 1435 1436 1437 1438 1439
		ntfs_error(sb, "Failed to get attribute search context.");
		goto get_ctx_vol_failed;
	}
	if (!lookup_attr(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0, ctx) ||
			ctx->attr->non_resident || ctx->attr->flags) {
err_put_vol:
		put_attr_search_ctx(ctx);
get_ctx_vol_failed:
1440
		unmap_mft_record(NTFS_I(vol->vol_ino));
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1441 1442 1443
		goto iput_volume_failed;
	}
	vi = (VOLUME_INFORMATION*)((char*)ctx->attr +
1444
			le16_to_cpu(ctx->attr->data.resident.value_offset));
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1445 1446
	/* Some bounds checks. */
	if ((u8*)vi < (u8*)ctx->attr || (u8*)vi +
1447
			le32_to_cpu(ctx->attr->data.resident.value_length) >
1448
			(u8*)ctx->attr + le32_to_cpu(ctx->attr->length))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1449
		goto err_put_vol;
1450
	/* Copy the volume flags and version to the ntfs_volume structure. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1451 1452 1453 1454
	vol->vol_flags = vi->flags;
	vol->major_ver = vi->major_ver;
	vol->minor_ver = vi->minor_ver;
	put_attr_search_ctx(ctx);
1455
	unmap_mft_record(NTFS_I(vol->vol_ino));
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1456 1457
	printk(KERN_INFO "NTFS volume version %i.%i.\n", vol->major_ver,
			vol->minor_ver);
1458
#ifdef NTFS_RW
1459 1460
	/* Make sure that no unsupported volume flags are set. */
	if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
1461 1462
		static const char *es1a = "Volume is dirty";
		static const char *es1b = "Volume has unsupported flags set";
1463
		static const char *es2 = ".  Run chkdsk and mount in Windows.";
1464 1465 1466
		const char *es1;
		
		es1 = vol->vol_flags & VOLUME_IS_DIRTY ? es1a : es1b;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
		/* If a read-write mount, convert it to a read-only mount. */
		if (!(sb->s_flags & MS_RDONLY)) {
			if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
					ON_ERRORS_CONTINUE))) {
				ntfs_error(sb, "%s and neither on_errors="
						"continue nor on_errors="
						"remount-ro was specified%s",
						es1, es2);
				goto iput_vol_err_out;
			}
			sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
			ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
		} else
			ntfs_warning(sb, "%s.  Will not be able to remount "
					"read-write%s", es1, es2);
		/*
		 * Do not set NVolErrors() because ntfs_remount() re-checks the
		 * flags which we need to do in case any flags have changed.
		 */
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1487
	/*
1488 1489
	 * Get the inode for the logfile, check it and determine if the volume
	 * was shutdown cleanly.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1490
	 */
1491 1492
	if (!load_and_check_logfile(vol) ||
			!ntfs_is_logfile_clean(vol->logfile_ino)) {
1493 1494 1495 1496
		static const char *es1a = "Failed to load $LogFile";
		static const char *es1b = "$LogFile is not clean";
		static const char *es2 = ".  Mount in Windows.";
		const char *es1;
1497

1498
		es1 = !vol->logfile_ino ? es1a : es1b;
1499 1500 1501 1502 1503 1504 1505
		/* If a read-write mount, convert it to a read-only mount. */
		if (!(sb->s_flags & MS_RDONLY)) {
			if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
					ON_ERRORS_CONTINUE))) {
				ntfs_error(sb, "%s and neither on_errors="
						"continue nor on_errors="
						"remount-ro was specified%s",
1506
						es1, es2);
1507 1508 1509
				goto iput_logfile_err_out;
			}
			sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1510
			ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1511 1512
		} else
			ntfs_warning(sb, "%s.  Will not be able to remount "
1513
					"read-write%s", es1, es2);
1514 1515
		/* This will prevent a read-write remount. */
		NVolSetErrors(vol);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
	}
	/* If (still) a read-write mount, mark the volume dirty. */
	if (!(sb->s_flags & MS_RDONLY) &&
			ntfs_set_volume_flags(vol, VOLUME_IS_DIRTY)) {
		static const char *es1 = "Failed to set dirty bit in volume "
				"information flags";
		static const char *es2 = ".  Run chkdsk.";

		/* Convert to a read-only mount. */
		if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
				ON_ERRORS_CONTINUE))) {
			ntfs_error(sb, "%s and neither on_errors=continue nor "
					"on_errors=remount-ro was specified%s",
					es1, es2);
			goto iput_logfile_err_out;
		}
		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
		sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
		/*
		 * Do not set NVolErrors() because ntfs_remount() might manage
		 * to set the dirty flag in which case all would be well.
		 */
	}
#if 0
	// TODO: Enable this code once we start modifying anything that is
	//	 different between NTFS 1.2 and 3.x...
	/*
	 * If (still) a read-write mount, set the NT4 compatibility flag on
	 * newer NTFS version volumes.
	 */
	if (!(sb->s_flags & MS_RDONLY) && (vol->major_ver > 1) &&
			ntfs_set_volume_flags(vol, VOLUME_MOUNTED_ON_NT4)) {
		static const char *es1 = "Failed to set NT4 compatibility flag";
		static const char *es2 = ".  Run chkdsk.";

		/* Convert to a read-only mount. */
		if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
				ON_ERRORS_CONTINUE))) {
			ntfs_error(sb, "%s and neither on_errors=continue nor "
					"on_errors=remount-ro was specified%s",
					es1, es2);
			goto iput_logfile_err_out;
		}
		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
		sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
		NVolSetErrors(vol);
	}
#endif
	/* If (still) a read-write mount, empty the logfile. */
	if (!(sb->s_flags & MS_RDONLY) &&
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
			!ntfs_empty_logfile(vol->logfile_ino)) {
		static const char *es1 = "Failed to empty $LogFile";
		static const char *es2 = ".  Mount in Windows.";

		/* Convert to a read-only mount. */
		if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
				ON_ERRORS_CONTINUE))) {
			ntfs_error(sb, "%s and neither on_errors=continue nor "
					"on_errors=remount-ro was specified%s",
					es1, es2);
			goto iput_logfile_err_out;
		}
		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1579
		sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
1580
		NVolSetErrors(vol);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1581
	}
1582
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1583
	/* Get the root directory inode. */
1584 1585 1586
	vol->root_ino = ntfs_iget(sb, FILE_root);
	if (IS_ERR(vol->root_ino) || is_bad_inode(vol->root_ino)) {
		if (!IS_ERR(vol->root_ino))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1587 1588
			iput(vol->root_ino);
		ntfs_error(sb, "Failed to load root directory.");
1589
		goto iput_logfile_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1590 1591 1592 1593 1594 1595
	}
	/* If on NTFS versions before 3.0, we are done. */
	if (vol->major_ver < 3)
		return TRUE;
	/* NTFS 3.0+ specific initialization. */
	/* Get the security descriptors inode. */
1596 1597 1598
	vol->secure_ino = ntfs_iget(sb, FILE_Secure);
	if (IS_ERR(vol->secure_ino) || is_bad_inode(vol->secure_ino)) {
		if (!IS_ERR(vol->secure_ino))
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1599 1600
			iput(vol->secure_ino);
		ntfs_error(sb, "Failed to load $Secure.");
1601
		goto iput_root_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1602 1603 1604
	}
	// FIXME: Initialize security.
	/* Get the extended system files' directory inode. */
1605 1606 1607 1608
	vol->extend_ino = ntfs_iget(sb, FILE_Extend);
	if (IS_ERR(vol->extend_ino) || is_bad_inode(vol->extend_ino)) {
		if (!IS_ERR(vol->extend_ino))
			iput(vol->extend_ino);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1609
		ntfs_error(sb, "Failed to load $Extend.");
1610
		goto iput_sec_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1611
	}
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
#ifdef NTFS_RW
	/* Find the quota file, load it if present, and set it up. */
	if (!load_and_init_quota(vol)) {
		static const char *es1 = "Failed to load $Quota";
		static const char *es2 = ".  Run chkdsk.";

		/* If a read-write mount, convert it to a read-only mount. */
		if (!(sb->s_flags & MS_RDONLY)) {
			if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
					ON_ERRORS_CONTINUE))) {
				ntfs_error(sb, "%s and neither on_errors="
						"continue nor on_errors="
						"remount-ro was specified%s",
						es1, es2);
				goto iput_quota_err_out;
			}
			sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
			ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
		} else
			ntfs_warning(sb, "%s.  Will not be able to remount "
					"read-write%s", es1, es2);
		/* This will prevent a read-write remount. */
		NVolSetErrors(vol);
	}
	/* If (still) a read-write mount, mark the quotas out of date. */
	if (!(sb->s_flags & MS_RDONLY) &&
			!ntfs_mark_quotas_out_of_date(vol)) {
		static const char *es1 = "Failed to mark quotas out of date";
		static const char *es2 = ".  Run chkdsk.";

		/* Convert to a read-only mount. */
		if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO |
				ON_ERRORS_CONTINUE))) {
			ntfs_error(sb, "%s and neither on_errors=continue nor "
					"on_errors=remount-ro was specified%s",
					es1, es2);
			goto iput_quota_err_out;
		}
		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
		sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
		NVolSetErrors(vol);
	}
	// TODO: Delete or checkpoint the $UsnJrnl if it exists.
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1656
	return TRUE;
1657 1658 1659 1660 1661 1662 1663 1664
#ifdef NTFS_RW
iput_quota_err_out:
	if (vol->quota_q_ino)
		iput(vol->quota_q_ino);
	if (vol->quota_ino)
		iput(vol->quota_ino);
	iput(vol->extend_ino);
#endif /* NTFS_RW */
1665
iput_sec_err_out:
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1666
	iput(vol->secure_ino);
1667
iput_root_err_out:
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1668
	iput(vol->root_ino);
1669 1670 1671 1672
iput_logfile_err_out:
#ifdef NTFS_RW
	if (vol->logfile_ino)
		iput(vol->logfile_ino);
1673
iput_vol_err_out:
1674
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1675
	iput(vol->vol_ino);
1676
iput_lcnbmp_err_out:
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1677
	iput(vol->lcnbmp_ino);
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
iput_attrdef_err_out:
	vol->attrdef_size = 0;
	if (vol->attrdef) {
		ntfs_free(vol->attrdef);
		vol->attrdef = NULL;
	}
#ifdef NTFS_RW
iput_upcase_err_out:
#endif /* NTFS_RW */
	vol->upcase_len = 0;
	down(&ntfs_lock);
	if (vol->upcase == default_upcase) {
		ntfs_nr_upcase_users--;
		vol->upcase = NULL;
	}
	up(&ntfs_lock);
	if (vol->upcase) {
		ntfs_free(vol->upcase);
		vol->upcase = NULL;
	}
1698 1699
iput_mftbmp_err_out:
	iput(vol->mftbmp_ino);
1700 1701 1702 1703 1704
iput_mirr_err_out:
#ifdef NTFS_RW
	if (vol->mftmirr_ino)
		iput(vol->mftmirr_ino);
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1705 1706 1707 1708 1709
	return FALSE;
}

/**
 * ntfs_put_super - called by the vfs to unmount a volume
1710
 * @sb:		vfs superblock of volume to unmount
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1711 1712 1713 1714 1715 1716
 *
 * ntfs_put_super() is called by the VFS (from fs/super.c::do_umount()) when
 * the volume is being unmounted (umount system call has been invoked) and it
 * releases all inodes and memory belonging to the NTFS specific part of the
 * super block.
 */
1717
static void ntfs_put_super(struct super_block *sb)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1718
{
1719
	ntfs_volume *vol = NTFS_SB(sb);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1720 1721

	ntfs_debug("Entering.");
1722 1723 1724 1725 1726 1727 1728 1729 1730
#ifdef NTFS_RW
	/*
	 * Commit all inodes while they are still open in case some of them
	 * cause others to be dirtied.
	 */
	ntfs_commit_inode(vol->vol_ino);

	/* NTFS 3.0+ specific. */
	if (vol->major_ver >= 3) {
1731 1732 1733 1734 1735 1736
		if (vol->quota_q_ino)
			ntfs_commit_inode(vol->quota_q_ino);
		if (vol->quota_ino)
			ntfs_commit_inode(vol->quota_ino);
		if (vol->extend_ino)
			ntfs_commit_inode(vol->extend_ino);
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
		if (vol->secure_ino)
			ntfs_commit_inode(vol->secure_ino);
	}

	ntfs_commit_inode(vol->root_ino);

	down_write(&vol->lcnbmp_lock);
	ntfs_commit_inode(vol->lcnbmp_ino);
	up_write(&vol->lcnbmp_lock);

	down_write(&vol->mftbmp_lock);
	ntfs_commit_inode(vol->mftbmp_ino);
	up_write(&vol->mftbmp_lock);

	if (vol->logfile_ino)
		ntfs_commit_inode(vol->logfile_ino);

	if (vol->mftmirr_ino)
		ntfs_commit_inode(vol->mftmirr_ino);
	ntfs_commit_inode(vol->mft_ino);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777

	/*
	 * If a read-write mount and no volume errors have occured, mark the
	 * volume clean.  Also, re-commit all affected inodes.
	 */
	if (!(sb->s_flags & MS_RDONLY)) {
		if (!NVolErrors(vol)) {
			if (ntfs_clear_volume_flags(vol, VOLUME_IS_DIRTY))
				ntfs_warning(sb, "Failed to clear dirty bit "
						"in volume information "
						"flags.  Run chkdsk.");
			ntfs_commit_inode(vol->vol_ino);
			ntfs_commit_inode(vol->root_ino);
			if (vol->mftmirr_ino)
				ntfs_commit_inode(vol->mftmirr_ino);
			ntfs_commit_inode(vol->mft_ino);
		} else {
			ntfs_warning(sb, "Volume has errors.  Leaving volume "
					"marked dirty.  Run chkdsk.");
		}
	}
1778 1779
#endif /* NTFS_RW */

Anton Altaparmakov's avatar
Anton Altaparmakov committed
1780 1781
	iput(vol->vol_ino);
	vol->vol_ino = NULL;
1782

Anton Altaparmakov's avatar
Anton Altaparmakov committed
1783 1784
	/* NTFS 3.0+ specific clean up. */
	if (vol->major_ver >= 3) {
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
#ifdef NTFS_RW
		if (vol->quota_q_ino) {
			iput(vol->quota_q_ino);
			vol->quota_q_ino = NULL;
		}
		if (vol->quota_ino) {
			iput(vol->quota_ino);
			vol->quota_ino = NULL;
		}
#endif /* NTFS_RW */
		if (vol->extend_ino) {
			iput(vol->extend_ino);
			vol->extend_ino = NULL;
		}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1799 1800 1801 1802 1803
		if (vol->secure_ino) {
			iput(vol->secure_ino);
			vol->secure_ino = NULL;
		}
	}
1804

Anton Altaparmakov's avatar
Anton Altaparmakov committed
1805 1806
	iput(vol->root_ino);
	vol->root_ino = NULL;
1807

Anton Altaparmakov's avatar
Anton Altaparmakov committed
1808 1809 1810 1811
	down_write(&vol->lcnbmp_lock);
	iput(vol->lcnbmp_ino);
	vol->lcnbmp_ino = NULL;
	up_write(&vol->lcnbmp_lock);
1812

1813 1814 1815 1816 1817
	down_write(&vol->mftbmp_lock);
	iput(vol->mftbmp_ino);
	vol->mftbmp_ino = NULL;
	up_write(&vol->mftbmp_lock);

1818
#ifdef NTFS_RW
1819 1820 1821 1822
	if (vol->logfile_ino) {
		iput(vol->logfile_ino);
		vol->logfile_ino = NULL;
	}
1823
	if (vol->mftmirr_ino) {
1824 1825 1826
		/* Re-commit the mft mirror and mft just in case. */
		ntfs_commit_inode(vol->mftmirr_ino);
		ntfs_commit_inode(vol->mft_ino);
1827 1828 1829
		iput(vol->mftmirr_ino);
		vol->mftmirr_ino = NULL;
	}
1830
	/*
1831 1832 1833 1834 1835
	 * If any dirty inodes are left, throw away all mft data page cache
	 * pages to allow a clean umount.  This should never happen any more
	 * due to mft.c::ntfs_mft_writepage() cleaning all the dirty pages as
	 * the underlying mft records are written out and cleaned.  If it does,
	 * happen anyway, we want to know...
1836 1837 1838
	 */
	ntfs_commit_inode(vol->mft_ino);
	write_inode_now(vol->mft_ino, 1);
1839 1840
	if (!list_empty(&sb->s_dirty)) {
		const char *s1, *s2;
1841 1842 1843 1844 1845

		down(&vol->mft_ino->i_sem);
		truncate_inode_pages(vol->mft_ino->i_mapping, 0);
		up(&vol->mft_ino->i_sem);
		write_inode_now(vol->mft_ino, 1);
1846 1847 1848
		if (!list_empty(&sb->s_dirty)) {
			static const char *_s1 = "inodes";
			static const char *_s2 = "";
1849 1850 1851
			s1 = _s1;
			s2 = _s2;
		} else {
1852 1853 1854
			static const char *_s1 = "mft pages";
			static const char *_s2 = "They have been thrown "
					"away.  ";
1855 1856 1857
			s1 = _s1;
			s2 = _s2;
		}
1858 1859
		ntfs_error(sb, "Dirty %s found at umount time.  %sYou should "
				"run chkdsk.  Please email "
1860 1861 1862 1863
				"linux-ntfs-dev@lists.sourceforge.net and say "
				"that you saw this message.  Thank you.", s1,
				s2);
	}
1864
#endif /* NTFS_RW */
1865 1866 1867 1868

	iput(vol->mft_ino);
	vol->mft_ino = NULL;

1869 1870 1871 1872 1873 1874
	/* Throw away the table of attribute definitions. */
	vol->attrdef_size = 0;
	if (vol->attrdef) {
		ntfs_free(vol->attrdef);
		vol->attrdef = NULL;
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1875 1876
	vol->upcase_len = 0;
	/*
1877 1878
	 * Destroy the global default upcase table if necessary.  Also decrease
	 * the number of upcase users if we are a user.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
	 */
	down(&ntfs_lock);
	if (vol->upcase == default_upcase) {
		ntfs_nr_upcase_users--;
		vol->upcase = NULL;
	}
	if (!ntfs_nr_upcase_users && default_upcase) {
		ntfs_free(default_upcase);
		default_upcase = NULL;
	}
	if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
		free_compression_buffers();
	up(&ntfs_lock);
	if (vol->upcase) {
		ntfs_free(vol->upcase);
		vol->upcase = NULL;
	}
	if (vol->nls_map) {
		unload_nls(vol->nls_map);
		vol->nls_map = NULL;
	}
1900
	sb->s_fs_info = NULL;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1901 1902 1903 1904 1905 1906 1907 1908
	kfree(vol);
	return;
}

/**
 * get_nr_free_clusters - return the number of free clusters on a volume
 * @vol:	ntfs volume for which to obtain free cluster count
 *
1909 1910 1911 1912
 * Calculate the number of free clusters on the mounted NTFS volume @vol. We
 * actually calculate the number of clusters in use instead because this
 * allows us to not care about partial pages as these will be just zero filled
 * and hence not be counted as allocated clusters.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1913
 *
1914 1915 1916 1917 1918 1919 1920 1921 1922
 * The only particularity is that clusters beyond the end of the logical ntfs
 * volume will be marked as allocated to prevent errors which means we have to
 * discount those at the end. This is important as the cluster bitmap always
 * has a size in multiples of 8 bytes, i.e. up to 63 clusters could be outside
 * the logical volume and marked in use when they are not as they do not exist.
 *
 * If any pages cannot be read we assume all clusters in the erroring pages are
 * in use. This means we return an underestimate on errors which is better than
 * an overestimate.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1923
 */
1924
static s64 get_nr_free_clusters(ntfs_volume *vol)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1925
{
1926 1927
	s64 nr_free = vol->nr_clusters;
	u32 *kaddr;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1928 1929 1930 1931
	struct address_space *mapping = vol->lcnbmp_ino->i_mapping;
	filler_t *readpage = (filler_t*)mapping->a_ops->readpage;
	struct page *page;
	unsigned long index, max_index;
1932
	unsigned int max_size;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1933 1934 1935 1936 1937 1938

	ntfs_debug("Entering.");
	/* Serialize accesses to the cluster bitmap. */
	down_read(&vol->lcnbmp_lock);
	/*
	 * Convert the number of bits into bytes rounded up, then convert into
1939 1940
	 * multiples of PAGE_CACHE_SIZE, rounding up so that if we have one
	 * full and one partial page max_index = 2.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1941
	 */
1942 1943
	max_index = (((vol->nr_clusters + 7) >> 3) + PAGE_CACHE_SIZE - 1) >>
			PAGE_CACHE_SHIFT;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1944 1945
	/* Use multiples of 4 bytes. */
	max_size = PAGE_CACHE_SIZE >> 2;
1946
	ntfs_debug("Reading $Bitmap, max_index = 0x%lx, max_size = 0x%x.",
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1947
			max_index, max_size);
1948 1949
	for (index = 0UL; index < max_index; index++) {
		unsigned int i;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1950 1951 1952 1953
		/*
		 * Read the page from page cache, getting it from backing store
		 * if necessary, and increment the use count.
		 */
1954
		page = read_cache_page(mapping, index, (filler_t*)readpage,
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1955 1956 1957 1958
				NULL);
		/* Ignore pages which errored synchronously. */
		if (IS_ERR(page)) {
			ntfs_debug("Sync read_cache_page() error. Skipping "
1959 1960
					"page (index 0x%lx).", index);
			nr_free -= PAGE_CACHE_SIZE * 8;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1961 1962
			continue;
		}
1963
		wait_on_page_locked(page);
1964
		/* Ignore pages which errored asynchronously. */
Andrew Morton's avatar
Andrew Morton committed
1965
		if (!PageUptodate(page)) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1966
			ntfs_debug("Async read_cache_page() error. Skipping "
1967
					"page (index 0x%lx).", index);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1968
			page_cache_release(page);
1969
			nr_free -= PAGE_CACHE_SIZE * 8;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1970 1971
			continue;
		}
1972
		kaddr = (u32*)kmap_atomic(page, KM_USER0);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1973
		/*
1974 1975 1976 1977 1978
		 * For each 4 bytes, subtract the number of set bits. If this
		 * is the last page and it is partial we don't really care as
		 * it just means we do a little extra work but it won't affect
		 * the result as all out of range bytes are set to zero by
		 * ntfs_readpage().
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1979
		 */
1980 1981 1982 1983
	  	for (i = 0; i < max_size; i++)
			nr_free -= (s64)hweight32(kaddr[i]);
		kunmap_atomic(kaddr, KM_USER0);
		page_cache_release(page);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1984
	}
1985 1986 1987 1988 1989 1990 1991
	ntfs_debug("Finished reading $Bitmap, last index = 0x%lx.", index - 1);
	/*
	 * Fixup for eventual bits outside logical ntfs volume (see function
	 * description above).
	 */
	if (vol->nr_clusters & 63)
		nr_free += 64 - (vol->nr_clusters & 63);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1992
	up_read(&vol->lcnbmp_lock);
1993 1994 1995
	/* If errors occured we may well have gone below zero, fix this. */
	if (nr_free < 0)
		nr_free = 0;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
1996 1997 1998 1999 2000
	ntfs_debug("Exiting.");
	return nr_free;
}

/**
2001
 * __get_nr_free_mft_records - return the number of free inodes on a volume
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2002 2003 2004
 * @vol:	ntfs volume for which to obtain free inode count
 *
 * Calculate the number of free mft records (inodes) on the mounted NTFS
2005 2006 2007
 * volume @vol. We actually calculate the number of mft records in use instead
 * because this allows us to not care about partial pages as these will be just
 * zero filled and hence not be counted as allocated mft record.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2008
 *
2009 2010 2011
 * If any pages cannot be read we assume all mft records in the erroring pages
 * are in use. This means we return an underestimate on errors which is better
 * than an overestimate.
2012 2013
 *
 * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2014
 */
2015
static unsigned long __get_nr_free_mft_records(ntfs_volume *vol)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2016
{
2017
	s64 nr_free;
2018 2019 2020
	u32 *kaddr;
	struct address_space *mapping = vol->mftbmp_ino->i_mapping;
	filler_t *readpage = (filler_t*)mapping->a_ops->readpage;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2021
	struct page *page;
2022 2023
	unsigned long index, max_index;
	unsigned int max_size;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2024

2025
	ntfs_debug("Entering.");
2026 2027
	/* Number of mft records in file system (at this point in time). */
	nr_free = vol->mft_ino->i_size >> vol->mft_record_size_bits;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2028
	/*
2029 2030 2031
	 * Convert the maximum number of set bits into bytes rounded up, then
	 * convert into multiples of PAGE_CACHE_SIZE, rounding up so that if we
	 * have one full and one partial page max_index = 2.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2032
	 */
2033 2034 2035
	max_index = ((((NTFS_I(vol->mft_ino)->initialized_size >>
			vol->mft_record_size_bits) + 7) >> 3) +
			PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2036 2037 2038 2039
	/* Use multiples of 4 bytes. */
	max_size = PAGE_CACHE_SIZE >> 2;
	ntfs_debug("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = "
			"0x%x.", max_index, max_size);
2040 2041 2042 2043 2044 2045 2046 2047 2048
	for (index = 0UL; index < max_index; index++) {
		unsigned int i;
		/*
		 * Read the page from page cache, getting it from backing store
		 * if necessary, and increment the use count.
		 */
		page = read_cache_page(mapping, index, (filler_t*)readpage,
				NULL);
		/* Ignore pages which errored synchronously. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2049
		if (IS_ERR(page)) {
2050 2051 2052
			ntfs_debug("Sync read_cache_page() error. Skipping "
					"page (index 0x%lx).", index);
			nr_free -= PAGE_CACHE_SIZE * 8;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2053 2054
			continue;
		}
2055
		wait_on_page_locked(page);
2056 2057 2058 2059 2060 2061 2062 2063 2064
		/* Ignore pages which errored asynchronously. */
		if (!PageUptodate(page)) {
			ntfs_debug("Async read_cache_page() error. Skipping "
					"page (index 0x%lx).", index);
			page_cache_release(page);
			nr_free -= PAGE_CACHE_SIZE * 8;
			continue;
		}
		kaddr = (u32*)kmap_atomic(page, KM_USER0);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2065
		/*
2066 2067 2068 2069 2070
		 * For each 4 bytes, subtract the number of set bits. If this
		 * is the last page and it is partial we don't really care as
		 * it just means we do a little extra work but it won't affect
		 * the result as all out of range bytes are set to zero by
		 * ntfs_readpage().
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2071
		 */
2072 2073 2074 2075
	  	for (i = 0; i < max_size; i++)
			nr_free -= (s64)hweight32(kaddr[i]);
		kunmap_atomic(kaddr, KM_USER0);
		page_cache_release(page);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2076
	}
2077
	ntfs_debug("Finished reading $MFT/$BITMAP, last index = 0x%lx.",
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2078
			index - 1);
2079 2080 2081 2082
	/* If errors occured we may well have gone below zero, fix this. */
	if (nr_free < 0)
		nr_free = 0;
	ntfs_debug("Exiting.");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
	return nr_free;
}

/**
 * ntfs_statfs - return information about mounted NTFS volume
 * @sb:		super block of mounted volume
 * @sfs:	statfs structure in which to return the information
 *
 * Return information about the mounted NTFS volume @sb in the statfs structure
 * pointed to by @sfs (this is initialized with zeros before ntfs_statfs is
 * called). We interpret the values to be correct of the moment in time at
 * which we are called. Most values are variable otherwise and this isn't just
 * the free values but the totals as well. For example we can increase the
 * total number of file nodes if we run out and we can keep doing this until
 * there is no more space on the volume left at all.
 *
 * Called from vfs_statfs which is used to handle the statfs, fstatfs, and
 * ustat system calls.
 *
 * Return 0 on success or -errno on error.
 */
2104
static int ntfs_statfs(struct super_block *sb, struct kstatfs *sfs)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
{
	ntfs_volume *vol = NTFS_SB(sb);
	s64 size;

	ntfs_debug("Entering.");
	/* Type of filesystem. */
	sfs->f_type   = NTFS_SB_MAGIC;
	/* Optimal transfer block size. */
	sfs->f_bsize  = PAGE_CACHE_SIZE;
	/*
	 * Total data blocks in file system in units of f_bsize and since
	 * inodes are also stored in data blocs ($MFT is a file) this is just
	 * the total clusters.
	 */
2119
	sfs->f_blocks = vol->nr_clusters << vol->cluster_size_bits >>
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2120 2121 2122 2123 2124 2125 2126 2127
				PAGE_CACHE_SHIFT;
	/* Free data blocks in file system in units of f_bsize. */
	size	      = get_nr_free_clusters(vol) << vol->cluster_size_bits >>
				PAGE_CACHE_SHIFT;
	if (size < 0LL)
		size = 0LL;
	/* Free blocks avail to non-superuser, same as above on NTFS. */
	sfs->f_bavail = sfs->f_bfree = size;
2128
	/* Serialize accesses to the inode bitmap. */
2129
	down_read(&vol->mftbmp_lock);
2130 2131 2132
	/* Number of inodes in file system (at this point in time). */
	sfs->f_files = vol->mft_ino->i_size >> vol->mft_record_size_bits;
	/* Free inodes in fs (based on current total count). */
2133 2134
	sfs->f_ffree = __get_nr_free_mft_records(vol);
	up_read(&vol->mftbmp_lock);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
	/*
	 * File system id. This is extremely *nix flavour dependent and even
	 * within Linux itself all fs do their own thing. I interpret this to
	 * mean a unique id associated with the mounted fs and not the id
	 * associated with the file system driver, the latter is already given
	 * by the file system type in sfs->f_type. Thus we use the 64-bit
	 * volume serial number splitting it into two 32-bit parts. We enter
	 * the least significant 32-bits in f_fsid[0] and the most significant
	 * 32-bits in f_fsid[1].
	 */
	sfs->f_fsid.val[0] = vol->serial_no & 0xffffffff;
	sfs->f_fsid.val[1] = (vol->serial_no >> 32) & 0xffffffff;
	/* Maximum length of filenames. */
	sfs->f_namelen	   = NTFS_MAX_NAME_LEN;
	return 0;
}

/**
 * The complete super operations.
 */
struct super_operations ntfs_sops = {
2156 2157
	.alloc_inode	= ntfs_alloc_big_inode,	  /* VFS: Allocate new inode. */
	.destroy_inode	= ntfs_destroy_big_inode, /* VFS: Deallocate inode. */
2158 2159 2160 2161 2162 2163
	.put_inode	= ntfs_put_inode,	  /* VFS: Called just before
						     the inode reference count
						     is decreased. */
#ifdef NTFS_RW
	//.dirty_inode	= NULL,			/* VFS: Called from
	//					   __mark_inode_dirty(). */
2164
	.write_inode	= ntfs_write_inode_vfs,	/* VFS: Write dirty inode to
2165
						   disk. */
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
	//.drop_inode	= NULL,			/* VFS: Called just after the
	//					   inode reference count has
	//					   been decreased to zero.
	//					   NOTE: The inode lock is
	//					   held. See fs/inode.c::
	//					   generic_drop_inode(). */
	//.delete_inode	= NULL,			/* VFS: Delete inode from disk.
	//					   Called when i_count becomes
	//					   0 and i_nlink is also 0. */
	//.write_super	= NULL,			/* Flush dirty super block to
	//					   disk. */
2177
	//.sync_fs	= NULL,			/* ? */
2178 2179
	//.write_super_lockfs	= NULL,		/* ? */
	//.unlockfs	= NULL,			/* ? */
2180
#endif /* NTFS_RW */
2181 2182 2183
	.put_super	= ntfs_put_super,	/* Syscall: umount. */
	.statfs		= ntfs_statfs,		/* Syscall: statfs */
	.remount_fs	= ntfs_remount,		/* Syscall: mount -o remount. */
2184
	.clear_inode	= ntfs_clear_big_inode,	/* VFS: Called when an inode is
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2185
						   removed from memory. */
2186 2187 2188
	//.umount_begin	= NULL,			/* Forced umount. */
	.show_options	= ntfs_show_options,	/* Show mount options in
						   proc. */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2189 2190
};

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224

/**
 * Declarations for NTFS specific export operations (fs/ntfs/namei.c).
 */
extern struct dentry *ntfs_get_parent(struct dentry *child_dent);
extern struct dentry *ntfs_get_dentry(struct super_block *sb, void *fh);

/**
 * Export operations allowing NFS exporting of mounted NTFS partitions.
 *
 * We use the default ->decode_fh() and ->encode_fh() for now.  Note that they
 * use 32 bits to store the inode number which is an unsigned long so on 64-bit
 * architectures is usually 64 bits so it would all fail horribly on huge
 * volumes.  I guess we need to define our own encode and decode fh functions
 * that store 64-bit inode numbers at some point but for now we will ignore the
 * problem...
 *
 * We also use the default ->get_name() helper (used by ->decode_fh() via
 * fs/exportfs/expfs.c::find_exported_dentry()) as that is completely fs
 * independent.
 *
 * The default ->get_parent() just returns -EACCES so we have to provide our
 * own and the default ->get_dentry() is incompatible with NTFS due to not
 * allowing the inode number 0 which is used in NTFS for the system file $MFT
 * and due to using iget() whereas NTFS needs ntfs_iget().
 */
static struct export_operations ntfs_export_ops = {
	.get_parent	= ntfs_get_parent,	/* Find the parent of a given
						   directory. */
	.get_dentry	= ntfs_get_dentry,	/* Find a dentry for the inode
						   given a file handle
						   sub-fragment. */
};

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
/**
 * ntfs_fill_super - mount an ntfs files system
 * @sb:		super block of ntfs file system to mount
 * @opt:	string containing the mount options
 * @silent:	silence error output
 *
 * ntfs_fill_super() is called by the VFS to mount the device described by @sb
 * with the mount otions in @data with the NTFS file system.
 *
 * If @silent is true, remain silent even if errors are detected. This is used
 * during bootup, when the kernel tries to mount the root file system with all
 * registered file systems one after the other until one succeeds. This implies
 * that all file systems except the correct one will quite correctly and
 * expectedly return an error, but nobody wants to see error messages when in
 * fact this is what is supposed to happen.
 *
 * NOTE: @sb->s_flags contains the mount options flags.
 */
static int ntfs_fill_super(struct super_block *sb, void *opt, const int silent)
{
	ntfs_volume *vol;
	struct buffer_head *bh;
	struct inode *tmp_ino;
2248
	int result;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2249 2250

	ntfs_debug("Entering.");
2251 2252
#ifndef NTFS_RW
	sb->s_flags |= MS_RDONLY | MS_NOATIME | MS_NODIRATIME;
2253
#endif /* ! NTFS_RW */
2254 2255
	/* Allocate a new ntfs_volume and place it in sb->s_fs_info. */
	sb->s_fs_info = kmalloc(sizeof(ntfs_volume), GFP_NOFS);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
	vol = NTFS_SB(sb);
	if (!vol) {
		if (!silent)
			ntfs_error(sb, "Allocation of NTFS volume structure "
					"failed. Aborting mount...");
		return -ENOMEM;
	}
	/* Initialize ntfs_volume structure. */
	memset(vol, 0, sizeof(ntfs_volume));
	vol->sb = sb;
	vol->upcase = NULL;
2267
	vol->attrdef = NULL;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2268
	vol->mft_ino = NULL;
2269 2270
	vol->mftbmp_ino = NULL;
	init_rwsem(&vol->mftbmp_lock);
2271
#ifdef NTFS_RW
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2272
	vol->mftmirr_ino = NULL;
2273
	vol->logfile_ino = NULL;
2274
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2275 2276 2277 2278 2279
	vol->lcnbmp_ino = NULL;
	init_rwsem(&vol->lcnbmp_lock);
	vol->vol_ino = NULL;
	vol->root_ino = NULL;
	vol->secure_ino = NULL;
2280 2281 2282 2283 2284
	vol->extend_ino = NULL;
#ifdef NTFS_RW
	vol->quota_ino = NULL;
	vol->quota_q_ino = NULL;
#endif /* NTFS_RW */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2285 2286 2287
	vol->nls_map = NULL;

	/*
Anton Altaparmakov's avatar
NTFS:  
Anton Altaparmakov committed
2288
	 * Default is group and other don't have any access to files or
2289
	 * directories while owner has full access. Further, files by default
2290
	 * are not executable but directories are of course browseable.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2291
	 */
2292 2293
	vol->fmask = 0177;
	vol->dmask = 0077;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2294

2295 2296
	unlock_kernel();

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2297 2298 2299
	/* Important to get the mount options dealt with now. */
	if (!parse_options(vol, (char*)opt))
		goto err_out_now;
2300

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2301 2302 2303 2304
	/*
	 * TODO: Fail safety check. In the future we should really be able to
	 * cope with this being the case, but for now just bail out.
	 */
2305
	if (bdev_hardsect_size(sb->s_bdev) > NTFS_BLOCK_SIZE) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2306 2307 2308 2309
		if (!silent)
			ntfs_error(sb, "Device has unsupported hardsect_size.");
		goto err_out_now;
	}
2310

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2311 2312 2313 2314
	/* Setup the device access block size to NTFS_BLOCK_SIZE. */
	if (sb_set_blocksize(sb, NTFS_BLOCK_SIZE) != NTFS_BLOCK_SIZE) {
		if (!silent)
			ntfs_error(sb, "Unable to set block size.");
2315
		goto err_out_now;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2316 2317 2318 2319 2320 2321 2322 2323 2324
	}

	/* Get the size of the device in units of NTFS_BLOCK_SIZE bytes. */
	vol->nr_blocks = sb->s_bdev->bd_inode->i_size >> NTFS_BLOCK_SIZE_BITS;

	/* Read the boot sector and return unlocked buffer head to it. */
	if (!(bh = read_ntfs_boot_sector(sb, silent))) {
		if (!silent)
			ntfs_error(sb, "Not an NTFS volume.");
2325
		goto err_out_now;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2326
	}
2327

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2328 2329 2330 2331 2332 2333
	/*
	 * Extract the data from the boot sector and setup the ntfs super block
	 * using it.
	 */
	result = parse_ntfs_boot_sector(vol, (NTFS_BOOT_SECTOR*)bh->b_data);

2334 2335 2336
	/* Initialize the cluster allocator. */
	setup_lcn_allocator(vol);

Anton Altaparmakov's avatar
Anton Altaparmakov committed
2337 2338 2339 2340 2341
	brelse(bh);

	if (!result) {
		if (!silent)
			ntfs_error(sb, "Unsupported NTFS filesystem.");
2342
		goto err_out_now;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2343 2344
	}

2345
	/*
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
	 * TODO: When we start coping with sector sizes different from
	 * NTFS_BLOCK_SIZE, we now probably need to set the blocksize of the
	 * device (probably to NTFS_BLOCK_SIZE).
	 */

	/* Setup remaining fields in the super block. */
	sb->s_magic = NTFS_SB_MAGIC;

	/*
	 * Ntfs allows 63 bits for the file size, i.e. correct would be:
2356
	 *	sb->s_maxbytes = ~0ULL >> 1;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
	 * But the kernel uses a long as the page cache page index which on
	 * 32-bit architectures is only 32-bits. MAX_LFS_FILESIZE is kernel
	 * defined to the maximum the page cache page index can cope with
	 * without overflowing the index or to 2^63 - 1, whichever is smaller.
	 */
	sb->s_maxbytes = MAX_LFS_FILESIZE;

	/*
	 * Now load the metadata required for the page cache and our address
	 * space operations to function. We do this by setting up a specialised
2367 2368 2369
	 * read_inode method and then just calling the normal iget() to obtain
	 * the inode for $MFT which is sufficient to allow our normal inode
	 * operations and associated address space operations to function.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2370
	 */
Alexander Viro's avatar
Alexander Viro committed
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
	sb->s_op = &ntfs_sops;
	tmp_ino = new_inode(sb);
	if (!tmp_ino) {
		if (!silent)
			ntfs_error(sb, "Failed to load essential metadata.");
		goto err_out_now;
	}
	tmp_ino->i_ino = FILE_MFT;
	insert_inode_hash(tmp_ino);
	if (ntfs_read_inode_mount(tmp_ino) < 0) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
		if (!silent)
			ntfs_error(sb, "Failed to load essential metadata.");
		goto iput_tmp_ino_err_out_now;
	}
	down(&ntfs_lock);
	/*
	 * The current mount is a compression user if the cluster size is
	 * less than or equal 4kiB.
	 */
	if (vol->cluster_size <= 4096 && !ntfs_nr_compression_users++) {
		result = allocate_compression_buffers();
		if (result) {
2393
			ntfs_error(NULL, "Failed to allocate buffers "
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2394 2395 2396 2397 2398 2399 2400
					"for compression engine.");
			ntfs_nr_compression_users--;
			up(&ntfs_lock);
			goto iput_tmp_ino_err_out_now;
		}
	}
	/*
2401 2402 2403
	 * Generate the global default upcase table if necessary.  Also
	 * temporarily increment the number of upcase users to avoid race
	 * conditions with concurrent (u)mounts.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2404
	 */
2405
	if (!default_upcase)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
		default_upcase = generate_default_upcase();
	ntfs_nr_upcase_users++;
	up(&ntfs_lock);
	/*
	 * From now on, ignore @silent parameter. If we fail below this line,
	 * it will be due to a corrupt fs or a system error, so we report it.
	 */
	/*
	 * Open the system files with normal access functions and complete
	 * setting up the ntfs super block.
	 */
	if (!load_system_files(vol)) {
		ntfs_error(sb, "Failed to load system files.");
		goto unl_upcase_iput_tmp_ino_err_out_now;
	}
	if ((sb->s_root = d_alloc_root(vol->root_ino))) {
2422
		/* We increment i_count simulating an ntfs_iget(). */
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2423 2424 2425 2426 2427 2428 2429 2430 2431
		atomic_inc(&vol->root_ino->i_count);
		ntfs_debug("Exiting, status successful.");
		/* Release the default upcase if it has no users. */
		down(&ntfs_lock);
		if (!--ntfs_nr_upcase_users && default_upcase) {
			ntfs_free(default_upcase);
			default_upcase = NULL;
		}
		up(&ntfs_lock);
2432
		sb->s_export_op = &ntfs_export_ops;
2433
		lock_kernel();
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2434 2435 2436 2437
		return 0;
	}
	ntfs_error(sb, "Failed to allocate root directory.");
	/* Clean up after the successful load_system_files() call from above. */
2438 2439 2440
	// TODO: Use ntfs_put_super() instead of repeating all this code...
	// FIXME: Should mark the volume clean as the error is most likely
	// 	  -ENOMEM.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2441 2442 2443 2444
	iput(vol->vol_ino);
	vol->vol_ino = NULL;
	/* NTFS 3.0+ specific clean up. */
	if (vol->major_ver >= 3) {
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
#ifdef NTFS_RW
		if (vol->quota_q_ino) {
			iput(vol->quota_q_ino);
			vol->quota_q_ino = NULL;
		}
		if (vol->quota_ino) {
			iput(vol->quota_ino);
			vol->quota_ino = NULL;
		}
#endif /* NTFS_RW */
		if (vol->extend_ino) {
			iput(vol->extend_ino);
			vol->extend_ino = NULL;
		}
		if (vol->secure_ino) {
			iput(vol->secure_ino);
			vol->secure_ino = NULL;
		}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2463 2464 2465 2466 2467
	}
	iput(vol->root_ino);
	vol->root_ino = NULL;
	iput(vol->lcnbmp_ino);
	vol->lcnbmp_ino = NULL;
2468 2469
	iput(vol->mftbmp_ino);
	vol->mftbmp_ino = NULL;
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
#ifdef NTFS_RW
	if (vol->logfile_ino) {
		iput(vol->logfile_ino);
		vol->logfile_ino = NULL;
	}
	if (vol->mftmirr_ino) {
		iput(vol->mftmirr_ino);
		vol->mftmirr_ino = NULL;
	}
#endif /* NTFS_RW */
2480 2481 2482 2483 2484 2485
	/* Throw away the table of attribute definitions. */
	vol->attrdef_size = 0;
	if (vol->attrdef) {
		ntfs_free(vol->attrdef);
		vol->attrdef = NULL;
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2486
	vol->upcase_len = 0;
2487 2488 2489 2490 2491 2492 2493
	down(&ntfs_lock);
	if (vol->upcase == default_upcase) {
		ntfs_nr_upcase_users--;
		vol->upcase = NULL;
	}
	up(&ntfs_lock);
	if (vol->upcase) {
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2494
		ntfs_free(vol->upcase);
2495 2496
		vol->upcase = NULL;
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2497 2498 2499 2500 2501 2502 2503
	if (vol->nls_map) {
		unload_nls(vol->nls_map);
		vol->nls_map = NULL;
	}
	/* Error exit code path. */
unl_upcase_iput_tmp_ino_err_out_now:
	/*
2504 2505
	 * Decrease the number of upcase users and destroy the global default
	 * upcase table if necessary.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
	 */
	down(&ntfs_lock);
	if (!--ntfs_nr_upcase_users && default_upcase) {
		ntfs_free(default_upcase);
		default_upcase = NULL;
	}
	if (vol->cluster_size <= 4096 && !--ntfs_nr_compression_users)
		free_compression_buffers();
	up(&ntfs_lock);
iput_tmp_ino_err_out_now:
	iput(tmp_ino);
2517
	if (vol->mft_ino && vol->mft_ino != tmp_ino)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2518
		iput(vol->mft_ino);
2519
	vol->mft_ino = NULL;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2520
	/*
2521
	 * This is needed to get ntfs_clear_extent_inode() called for each
2522 2523 2524
	 * inode we have ever called ntfs_iget()/iput() on, otherwise we A)
	 * leak resources and B) a subsequent mount fails automatically due to
	 * ntfs_iget() never calling down into our ntfs_read_locked_inode()
2525 2526
	 * method again... FIXME: Do we need to do this twice now because of
	 * attribute inodes? I think not, so leave as is for now... (AIA)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2527 2528 2529 2530 2531
	 */
	if (invalidate_inodes(sb)) {
		ntfs_error(sb, "Busy inodes left. This is most likely a NTFS "
				"driver bug.");
		/* Copied from fs/super.c. I just love this message. (-; */
2532
		printk("NTFS: Busy inodes after umount. Self-destruct in 5 "
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2533 2534 2535 2536
				"seconds.  Have a nice day...\n");
	}
	/* Errors at this stage are irrelevant. */
err_out_now:
2537
	lock_kernel();
2538
	sb->s_fs_info = NULL;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
	kfree(vol);
	ntfs_debug("Failed, returning -EINVAL.");
	return -EINVAL;
}

/*
 * This is a slab cache to optimize allocations and deallocations of Unicode
 * strings of the maximum length allowed by NTFS, which is NTFS_MAX_NAME_LEN
 * (255) Unicode characters + a terminating NULL Unicode character.
 */
kmem_cache_t *ntfs_name_cache;

/* Slab caches for efficient allocation/deallocation of of inodes. */
kmem_cache_t *ntfs_inode_cache;
kmem_cache_t *ntfs_big_inode_cache;

/* Init once constructor for the inode slab cache. */
static void ntfs_big_inode_init_once(void *foo, kmem_cache_t *cachep,
		unsigned long flags)
{
	ntfs_inode *ni = (ntfs_inode *)foo;

	if ((flags & (SLAB_CTOR_VERIFY|SLAB_CTOR_CONSTRUCTOR)) ==
			SLAB_CTOR_CONSTRUCTOR)
		inode_init_once(VFS_I(ni));
}

/*
2567 2568
 * Slab caches to optimize allocations and deallocations of attribute search
 * contexts and index contexts, respectively.
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2569 2570
 */
kmem_cache_t *ntfs_attr_ctx_cache;
2571
kmem_cache_t *ntfs_index_ctx_cache;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2572 2573 2574 2575 2576 2577 2578 2579 2580

/* A global default upcase table and a corresponding reference count. */
wchar_t *default_upcase = NULL;
unsigned long ntfs_nr_upcase_users = 0;

/* Driver wide semaphore. */
DECLARE_MUTEX(ntfs_lock);

static struct super_block *ntfs_get_sb(struct file_system_type *fs_type,
2581
	int flags, const char *dev_name, void *data)
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2582 2583 2584 2585 2586
{
	return get_sb_bdev(fs_type, flags, dev_name, data, ntfs_fill_super);
}

static struct file_system_type ntfs_fs_type = {
2587 2588 2589 2590 2591
	.owner		= THIS_MODULE,
	.name		= "ntfs",
	.get_sb		= ntfs_get_sb,
	.kill_sb	= kill_block_super,
	.fs_flags	= FS_REQUIRES_DEV,
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2592 2593 2594
};

/* Stable names for the slab caches. */
2595
static const char ntfs_index_ctx_cache_name[] = "ntfs_index_ctx_cache";
2596 2597 2598 2599
static const char ntfs_attr_ctx_cache_name[] = "ntfs_attr_ctx_cache";
static const char ntfs_name_cache_name[] = "ntfs_name_cache";
static const char ntfs_inode_cache_name[] = "ntfs_inode_cache";
static const char ntfs_big_inode_cache_name[] = "ntfs_big_inode_cache";
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2600 2601 2602 2603 2604 2605 2606

static int __init init_ntfs_fs(void)
{
	int err = 0;

	/* This may be ugly but it results in pretty output so who cares. (-8 */
	printk(KERN_INFO "NTFS driver " NTFS_VERSION " [Flags: R/"
2607
#ifdef NTFS_RW
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
			"W"
#else
			"O"
#endif
#ifdef DEBUG
			" DEBUG"
#endif
#ifdef MODULE
			" MODULE"
#endif
2618
			"].\n");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2619 2620 2621

	ntfs_debug("Debug messages are enabled.");

2622 2623 2624 2625 2626 2627 2628 2629
	ntfs_index_ctx_cache = kmem_cache_create(ntfs_index_ctx_cache_name,
			sizeof(ntfs_index_context), 0 /* offset */,
			SLAB_HWCACHE_ALIGN, NULL /* ctor */, NULL /* dtor */);
	if (!ntfs_index_ctx_cache) {
		printk(KERN_CRIT "NTFS: Failed to create %s!\n",
				ntfs_index_ctx_cache_name);
		goto ictx_err_out;
	}
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2630 2631 2632 2633 2634 2635
	ntfs_attr_ctx_cache = kmem_cache_create(ntfs_attr_ctx_cache_name,
			sizeof(attr_search_context), 0 /* offset */,
			SLAB_HWCACHE_ALIGN, NULL /* ctor */, NULL /* dtor */);
	if (!ntfs_attr_ctx_cache) {
		printk(KERN_CRIT "NTFS: Failed to create %s!\n",
				ntfs_attr_ctx_cache_name);
2636
		goto actx_err_out;
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2637 2638 2639
	}

	ntfs_name_cache = kmem_cache_create(ntfs_name_cache_name,
2640
			(NTFS_MAX_NAME_LEN+1) * sizeof(ntfschar), 0,
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2641 2642 2643 2644 2645 2646 2647 2648
			SLAB_HWCACHE_ALIGN, NULL, NULL);
	if (!ntfs_name_cache) {
		printk(KERN_CRIT "NTFS: Failed to create %s!\n",
				ntfs_name_cache_name);
		goto name_err_out;
	}

	ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
2649
			sizeof(ntfs_inode), 0,
2650
			SLAB_RECLAIM_ACCOUNT, NULL, NULL);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2651 2652 2653 2654 2655 2656 2657
	if (!ntfs_inode_cache) {
		printk(KERN_CRIT "NTFS: Failed to create %s!\n",
				ntfs_inode_cache_name);
		goto inode_err_out;
	}

	ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
2658
			sizeof(big_ntfs_inode), 0,
2659
			SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT,
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
			ntfs_big_inode_init_once, NULL);
	if (!ntfs_big_inode_cache) {
		printk(KERN_CRIT "NTFS: Failed to create %s!\n",
				ntfs_big_inode_cache_name);
		goto big_inode_err_out;
	}

	/* Register the ntfs sysctls. */
	err = ntfs_sysctl(1);
	if (err) {
		printk(KERN_CRIT "NTFS: Failed to register NTFS sysctls!\n");
		goto sysctl_err_out;
	}

	err = register_filesystem(&ntfs_fs_type);
	if (!err) {
		ntfs_debug("NTFS driver registered successfully.");
		return 0; /* Success! */
	}
	printk(KERN_CRIT "NTFS: Failed to register NTFS file system driver!\n");

sysctl_err_out:
	kmem_cache_destroy(ntfs_big_inode_cache);
big_inode_err_out:
	kmem_cache_destroy(ntfs_inode_cache);
inode_err_out:
	kmem_cache_destroy(ntfs_name_cache);
name_err_out:
	kmem_cache_destroy(ntfs_attr_ctx_cache);
2689 2690 2691
actx_err_out:
	kmem_cache_destroy(ntfs_index_ctx_cache);
ictx_err_out:
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
	if (!err) {
		printk(KERN_CRIT "NTFS: Aborting NTFS file system driver "
				"registration...\n");
		err = -ENOMEM;
	}
	return err;
}

static void __exit exit_ntfs_fs(void)
{
	int err = 0;

	ntfs_debug("Unregistering NTFS driver.");

	unregister_filesystem(&ntfs_fs_type);

	if (kmem_cache_destroy(ntfs_big_inode_cache) && (err = 1))
		printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
				ntfs_big_inode_cache_name);
	if (kmem_cache_destroy(ntfs_inode_cache) && (err = 1))
		printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
				ntfs_inode_cache_name);
	if (kmem_cache_destroy(ntfs_name_cache) && (err = 1))
		printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
				ntfs_name_cache_name);
	if (kmem_cache_destroy(ntfs_attr_ctx_cache) && (err = 1))
		printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
				ntfs_attr_ctx_cache_name);
2720 2721 2722
	if (kmem_cache_destroy(ntfs_index_ctx_cache) && (err = 1))
		printk(KERN_CRIT "NTFS: Failed to destory %s.\n",
				ntfs_index_ctx_cache_name);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2723 2724 2725 2726
	if (err)
		printk(KERN_CRIT "NTFS: This causes memory to leak! There is "
				"probably a BUG in the driver! Please report "
				"you saw this message to "
2727
				"linux-ntfs-dev@lists.sourceforge.net\n");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2728 2729 2730 2731
	/* Unregister the ntfs sysctls. */
	ntfs_sysctl(0);
}

2732
MODULE_AUTHOR("Anton Altaparmakov <aia21@cantab.net>");
2733
MODULE_DESCRIPTION("NTFS 1.2/3.x driver - Copyright (c) 2001-2004 Anton Altaparmakov");
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2734 2735
MODULE_LICENSE("GPL");
#ifdef DEBUG
2736
module_param(debug_msgs, bool, 0);
Anton Altaparmakov's avatar
Anton Altaparmakov committed
2737 2738 2739 2740 2741
MODULE_PARM_DESC(debug_msgs, "Enable debug messages.");
#endif

module_init(init_ntfs_fs)
module_exit(exit_ntfs_fs)