xref: /linux/fs/ntfs/super.c (revision feccce4df0866783b65b493bba0964aeed4226dc)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NTFS kernel super block handling.
4  *
5  * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
6  * Copyright (c) 2001,2002 Richard Russon
7  * Copyright (c) 2025 LG Electronics Co., Ltd.
8  */
9 
10 #include <linux/blkdev.h>	/* For bdev_logical_block_size(). */
11 #include <linux/backing-dev.h>
12 #include <linux/vfs.h>
13 #include <linux/fs_struct.h>
14 #include <linux/sched/mm.h>
15 #include <linux/fs_context.h>
16 #include <linux/fs_parser.h>
17 
18 #include "sysctl.h"
19 #include "logfile.h"
20 #include "index.h"
21 #include "mft.h"
22 #include "ntfs.h"
23 #include "ea.h"
24 #include "bitmap.h"
25 #include "volume.h"
26 #include "stream.h"
27 
28 /* A global default upcase table and a corresponding reference count. */
29 static __le16 *default_upcase;
30 static unsigned long ntfs_nr_upcase_users;
31 
32 static struct workqueue_struct *ntfs_wq;
33 
34 /* Error constants/strings used in inode.c::ntfs_show_options(). */
35 enum {
36 	/* One of these must be present, default is ON_ERRORS_CONTINUE. */
37 	ON_ERRORS_PANIC = 0x01,
38 	ON_ERRORS_REMOUNT_RO = 0x02,
39 	ON_ERRORS_CONTINUE = 0x04,
40 };
41 
42 static const struct constant_table ntfs_param_enums[] = {
43 	{ "panic",		ON_ERRORS_PANIC },
44 	{ "remount-ro",		ON_ERRORS_REMOUNT_RO },
45 	{ "continue",		ON_ERRORS_CONTINUE },
46 	{}
47 };
48 
49 enum {
50 	NATIVE_SYMLINK_RAW,
51 	NATIVE_SYMLINK_REL,
52 };
53 
54 static const struct constant_table ntfs_native_symlink_enums[] = {
55 	{ "raw",		NATIVE_SYMLINK_RAW },
56 	{ "rel",		NATIVE_SYMLINK_REL },
57 	{}
58 };
59 
60 enum {
61 	SYMLINK_WSL,
62 	SYMLINK_NATIVE,
63 };
64 
65 static const struct constant_table ntfs_symlink_enums[] = {
66 	{ "wsl",		SYMLINK_WSL },
67 	{ "native",		SYMLINK_NATIVE },
68 	{}
69 };
70 
71 enum {
72 	STREAMS_INTERFACE_NONE,
73 	STREAMS_INTERFACE_WINDOWS,
74 };
75 
76 static const struct constant_table ntfs_streams_interface_enums[] = {
77 	{ "none",	STREAMS_INTERFACE_NONE },
78 	{ "windows",	STREAMS_INTERFACE_WINDOWS },
79 	{}
80 };
81 
82 enum {
83 	Opt_uid,
84 	Opt_gid,
85 	Opt_umask,
86 	Opt_dmask,
87 	Opt_fmask,
88 	Opt_errors,
89 	Opt_nls,
90 	Opt_charset,
91 	Opt_show_sys_files,
92 	Opt_show_meta,
93 	Opt_case_sensitive,
94 	Opt_disable_sparse,
95 	Opt_sparse,
96 	Opt_mft_zone_multiplier,
97 	Opt_preallocated_size,
98 	Opt_sys_immutable,
99 	Opt_nohidden,
100 	Opt_hide_dot_files,
101 	Opt_check_windows_names,
102 	Opt_acl,
103 	Opt_discard,
104 	Opt_nocase,
105 	Opt_native_symlink,
106 	Opt_symlink,
107 	Opt_streams_interface,
108 };
109 
110 static const struct fs_parameter_spec ntfs_parameters[] = {
111 	fsparam_u32("uid",			Opt_uid),
112 	fsparam_u32("gid",			Opt_gid),
113 	fsparam_u32oct("umask",			Opt_umask),
114 	fsparam_u32oct("dmask",			Opt_dmask),
115 	fsparam_u32oct("fmask",			Opt_fmask),
116 	fsparam_string("nls",			Opt_nls),
117 	fsparam_string("iocharset",		Opt_charset),
118 	fsparam_enum("errors",			Opt_errors, ntfs_param_enums),
119 	fsparam_flag("show_sys_files",		Opt_show_sys_files),
120 	fsparam_flag("showmeta",		Opt_show_meta),
121 	fsparam_flag("case_sensitive",		Opt_case_sensitive),
122 	fsparam_flag("disable_sparse",		Opt_disable_sparse),
123 	fsparam_s32("mft_zone_multiplier",	Opt_mft_zone_multiplier),
124 	fsparam_u64("preallocated_size",	Opt_preallocated_size),
125 	fsparam_flag("sys_immutable",		Opt_sys_immutable),
126 	fsparam_flag("nohidden",		Opt_nohidden),
127 	fsparam_flag("hide_dot_files",		Opt_hide_dot_files),
128 	fsparam_flag("windows_names",		Opt_check_windows_names),
129 	fsparam_flag("acl",			Opt_acl),
130 	fsparam_flag("discard",			Opt_discard),
131 	fsparam_flag("sparse",			Opt_sparse),
132 	fsparam_flag("nocase",			Opt_nocase),
133 	fsparam_enum("native_symlink",		Opt_native_symlink, ntfs_native_symlink_enums),
134 	fsparam_enum("symlink",			Opt_symlink, ntfs_symlink_enums),
135 	fsparam_enum("streams_interface",	Opt_streams_interface,
136 		     ntfs_streams_interface_enums),
137 	{}
138 };
139 
140 static int ntfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
141 {
142 	struct ntfs_volume *vol = fc->s_fs_info;
143 	struct fs_parse_result result;
144 	int opt;
145 
146 	opt = fs_parse(fc, ntfs_parameters, param, &result);
147 	if (opt < 0)
148 		return opt;
149 
150 	switch (opt) {
151 	case Opt_uid:
152 		vol->uid = make_kuid(current_user_ns(), result.uint_32);
153 		break;
154 	case Opt_gid:
155 		vol->gid = make_kgid(current_user_ns(), result.uint_32);
156 		break;
157 	case Opt_umask:
158 		vol->fmask = vol->dmask = result.uint_32;
159 		break;
160 	case Opt_dmask:
161 		vol->dmask = result.uint_32;
162 		break;
163 	case Opt_fmask:
164 		vol->fmask = result.uint_32;
165 		break;
166 	case Opt_errors:
167 		vol->on_errors = result.uint_32;
168 		break;
169 	case Opt_nls:
170 	case Opt_charset:
171 		if (vol->nls_map)
172 			unload_nls(vol->nls_map);
173 		vol->nls_map = load_nls(param->string);
174 		if (!vol->nls_map) {
175 			ntfs_error(vol->sb, "Failed to load NLS table '%s'.",
176 				   param->string);
177 			return -EINVAL;
178 		}
179 		break;
180 	case Opt_mft_zone_multiplier:
181 		if (vol->mft_zone_multiplier && vol->mft_zone_multiplier !=
182 				result.int_32) {
183 			ntfs_error(vol->sb, "Cannot change mft_zone_multiplier on remount.");
184 			return -EINVAL;
185 		}
186 		if (result.int_32 < 1 || result.int_32 > 4) {
187 			ntfs_error(vol->sb,
188 				"Invalid mft_zone_multiplier. Using default value, i.e. 1.");
189 			vol->mft_zone_multiplier = 1;
190 		} else
191 			vol->mft_zone_multiplier = result.int_32;
192 		break;
193 	case Opt_show_sys_files:
194 	case Opt_show_meta:
195 		if (result.boolean)
196 			NVolSetShowSystemFiles(vol);
197 		else
198 			NVolClearShowSystemFiles(vol);
199 		break;
200 	case Opt_case_sensitive:
201 		if (result.boolean)
202 			NVolSetCaseSensitive(vol);
203 		else
204 			NVolClearCaseSensitive(vol);
205 		break;
206 	case Opt_nocase:
207 		if (result.boolean)
208 			NVolClearCaseSensitive(vol);
209 		else
210 			NVolSetCaseSensitive(vol);
211 		break;
212 	case Opt_preallocated_size:
213 		vol->preallocated_size = (loff_t)result.uint_64;
214 		break;
215 	case Opt_sys_immutable:
216 		if (result.boolean)
217 			NVolSetSysImmutable(vol);
218 		else
219 			NVolClearSysImmutable(vol);
220 		break;
221 	case Opt_nohidden:
222 		if (result.boolean)
223 			NVolClearShowHiddenFiles(vol);
224 		else
225 			NVolSetShowHiddenFiles(vol);
226 		break;
227 	case Opt_hide_dot_files:
228 		if (result.boolean)
229 			NVolSetHideDotFiles(vol);
230 		else
231 			NVolClearHideDotFiles(vol);
232 		break;
233 	case Opt_check_windows_names:
234 		if (result.boolean)
235 			NVolSetCheckWindowsNames(vol);
236 		else
237 			NVolClearCheckWindowsNames(vol);
238 		break;
239 	case Opt_acl:
240 #ifdef CONFIG_NTFS_FS_POSIX_ACL
241 		if (result.boolean)
242 			fc->sb_flags |= SB_POSIXACL;
243 		else
244 			fc->sb_flags &= ~SB_POSIXACL;
245 		break;
246 #else
247 		return -EINVAL;
248 #endif
249 	case Opt_discard:
250 		if (result.boolean)
251 			NVolSetDiscard(vol);
252 		else
253 			NVolClearDiscard(vol);
254 		break;
255 	case Opt_disable_sparse:
256 		if (result.boolean)
257 			NVolSetDisableSparse(vol);
258 		else
259 			NVolClearDisableSparse(vol);
260 		break;
261 	case Opt_native_symlink:
262 		if (result.uint_32 == NATIVE_SYMLINK_REL)
263 			NVolSetNativeSymlinkRel(vol);
264 		else
265 			NVolClearNativeSymlinkRel(vol);
266 		break;
267 	case Opt_symlink:
268 		if (result.uint_32 == SYMLINK_NATIVE)
269 			NVolSetSymlinkNative(vol);
270 		else
271 			NVolClearSymlinkNative(vol);
272 		break;
273 	case Opt_streams_interface: {
274 		bool streams_windows =
275 			result.uint_32 == STREAMS_INTERFACE_WINDOWS;
276 
277 		if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE &&
278 		    NVolStreamsWindows(NTFS_SB(fc->root->d_sb)) != streams_windows) {
279 			ntfs_warning(fc->root->d_sb,
280 				     "Cannot change streams_interface on remount.");
281 			return -EINVAL;
282 		}
283 		if (streams_windows)
284 			NVolSetStreamsWindows(vol);
285 		else
286 			NVolClearStreamsWindows(vol);
287 		break;
288 	}
289 	case Opt_sparse:
290 		break;
291 	default:
292 		return -EINVAL;
293 	}
294 
295 	return 0;
296 }
297 
298 static int ntfs_sync_volume_dirty_state(struct ntfs_volume *vol);
299 
300 static int ntfs_reconfigure(struct fs_context *fc)
301 {
302 	struct super_block *sb = fc->root->d_sb;
303 	struct ntfs_volume *vol = NTFS_SB(sb);
304 	int err;
305 
306 	ntfs_debug("Entering with remount");
307 
308 	err = sync_filesystem(sb);
309 	if (err) {
310 		ntfs_warning(sb, "Failed to sync the filesystem.");
311 		/* A forced remount must still turn the superblock read-only. */
312 		if (!(fc->sb_flags & SB_FORCE))
313 			return err;
314 	}
315 
316 	/*
317 	 * For the read-write compiled driver, if we are remounting read-write,
318 	 * make sure there are no volume errors and that no unsupported volume
319 	 * flags are set.  Also, empty the logfile journal as it would become
320 	 * stale as soon as something is written to the volume and mark the
321 	 * volume dirty so that chkdsk is run if the volume is not umounted
322 	 * cleanly.
323 	 *
324 	 * When remounting read-only, mark the volume clean if no volume errors
325 	 * have occurred.
326 	 */
327 	if (sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY)) {
328 		static const char *es = ".  Cannot remount read-write.";
329 
330 		/* Remounting read-write. */
331 		if (!vol->mft_write_supported) {
332 			ntfs_error(sb,
333 				   "MFT writeback is unsupported for this geometry%s",
334 				   es);
335 			return -EROFS;
336 		}
337 		if (NVolErrors(vol)) {
338 			ntfs_error(sb, "Volume has errors and is read-only%s",
339 					es);
340 			return -EROFS;
341 		}
342 		if (vol->vol_flags & VOLUME_IS_DIRTY) {
343 			ntfs_error(sb, "Volume is dirty and read-only%s", es);
344 			return -EROFS;
345 		}
346 		if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
347 			ntfs_error(sb, "Volume has been modified by chkdsk and is read-only%s", es);
348 			return -EROFS;
349 		}
350 		if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
351 			ntfs_error(sb, "Volume has unsupported flags set (0x%x) and is read-only%s",
352 					le16_to_cpu(vol->vol_flags), es);
353 			return -EROFS;
354 		}
355 		if (vol->logfile_ino && !ntfs_empty_logfile(vol->logfile_ino)) {
356 			ntfs_error(sb, "Failed to empty journal LogFile%s",
357 					es);
358 			NVolSetErrors(vol);
359 			return -EROFS;
360 		}
361 	} else if (!sb_rdonly(sb) && (fc->sb_flags & SB_RDONLY)) {
362 		/* Remounting read-only. */
363 		/*
364 		 * With errors recorded the dirty bit is set rather than
365 		 * cleared, and it is committed right away: the VFS does
366 		 * not sync the filesystem during a remount, and once the
367 		 * remount succeeds no further persistence point exists -
368 		 * ntfs_sync_fs() is only ever invoked for read-write
369 		 * superblocks (all its VFS callers skip read-only ones)
370 		 * and ntfs_put_super() skips them, so the only remaining
371 		 * write would be the evict-time commit at unmount, which
372 		 * a crash never reaches.  An error recorded only after
373 		 * the remount is still never persisted; a failed commit
374 		 * or flush fails the remount, leaving the superblock
375 		 * read-write so ntfs_put_super() retries at unmount.
376 		 */
377 		/*
378 		 * A forced remount does not drain writers in progress,
379 		 * so one may still be modifying metadata when the flags
380 		 * are committed: never clear the dirty bit then; if
381 		 * errors have been recorded, the update preserves or
382 		 * sets it; otherwise, skip the update entirely.
383 		 */
384 		if (!(fc->sb_flags & SB_FORCE) || NVolErrors(vol)) {
385 			err = ntfs_sync_volume_dirty_state(vol);
386 			if (err) {
387 				ntfs_warning(sb,
388 					"Failed to update dirty bit in volume information flags.  Run chkdsk.");
389 				return err;
390 			}
391 		}
392 		if (NInoDirty(NTFS_I(vol->vol_ino))) {
393 			/* ntfs_commit_inode() would discard the error. */
394 			err = __ntfs_write_inode(vol->vol_ino, 1);
395 			if (err) {
396 				ntfs_warning(sb,
397 					"Failed to commit volume information flags.  Run chkdsk.");
398 				return err;
399 			}
400 			/*
401 			 * write_mft_record() redirties the record on
402 			 * -ENOMEM and still reports success.
403 			 */
404 			if (NInoDirty(NTFS_I(vol->vol_ino))) {
405 				ntfs_warning(sb,
406 					"Volume information flags remain dirty after commit.  Run chkdsk.");
407 				return -EIO;
408 			}
409 			err = blkdev_issue_flush(sb->s_bdev);
410 			if (err) {
411 				ntfs_warning(sb,
412 					"Failed to flush volume information flags.  Run chkdsk.");
413 				return err;
414 			}
415 		}
416 	}
417 
418 	ntfs_debug("Done.");
419 	return 0;
420 }
421 
422 const struct option_t on_errors_arr[] = {
423 	{ ON_ERRORS_PANIC,	"panic" },
424 	{ ON_ERRORS_REMOUNT_RO,	"remount-ro", },
425 	{ ON_ERRORS_CONTINUE,	"continue", },
426 	{ 0,			NULL }
427 };
428 
429 void ntfs_handle_error(struct super_block *sb)
430 {
431 	struct ntfs_volume *vol = NTFS_SB(sb);
432 
433 	if (sb_rdonly(sb))
434 		return;
435 
436 	if (vol->on_errors == ON_ERRORS_REMOUNT_RO) {
437 		sb->s_flags |= SB_RDONLY;
438 		pr_crit("(device %s): Filesystem has been set read-only\n",
439 			sb->s_id);
440 	} else if (vol->on_errors == ON_ERRORS_PANIC) {
441 		panic("ntfs: (device %s): panic from previous error\n",
442 		      sb->s_id);
443 	} else if (vol->on_errors == ON_ERRORS_CONTINUE) {
444 		if (errseq_check(&sb->s_wb_err, vol->wb_err) == -ENODEV) {
445 			NVolSetShutdown(vol);
446 			vol->wb_err = sb->s_wb_err;
447 		}
448 	}
449 }
450 
451 /*
452  * ntfs_write_volume_flags - apply flag changes to the volume information flags
453  * @vol:	ntfs volume on which to modify the flags
454  * @set_bits:	bits to set in the volume information flags
455  * @clear_bits:	bits to clear in the volume information flags
456  * @dirty_if_errors:	force VOLUME_IS_DIRTY on when NVolErrors() is set
457  *
458  * Internal function.  You probably want to use ntfs_{set,clear}_volume_flags()
459  * or ntfs_sync_volume_dirty_state() instead (see below).
460  *
461  * Combine @set_bits and @clear_bits with the current in-memory flag state and
462  * write the result back.  The set/clear helpers pass only the bits to modify,
463  * not the complete flag state.  The read-modify-write happens under
464  * ni->mrec_lock so that concurrent set/clear operations cannot lose updates.
465  * All bit manipulation is done on CPU-endian values, and the result is
466  * converted back to little-endian before storing it.
467  *
468  * When @dirty_if_errors is true and errors have been recorded on @vol,
469  * VOLUME_IS_DIRTY is forced on after the requested changes.  NVolErrors() is
470  * evaluated under the same mrec_lock, which orders this against other
471  * locked flag updates; the runtime error paths themselves record the flag
472  * lock-free, so see ntfs_sync_volume_dirty_state() for the guarantee this
473  * provides against them.
474  *
475  * Return 0 on success and -errno on error.
476  */
477 static int ntfs_write_volume_flags(struct ntfs_volume *vol,
478 		const __le16 set_bits, const __le16 clear_bits,
479 		const bool dirty_if_errors)
480 {
481 	struct ntfs_inode *ni = NTFS_I(vol->vol_ino);
482 	struct volume_information *vi;
483 	struct ntfs_attr_search_ctx *ctx;
484 	u16 flags;
485 	int err;
486 
487 	mutex_lock(&ni->mrec_lock);
488 
489 	flags = le16_to_cpu(vol->vol_flags);
490 	flags |= le16_to_cpu(set_bits) & le16_to_cpu(VOLUME_FLAGS_MASK);
491 	flags &= ~(le16_to_cpu(clear_bits) & le16_to_cpu(VOLUME_FLAGS_MASK));
492 	if (dirty_if_errors && NVolErrors(vol))
493 		flags |= le16_to_cpu(VOLUME_IS_DIRTY);
494 	ntfs_debug("Entering, old flags = 0x%x, new flags = 0x%x.",
495 			le16_to_cpu(vol->vol_flags), flags);
496 
497 	if (le16_to_cpu(vol->vol_flags) == flags)
498 		goto done;
499 
500 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
501 	if (!ctx) {
502 		err = -ENOMEM;
503 		goto put_unm_err_out;
504 	}
505 
506 	err = ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
507 			ctx);
508 	if (err)
509 		goto put_unm_err_out;
510 
511 	vi = (struct volume_information *)((u8 *)ctx->attr +
512 			le16_to_cpu(ctx->attr->data.resident.value_offset));
513 	vol->vol_flags = vi->flags = cpu_to_le16(flags);
514 	mark_mft_record_dirty(ctx->ntfs_ino);
515 	ntfs_attr_put_search_ctx(ctx);
516 done:
517 	mutex_unlock(&ni->mrec_lock);
518 	ntfs_debug("Done.");
519 	return 0;
520 put_unm_err_out:
521 	if (ctx)
522 		ntfs_attr_put_search_ctx(ctx);
523 	mutex_unlock(&ni->mrec_lock);
524 	ntfs_error(vol->sb, "Failed with error code %i.", -err);
525 	return err;
526 }
527 
528 /*
529  * ntfs_set_volume_flags - set bits in the volume information flags
530  * @vol:	ntfs volume on which to modify the flags
531  * @flags:	flags to set on the volume
532  *
533  * Set the bits in @flags in the volume information flags on the volume @vol.
534  * The bits are combined with the current flag state under the lock in
535  * ntfs_write_volume_flags(), so concurrent updates are not lost.
536  *
537  * Return 0 on success and -errno on error.
538  */
539 int ntfs_set_volume_flags(struct ntfs_volume *vol, __le16 flags)
540 {
541 	return ntfs_write_volume_flags(vol, flags, 0, false);
542 }
543 
544 /*
545  * ntfs_sync_volume_dirty_state - persist the dirty bit per the error state
546  * @vol:	ntfs volume whose dirty bit to persist
547  *
548  * Set VOLUME_IS_DIRTY if errors have been recorded on @vol and clear it
549  * otherwise, under the $Volume mrec_lock.
550  *
551  * The guarantee this provides is eventual, not instantaneous: the runtime
552  * error paths record NVolErrors() with a lock-free set_bit(), so a
553  * persistence point that evaluates the flag just before an error is
554  * recorded can still leave the on-disk bit clean.  This is sound because
555  * NVolErrors() is sticky (nothing clears it for the lifetime of the mount)
556  * and every persistence point re-derives the on-disk bit from it; the
557  * last one, ntfs_put_super(), runs after evict_inodes() on a quiesced
558  * filesystem, so a volume that is read-write at unmount time cannot
559  * unmount clean.  A volume that is already read-only when the error is
560  * recorded (errors=remount-ro flips the superblock on the first error,
561  * as does an earlier remount-ro) has no persistence point left and
562  * keeps whatever on-disk bit it had; that behaviour is unchanged.  The
563  * residual window is a crash between the error and the next
564  * persistence point.
565  *
566  * This is the single point that persists the in-memory error state to disk.
567  * The runtime error paths only record NVolErrors() because they run under a
568  * variety of ntfs locks the dirty-bit write cannot be taken under (runlist
569  * locks, vol->lcnbmp_lock, vol->mftbmp_lock, mrec_locks); a sync of a
570  * volume with recorded errors, a remount to read-only, or the unmount,
571  * then persists the flag here.
572  *
573  * A hibernated volume is not written from these persistence paths:
574  * resuming Windows from a modified image corrupts it, so the dirty bit
575  * is left as it is on disk and only the in-memory error state is kept.
576  *
577  * Return 0 on success and -errno on error.
578  */
579 static int ntfs_sync_volume_dirty_state(struct ntfs_volume *vol)
580 {
581 	if (NVolHibernated(vol))
582 		return 0;
583 	return ntfs_write_volume_flags(vol, 0, VOLUME_IS_DIRTY, true);
584 }
585 
586 int ntfs_write_volume_label(struct ntfs_volume *vol, char *label)
587 {
588 	struct ntfs_inode *vol_ni = NTFS_I(vol->vol_ino);
589 	struct ntfs_attr_search_ctx *ctx;
590 	char *new_label;
591 	__le16 *uname;
592 	int uname_len, ret;
593 
594 	uname_len = ntfs_nlstoucs(vol, label, strlen(label),
595 				  &uname, FSLABEL_MAX);
596 	if (uname_len < 0) {
597 		ntfs_error(vol->sb,
598 			"Failed to convert volume label '%s' to Unicode.",
599 			label);
600 		return uname_len;
601 	}
602 
603 	if (uname_len > NTFS_MAX_LABEL_LEN) {
604 		ntfs_error(vol->sb,
605 			   "Volume label is too long (max %d characters).",
606 			   NTFS_MAX_LABEL_LEN);
607 		kvfree(uname);
608 		return -EINVAL;
609 	}
610 
611 	/*
612 	 * Allocate the in-memory label copy up front. If kstrdup() fails we
613 	 * bail out before touching on-disk metadata, so the in-memory label
614 	 * and the on-disk label stay in sync.
615 	 */
616 	new_label = kstrdup(label, GFP_KERNEL);
617 	if (!new_label) {
618 		kvfree(uname);
619 		return -ENOMEM;
620 	}
621 
622 	mutex_lock(&vol_ni->mrec_lock);
623 	ctx = ntfs_attr_get_search_ctx(vol_ni, NULL);
624 	if (!ctx) {
625 		ret = -ENOMEM;
626 		goto out;
627 	}
628 
629 	ret = ntfs_attr_lookup(AT_VOLUME_NAME, NULL, 0, 0, 0, NULL, 0,
630 			       ctx);
631 	if (!ret)
632 		ret = ntfs_attr_record_rm(ctx);
633 	else if (ret == -ENOENT)
634 		ret = 0;
635 	ntfs_attr_put_search_ctx(ctx);
636 	if (ret)
637 		goto out;
638 
639 	ret = ntfs_resident_attr_record_add(vol_ni, AT_VOLUME_NAME, AT_UNNAMED, 0,
640 					    (u8 *)uname, uname_len * sizeof(__le16), 0);
641 out:
642 	if (ret >= 0) {
643 		char *old_label;
644 
645 		mutex_lock(&vol->volume_label_lock);
646 		old_label = vol->volume_label;
647 		vol->volume_label = new_label;
648 		mutex_unlock(&vol->volume_label_lock);
649 
650 		kfree(old_label);
651 		mark_inode_dirty_sync(vol->vol_ino);
652 		ret = 0;
653 	}
654 	mutex_unlock(&vol_ni->mrec_lock);
655 	kvfree(uname);
656 
657 	if (ret < 0)
658 		kfree(new_label);
659 	return ret;
660 }
661 
662 /*
663  * is_boot_sector_ntfs - check whether a boot sector is a valid NTFS boot sector
664  * @sb:		Super block of the device to which @b belongs.
665  * @b:		Boot sector of device @sb to check.
666  * @silent:	If 'true', all output will be silenced.
667  *
668  * is_boot_sector_ntfs() checks whether the boot sector @b is a valid NTFS boot
669  * sector. Returns 'true' if it is valid and 'false' if not.
670  *
671  * @sb is only needed for warning/error output, i.e. it can be NULL when silent
672  * is 'true'.
673  */
674 static bool is_boot_sector_ntfs(const struct super_block *sb,
675 		const struct ntfs_boot_sector *b, const bool silent)
676 {
677 	u16 sector_size = le16_to_cpu(b->bpb.bytes_per_sector);
678 
679 	/*
680 	 * Check that checksum == sum of u32 values from b to the checksum
681 	 * field.  If checksum is zero, no checking is done.  We will work when
682 	 * the checksum test fails, since some utilities update the boot sector
683 	 * ignoring the checksum which leaves the checksum out-of-date.  We
684 	 * report a warning if this is the case.
685 	 */
686 	if ((void *)b < (void *)&b->checksum && b->checksum && !silent) {
687 		__le32 *u;
688 		u32 i;
689 
690 		for (i = 0, u = (__le32 *)b; u < (__le32 *)(&b->checksum); ++u)
691 			i += le32_to_cpup(u);
692 		if (le32_to_cpu(b->checksum) != i)
693 			ntfs_warning(sb, "Invalid boot sector checksum.");
694 	}
695 	/* Check OEMidentifier is "NTFS    " */
696 	if (b->oem_id != magicNTFS)
697 		goto not_ntfs;
698 	/* Check bytes per sector value is between 256 and 4096. */
699 	if (sector_size < 0x100 || sector_size > 0x1000 ||
700 	    !is_power_of_2(sector_size))
701 		goto not_ntfs;
702 	/*
703 	 * Check sectors per cluster value is valid and the cluster size
704 	 * is not above the maximum (2MB).
705 	 */
706 	if (b->bpb.sectors_per_cluster < 0xf4 &&
707 	    !is_power_of_2(b->bpb.sectors_per_cluster))
708 		goto not_ntfs;
709 
710 	/* Check reserved/unused fields are really zero. */
711 	if (le16_to_cpu(b->bpb.reserved_sectors) ||
712 			le16_to_cpu(b->bpb.root_entries) ||
713 			le16_to_cpu(b->bpb.sectors) ||
714 			le16_to_cpu(b->bpb.sectors_per_fat) ||
715 			le32_to_cpu(b->bpb.large_sectors) || b->bpb.fats)
716 		goto not_ntfs;
717 	/* Check clusters per file mft record value is valid. */
718 	if ((u8)b->clusters_per_mft_record < 0xe1 ||
719 			(u8)b->clusters_per_mft_record > 0xf7)
720 		switch (b->clusters_per_mft_record) {
721 		case 1: case 2: case 4: case 8: case 16: case 32: case 64:
722 			break;
723 		default:
724 			goto not_ntfs;
725 		}
726 	/* Check clusters per index block value is valid. */
727 	if ((u8)b->clusters_per_index_record < 0xe1 ||
728 			(u8)b->clusters_per_index_record > 0xf7)
729 		switch (b->clusters_per_index_record) {
730 		case 1: case 2: case 4: case 8: case 16: case 32: case 64:
731 			break;
732 		default:
733 			goto not_ntfs;
734 		}
735 	/*
736 	 * Check for valid end of sector marker. We will work without it, but
737 	 * many BIOSes will refuse to boot from a bootsector if the magic is
738 	 * incorrect, so we emit a warning.
739 	 */
740 	if (!silent && b->end_of_sector_marker != cpu_to_le16(0xaa55))
741 		ntfs_warning(sb, "Invalid end of sector marker.");
742 	return true;
743 not_ntfs:
744 	return false;
745 }
746 
747 /*
748  * read_ntfs_boot_sector - read the NTFS boot sector of a device
749  * @sb:		super block of device to read the boot sector from
750  * @silent:	if true, suppress all output
751  *
752  * Reads the boot sector from the device and validates it.
753  */
754 static char *read_ntfs_boot_sector(struct super_block *sb,
755 		const int silent)
756 {
757 	char *boot_sector;
758 
759 	boot_sector = kzalloc(PAGE_SIZE, GFP_NOFS);
760 	if (!boot_sector)
761 		return NULL;
762 
763 	if (ntfs_bdev_read(sb->s_bdev, boot_sector, 0, PAGE_SIZE)) {
764 		if (!silent)
765 			ntfs_error(sb, "Unable to read primary boot sector.");
766 		kfree(boot_sector);
767 		return NULL;
768 	}
769 
770 	if (!is_boot_sector_ntfs(sb, (struct ntfs_boot_sector *)boot_sector,
771 				 silent)) {
772 		if (!silent)
773 			ntfs_error(sb, "Primary boot sector is invalid.");
774 		kfree(boot_sector);
775 		return NULL;
776 	}
777 
778 	return boot_sector;
779 }
780 
781 static bool ntfs_validate_mft_io_geometry(struct ntfs_volume *vol,
782 					  const unsigned int logical_block_size)
783 {
784 	struct super_block *sb = vol->sb;
785 	u32 mft_io_unit_size = 0;
786 	bool mft_write_supported = true;
787 
788 	if (!is_power_of_2(logical_block_size) ||
789 	    logical_block_size > PAGE_SIZE ||
790 	    !is_power_of_2(vol->sector_size) ||
791 	    vol->sector_size < logical_block_size ||
792 	    vol->sector_size % logical_block_size ||
793 	    !is_power_of_2(vol->cluster_size) ||
794 	    !is_power_of_2(vol->mft_record_size) ||
795 	    vol->mft_record_size > PAGE_SIZE)
796 		goto err;
797 
798 	mft_io_unit_size = max(logical_block_size, vol->mft_record_size);
799 	if (mft_io_unit_size > PAGE_SIZE ||
800 	    mft_io_unit_size % logical_block_size ||
801 	    mft_io_unit_size % vol->mft_record_size)
802 		goto err;
803 
804 	/*
805 	 * The current direct-write path stores at most two MFT runlist
806 	 * segments. Keep valid but larger records read-only until that path
807 	 * can map an arbitrary number of segments.
808 	 */
809 	if (vol->mft_record_size > 2 * (u64)vol->cluster_size)
810 		mft_write_supported = false;
811 
812 	/*
813 	 * A containing device block is currently mapped through one MFT
814 	 * runlist element. Keep valid geometries that require crossing a
815 	 * cluster read-only until the mapping is generalized.
816 	 */
817 	if (mft_io_unit_size > vol->mft_record_size &&
818 	    (vol->cluster_size < mft_io_unit_size ||
819 	     vol->cluster_size % mft_io_unit_size))
820 		mft_write_supported = false;
821 
822 	vol->mft_io_unit_size = mft_io_unit_size;
823 	vol->mft_write_supported = mft_write_supported;
824 	return true;
825 
826 err:
827 	ntfs_error(sb,
828 		   "Unsupported MFT I/O geometry (logical %u, block %lu, sector %u, cluster %u, MFT record %u, I/O unit %u).",
829 		   logical_block_size, sb->s_blocksize,
830 		   (unsigned int)vol->sector_size, vol->cluster_size,
831 		   vol->mft_record_size, mft_io_unit_size);
832 	return false;
833 }
834 
835 /*
836  * parse_ntfs_boot_sector - parse the boot sector and store the data in @vol
837  * @vol:	volume structure to initialise with data from boot sector
838  * @b:		boot sector to parse
839  *
840  * Parse the ntfs boot sector @b and store all imporant information therein in
841  * the ntfs super block @vol.  Return 'true' on success and 'false' on error.
842  */
843 static bool parse_ntfs_boot_sector(struct ntfs_volume *vol,
844 		const struct ntfs_boot_sector *b)
845 {
846 	unsigned int sectors_per_cluster, sectors_per_cluster_bits, nr_hidden_sects;
847 	unsigned int logical_block_size;
848 	int clusters_per_mft_record, clusters_per_index_record;
849 	u64 ll;
850 
851 	logical_block_size = bdev_logical_block_size(vol->sb->s_bdev);
852 	vol->sector_size = le16_to_cpu(b->bpb.bytes_per_sector);
853 	vol->sector_size_bits = ffs(vol->sector_size) - 1;
854 	ntfs_debug("vol->sector_size = %i (0x%x)", vol->sector_size,
855 			vol->sector_size);
856 	ntfs_debug("vol->sector_size_bits = %i (0x%x)", vol->sector_size_bits,
857 			vol->sector_size_bits);
858 	if (vol->sector_size < vol->sb->s_blocksize) {
859 		ntfs_error(vol->sb,
860 			"Sector size (%i) is smaller than the device block size (%lu).  This is not supported.",
861 			vol->sector_size, vol->sb->s_blocksize);
862 		return false;
863 	}
864 
865 	if (b->bpb.sectors_per_cluster >= 0xf4)
866 		sectors_per_cluster = 1U << -(s8)b->bpb.sectors_per_cluster;
867 	else
868 		sectors_per_cluster = b->bpb.sectors_per_cluster;
869 	ntfs_debug("sectors_per_cluster = 0x%x", b->bpb.sectors_per_cluster);
870 	sectors_per_cluster_bits = ffs(sectors_per_cluster) - 1;
871 	ntfs_debug("sectors_per_cluster_bits = 0x%x",
872 			sectors_per_cluster_bits);
873 	nr_hidden_sects = le32_to_cpu(b->bpb.hidden_sectors);
874 	ntfs_debug("number of hidden sectors = 0x%x", nr_hidden_sects);
875 	vol->cluster_size = vol->sector_size << sectors_per_cluster_bits;
876 	vol->cluster_size_mask = vol->cluster_size - 1;
877 	vol->cluster_size_bits = ffs(vol->cluster_size) - 1;
878 	ntfs_debug("vol->cluster_size = %i (0x%x)", vol->cluster_size,
879 			vol->cluster_size);
880 	ntfs_debug("vol->cluster_size_mask = 0x%x", vol->cluster_size_mask);
881 	ntfs_debug("vol->cluster_size_bits = %i", vol->cluster_size_bits);
882 	if (vol->cluster_size < vol->sector_size) {
883 		ntfs_error(vol->sb,
884 			"Cluster size (%i) is smaller than the sector size (%i).  This is not supported.",
885 			vol->cluster_size, vol->sector_size);
886 		return false;
887 	}
888 	clusters_per_mft_record = b->clusters_per_mft_record;
889 	ntfs_debug("clusters_per_mft_record = %i (0x%x)",
890 			clusters_per_mft_record, clusters_per_mft_record);
891 	if (clusters_per_mft_record > 0)
892 		vol->mft_record_size = vol->cluster_size <<
893 				(ffs(clusters_per_mft_record) - 1);
894 	else
895 		/*
896 		 * When mft_record_size < cluster_size, clusters_per_mft_record
897 		 * = -log2(mft_record_size) bytes. mft_record_size normaly is
898 		 * 1024 bytes, which is encoded as 0xF6 (-10 in decimal).
899 		 */
900 		vol->mft_record_size = 1U << -clusters_per_mft_record;
901 	vol->mft_record_size_mask = vol->mft_record_size - 1;
902 	vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1;
903 	ntfs_debug("vol->mft_record_size = %i (0x%x)", vol->mft_record_size,
904 			vol->mft_record_size);
905 	ntfs_debug("vol->mft_record_size_mask = 0x%x",
906 			vol->mft_record_size_mask);
907 	ntfs_debug("vol->mft_record_size_bits = %i (0x%x)",
908 			vol->mft_record_size_bits, vol->mft_record_size_bits);
909 	/*
910 	 * We cannot support mft record sizes above the PAGE_SIZE since
911 	 * we store $MFT/$DATA, the table of mft records in the page cache.
912 	 */
913 	if (vol->mft_record_size > PAGE_SIZE) {
914 		ntfs_error(vol->sb,
915 			"Mft record size (%i) exceeds the PAGE_SIZE on your system (%lu).  This is not supported.",
916 			vol->mft_record_size, PAGE_SIZE);
917 		return false;
918 	}
919 	/* We cannot support mft record sizes below the sector size. */
920 	if (vol->mft_record_size < vol->sector_size) {
921 		ntfs_warning(vol->sb, "Mft record size (%i) is smaller than the sector size (%i).",
922 				vol->mft_record_size, vol->sector_size);
923 	}
924 	if (!ntfs_validate_mft_io_geometry(vol, logical_block_size))
925 		return false;
926 
927 	clusters_per_index_record = b->clusters_per_index_record;
928 	ntfs_debug("clusters_per_index_record = %i (0x%x)",
929 			clusters_per_index_record, clusters_per_index_record);
930 	if (clusters_per_index_record > 0)
931 		vol->index_record_size = vol->cluster_size <<
932 				(ffs(clusters_per_index_record) - 1);
933 	else
934 		/*
935 		 * When index_record_size < cluster_size,
936 		 * clusters_per_index_record = -log2(index_record_size) bytes.
937 		 * index_record_size normaly equals 4096 bytes, which is
938 		 * encoded as 0xF4 (-12 in decimal).
939 		 */
940 		vol->index_record_size = 1U << -clusters_per_index_record;
941 	vol->index_record_size_mask = vol->index_record_size - 1;
942 	vol->index_record_size_bits = ffs(vol->index_record_size) - 1;
943 	ntfs_debug("vol->index_record_size = %i (0x%x)",
944 			vol->index_record_size, vol->index_record_size);
945 	ntfs_debug("vol->index_record_size_mask = 0x%x",
946 			vol->index_record_size_mask);
947 	ntfs_debug("vol->index_record_size_bits = %i (0x%x)",
948 			vol->index_record_size_bits,
949 			vol->index_record_size_bits);
950 	/* We cannot support index record sizes below the sector size. */
951 	if (vol->index_record_size < vol->sector_size) {
952 		ntfs_error(vol->sb,
953 			   "Index record size (%i) is smaller than the sector size (%i).  This is not supported.",
954 			   vol->index_record_size, vol->sector_size);
955 		return false;
956 	}
957 	/*
958 	 * Get the size of the volume in clusters and check for 64-bit-ness.
959 	 * Windows currently only uses 32 bits to save the clusters so we do
960 	 * the same as it is much faster on 32-bit CPUs.
961 	 */
962 	ll = le64_to_cpu(b->number_of_sectors) >> sectors_per_cluster_bits;
963 	if (ll >= 1ULL << 32) {
964 		ntfs_error(vol->sb, "Cannot handle 64-bit clusters.");
965 		return false;
966 	}
967 	vol->nr_clusters = ll;
968 	ntfs_debug("vol->nr_clusters = 0x%llx", vol->nr_clusters);
969 	ll = le64_to_cpu(b->mft_lcn);
970 	if (ll >= (u64)vol->nr_clusters) {
971 		ntfs_error(vol->sb, "MFT LCN (%llu, 0x%llx) is beyond end of volume.  Weird.",
972 				ll, ll);
973 		return false;
974 	}
975 	vol->mft_lcn = ll;
976 	ntfs_debug("vol->mft_lcn = 0x%llx", vol->mft_lcn);
977 	ll = le64_to_cpu(b->mftmirr_lcn);
978 	if (ll >= (u64)vol->nr_clusters) {
979 		ntfs_error(vol->sb, "MFTMirr LCN (%llu, 0x%llx) is beyond end of volume.  Weird.",
980 				ll, ll);
981 		return false;
982 	}
983 	vol->mftmirr_lcn = ll;
984 	ntfs_debug("vol->mftmirr_lcn = 0x%llx", vol->mftmirr_lcn);
985 	/*
986 	 * Work out the size of the mft mirror in number of mft records. If the
987 	 * cluster size is less than or equal to the size taken by four mft
988 	 * records, the mft mirror stores the first four mft records. If the
989 	 * cluster size is bigger than the size taken by four mft records, the
990 	 * mft mirror contains as many mft records as will fit into one
991 	 * cluster.
992 	 */
993 	if (vol->cluster_size <= (4 << vol->mft_record_size_bits))
994 		vol->mftmirr_size = 4;
995 	else
996 		vol->mftmirr_size = vol->cluster_size >>
997 				vol->mft_record_size_bits;
998 	ntfs_debug("vol->mftmirr_size = %i", vol->mftmirr_size);
999 	vol->serial_no = le64_to_cpu(b->volume_serial_number);
1000 	super_set_uuid(vol->sb, (const u8 *)&b->volume_serial_number,
1001 		       sizeof(b->volume_serial_number));
1002 	ntfs_debug("vol->serial_no = 0x%llx", vol->serial_no);
1003 
1004 	vol->sparse_compression_unit = 4;
1005 	if (vol->cluster_size > 4096) {
1006 		switch (vol->cluster_size) {
1007 		case 65536:
1008 			vol->sparse_compression_unit = 0;
1009 			break;
1010 		case 32768:
1011 			vol->sparse_compression_unit = 1;
1012 			break;
1013 		case 16384:
1014 			vol->sparse_compression_unit = 2;
1015 			break;
1016 		case 8192:
1017 			vol->sparse_compression_unit = 3;
1018 			break;
1019 		}
1020 	}
1021 
1022 	return true;
1023 }
1024 
1025 /*
1026  * ntfs_setup_allocators - initialize the cluster and mft allocators
1027  * @vol:	volume structure for which to setup the allocators
1028  *
1029  * Setup the cluster (lcn) and mft allocators to the starting values.
1030  */
1031 static void ntfs_setup_allocators(struct ntfs_volume *vol)
1032 {
1033 	s64 mft_zone_size, mft_lcn;
1034 
1035 	ntfs_debug("vol->mft_zone_multiplier = 0x%x",
1036 			vol->mft_zone_multiplier);
1037 	/* Determine the size of the MFT zone. */
1038 	mft_zone_size = vol->nr_clusters;
1039 	switch (vol->mft_zone_multiplier) {  /* % of volume size in clusters */
1040 	case 4:
1041 		mft_zone_size >>= 1;			/* 50%   */
1042 		break;
1043 	case 3:
1044 		mft_zone_size = (mft_zone_size +
1045 				(mft_zone_size >> 1)) >> 2;	/* 37.5% */
1046 		break;
1047 	case 2:
1048 		mft_zone_size >>= 2;			/* 25%   */
1049 		break;
1050 	/* case 1: */
1051 	default:
1052 		mft_zone_size >>= 3;			/* 12.5% */
1053 		break;
1054 	}
1055 	/* Setup the mft zone. */
1056 	vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
1057 	ntfs_debug("vol->mft_zone_pos = 0x%llx", vol->mft_zone_pos);
1058 	/*
1059 	 * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
1060 	 * source) and if the actual mft_lcn is in the expected place or even
1061 	 * further to the front of the volume, extend the mft_zone to cover the
1062 	 * beginning of the volume as well.  This is in order to protect the
1063 	 * area reserved for the mft bitmap as well within the mft_zone itself.
1064 	 * On non-standard volumes we do not protect it as the overhead would
1065 	 * be higher than the speed increase we would get by doing it.
1066 	 */
1067 	mft_lcn = NTFS_B_TO_CLU(vol, 8192 + 2 * vol->cluster_size - 1);
1068 	if (mft_lcn * vol->cluster_size < 16 * 1024)
1069 		mft_lcn = (16 * 1024 + vol->cluster_size - 1) >>
1070 				vol->cluster_size_bits;
1071 	if (vol->mft_zone_start <= mft_lcn)
1072 		vol->mft_zone_start = 0;
1073 	ntfs_debug("vol->mft_zone_start = 0x%llx", vol->mft_zone_start);
1074 	/*
1075 	 * Need to cap the mft zone on non-standard volumes so that it does
1076 	 * not point outside the boundaries of the volume.  We do this by
1077 	 * halving the zone size until we are inside the volume.
1078 	 */
1079 	vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
1080 	while (vol->mft_zone_end >= vol->nr_clusters) {
1081 		mft_zone_size >>= 1;
1082 		vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
1083 	}
1084 	ntfs_debug("vol->mft_zone_end = 0x%llx", vol->mft_zone_end);
1085 	/*
1086 	 * Set the current position within each data zone to the start of the
1087 	 * respective zone.
1088 	 */
1089 	vol->data1_zone_pos = vol->mft_zone_end;
1090 	ntfs_debug("vol->data1_zone_pos = 0x%llx", vol->data1_zone_pos);
1091 	vol->data2_zone_pos = 0;
1092 	ntfs_debug("vol->data2_zone_pos = 0x%llx", vol->data2_zone_pos);
1093 
1094 	/* Set the mft data allocation position to mft record 24. */
1095 	vol->mft_data_pos = 24;
1096 	ntfs_debug("vol->mft_data_pos = 0x%llx", vol->mft_data_pos);
1097 }
1098 
1099 static struct lock_class_key mftmirr_runlist_lock_key,
1100 			     mftmirr_mrec_lock_key;
1101 /*
1102  * load_and_init_mft_mirror - load and setup the mft mirror inode for a volume
1103  * @vol:	ntfs super block describing device whose mft mirror to load
1104  *
1105  * Return 'true' on success or 'false' on error.
1106  */
1107 static bool load_and_init_mft_mirror(struct ntfs_volume *vol)
1108 {
1109 	struct inode *tmp_ino;
1110 	struct ntfs_inode *tmp_ni;
1111 
1112 	ntfs_debug("Entering.");
1113 	/* Get mft mirror inode. */
1114 	tmp_ino = ntfs_iget(vol->sb, FILE_MFTMirr);
1115 	if (IS_ERR(tmp_ino)) {
1116 		if (!IS_ERR(tmp_ino))
1117 			iput(tmp_ino);
1118 		/* Caller will display error message. */
1119 		return false;
1120 	}
1121 	lockdep_set_class(&NTFS_I(tmp_ino)->runlist.lock,
1122 			  &mftmirr_runlist_lock_key);
1123 	lockdep_set_class(&NTFS_I(tmp_ino)->mrec_lock,
1124 			  &mftmirr_mrec_lock_key);
1125 	/*
1126 	 * Re-initialize some specifics about $MFTMirr's inode as
1127 	 * ntfs_read_inode() will have set up the default ones.
1128 	 */
1129 	/* Set uid and gid to root. */
1130 	tmp_ino->i_uid = GLOBAL_ROOT_UID;
1131 	tmp_ino->i_gid = GLOBAL_ROOT_GID;
1132 	/* Regular file.  No access for anyone. */
1133 	tmp_ino->i_mode = S_IFREG;
1134 	/* No VFS initiated operations allowed for $MFTMirr. */
1135 	tmp_ino->i_op = &ntfs_empty_inode_ops;
1136 	tmp_ino->i_fop = &ntfs_empty_file_ops;
1137 	/* Put in our special address space operations. */
1138 	tmp_ino->i_mapping->a_ops = &ntfs_aops;
1139 	tmp_ni = NTFS_I(tmp_ino);
1140 	/* The $MFTMirr, like the $MFT is multi sector transfer protected. */
1141 	NInoSetMstProtected(tmp_ni);
1142 	NInoSetSparseDisabled(tmp_ni);
1143 	/*
1144 	 * Set up our little cheat allowing us to reuse the async read io
1145 	 * completion handler for directories.
1146 	 */
1147 	tmp_ni->itype.index.block_size = vol->mft_record_size;
1148 	tmp_ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1149 	vol->mftmirr_ino = tmp_ino;
1150 	ntfs_debug("Done.");
1151 	return true;
1152 }
1153 
1154 /*
1155  * check_mft_mirror - compare contents of the mft mirror with the mft
1156  * @vol:	ntfs super block describing device whose mft mirror to check
1157  *
1158  * Return 'true' on success or 'false' on error.
1159  *
1160  * Note, this function also results in the mft mirror runlist being completely
1161  * mapped into memory.  The mft mirror write code requires this and will BUG()
1162  * should it find an unmapped runlist element.
1163  */
1164 static bool check_mft_mirror(struct ntfs_volume *vol)
1165 {
1166 	struct super_block *sb = vol->sb;
1167 	struct ntfs_inode *mirr_ni;
1168 	struct folio *mft_folio = NULL, *mirr_folio = NULL;
1169 	u8 *kmft = NULL, *kmirr = NULL, *kmft_base = NULL, *kmirr_base = NULL;
1170 	struct runlist_element *rl, rl2[2];
1171 	pgoff_t index;
1172 	int mrecs_per_page, i;
1173 
1174 	ntfs_debug("Entering.");
1175 	/* Compare contents of $MFT and $MFTMirr. */
1176 	mrecs_per_page = PAGE_SIZE / vol->mft_record_size;
1177 	index = i = 0;
1178 	do {
1179 		u32 bytes;
1180 
1181 		/* Switch pages if necessary. */
1182 		if (!(i % mrecs_per_page)) {
1183 			if (index) {
1184 				kunmap_local(kmirr_base);
1185 				folio_put(mirr_folio);
1186 				kunmap_local(kmft_base);
1187 				folio_put(mft_folio);
1188 			}
1189 			/* Get the $MFT page. */
1190 			mft_folio = read_mapping_folio(vol->mft_ino->i_mapping,
1191 					index, NULL);
1192 			if (IS_ERR(mft_folio)) {
1193 				ntfs_error(sb, "Failed to read $MFT.");
1194 				return false;
1195 			}
1196 			kmft_base = kmap_local_folio(mft_folio, 0);
1197 			kmft = kmft_base;
1198 			/* Get the $MFTMirr page. */
1199 			mirr_folio = read_mapping_folio(vol->mftmirr_ino->i_mapping,
1200 					index, NULL);
1201 			if (IS_ERR(mirr_folio)) {
1202 				ntfs_error(sb, "Failed to read $MFTMirr.");
1203 				goto mft_unmap_out;
1204 			}
1205 			kmirr_base = kmap_local_folio(mirr_folio, 0);
1206 			kmirr = kmirr_base;
1207 			++index;
1208 		}
1209 
1210 		/* Do not check the record if it is not in use. */
1211 		if (((struct mft_record *)kmft)->flags & MFT_RECORD_IN_USE) {
1212 			/* Make sure the record is ok. */
1213 			if (ntfs_is_baad_recordp((__le32 *)kmft)) {
1214 				ntfs_error(sb,
1215 					"Incomplete multi sector transfer detected in mft record %i.",
1216 					i);
1217 mm_unmap_out:
1218 				kunmap_local(kmirr_base);
1219 				folio_put(mirr_folio);
1220 mft_unmap_out:
1221 				kunmap_local(kmft_base);
1222 				folio_put(mft_folio);
1223 				return false;
1224 			}
1225 		}
1226 		/* Do not check the mirror record if it is not in use. */
1227 		if (((struct mft_record *)kmirr)->flags & MFT_RECORD_IN_USE) {
1228 			if (ntfs_is_baad_recordp((__le32 *)kmirr)) {
1229 				ntfs_error(sb,
1230 					"Incomplete multi sector transfer detected in mft mirror record %i.",
1231 					i);
1232 				goto mm_unmap_out;
1233 			}
1234 		}
1235 		/* Get the amount of data in the current record. */
1236 		bytes = le32_to_cpu(((struct mft_record *)kmft)->bytes_in_use);
1237 		if (bytes < sizeof(struct mft_record_old) ||
1238 		    bytes > vol->mft_record_size ||
1239 		    ntfs_is_baad_recordp((__le32 *)kmft)) {
1240 			bytes = le32_to_cpu(((struct mft_record *)kmirr)->bytes_in_use);
1241 			if (bytes < sizeof(struct mft_record_old) ||
1242 			    bytes > vol->mft_record_size ||
1243 			    ntfs_is_baad_recordp((__le32 *)kmirr))
1244 				bytes = vol->mft_record_size;
1245 		}
1246 		/* Compare the two records. */
1247 		if (memcmp(kmft, kmirr, bytes)) {
1248 			ntfs_error(sb,
1249 				   "$MFT and $MFTMirr record %i do not match.  Run chkdsk.",
1250 				   i);
1251 			goto mm_unmap_out;
1252 		}
1253 		kmft += vol->mft_record_size;
1254 		kmirr += vol->mft_record_size;
1255 	} while (++i < vol->mftmirr_size);
1256 	/* Release the last folios. */
1257 	kunmap_local(kmirr_base);
1258 	folio_put(mirr_folio);
1259 	kunmap_local(kmft_base);
1260 	folio_put(mft_folio);
1261 
1262 	/* Construct the mft mirror runlist by hand. */
1263 	rl2[0].vcn = 0;
1264 	rl2[0].lcn = vol->mftmirr_lcn;
1265 	rl2[0].length = NTFS_B_TO_CLU(vol, vol->mftmirr_size * vol->mft_record_size +
1266 				vol->cluster_size - 1);
1267 	rl2[1].vcn = rl2[0].length;
1268 	rl2[1].lcn = LCN_ENOENT;
1269 	rl2[1].length = 0;
1270 	/*
1271 	 * Because we have just read all of the mft mirror, we know we have
1272 	 * mapped the full runlist for it.
1273 	 */
1274 	mirr_ni = NTFS_I(vol->mftmirr_ino);
1275 	down_read(&mirr_ni->runlist.lock);
1276 	rl = mirr_ni->runlist.rl;
1277 	/* Compare the two runlists.  They must be identical. */
1278 	i = 0;
1279 	do {
1280 		if (rl2[i].vcn != rl[i].vcn || rl2[i].lcn != rl[i].lcn ||
1281 				rl2[i].length != rl[i].length) {
1282 			ntfs_error(sb, "$MFTMirr location mismatch.  Run chkdsk.");
1283 			up_read(&mirr_ni->runlist.lock);
1284 			return false;
1285 		}
1286 	} while (rl2[i++].length);
1287 	up_read(&mirr_ni->runlist.lock);
1288 	ntfs_debug("Done.");
1289 	return true;
1290 }
1291 
1292 /*
1293  * load_and_check_logfile - load and check the logfile inode for a volume
1294  * @vol: ntfs volume to load the logfile for
1295  * @rp: on success, set to the restart page header
1296  *
1297  * Return 0 on success or errno on error.
1298  */
1299 static int load_and_check_logfile(struct ntfs_volume *vol,
1300 				  struct restart_page_header **rp)
1301 {
1302 	struct inode *tmp_ino;
1303 	int err = 0;
1304 
1305 	ntfs_debug("Entering.");
1306 	tmp_ino = ntfs_iget(vol->sb, FILE_LogFile);
1307 	if (IS_ERR(tmp_ino)) {
1308 		if (!IS_ERR(tmp_ino))
1309 			iput(tmp_ino);
1310 		/* Caller will display error message. */
1311 		return -ENOENT;
1312 	}
1313 	if (!ntfs_check_logfile(tmp_ino, rp))
1314 		err = -EINVAL;
1315 	NInoSetSparseDisabled(NTFS_I(tmp_ino));
1316 	vol->logfile_ino = tmp_ino;
1317 	ntfs_debug("Done.");
1318 	return err;
1319 }
1320 
1321 #define NTFS_HIBERFIL_HEADER_SIZE	4096
1322 
1323 /*
1324  * check_windows_hibernation_status - check if Windows is suspended on a volume
1325  * @vol:	ntfs super block of device to check
1326  *
1327  * Check if Windows is hibernated on the ntfs volume @vol.  This is done by
1328  * looking for the file hiberfil.sys in the root directory of the volume.  If
1329  * the file is not present Windows is definitely not suspended.
1330  *
1331  * If hiberfil.sys exists and is less than 4kiB in size it means Windows is
1332  * definitely suspended (this volume is not the system volume).  Caveat:  on a
1333  * system with many volumes it is possible that the < 4kiB check is bogus but
1334  * for now this should do fine.
1335  *
1336  * If hiberfil.sys exists and is larger than 4kiB in size, we need to read the
1337  * hiberfil header (which is the first 4kiB).  If this begins with "hibr",
1338  * Windows is definitely suspended.  If it is completely full of zeroes,
1339  * Windows is definitely not hibernated.  Any other case is treated as if
1340  * Windows is suspended.  This caters for the above mentioned caveat of a
1341  * system with many volumes where no "hibr" magic would be present and there is
1342  * no zero header.
1343  *
1344  * Return 0 if Windows is not hibernated on the volume, >0 if Windows is
1345  * hibernated on the volume, and -errno on error.
1346  */
1347 static int check_windows_hibernation_status(struct ntfs_volume *vol)
1348 {
1349 	static const __le16 hiberfil[13] = { cpu_to_le16('h'),
1350 			cpu_to_le16('i'), cpu_to_le16('b'),
1351 			cpu_to_le16('e'), cpu_to_le16('r'),
1352 			cpu_to_le16('f'), cpu_to_le16('i'),
1353 			cpu_to_le16('l'), cpu_to_le16('.'),
1354 			cpu_to_le16('s'), cpu_to_le16('y'),
1355 			cpu_to_le16('s'), 0 };
1356 	u64 mref;
1357 	struct inode *vi;
1358 	struct folio *folio;
1359 	u32 *kaddr, *kend, *start_addr = NULL;
1360 	struct ntfs_name *name = NULL;
1361 	int ret = 1;
1362 
1363 	ntfs_debug("Entering.");
1364 	/*
1365 	 * Find the inode number for the hibernation file by looking up the
1366 	 * filename hiberfil.sys in the root directory.
1367 	 */
1368 	inode_lock(vol->root_ino);
1369 	mref = ntfs_lookup_inode_by_name(NTFS_I(vol->root_ino), hiberfil, 12,
1370 			&name);
1371 	inode_unlock(vol->root_ino);
1372 	kfree(name);
1373 	if (IS_ERR_MREF(mref)) {
1374 		ret = MREF_ERR(mref);
1375 		/* If the file does not exist, Windows is not hibernated. */
1376 		if (ret == -ENOENT) {
1377 			ntfs_debug("hiberfil.sys not present.  Windows is not hibernated on the volume.");
1378 			return 0;
1379 		}
1380 		/* A real error occurred. */
1381 		ntfs_error(vol->sb, "Failed to find inode number for hiberfil.sys.");
1382 		return ret;
1383 	}
1384 	/* Get the inode. */
1385 	vi = ntfs_iget(vol->sb, MREF(mref));
1386 	if (IS_ERR(vi)) {
1387 		if (!IS_ERR(vi))
1388 			iput(vi);
1389 		ntfs_error(vol->sb, "Failed to load hiberfil.sys.");
1390 		return IS_ERR(vi) ? PTR_ERR(vi) : -EIO;
1391 	}
1392 	if (unlikely(i_size_read(vi) < NTFS_HIBERFIL_HEADER_SIZE)) {
1393 		ntfs_debug("hiberfil.sys is smaller than 4kiB (0x%llx).  Windows is hibernated on the volume.  This is not the system volume.",
1394 				i_size_read(vi));
1395 		goto iput_out;
1396 	}
1397 
1398 	folio = read_mapping_folio(vi->i_mapping, 0, NULL);
1399 	if (IS_ERR(folio)) {
1400 		ntfs_error(vol->sb, "Failed to read from hiberfil.sys.");
1401 		ret = PTR_ERR(folio);
1402 		goto iput_out;
1403 	}
1404 	start_addr = (u32 *)kmap_local_folio(folio, 0);
1405 	kaddr = start_addr;
1406 	if (*(__le32 *)kaddr == cpu_to_le32(0x72626968)/*'hibr'*/) {
1407 		ntfs_debug("Magic \"hibr\" found in hiberfil.sys.  Windows is hibernated on the volume.  This is the system volume.");
1408 		goto unm_iput_out;
1409 	}
1410 	kend = kaddr + NTFS_HIBERFIL_HEADER_SIZE/sizeof(*kaddr);
1411 	do {
1412 		if (unlikely(*kaddr)) {
1413 			ntfs_debug("hiberfil.sys is larger than 4kiB (0x%llx), does not contain the \"hibr\" magic, and does not have a zero header.  Windows is hibernated on the volume.  This is not the system volume.",
1414 					i_size_read(vi));
1415 			goto unm_iput_out;
1416 		}
1417 	} while (++kaddr < kend);
1418 	ntfs_debug("hiberfil.sys contains a zero header.  Windows is not hibernated on the volume.  This is the system volume.");
1419 	ret = 0;
1420 unm_iput_out:
1421 	kunmap_local(start_addr);
1422 	folio_put(folio);
1423 iput_out:
1424 	iput(vi);
1425 	return ret;
1426 }
1427 
1428 /*
1429  * load_and_init_attrdef - load the attribute definitions table for a volume
1430  * @vol:	ntfs super block describing device whose attrdef to load
1431  *
1432  * Return 'true' on success or 'false' on error.
1433  */
1434 static bool load_and_init_attrdef(struct ntfs_volume *vol)
1435 {
1436 	loff_t i_size;
1437 	struct super_block *sb = vol->sb;
1438 	struct inode *ino;
1439 	struct folio *folio;
1440 	u8 *addr;
1441 	pgoff_t index, max_index;
1442 	unsigned int size;
1443 
1444 	ntfs_debug("Entering.");
1445 	/* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */
1446 	ino = ntfs_iget(sb, FILE_AttrDef);
1447 	if (IS_ERR(ino))
1448 		goto failed;
1449 	NInoSetSparseDisabled(NTFS_I(ino));
1450 	/* FILE_AttrDef must hold at least one entry and fit inside 31 bits. */
1451 	i_size = i_size_read(ino);
1452 	if (i_size < (s64)sizeof(struct attr_def) || i_size > 0x7fffffff)
1453 		goto iput_failed;
1454 	vol->attrdef = kvzalloc(i_size, GFP_NOFS);
1455 	if (!vol->attrdef)
1456 		goto iput_failed;
1457 	index = 0;
1458 	max_index = i_size >> PAGE_SHIFT;
1459 	size = PAGE_SIZE;
1460 	while (index < max_index) {
1461 		/* Read the attrdef table and copy it into the linear buffer. */
1462 read_partial_attrdef_page:
1463 		folio = read_mapping_folio(ino->i_mapping, index, NULL);
1464 		if (IS_ERR(folio))
1465 			goto free_iput_failed;
1466 		addr = kmap_local_folio(folio, 0);
1467 		memcpy((u8 *)vol->attrdef + (index++ << PAGE_SHIFT),
1468 				addr, size);
1469 		kunmap_local(addr);
1470 		folio_put(folio);
1471 	}
1472 	if (size == PAGE_SIZE) {
1473 		size = i_size & ~PAGE_MASK;
1474 		if (size)
1475 			goto read_partial_attrdef_page;
1476 	}
1477 	vol->attrdef_size = i_size;
1478 	ntfs_debug("Read %llu bytes from $AttrDef.", i_size);
1479 	iput(ino);
1480 	return true;
1481 free_iput_failed:
1482 	kvfree(vol->attrdef);
1483 	vol->attrdef = NULL;
1484 iput_failed:
1485 	iput(ino);
1486 failed:
1487 	ntfs_error(sb, "Failed to initialize attribute definition table.");
1488 	return false;
1489 }
1490 
1491 /*
1492  * load_and_init_upcase - load the upcase table for an ntfs volume
1493  * @vol:	ntfs super block describing device whose upcase to load
1494  *
1495  * Return 'true' on success or 'false' on error.
1496  */
1497 static bool load_and_init_upcase(struct ntfs_volume *vol)
1498 {
1499 	loff_t i_size;
1500 	struct super_block *sb = vol->sb;
1501 	struct inode *ino;
1502 	struct folio *folio;
1503 	u8 *addr;
1504 	pgoff_t index, max_index;
1505 	unsigned int size;
1506 
1507 	ntfs_debug("Entering.");
1508 	/* Read upcase table and setup vol->upcase and vol->upcase_len. */
1509 	ino = ntfs_iget(sb, FILE_UpCase);
1510 	if (IS_ERR(ino))
1511 		goto upcase_failed;
1512 	/*
1513 	 * The upcase size must not be above 64k Unicode characters, must not
1514 	 * be zero and must be a multiple of sizeof(__le16).
1515 	 */
1516 	i_size = i_size_read(ino);
1517 	if (!i_size || i_size & (sizeof(__le16) - 1) ||
1518 			i_size > 64ULL * 1024 * sizeof(__le16))
1519 		goto iput_upcase_failed;
1520 	vol->upcase = kvzalloc(i_size, GFP_NOFS);
1521 	if (!vol->upcase)
1522 		goto iput_upcase_failed;
1523 	index = 0;
1524 	max_index = i_size >> PAGE_SHIFT;
1525 	size = PAGE_SIZE;
1526 	while (index < max_index) {
1527 		/* Read the upcase table and copy it into the linear buffer. */
1528 read_partial_upcase_page:
1529 		folio = read_mapping_folio(ino->i_mapping, index, NULL);
1530 		if (IS_ERR(folio))
1531 			goto iput_upcase_failed;
1532 		addr = kmap_local_folio(folio, 0);
1533 		memcpy((char *)vol->upcase + (index++ << PAGE_SHIFT),
1534 				addr, size);
1535 		kunmap_local(addr);
1536 		folio_put(folio);
1537 	}
1538 	if (size == PAGE_SIZE) {
1539 		size = i_size & ~PAGE_MASK;
1540 		if (size)
1541 			goto read_partial_upcase_page;
1542 	}
1543 	vol->upcase_len = i_size >> sizeof(unsigned char);
1544 	ntfs_debug("Read %llu bytes from $UpCase (expected %zu bytes).",
1545 			i_size, 64 * 1024 * sizeof(__le16));
1546 	iput(ino);
1547 	mutex_lock(&ntfs_lock);
1548 	if (!default_upcase) {
1549 		ntfs_debug("Using volume specified $UpCase since default is not present.");
1550 		mutex_unlock(&ntfs_lock);
1551 		return true;
1552 	}
1553 	if (default_upcase_len == vol->upcase_len &&
1554 	    !memcmp(vol->upcase, default_upcase,
1555 		    default_upcase_len * sizeof(*default_upcase))) {
1556 		kvfree(vol->upcase);
1557 		vol->upcase = default_upcase;
1558 		ntfs_nr_upcase_users++;
1559 		mutex_unlock(&ntfs_lock);
1560 		ntfs_debug("Volume specified $UpCase matches default. Using default.");
1561 		return true;
1562 	}
1563 	mutex_unlock(&ntfs_lock);
1564 	ntfs_debug("Using volume specified $UpCase since it does not match the default.");
1565 	return true;
1566 iput_upcase_failed:
1567 	iput(ino);
1568 	kvfree(vol->upcase);
1569 	vol->upcase = NULL;
1570 upcase_failed:
1571 	mutex_lock(&ntfs_lock);
1572 	if (default_upcase) {
1573 		vol->upcase = default_upcase;
1574 		vol->upcase_len = default_upcase_len;
1575 		ntfs_nr_upcase_users++;
1576 		mutex_unlock(&ntfs_lock);
1577 		ntfs_error(sb, "Failed to load $UpCase from the volume. Using default.");
1578 		return true;
1579 	}
1580 	mutex_unlock(&ntfs_lock);
1581 	ntfs_error(sb, "Failed to initialize upcase table.");
1582 	return false;
1583 }
1584 
1585 static int ntfs_validate_badclus(struct ntfs_volume *vol,
1586 		const struct runlist *runlist, s64 *bad_clusters)
1587 {
1588 	const struct runlist_element *rl = runlist->rl;
1589 	s64 next_vcn = 0, bad = 0;
1590 	size_t i;
1591 
1592 	if (!rl)
1593 		return -EIO;
1594 
1595 	for (i = 0; i < runlist->count; i++) {
1596 		if (!rl[i].length) {
1597 			if (i != runlist->count - 1 ||
1598 			    rl[i].vcn != vol->nr_clusters ||
1599 			    rl[i].lcn != LCN_ENOENT ||
1600 			    next_vcn != vol->nr_clusters)
1601 				return -EIO;
1602 			*bad_clusters = bad;
1603 			return 0;
1604 		}
1605 		if (rl[i].vcn != next_vcn || rl[i].length < 0 ||
1606 		    rl[i].length > vol->nr_clusters - next_vcn)
1607 			return -EIO;
1608 		if (rl[i].lcn != LCN_HOLE) {
1609 			/* Each bad cluster is mapped to its own volume offset. */
1610 			if (rl[i].lcn != rl[i].vcn)
1611 				return -EIO;
1612 			bad += rl[i].length;
1613 		}
1614 		next_vcn += rl[i].length;
1615 	}
1616 	return -EIO;
1617 }
1618 
1619 /*
1620  * Read the allocation of $BadClus:$Bad, not its data. initialized_size may
1621  * be zero even when the runlist contains bad clusters. Validate every run
1622  * before repairing $Bitmap, and let the later free-space scan account for
1623  * the reservations without subtracting the bad-cluster count again.
1624  */
1625 static int load_and_check_badclus(struct ntfs_volume *vol)
1626 {
1627 	static __le16 bad_name[] = {
1628 		cpu_to_le16('$'), cpu_to_le16('B'),
1629 		cpu_to_le16('a'), cpu_to_le16('d'),
1630 	};
1631 	struct super_block *sb = vol->sb;
1632 	struct inode *base_ino, *bad_ino;
1633 	struct ntfs_inode *ni;
1634 	s64 free_bits = 0;
1635 	u64 size = ntfs_cluster_to_bytes(vol, vol->nr_clusters);
1636 	size_t i;
1637 	int err;
1638 
1639 	base_ino = ntfs_iget(sb, FILE_BadClus);
1640 	if (IS_ERR(base_ino))
1641 		return PTR_ERR(base_ino);
1642 	if (!S_ISREG(base_ino->i_mode)) {
1643 		err = -EIO;
1644 		goto iput_base;
1645 	}
1646 	bad_ino = ntfs_attr_iget(base_ino, AT_DATA, bad_name,
1647 				 ARRAY_SIZE(bad_name));
1648 	if (IS_ERR(bad_ino)) {
1649 		err = PTR_ERR(bad_ino);
1650 		goto iput_base;
1651 	}
1652 	ni = NTFS_I(bad_ino);
1653 	if (!NInoNonResident(ni) || NInoCompressed(ni) || NInoEncrypted(ni) ||
1654 	    ni->data_size != size || ni->allocated_size != size) {
1655 		err = -EIO;
1656 		goto iput_bad;
1657 	}
1658 
1659 	down_write(&ni->runlist.lock);
1660 	err = ntfs_attr_map_whole_runlist(ni);
1661 	if (err)
1662 		goto unlock;
1663 	err = ntfs_validate_badclus(vol, &ni->runlist, &vol->bad_clusters);
1664 	if (err)
1665 		goto unlock;
1666 	for (i = 0; i < ni->runlist.count - 1; i++) {
1667 		struct runlist_element *rl = &ni->runlist.rl[i];
1668 
1669 		if (rl->lcn == LCN_HOLE)
1670 			continue;
1671 		err = ntfs_bitmap_check_used(vol, rl->lcn, rl->length,
1672 					     !sb_rdonly(sb), &free_bits);
1673 		if (err)
1674 			break;
1675 	}
1676 unlock:
1677 	up_write(&ni->runlist.lock);
1678 iput_bad:
1679 	iput(bad_ino);
1680 iput_base:
1681 	iput(base_ino);
1682 	if (err)
1683 		return err;
1684 	if (free_bits) {
1685 		/* A read-only mount must not later remount RW without repair. */
1686 		if (sb_rdonly(sb))
1687 			return -EIO;
1688 		err = filemap_write_and_wait(vol->lcnbmp_ino->i_mapping);
1689 		if (err)
1690 			return err;
1691 		err = blkdev_issue_flush(sb->s_bdev);
1692 		if (err)
1693 			return err;
1694 		ntfs_warning(sb,
1695 			     "Marked %lld bad clusters as used in $Bitmap.",
1696 			     free_bits);
1697 	}
1698 	if (vol->bad_clusters)
1699 		pr_info("volume contains %lld bad clusters, dev %s\n",
1700 			vol->bad_clusters, sb->s_id);
1701 	return 0;
1702 }
1703 
1704 /*
1705  * The lcn and mft bitmap inodes are NTFS-internal inodes with
1706  * their own special locking rules:
1707  */
1708 static struct lock_class_key
1709 	lcnbmp_runlist_lock_key, lcnbmp_mrec_lock_key,
1710 	mftbmp_runlist_lock_key, mftbmp_mrec_lock_key;
1711 
1712 /*
1713  * load_system_files - open the system files using normal functions
1714  * @vol:	ntfs super block describing device whose system files to load
1715  *
1716  * Open the system files with normal access functions and complete setting up
1717  * the ntfs super block @vol.
1718  *
1719  * Return 0 on success and -errno on error.
1720  */
1721 static int load_system_files(struct ntfs_volume *vol)
1722 {
1723 	struct super_block *sb = vol->sb;
1724 	struct mft_record *m;
1725 	struct volume_information *vi;
1726 	struct ntfs_attr_search_ctx *ctx;
1727 	struct restart_page_header *rp;
1728 	int err, ret = -EINVAL;
1729 	u8 saved_on_errors;
1730 
1731 	ntfs_debug("Entering.");
1732 	/* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */
1733 	if (!load_and_init_mft_mirror(vol) || !check_mft_mirror(vol)) {
1734 		/* If a read-write mount, convert it to a read-only mount. */
1735 		if (!sb_rdonly(sb) && vol->on_errors == ON_ERRORS_REMOUNT_RO) {
1736 			static const char *es1 = "Failed to load $MFTMirr";
1737 			static const char *es2 = "$MFTMirr does not match $MFT";
1738 			static const char *es3 = ".  Run ntfsck and/or chkdsk.";
1739 
1740 			sb->s_flags |= SB_RDONLY;
1741 			ntfs_error(sb, "%s.  Mounting read-only%s",
1742 					!vol->mftmirr_ino ? es1 : es2, es3);
1743 		}
1744 		NVolSetErrors(vol);
1745 	}
1746 	/* Get mft bitmap attribute inode. */
1747 	vol->mftbmp_ino = ntfs_attr_iget(vol->mft_ino, AT_BITMAP, NULL, 0);
1748 	if (IS_ERR(vol->mftbmp_ino)) {
1749 		ntfs_error(sb, "Failed to load $MFT/$BITMAP attribute.");
1750 		goto iput_mirr_err_out;
1751 	}
1752 	lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->runlist.lock,
1753 			   &mftbmp_runlist_lock_key);
1754 	lockdep_set_class(&NTFS_I(vol->mftbmp_ino)->mrec_lock,
1755 			   &mftbmp_mrec_lock_key);
1756 	/* Read upcase table and setup @vol->upcase and @vol->upcase_len. */
1757 	if (!load_and_init_upcase(vol))
1758 		goto iput_mftbmp_err_out;
1759 	/*
1760 	 * Read attribute definitions table and setup @vol->attrdef and
1761 	 * @vol->attrdef_size.
1762 	 */
1763 	if (!load_and_init_attrdef(vol))
1764 		goto iput_upcase_err_out;
1765 	/*
1766 	 * Get the cluster allocation bitmap inode and verify the size, no
1767 	 * need for any locking at this stage as we are already running
1768 	 * exclusively as we are mount in progress task.
1769 	 */
1770 	vol->lcnbmp_ino = ntfs_iget(sb, FILE_Bitmap);
1771 	if (IS_ERR(vol->lcnbmp_ino)) {
1772 		if (!IS_ERR(vol->lcnbmp_ino))
1773 			iput(vol->lcnbmp_ino);
1774 		goto bitmap_failed;
1775 	}
1776 	lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->runlist.lock,
1777 			   &lcnbmp_runlist_lock_key);
1778 	lockdep_set_class(&NTFS_I(vol->lcnbmp_ino)->mrec_lock,
1779 			   &lcnbmp_mrec_lock_key);
1780 
1781 	NInoSetSparseDisabled(NTFS_I(vol->lcnbmp_ino));
1782 	if ((vol->nr_clusters + 7) >> 3 > i_size_read(vol->lcnbmp_ino)) {
1783 		iput(vol->lcnbmp_ino);
1784 bitmap_failed:
1785 		ntfs_error(sb, "Failed to load $Bitmap.");
1786 		goto iput_attrdef_err_out;
1787 	}
1788 	/*
1789 	 * Get the volume inode and setup our cache of the volume flags and
1790 	 * version.
1791 	 */
1792 	vol->vol_ino = ntfs_iget(sb, FILE_Volume);
1793 	if (IS_ERR(vol->vol_ino)) {
1794 		vol->vol_ino = NULL;
1795 volume_failed:
1796 		ntfs_error(sb, "Failed to load $Volume.");
1797 		goto iput_lcnbmp_err_out;
1798 	}
1799 	m = map_mft_record(NTFS_I(vol->vol_ino));
1800 	if (IS_ERR(m)) {
1801 iput_volume_failed:
1802 		iput(vol->vol_ino);
1803 		vol->vol_ino = NULL;
1804 		goto volume_failed;
1805 	}
1806 
1807 	ctx = ntfs_attr_get_search_ctx(NTFS_I(vol->vol_ino), m);
1808 	if (!ctx) {
1809 		ntfs_error(sb, "Failed to get attribute search context.");
1810 		goto get_ctx_vol_failed;
1811 	}
1812 
1813 	if (!ntfs_attr_lookup(AT_VOLUME_NAME, NULL, 0, 0, 0, NULL, 0, ctx) &&
1814 	    !ctx->attr->non_resident &&
1815 	    !(ctx->attr->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED)) &&
1816 	    le32_to_cpu(ctx->attr->data.resident.value_length) > 0) {
1817 		err = ntfs_ucstonls(vol, (__le16 *)((u8 *)ctx->attr +
1818 				    le16_to_cpu(ctx->attr->data.resident.value_offset)),
1819 				    le32_to_cpu(ctx->attr->data.resident.value_length) / 2,
1820 				    &vol->volume_label, NTFS_MAX_LABEL_LEN);
1821 		if (err < 0)
1822 			vol->volume_label = NULL;
1823 	}
1824 
1825 	ntfs_attr_reinit_search_ctx(ctx);
1826 	if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, NULL, 0, 0, 0, NULL, 0,
1827 			ctx) || ctx->attr->non_resident || ctx->attr->flags) {
1828 		ntfs_attr_put_search_ctx(ctx);
1829 get_ctx_vol_failed:
1830 		unmap_mft_record(NTFS_I(vol->vol_ino));
1831 		goto iput_volume_failed;
1832 	}
1833 	vi = (struct volume_information *)((char *)ctx->attr +
1834 			le16_to_cpu(ctx->attr->data.resident.value_offset));
1835 	/* Copy the volume flags and version to the struct ntfs_volume structure. */
1836 	vol->vol_flags = vi->flags;
1837 	vol->major_ver = vi->major_ver;
1838 	vol->minor_ver = vi->minor_ver;
1839 	ntfs_attr_put_search_ctx(ctx);
1840 	unmap_mft_record(NTFS_I(vol->vol_ino));
1841 	pr_info("volume version %i.%i, dev %s, cluster size %d\n",
1842 		vol->major_ver, vol->minor_ver, sb->s_id, vol->cluster_size);
1843 
1844 	/* Make sure that no unsupported volume flags are set. */
1845 	if (vol->vol_flags & VOLUME_MUST_MOUNT_RO_MASK) {
1846 		static const char *es1a = "Volume is dirty";
1847 		static const char *es1b = "Volume has been modified by chkdsk";
1848 		static const char *es1c = "Volume has unsupported flags set";
1849 		static const char *es2a = ".  Run chkdsk and mount in Windows.";
1850 		static const char *es2b = ".  Mount in Windows.";
1851 		const char *es1, *es2;
1852 
1853 		es2 = es2a;
1854 		if (vol->vol_flags & VOLUME_IS_DIRTY)
1855 			es1 = es1a;
1856 		else if (vol->vol_flags & VOLUME_MODIFIED_BY_CHKDSK) {
1857 			es1 = es1b;
1858 			es2 = es2b;
1859 		} else {
1860 			es1 = es1c;
1861 			ntfs_warning(sb, "Unsupported volume flags 0x%x encountered.",
1862 					(unsigned int)le16_to_cpu(vol->vol_flags));
1863 		}
1864 		/* If a read-write mount, convert it to a read-only mount. */
1865 		if (!sb_rdonly(sb) && vol->on_errors == ON_ERRORS_REMOUNT_RO) {
1866 			sb->s_flags |= SB_RDONLY;
1867 			ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1868 		}
1869 		/*
1870 		 * Do not set NVolErrors() because ntfs_remount() re-checks the
1871 		 * flags which we need to do in case any flags have changed.
1872 		 */
1873 	}
1874 	/*
1875 	 * Get the inode for the logfile, check it and determine if the volume
1876 	 * was shutdown cleanly.
1877 	 */
1878 	rp = NULL;
1879 	err = load_and_check_logfile(vol, &rp);
1880 	if (err) {
1881 		/* If a read-write mount, convert it to a read-only mount. */
1882 		if (!sb_rdonly(sb) && vol->on_errors == ON_ERRORS_REMOUNT_RO) {
1883 			sb->s_flags |= SB_RDONLY;
1884 			ntfs_error(sb, "Failed to load LogFile. Mounting read-only.");
1885 		}
1886 		NVolSetErrors(vol);
1887 	}
1888 
1889 	kvfree(rp);
1890 	/* Get the root directory inode so we can do path lookups. */
1891 	vol->root_ino = ntfs_iget(sb, FILE_root);
1892 	if (IS_ERR(vol->root_ino)) {
1893 		if (!IS_ERR(vol->root_ino))
1894 			iput(vol->root_ino);
1895 		ntfs_error(sb, "Failed to load root directory.");
1896 		goto iput_logfile_err_out;
1897 	}
1898 	/*
1899 	 * Check if Windows is suspended to disk on the target volume.  If it
1900 	 * is hibernated, we must not write *anything* to the disk so set
1901 	 * NVolErrors() without setting the dirty volume flag and mount
1902 	 * read-only.  This will prevent read-write remounting and it will also
1903 	 * prevent all writes.
1904 	 *
1905 	 * Nested lookup and inode-loading errors must not panic before the
1906 	 * read-only fallback has run.  Temporarily use errors=remount-ro
1907 	 * instead of errors=panic, preserving any read-only transition even
1908 	 * if an error is not propagated to the check's return value or
1909 	 * recorded in NVolErrors().  This is safe during initial mount,
1910 	 * before the super block is published.
1911 	 */
1912 	saved_on_errors = vol->on_errors;
1913 	if (saved_on_errors == ON_ERRORS_PANIC)
1914 		vol->on_errors = ON_ERRORS_REMOUNT_RO;
1915 	err = check_windows_hibernation_status(vol);
1916 	vol->on_errors = saved_on_errors;
1917 	if (unlikely(err)) {
1918 		static const char *es1a = "Failed to determine if Windows is hibernated";
1919 		static const char *es1b = "Windows is hibernated";
1920 		static const char *es2 = ".  Run chkdsk.";
1921 		const char *es1;
1922 
1923 		es1 = err < 0 ? es1a : es1b;
1924 		/* Hibernation safety takes precedence over the errors= policy. */
1925 		sb->s_flags |= SB_RDONLY;
1926 		NVolSetErrors(vol);
1927 		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1928 
1929 		/*
1930 		 * Remember it for the lifetime of the mount: see
1931 		 * ntfs_sync_volume_dirty_state().
1932 		 */
1933 		NVolSetHibernated(vol);
1934 	} else if (!sb_rdonly(sb) && NVolErrors(vol)) {
1935 		/* Match the read-write remount restriction for recorded errors. */
1936 		sb->s_flags |= SB_RDONLY;
1937 		ntfs_error(sb,
1938 		    "Errors were recorded during mount.  Mounting read-only.  Run chkdsk.");
1939 	}
1940 
1941 	/* Check bad clusters after hibernation checks and before any writes. */
1942 	saved_on_errors = vol->on_errors;
1943 	if (saved_on_errors == ON_ERRORS_PANIC)
1944 		vol->on_errors = ON_ERRORS_REMOUNT_RO;
1945 	err = load_and_check_badclus(vol);
1946 	vol->on_errors = saved_on_errors;
1947 	if (err == -ENOMEM) {
1948 		ret = err;
1949 		ntfs_warning(sb, "Not enough memory to load $BadClus.");
1950 		goto iput_root_err_out;
1951 	}
1952 	if (err) {
1953 		sb->s_flags |= SB_RDONLY;
1954 		NVolSetErrors(vol);
1955 		ntfs_error(sb,
1956 			   "Failed to initialize $BadClus (%d). Mounting read-only. Run fsck.ntfs or chkdsk.",
1957 			   err);
1958 	}
1959 
1960 	/* If (still) a read-write mount, empty the logfile. */
1961 	if (!sb_rdonly(sb) &&
1962 	    vol->logfile_ino && !ntfs_empty_logfile(vol->logfile_ino) &&
1963 	    vol->on_errors == ON_ERRORS_REMOUNT_RO) {
1964 		static const char *es1 = "Failed to empty LogFile";
1965 		static const char *es2 = ".  Mount in Windows.";
1966 
1967 		/* Convert to a read-only mount. */
1968 		ntfs_error(sb, "%s.  Mounting read-only%s", es1, es2);
1969 		sb->s_flags |= SB_RDONLY;
1970 		NVolSetErrors(vol);
1971 	}
1972 	/* If on NTFS versions before 3.0, we are done. */
1973 	if (unlikely(vol->major_ver < 3))
1974 		return 0;
1975 	/* NTFS 3.0+ specific initialization. */
1976 	/* Get the security descriptors inode. */
1977 	vol->secure_ino = ntfs_iget(sb, FILE_Secure);
1978 	if (IS_ERR(vol->secure_ino)) {
1979 		if (!IS_ERR(vol->secure_ino))
1980 			iput(vol->secure_ino);
1981 		ntfs_error(sb, "Failed to load $Secure.");
1982 		goto iput_root_err_out;
1983 	}
1984 	/* Get the extended system files' directory inode. */
1985 	vol->extend_ino = ntfs_iget(sb, FILE_Extend);
1986 	if (IS_ERR(vol->extend_ino) ||
1987 	    !S_ISDIR(vol->extend_ino->i_mode)) {
1988 		if (!IS_ERR(vol->extend_ino))
1989 			iput(vol->extend_ino);
1990 		ntfs_error(sb, "Failed to load $Extend.");
1991 		goto iput_sec_err_out;
1992 	}
1993 	return 0;
1994 
1995 iput_sec_err_out:
1996 	iput(vol->secure_ino);
1997 iput_root_err_out:
1998 	iput(vol->root_ino);
1999 iput_logfile_err_out:
2000 	if (vol->logfile_ino)
2001 		iput(vol->logfile_ino);
2002 	iput(vol->vol_ino);
2003 	/* Do not leave a stale pointer behind for the rest of the teardown. */
2004 	vol->vol_ino = NULL;
2005 iput_lcnbmp_err_out:
2006 	iput(vol->lcnbmp_ino);
2007 iput_attrdef_err_out:
2008 	vol->attrdef_size = 0;
2009 	if (vol->attrdef) {
2010 		kvfree(vol->attrdef);
2011 		vol->attrdef = NULL;
2012 	}
2013 iput_upcase_err_out:
2014 	vol->upcase_len = 0;
2015 	mutex_lock(&ntfs_lock);
2016 	if (vol->upcase && vol->upcase == default_upcase) {
2017 		ntfs_nr_upcase_users--;
2018 		vol->upcase = NULL;
2019 	}
2020 	mutex_unlock(&ntfs_lock);
2021 	if (vol->upcase) {
2022 		kvfree(vol->upcase);
2023 		vol->upcase = NULL;
2024 	}
2025 iput_mftbmp_err_out:
2026 	iput(vol->mftbmp_ino);
2027 iput_mirr_err_out:
2028 	iput(vol->mftmirr_ino);
2029 	return ret;
2030 }
2031 
2032 static void ntfs_volume_free(struct ntfs_volume *vol)
2033 {
2034 	/* Throw away the table of attribute definitions. */
2035 	vol->attrdef_size = 0;
2036 	if (vol->attrdef) {
2037 		kvfree(vol->attrdef);
2038 		vol->attrdef = NULL;
2039 	}
2040 	vol->upcase_len = 0;
2041 	/*
2042 	 * Destroy the global default upcase table if necessary.  Also decrease
2043 	 * the number of upcase users if we are a user.
2044 	 */
2045 	mutex_lock(&ntfs_lock);
2046 	if (vol->upcase && vol->upcase == default_upcase) {
2047 		ntfs_nr_upcase_users--;
2048 		vol->upcase = NULL;
2049 	}
2050 
2051 	if (!ntfs_nr_upcase_users) {
2052 		kvfree(default_upcase);
2053 		default_upcase = NULL;
2054 	}
2055 
2056 	free_compression_buffers();
2057 
2058 	mutex_unlock(&ntfs_lock);
2059 	if (vol->upcase) {
2060 		kvfree(vol->upcase);
2061 		vol->upcase = NULL;
2062 	}
2063 
2064 	unload_nls(vol->nls_map);
2065 
2066 	kvfree(vol->lcn_empty_bits_per_page);
2067 	kfree(vol->volume_label);
2068 	kfree(vol);
2069 }
2070 
2071 /*
2072  * ntfs_put_super - called by the vfs to unmount a volume
2073  * @sb:		vfs superblock of volume to unmount
2074  */
2075 static void ntfs_put_super(struct super_block *sb)
2076 {
2077 	struct ntfs_volume *vol = NTFS_SB(sb);
2078 
2079 	pr_info("Entering %s, dev %s\n", __func__, sb->s_id);
2080 
2081 	cancel_work_sync(&vol->precalc_work);
2082 
2083 	/*
2084 	 * Commit all inodes while they are still open in case some of them
2085 	 * cause others to be dirtied.
2086 	 */
2087 	ntfs_commit_inode(vol->vol_ino);
2088 
2089 	/* NTFS 3.0+ specific. */
2090 	if (vol->major_ver >= 3) {
2091 		if (vol->extend_ino)
2092 			ntfs_commit_inode(vol->extend_ino);
2093 		if (vol->secure_ino)
2094 			ntfs_commit_inode(vol->secure_ino);
2095 	}
2096 
2097 	ntfs_commit_inode(vol->root_ino);
2098 
2099 	ntfs_commit_inode(vol->lcnbmp_ino);
2100 
2101 	/*
2102 	 * the GFP_NOFS scope is not needed because ntfs_commit_inode
2103 	 * does nothing
2104 	 */
2105 	ntfs_commit_inode(vol->mftbmp_ino);
2106 
2107 	if (vol->logfile_ino)
2108 		ntfs_commit_inode(vol->logfile_ino);
2109 
2110 	if (vol->mftmirr_ino)
2111 		ntfs_commit_inode(vol->mftmirr_ino);
2112 	ntfs_commit_inode(vol->mft_ino);
2113 
2114 	/*
2115 	 * If a read-write mount, re-commit all affected inodes once more.
2116 	 * The dirty state itself is persisted at the end of ntfs_put_super(),
2117 	 * after the last commits and the final write_inode_now(): those can
2118 	 * still record errors via __ntfs_write_inode(), and the sync must
2119 	 * evaluate NVolErrors() with the last setter already run.
2120 	 */
2121 	if (!sb_rdonly(sb)) {
2122 		if (!NVolErrors(vol)) {
2123 			ntfs_commit_inode(vol->root_ino);
2124 			if (vol->mftmirr_ino)
2125 				ntfs_commit_inode(vol->mftmirr_ino);
2126 			ntfs_commit_inode(vol->mft_ino);
2127 		}
2128 	}
2129 
2130 	/* NTFS 3.0+ specific clean up. */
2131 	if (vol->major_ver >= 3) {
2132 		if (vol->extend_ino) {
2133 			iput(vol->extend_ino);
2134 			vol->extend_ino = NULL;
2135 		}
2136 		if (vol->secure_ino) {
2137 			iput(vol->secure_ino);
2138 			vol->secure_ino = NULL;
2139 		}
2140 	}
2141 
2142 	iput(vol->root_ino);
2143 	vol->root_ino = NULL;
2144 
2145 	iput(vol->lcnbmp_ino);
2146 	vol->lcnbmp_ino = NULL;
2147 
2148 	iput(vol->mftbmp_ino);
2149 	vol->mftbmp_ino = NULL;
2150 
2151 	if (vol->logfile_ino) {
2152 		iput(vol->logfile_ino);
2153 		vol->logfile_ino = NULL;
2154 	}
2155 	if (vol->mftmirr_ino) {
2156 		/* Re-commit the mft mirror and mft just in case. */
2157 		ntfs_commit_inode(vol->mftmirr_ino);
2158 		ntfs_commit_inode(vol->mft_ino);
2159 	}
2160 	/*
2161 	 * We should have no dirty inodes left, due to
2162 	 * mft.c::ntfs_mft_writepage() cleaning all the dirty pages as
2163 	 * the underlying mft records are written out and cleaned.
2164 	 */
2165 	ntfs_commit_inode(vol->mft_ino);
2166 	write_inode_now(vol->mft_ino, 1);
2167 
2168 	/*
2169 	 * If a read-write mount, persist the error state in the volume flags:
2170 	 * mark the volume clean if no volume errors have occurred, and make
2171 	 * sure VOLUME_IS_DIRTY is on disk if any have, so chkdsk runs on the
2172 	 * next mount.
2173 	 */
2174 	if (!sb_rdonly(sb)) {
2175 		if (ntfs_sync_volume_dirty_state(vol)) {
2176 			ntfs_warning(sb,
2177 				"Failed to sync dirty bit in volume information flags.  Run chkdsk.");
2178 		} else {
2179 			/*
2180 			 * __ntfs_write_inode(), not the void
2181 			 * ntfs_commit_inode() wrapper: the error can only
2182 			 * be warned about here.  The mirror inode is only
2183 			 * released below: writing the $Volume record (mft
2184 			 * record number 3, below vol->mftmirr_size) mirrors
2185 			 * it through ntfs_sync_mft_mirror(), which fails
2186 			 * with -EIO once vol->mftmirr_ino is gone.
2187 			 */
2188 			if (__ntfs_write_inode(vol->vol_ino, 1)) {
2189 				ntfs_warning(sb,
2190 					"Failed to commit volume information flags.  Run chkdsk.");
2191 			} else if (NInoDirty(NTFS_I(vol->vol_ino))) {
2192 				ntfs_warning(sb,
2193 					"Volume information flags remain dirty after commit.  Run chkdsk.");
2194 			} else if (NVolErrors(vol)) {
2195 				/*
2196 				 * Only warn once the commit has succeeded,
2197 				 * or this could contradict a failure
2198 				 * reported above.
2199 				 */
2200 				ntfs_warning(sb,
2201 					"Volume has errors.  Leaving volume marked dirty.  Run chkdsk.");
2202 			}
2203 		}
2204 	}
2205 
2206 	/*
2207 	 * Release $Volume while the mft inode is still available: if the
2208 	 * commit above failed before it could clear the dirty flag,
2209 	 * ntfs_evict_big_inode() commits the inode again on its way out,
2210 	 * and __ntfs_write_inode() needs vol->mft_ino to look up the
2211 	 * runlist of the record to write.
2212 	 */
2213 	iput(vol->vol_ino);
2214 	vol->vol_ino = NULL;
2215 
2216 	if (vol->mftmirr_ino) {
2217 		iput(vol->mftmirr_ino);
2218 		vol->mftmirr_ino = NULL;
2219 	}
2220 
2221 	iput(vol->mft_ino);
2222 	vol->mft_ino = NULL;
2223 	blkdev_issue_flush(sb->s_bdev);
2224 
2225 	ntfs_volume_free(vol);
2226 }
2227 
2228 int ntfs_force_shutdown(struct super_block *sb, u32 flags)
2229 {
2230 	struct ntfs_volume *vol = NTFS_SB(sb);
2231 	int ret;
2232 
2233 	if (NVolShutdown(vol))
2234 		return 0;
2235 
2236 	switch (flags) {
2237 	case FS_SHUTDOWN_FLAGS_DEFAULT:
2238 	case FS_SHUTDOWN_FLAGS_LOGFLUSH:
2239 		ret = bdev_freeze(sb->s_bdev);
2240 		if (ret)
2241 			return ret;
2242 		bdev_thaw(sb->s_bdev);
2243 		NVolSetShutdown(vol);
2244 		break;
2245 	case FS_SHUTDOWN_FLAGS_NOLOGFLUSH:
2246 		NVolSetShutdown(vol);
2247 		break;
2248 	default:
2249 		return -EINVAL;
2250 	}
2251 
2252 	return 0;
2253 }
2254 
2255 static void ntfs_shutdown(struct super_block *sb)
2256 {
2257 	ntfs_force_shutdown(sb, FS_SHUTDOWN_FLAGS_NOLOGFLUSH);
2258 
2259 }
2260 
2261 static int ntfs_sync_fs(struct super_block *sb, int wait)
2262 {
2263 	struct ntfs_volume *vol = NTFS_SB(sb);
2264 	int ret, err = 0;
2265 
2266 	if (NVolShutdown(vol))
2267 		return -EIO;
2268 
2269 	if (!wait)
2270 		return 0;
2271 
2272 	/*
2273 	 * The volume dirty bit is deliberately not cleared here: a sync
2274 	 * running concurrently with an in-flight modification could clear
2275 	 * and persist a bit that was just set, leaving the modification
2276 	 * on a volume that is clean on disk.  The bit is only cleared at
2277 	 * the quiescent state transitions, remounting read-only and clean
2278 	 * unmount.  A recorded error state, however, is persisted right
2279 	 * away so that it is not lost to a crash on a volume that has
2280 	 * seen no modification; with NVolErrors() set this can only set
2281 	 * the bit, never clear it.
2282 	 */
2283 	if (NVolErrors(vol) &&
2284 	    ntfs_sync_volume_dirty_state(vol)) {
2285 		ntfs_warning(sb, "Failed to sync dirty bit in volume information flags.  Run chkdsk.");
2286 		err = -EIO;
2287 	}
2288 	sync_inodes_sb(sb);
2289 	ret = sync_blockdev(sb->s_bdev);
2290 	if (ret && !err)
2291 		err = ret;
2292 
2293 	ret = blkdev_issue_flush(sb->s_bdev);
2294 	if (ret && !err)
2295 		err = ret;
2296 	return err;
2297 }
2298 
2299 /*
2300  * get_nr_free_clusters - return the number of free clusters on a volume
2301  * @vol:	ntfs volume for which to obtain free cluster count
2302  *
2303  * Calculate the number of free clusters on the mounted NTFS volume @vol. We
2304  * actually calculate the number of clusters in use instead because this
2305  * allows us to not care about partial pages as these will be just zero filled
2306  * and hence not be counted as allocated clusters.
2307  *
2308  * The only particularity is that clusters beyond the end of the logical ntfs
2309  * volume will be marked as allocated to prevent errors which means we have to
2310  * discount those at the end. This is important as the cluster bitmap always
2311  * has a size in multiples of 8 bytes, i.e. up to 63 clusters could be outside
2312  * the logical volume and marked in use when they are not as they do not exist.
2313  *
2314  * If any pages cannot be read we assume all clusters in the erroring pages are
2315  * in use. This means we return an underestimate on errors which is better than
2316  * an overestimate.
2317  */
2318 s64 get_nr_free_clusters(struct ntfs_volume *vol)
2319 {
2320 	s64 nr_free = vol->nr_clusters;
2321 	u32 nr_used;
2322 	struct address_space *mapping = vol->lcnbmp_ino->i_mapping;
2323 	struct folio *folio;
2324 	pgoff_t index, max_index;
2325 	struct file_ra_state ra = { 0 };
2326 
2327 	ntfs_debug("Entering.");
2328 	/* Serialize accesses to the cluster bitmap. */
2329 
2330 	if (NVolFreeClusterKnown(vol))
2331 		return atomic64_read(&vol->free_clusters);
2332 
2333 	file_ra_state_init(&ra, mapping);
2334 
2335 	/*
2336 	 * Convert the number of bits into bytes rounded up, then convert into
2337 	 * multiples of PAGE_SIZE, rounding up so that if we have one
2338 	 * full and one partial page max_index = 2.
2339 	 */
2340 	max_index = (((vol->nr_clusters + 7) >> 3) + PAGE_SIZE - 1) >>
2341 			PAGE_SHIFT;
2342 	/* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2343 	ntfs_debug("Reading $Bitmap, max_index = 0x%lx, max_size = 0x%lx.",
2344 			max_index, PAGE_SIZE / 4);
2345 	for (index = 0; index < max_index; index++) {
2346 		unsigned long *kaddr;
2347 
2348 		/*
2349 		 * Get folio from page cache, getting it from backing store
2350 		 * if necessary, and increment the use count.
2351 		 */
2352 		folio = ntfs_get_locked_folio(mapping, index, max_index, &ra);
2353 
2354 		/* Ignore pages which errored synchronously. */
2355 		if (IS_ERR(folio)) {
2356 			ntfs_debug("Skipping page (index 0x%lx).", index);
2357 			nr_free -= PAGE_SIZE * 8;
2358 			vol->lcn_empty_bits_per_page[index] = 0;
2359 			continue;
2360 		}
2361 
2362 		kaddr = kmap_local_folio(folio, 0);
2363 		/*
2364 		 * Subtract the number of set bits. If this
2365 		 * is the last page and it is partial we don't really care as
2366 		 * it just means we do a little extra work but it won't affect
2367 		 * the result as all out of range bytes are set to zero by
2368 		 * ntfs_readpage().
2369 		 */
2370 		nr_used = bitmap_weight(kaddr, PAGE_SIZE * BITS_PER_BYTE);
2371 		nr_free -= nr_used;
2372 		vol->lcn_empty_bits_per_page[index] = PAGE_SIZE * BITS_PER_BYTE - nr_used;
2373 		kunmap_local(kaddr);
2374 		folio_unlock(folio);
2375 		folio_put(folio);
2376 	}
2377 	ntfs_debug("Finished reading $Bitmap, last index = 0x%lx.", index - 1);
2378 	/*
2379 	 * Fixup for eventual bits outside logical ntfs volume (see function
2380 	 * description above).
2381 	 */
2382 	if (vol->nr_clusters & 63)
2383 		nr_free += 64 - (vol->nr_clusters & 63);
2384 
2385 	/* If errors occurred we may well have gone below zero, fix this. */
2386 	if (nr_free < 0)
2387 		nr_free = 0;
2388 	else
2389 		atomic64_set(&vol->free_clusters, nr_free);
2390 
2391 	NVolSetFreeClusterKnown(vol);
2392 	wake_up_all(&vol->free_waitq);
2393 	ntfs_debug("Exiting.");
2394 	return nr_free;
2395 }
2396 
2397 /*
2398  * @nr_clusters is the number of clusters requested for allocation.
2399  *
2400  * Return the number of clusters available for allocation within
2401  * the range of @nr_clusters, which is counts that considered
2402  * for delayed allocation.
2403  */
2404 s64 ntfs_available_clusters_count(struct ntfs_volume *vol, s64 nr_clusters)
2405 {
2406 	s64 free_clusters;
2407 
2408 	/* wait event */
2409 	if (!NVolFreeClusterKnown(vol))
2410 		wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
2411 
2412 	free_clusters = atomic64_read(&vol->free_clusters) -
2413 		atomic64_read(&vol->dirty_clusters);
2414 	if (free_clusters <= 0)
2415 		return -ENOSPC;
2416 	else if (free_clusters < nr_clusters)
2417 		nr_clusters = free_clusters;
2418 
2419 	return nr_clusters;
2420 }
2421 
2422 /*
2423  * __get_nr_free_mft_records - return the number of free inodes on a volume
2424  * @vol:	ntfs volume for which to obtain free inode count
2425  * @nr_free:	number of mft records in filesystem
2426  * @max_index:	maximum number of pages containing set bits
2427  *
2428  * Calculate the number of free mft records (inodes) on the mounted NTFS
2429  * volume @vol. We actually calculate the number of mft records in use instead
2430  * because this allows us to not care about partial pages as these will be just
2431  * zero filled and hence not be counted as allocated mft record.
2432  *
2433  * If any pages cannot be read we assume all mft records in the erroring pages
2434  * are in use. This means we return an underestimate on errors which is better
2435  * than an overestimate.
2436  *
2437  * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing.
2438  */
2439 static unsigned long __get_nr_free_mft_records(struct ntfs_volume *vol,
2440 		s64 nr_free, const pgoff_t max_index)
2441 {
2442 	struct address_space *mapping = vol->mftbmp_ino->i_mapping;
2443 	struct folio *folio;
2444 	pgoff_t index;
2445 	struct file_ra_state ra = { 0 };
2446 
2447 	ntfs_debug("Entering.");
2448 
2449 	file_ra_state_init(&ra, mapping);
2450 
2451 	/* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */
2452 	ntfs_debug("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = 0x%lx.",
2453 			max_index, PAGE_SIZE / 4);
2454 	for (index = 0; index < max_index; index++) {
2455 		unsigned long *kaddr;
2456 
2457 		/*
2458 		 * Get folio from page cache, getting it from backing store
2459 		 * if necessary, and increment the use count.
2460 		 */
2461 		folio = ntfs_get_locked_folio(mapping, index, max_index, &ra);
2462 
2463 		/* Ignore pages which errored synchronously. */
2464 		if (IS_ERR(folio)) {
2465 			ntfs_debug("read_mapping_page() error. Skipping page (index 0x%lx).",
2466 					index);
2467 			nr_free -= PAGE_SIZE * 8;
2468 			continue;
2469 		}
2470 
2471 		kaddr = kmap_local_folio(folio, 0);
2472 		/*
2473 		 * Subtract the number of set bits. If this
2474 		 * is the last page and it is partial we don't really care as
2475 		 * it just means we do a little extra work but it won't affect
2476 		 * the result as all out of range bytes are set to zero by
2477 		 * ntfs_readpage().
2478 		 */
2479 		nr_free -= bitmap_weight(kaddr,
2480 					PAGE_SIZE * BITS_PER_BYTE);
2481 		kunmap_local(kaddr);
2482 		folio_unlock(folio);
2483 		folio_put(folio);
2484 	}
2485 	ntfs_debug("Finished reading $MFT/$BITMAP, last index = 0x%lx.",
2486 			index - 1);
2487 	/* If errors occurred we may well have gone below zero, fix this. */
2488 	if (nr_free < 0)
2489 		nr_free = 0;
2490 	atomic64_set(&vol->free_mft_records, nr_free);
2491 
2492 	ntfs_debug("Exiting.");
2493 	return nr_free;
2494 }
2495 
2496 /*
2497  * ntfs_statfs - return information about mounted NTFS volume
2498  * @dentry:	dentry from mounted volume
2499  * @sfs:	statfs structure in which to return the information
2500  *
2501  * Return information about the mounted NTFS volume @dentry in the statfs structure
2502  * pointed to by @sfs (this is initialized with zeros before ntfs_statfs is
2503  * called). We interpret the values to be correct of the moment in time at
2504  * which we are called. Most values are variable otherwise and this isn't just
2505  * the free values but the totals as well. For example we can increase the
2506  * total number of file nodes if we run out and we can keep doing this until
2507  * there is no more space on the volume left at all.
2508  *
2509  * Called from vfs_statfs which is used to handle the statfs, fstatfs, and
2510  * ustat system calls.
2511  *
2512  * Return 0 on success or -errno on error.
2513  */
2514 static int ntfs_statfs(struct dentry *dentry, struct kstatfs *sfs)
2515 {
2516 	struct super_block *sb = dentry->d_sb;
2517 	s64 size;
2518 	struct ntfs_volume *vol = NTFS_SB(sb);
2519 	struct ntfs_inode *mft_ni = NTFS_I(vol->mft_ino);
2520 	unsigned long flags;
2521 
2522 	ntfs_debug("Entering.");
2523 	/* Type of filesystem. */
2524 	sfs->f_type   = NTFS_SB_MAGIC;
2525 	/* Optimal transfer block size. */
2526 	sfs->f_bsize = vol->cluster_size;
2527 	/* Fundamental file system block size, used as the unit. */
2528 	sfs->f_frsize = vol->cluster_size;
2529 
2530 	/*
2531 	 * Total data blocks in filesystem in units of f_bsize and since
2532 	 * inodes are also stored in data blocs ($MFT is a file) this is just
2533 	 * the total clusters.
2534 	 */
2535 	sfs->f_blocks = vol->nr_clusters;
2536 
2537 	/* wait event */
2538 	if (!NVolFreeClusterKnown(vol))
2539 		wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
2540 
2541 	/* Free data blocks in filesystem in units of f_bsize. */
2542 	size = atomic64_read(&vol->free_clusters) -
2543 		atomic64_read(&vol->dirty_clusters);
2544 	if (size < 0LL)
2545 		size = 0LL;
2546 
2547 	/* Free blocks avail to non-superuser, same as above on NTFS. */
2548 	sfs->f_bavail = sfs->f_bfree = size;
2549 
2550 	/* Number of inodes in filesystem (at this point in time). */
2551 	read_lock_irqsave(&mft_ni->size_lock, flags);
2552 	sfs->f_files = i_size_read(vol->mft_ino) >> vol->mft_record_size_bits;
2553 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
2554 
2555 	/* Free inodes in fs (based on current total count). */
2556 	size = atomic64_read(&vol->free_mft_records);
2557 	if (unlikely(size < 0 || size > (s64)sfs->f_files))
2558 		ntfs_warning(vol->sb, "Invalid free MFT record count %lld.", size);
2559 	if (size < 0)
2560 		size = 0;
2561 	else if (size > (s64)sfs->f_files)
2562 		size = sfs->f_files;
2563 	sfs->f_ffree = size;
2564 
2565 	/*
2566 	 * File system id. This is extremely *nix flavour dependent and even
2567 	 * within Linux itself all fs do their own thing. I interpret this to
2568 	 * mean a unique id associated with the mounted fs and not the id
2569 	 * associated with the filesystem driver, the latter is already given
2570 	 * by the filesystem type in sfs->f_type. Thus we use the 64-bit
2571 	 * volume serial number splitting it into two 32-bit parts. We enter
2572 	 * the least significant 32-bits in f_fsid[0] and the most significant
2573 	 * 32-bits in f_fsid[1].
2574 	 */
2575 	sfs->f_fsid = u64_to_fsid(vol->serial_no);
2576 	/* Maximum length of filenames. */
2577 	sfs->f_namelen	   = NTFS_MAX_NAME_LEN;
2578 
2579 	return 0;
2580 }
2581 
2582 static int ntfs_write_inode(struct inode *vi, struct writeback_control *wbc)
2583 {
2584 	return __ntfs_write_inode(vi, wbc->sync_mode == WB_SYNC_ALL);
2585 }
2586 
2587 /*
2588  * The complete super operations.
2589  */
2590 static const struct super_operations ntfs_sops = {
2591 	.alloc_inode	= ntfs_alloc_big_inode,	  /* VFS: Allocate new inode. */
2592 	.free_inode	= ntfs_free_big_inode, /* VFS: Deallocate inode. */
2593 	.drop_inode	= ntfs_drop_big_inode,
2594 	.write_inode	= ntfs_write_inode,	/* VFS: Write dirty inode to disk. */
2595 	.put_super	= ntfs_put_super,	/* Syscall: umount. */
2596 	.shutdown	= ntfs_shutdown,
2597 	.sync_fs	= ntfs_sync_fs,		/* Syscall: sync. */
2598 	.statfs		= ntfs_statfs,		/* Syscall: statfs */
2599 	.evict_inode	= ntfs_evict_big_inode,
2600 	.show_options	= ntfs_show_options,	/* Show mount options in proc. */
2601 };
2602 
2603 static void precalc_free_clusters(struct work_struct *work)
2604 {
2605 	struct ntfs_volume *vol = container_of(work, struct ntfs_volume, precalc_work);
2606 	s64 nr_free;
2607 
2608 	nr_free = get_nr_free_clusters(vol);
2609 
2610 	ntfs_debug("pre-calculate free clusters(%lld) using workqueue",
2611 			nr_free);
2612 }
2613 
2614 static struct lock_class_key ntfs_mft_inval_lock_key;
2615 
2616 /*
2617  * ntfs_fill_super - mount an ntfs filesystem
2618  * @sb: super block of the device to mount
2619  * @fc: filesystem context containing mount options
2620  *
2621  * ntfs_fill_super() is called by the VFS to mount the device described by @sb
2622  * with the mount otions in @data with the NTFS filesystem.
2623  *
2624  * If @silent is true, remain silent even if errors are detected. This is used
2625  * during bootup, when the kernel tries to mount the root filesystem with all
2626  * registered filesystems one after the other until one succeeds. This implies
2627  * that all filesystems except the correct one will quite correctly and
2628  * expectedly return an error, but nobody wants to see error messages when in
2629  * fact this is what is supposed to happen.
2630  */
2631 static int ntfs_fill_super(struct super_block *sb, struct fs_context *fc)
2632 {
2633 	char *boot;
2634 	struct inode *tmp_ino;
2635 	int blocksize, result, err = -EINVAL;
2636 	pgoff_t lcn_bit_pages;
2637 	struct ntfs_volume *vol = NTFS_SB(sb);
2638 	int silent = fc->sb_flags & SB_SILENT;
2639 
2640 	vol->sb = sb;
2641 
2642 	/*
2643 	 * We do a pretty difficult piece of bootstrap by reading the
2644 	 * MFT (and other metadata) from disk into memory. We'll only
2645 	 * release this metadata during umount, so the locking patterns
2646 	 * observed during bootstrap do not count. So turn off the
2647 	 * observation of locking patterns (strictly for this context
2648 	 * only) while mounting NTFS. [The validator is still active
2649 	 * otherwise, even for this context: it will for example record
2650 	 * lock class registrations.]
2651 	 */
2652 	lockdep_off();
2653 	ntfs_debug("Entering.");
2654 
2655 	if (vol->nls_map && !strcmp(vol->nls_map->charset, "utf8"))
2656 		vol->nls_utf8 = true;
2657 	if (NVolDisableSparse(vol))
2658 		vol->preallocated_size = 0;
2659 
2660 	if (NVolDiscard(vol) && !bdev_max_discard_sectors(sb->s_bdev)) {
2661 		ntfs_warning(
2662 			sb,
2663 			"Discard requested but device does not support discard.  Discard disabled.");
2664 		NVolClearDiscard(vol);
2665 	}
2666 
2667 	/* We support sector sizes up to the PAGE_SIZE. */
2668 	if (bdev_logical_block_size(sb->s_bdev) > PAGE_SIZE) {
2669 		if (!silent)
2670 			ntfs_error(sb,
2671 				"Device has unsupported sector size (%i).  The maximum supported sector size on this architecture is %lu bytes.",
2672 				bdev_logical_block_size(sb->s_bdev),
2673 				PAGE_SIZE);
2674 		goto err_out_now;
2675 	}
2676 
2677 	/*
2678 	 * Setup the device access block size to NTFS_BLOCK_SIZE or the hard
2679 	 * sector size, whichever is bigger.
2680 	 */
2681 	blocksize = sb_min_blocksize(sb, NTFS_BLOCK_SIZE);
2682 	if (blocksize < NTFS_BLOCK_SIZE) {
2683 		if (!silent)
2684 			ntfs_error(sb, "Unable to set device block size.");
2685 		goto err_out_now;
2686 	}
2687 
2688 	ntfs_debug("Set device block size to %i bytes (block size bits %i).",
2689 			blocksize, sb->s_blocksize_bits);
2690 	/* Determine the size of the device in units of block_size bytes. */
2691 	if (!bdev_nr_bytes(sb->s_bdev)) {
2692 		if (!silent)
2693 			ntfs_error(sb, "Unable to determine device size.");
2694 		goto err_out_now;
2695 	}
2696 	vol->nr_blocks = bdev_nr_bytes(sb->s_bdev) >>
2697 			sb->s_blocksize_bits;
2698 	/* Read the boot sector and return unlocked buffer head to it. */
2699 	boot = read_ntfs_boot_sector(sb, silent);
2700 	if (!boot) {
2701 		if (!silent)
2702 			ntfs_error(sb, "Not an NTFS volume.");
2703 		goto err_out_now;
2704 	}
2705 	/*
2706 	 * Extract the data from the boot sector and setup the ntfs volume
2707 	 * using it.
2708 	 */
2709 	result = parse_ntfs_boot_sector(vol, (struct ntfs_boot_sector *)boot);
2710 	kfree(boot);
2711 	if (!result) {
2712 		if (!silent)
2713 			ntfs_error(sb, "Unsupported NTFS filesystem.");
2714 		goto err_out_now;
2715 	}
2716 	if (!vol->mft_write_supported && !sb_rdonly(sb)) {
2717 		sb->s_flags |= SB_RDONLY;
2718 		ntfs_warning(sb,
2719 			     "MFT writeback is unsupported for this geometry. Mounting read-only.");
2720 	}
2721 
2722 	if (vol->sector_size > blocksize) {
2723 		blocksize = sb_set_blocksize(sb, vol->sector_size);
2724 		if (blocksize != vol->sector_size) {
2725 			if (!silent)
2726 				ntfs_error(sb,
2727 					   "Unable to set device block size to sector size (%i).",
2728 					   vol->sector_size);
2729 			goto err_out_now;
2730 		}
2731 		vol->nr_blocks = bdev_nr_bytes(sb->s_bdev) >>
2732 				sb->s_blocksize_bits;
2733 		ntfs_debug("Changed device block size to %i bytes (block size bits %i) to match volume sector size.",
2734 				blocksize, sb->s_blocksize_bits);
2735 	}
2736 	/* Initialize the cluster and mft allocators. */
2737 	ntfs_setup_allocators(vol);
2738 	/* Setup remaining fields in the super block. */
2739 	sb->s_magic = NTFS_SB_MAGIC;
2740 	/*
2741 	 * Ntfs allows 63 bits for the file size, i.e. correct would be:
2742 	 *	sb->s_maxbytes = ~0ULL >> 1;
2743 	 * But the kernel uses a long as the page cache page index which on
2744 	 * 32-bit architectures is only 32-bits. MAX_LFS_FILESIZE is kernel
2745 	 * defined to the maximum the page cache page index can cope with
2746 	 * without overflowing the index or to 2^63 - 1, whichever is smaller.
2747 	 */
2748 	sb->s_maxbytes = MAX_LFS_FILESIZE;
2749 	/* Ntfs measures time in 100ns intervals. */
2750 	sb->s_time_gran = 100;
2751 
2752 	sb->s_xattr = ntfs_xattr_handlers;
2753 	/*
2754 	 * Now load the metadata required for the page cache and our address
2755 	 * space operations to function. We do this by setting up a specialised
2756 	 * read_inode method and then just calling the normal iget() to obtain
2757 	 * the inode for $MFT which is sufficient to allow our normal inode
2758 	 * operations and associated address space operations to function.
2759 	 */
2760 	sb->s_op = &ntfs_sops;
2761 	if (NVolStreamsWindows(vol))
2762 		ntfs_set_default_dentry_ops(sb);
2763 	tmp_ino = new_inode(sb);
2764 	if (!tmp_ino) {
2765 		if (!silent)
2766 			ntfs_error(sb, "Failed to load essential metadata.");
2767 		goto err_out_now;
2768 	}
2769 
2770 	tmp_ino->i_ino = FILE_MFT;
2771 	insert_inode_hash(tmp_ino);
2772 	if (ntfs_read_inode_mount(tmp_ino) < 0) {
2773 		if (!silent)
2774 			ntfs_error(sb, "Failed to load essential metadata.");
2775 		goto iput_tmp_ino_err_out_now;
2776 	}
2777 	lockdep_set_class(&tmp_ino->i_mapping->invalidate_lock,
2778 			  &ntfs_mft_inval_lock_key);
2779 
2780 	mutex_lock(&ntfs_lock);
2781 
2782 	/*
2783 	 * Generate the global default upcase table if necessary.  Also
2784 	 * temporarily increment the number of upcase users to avoid race
2785 	 * conditions with concurrent (u)mounts.
2786 	 */
2787 	if (!default_upcase)
2788 		default_upcase = generate_default_upcase();
2789 	ntfs_nr_upcase_users++;
2790 	mutex_unlock(&ntfs_lock);
2791 
2792 	lcn_bit_pages = (((vol->nr_clusters + 7) >> 3) + PAGE_SIZE - 1) >> PAGE_SHIFT;
2793 	vol->lcn_empty_bits_per_page = kvmalloc_array(lcn_bit_pages, sizeof(unsigned int),
2794 						      GFP_KERNEL);
2795 	if (!vol->lcn_empty_bits_per_page) {
2796 		ntfs_error(sb,
2797 			   "Unable to allocate pages for storing LCN empty bit counts\n");
2798 		goto unl_upcase_iput_tmp_ino_err_out_now;
2799 	}
2800 
2801 	/*
2802 	 * From now on, ignore @silent parameter. If we fail below this line,
2803 	 * it will be due to a corrupt fs or a system error, so we report it.
2804 	 */
2805 	/*
2806 	 * Open the system files with normal access functions and complete
2807 	 * setting up the ntfs super block.
2808 	 */
2809 	result = load_system_files(vol);
2810 	if (result) {
2811 		err = result;
2812 		ntfs_warning(sb, "Failed to load system files (%d).", err);
2813 		goto unl_upcase_iput_tmp_ino_err_out_now;
2814 	}
2815 
2816 	/* We grab a reference, simulating an ntfs_iget(). */
2817 	ihold(vol->root_ino);
2818 	sb->s_root = d_make_root(vol->root_ino);
2819 	if (sb->s_root) {
2820 		s64 nr_records;
2821 
2822 		ntfs_debug("Exiting, status successful.");
2823 
2824 		/* Release the default upcase if it has no users. */
2825 		mutex_lock(&ntfs_lock);
2826 		if (!--ntfs_nr_upcase_users && default_upcase) {
2827 			kvfree(default_upcase);
2828 			default_upcase = NULL;
2829 		}
2830 		mutex_unlock(&ntfs_lock);
2831 		sb->s_export_op = &ntfs_export_ops;
2832 		lockdep_on();
2833 
2834 		nr_records = __get_nr_free_mft_records(vol,
2835 				i_size_read(vol->mft_ino) >> vol->mft_record_size_bits,
2836 				((((NTFS_I(vol->mft_ino)->initialized_size >>
2837 				    vol->mft_record_size_bits) +
2838 				   7) >> 3) + PAGE_SIZE - 1) >> PAGE_SHIFT);
2839 		ntfs_debug("Free mft records(%lld)", nr_records);
2840 
2841 		init_waitqueue_head(&vol->free_waitq);
2842 		INIT_WORK(&vol->precalc_work, precalc_free_clusters);
2843 		queue_work(ntfs_wq, &vol->precalc_work);
2844 		return 0;
2845 	}
2846 	ntfs_error(sb, "Failed to allocate root directory.");
2847 	/* Clean up after the successful load_system_files() call from above. */
2848 	iput(vol->vol_ino);
2849 	vol->vol_ino = NULL;
2850 	/* NTFS 3.0+ specific clean up. */
2851 	if (vol->major_ver >= 3) {
2852 		if (vol->extend_ino) {
2853 			iput(vol->extend_ino);
2854 			vol->extend_ino = NULL;
2855 		}
2856 		if (vol->secure_ino) {
2857 			iput(vol->secure_ino);
2858 			vol->secure_ino = NULL;
2859 		}
2860 	}
2861 	iput(vol->root_ino);
2862 	vol->root_ino = NULL;
2863 	iput(vol->lcnbmp_ino);
2864 	vol->lcnbmp_ino = NULL;
2865 	iput(vol->mftbmp_ino);
2866 	vol->mftbmp_ino = NULL;
2867 	if (vol->logfile_ino) {
2868 		iput(vol->logfile_ino);
2869 		vol->logfile_ino = NULL;
2870 	}
2871 	if (vol->mftmirr_ino) {
2872 		iput(vol->mftmirr_ino);
2873 		vol->mftmirr_ino = NULL;
2874 	}
2875 	/* Throw away the table of attribute definitions. */
2876 	vol->attrdef_size = 0;
2877 	if (vol->attrdef) {
2878 		kvfree(vol->attrdef);
2879 		vol->attrdef = NULL;
2880 	}
2881 	vol->upcase_len = 0;
2882 	mutex_lock(&ntfs_lock);
2883 	if (vol->upcase && vol->upcase == default_upcase) {
2884 		ntfs_nr_upcase_users--;
2885 		vol->upcase = NULL;
2886 	}
2887 	mutex_unlock(&ntfs_lock);
2888 	if (vol->upcase) {
2889 		kvfree(vol->upcase);
2890 		vol->upcase = NULL;
2891 	}
2892 	if (vol->nls_map) {
2893 		unload_nls(vol->nls_map);
2894 		vol->nls_map = NULL;
2895 	}
2896 	/* Error exit code path. */
2897 unl_upcase_iput_tmp_ino_err_out_now:
2898 	/*
2899 	 * Decrease the number of upcase users and destroy the global default
2900 	 * upcase table if necessary.
2901 	 */
2902 	mutex_lock(&ntfs_lock);
2903 	if (!--ntfs_nr_upcase_users && default_upcase) {
2904 		kvfree(default_upcase);
2905 		default_upcase = NULL;
2906 	}
2907 
2908 	mutex_unlock(&ntfs_lock);
2909 iput_tmp_ino_err_out_now:
2910 	iput(tmp_ino);
2911 	if (vol->mft_ino && vol->mft_ino != tmp_ino)
2912 		iput(vol->mft_ino);
2913 	vol->mft_ino = NULL;
2914 	/* Errors at this stage are irrelevant. */
2915 err_out_now:
2916 	sb->s_fs_info = NULL;
2917 	kvfree(vol->lcn_empty_bits_per_page);
2918 	kfree(vol->volume_label);
2919 	unload_nls(vol->nls_map);
2920 	kfree(vol);
2921 	ntfs_debug("Failed, returning %d.", err);
2922 	lockdep_on();
2923 	return err;
2924 }
2925 
2926 /*
2927  * This is a slab cache to optimize allocations and deallocations of Unicode
2928  * strings of the maximum length allowed by NTFS, which is NTFS_MAX_NAME_LEN
2929  * (255) Unicode characters + a terminating NULL Unicode character.
2930  */
2931 struct kmem_cache *ntfs_name_cache;
2932 
2933 /* Slab caches for efficient allocation/deallocation of inodes. */
2934 struct kmem_cache *ntfs_inode_cache;
2935 struct kmem_cache *ntfs_big_inode_cache;
2936 
2937 /* Init once constructor for the inode slab cache. */
2938 static void ntfs_big_inode_init_once(void *foo)
2939 {
2940 	struct ntfs_inode *ni = foo;
2941 
2942 	inode_init_once(VFS_I(ni));
2943 }
2944 
2945 /*
2946  * Slab caches to optimize allocations and deallocations of attribute search
2947  * contexts and index contexts, respectively.
2948  */
2949 struct kmem_cache *ntfs_attr_ctx_cache;
2950 struct kmem_cache *ntfs_index_ctx_cache;
2951 
2952 /* Driver wide mutex. */
2953 DEFINE_MUTEX(ntfs_lock);
2954 
2955 static int ntfs_get_tree(struct fs_context *fc)
2956 {
2957 	return get_tree_bdev(fc, ntfs_fill_super);
2958 }
2959 
2960 static void ntfs_free_fs_context(struct fs_context *fc)
2961 {
2962 	struct ntfs_volume *vol = fc->s_fs_info;
2963 
2964 	if (vol)
2965 		ntfs_volume_free(vol);
2966 }
2967 
2968 static const struct fs_context_operations ntfs_context_ops = {
2969 	.parse_param	= ntfs_parse_param,
2970 	.get_tree	= ntfs_get_tree,
2971 	.free		= ntfs_free_fs_context,
2972 	.reconfigure	= ntfs_reconfigure,
2973 };
2974 
2975 static int ntfs_init_fs_context(struct fs_context *fc)
2976 {
2977 	struct ntfs_volume *vol;
2978 
2979 	/* Allocate a new struct ntfs_volume and place it in sb->s_fs_info. */
2980 	vol = kmalloc_obj(struct ntfs_volume, GFP_NOFS);
2981 	if (!vol)
2982 		return -ENOMEM;
2983 
2984 	/* Initialize struct ntfs_volume structure. */
2985 	*vol = (struct ntfs_volume) {
2986 		.uid = INVALID_UID,
2987 		.gid = INVALID_GID,
2988 		.fmask = 0,
2989 		.dmask = 0,
2990 		.mft_zone_multiplier = 1,
2991 		.on_errors = ON_ERRORS_CONTINUE,
2992 		.nls_map = load_nls_default(),
2993 		.preallocated_size = NTFS_DEF_PREALLOC_SIZE,
2994 	};
2995 
2996 	NVolSetShowHiddenFiles(vol);
2997 	NVolSetCaseSensitive(vol);
2998 	init_rwsem(&vol->mftbmp_lock);
2999 	init_rwsem(&vol->lcnbmp_lock);
3000 	mutex_init(&vol->volume_label_lock);
3001 
3002 	fc->s_fs_info = vol;
3003 	fc->ops = &ntfs_context_ops;
3004 	return 0;
3005 }
3006 
3007 static struct file_system_type ntfs_fs_type = {
3008 	.owner                  = THIS_MODULE,
3009 	.name                   = "ntfs",
3010 	.init_fs_context        = ntfs_init_fs_context,
3011 	.parameters             = ntfs_parameters,
3012 	.kill_sb                = kill_block_super,
3013 	.fs_flags               = FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
3014 };
3015 MODULE_ALIAS_FS("ntfs");
3016 
3017 static int ntfs_workqueue_init(void)
3018 {
3019 	ntfs_wq = alloc_workqueue("ntfs-bg-io", WQ_PERCPU, 0);
3020 	if (!ntfs_wq)
3021 		return -ENOMEM;
3022 	return 0;
3023 }
3024 
3025 static void ntfs_workqueue_destroy(void)
3026 {
3027 	destroy_workqueue(ntfs_wq);
3028 	ntfs_wq = NULL;
3029 }
3030 
3031 /* Stable names for the slab caches. */
3032 static const char ntfs_index_ctx_cache_name[] = "ntfs_index_ctx_cache";
3033 static const char ntfs_attr_ctx_cache_name[] = "ntfs_attr_ctx_cache";
3034 static const char ntfs_name_cache_name[] = "ntfs_name_cache";
3035 static const char ntfs_inode_cache_name[] = "ntfs_inode_cache";
3036 static const char ntfs_big_inode_cache_name[] = "ntfs_big_inode_cache";
3037 
3038 static int __init init_ntfs_fs(void)
3039 {
3040 	int err = 0;
3041 
3042 	err = ntfs_workqueue_init();
3043 	if (err) {
3044 		pr_crit("Failed to register workqueue!\n");
3045 		return err;
3046 	}
3047 
3048 	err = ntfs_mft_bioset_init();
3049 	if (err) {
3050 		pr_crit("Failed to initialize NTFS MFT bioset!\n");
3051 		ntfs_workqueue_destroy();
3052 		return err;
3053 	}
3054 
3055 	ntfs_index_ctx_cache = kmem_cache_create(ntfs_index_ctx_cache_name,
3056 			sizeof(struct ntfs_index_context), 0 /* offset */,
3057 			SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3058 	if (!ntfs_index_ctx_cache) {
3059 		pr_crit("Failed to create %s!\n", ntfs_index_ctx_cache_name);
3060 		goto ictx_err_out;
3061 	}
3062 	ntfs_attr_ctx_cache = kmem_cache_create(ntfs_attr_ctx_cache_name,
3063 			sizeof(struct ntfs_attr_search_ctx), 0 /* offset */,
3064 			SLAB_HWCACHE_ALIGN, NULL /* ctor */);
3065 	if (!ntfs_attr_ctx_cache) {
3066 		pr_crit("NTFS: Failed to create %s!\n",
3067 			ntfs_attr_ctx_cache_name);
3068 		goto actx_err_out;
3069 	}
3070 
3071 	ntfs_name_cache = kmem_cache_create(ntfs_name_cache_name,
3072 			(NTFS_MAX_NAME_LEN+2) * sizeof(__le16), 0,
3073 			SLAB_HWCACHE_ALIGN, NULL);
3074 	if (!ntfs_name_cache) {
3075 		pr_crit("Failed to create %s!\n", ntfs_name_cache_name);
3076 		goto name_err_out;
3077 	}
3078 
3079 	ntfs_inode_cache = kmem_cache_create(ntfs_inode_cache_name,
3080 			sizeof(struct ntfs_inode), 0, SLAB_RECLAIM_ACCOUNT, NULL);
3081 	if (!ntfs_inode_cache) {
3082 		pr_crit("Failed to create %s!\n", ntfs_inode_cache_name);
3083 		goto inode_err_out;
3084 	}
3085 
3086 	ntfs_big_inode_cache = kmem_cache_create(ntfs_big_inode_cache_name,
3087 			sizeof(struct big_ntfs_inode), 0, SLAB_HWCACHE_ALIGN |
3088 			SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
3089 			ntfs_big_inode_init_once);
3090 	if (!ntfs_big_inode_cache) {
3091 		pr_crit("Failed to create %s!\n", ntfs_big_inode_cache_name);
3092 		goto big_inode_err_out;
3093 	}
3094 
3095 	/* Register the ntfs sysctls. */
3096 	err = ntfs_sysctl(1);
3097 	if (err) {
3098 		pr_crit("Failed to register NTFS sysctls!\n");
3099 		goto sysctl_err_out;
3100 	}
3101 
3102 	err = register_filesystem(&ntfs_fs_type);
3103 	if (!err) {
3104 		ntfs_debug("NTFS driver registered successfully.");
3105 		return 0; /* Success! */
3106 	}
3107 	pr_crit("Failed to register NTFS filesystem driver!\n");
3108 
3109 	/* Unregister the ntfs sysctls. */
3110 	ntfs_sysctl(0);
3111 sysctl_err_out:
3112 	kmem_cache_destroy(ntfs_big_inode_cache);
3113 big_inode_err_out:
3114 	kmem_cache_destroy(ntfs_inode_cache);
3115 inode_err_out:
3116 	kmem_cache_destroy(ntfs_name_cache);
3117 name_err_out:
3118 	kmem_cache_destroy(ntfs_attr_ctx_cache);
3119 actx_err_out:
3120 	kmem_cache_destroy(ntfs_index_ctx_cache);
3121 ictx_err_out:
3122 	ntfs_mft_bioset_exit();
3123 	if (!err) {
3124 		pr_crit("Aborting NTFS filesystem driver registration...\n");
3125 		err = -ENOMEM;
3126 	}
3127 	return err;
3128 }
3129 
3130 static void __exit exit_ntfs_fs(void)
3131 {
3132 	ntfs_debug("Unregistering NTFS driver.");
3133 
3134 	unregister_filesystem(&ntfs_fs_type);
3135 
3136 	/*
3137 	 * Make sure all delayed rcu free inodes are flushed before we
3138 	 * destroy cache.
3139 	 */
3140 	rcu_barrier();
3141 	ntfs_mft_bioset_exit();
3142 #ifdef CONFIG_NTFS_FS_WOF_COMPRESSION
3143 	ntfs_wof_free_workspaces();
3144 #endif
3145 	kmem_cache_destroy(ntfs_big_inode_cache);
3146 	kmem_cache_destroy(ntfs_inode_cache);
3147 	kmem_cache_destroy(ntfs_name_cache);
3148 	kmem_cache_destroy(ntfs_attr_ctx_cache);
3149 	kmem_cache_destroy(ntfs_index_ctx_cache);
3150 	ntfs_workqueue_destroy();
3151 	/* Unregister the ntfs sysctls. */
3152 	ntfs_sysctl(0);
3153 }
3154 
3155 module_init(init_ntfs_fs);
3156 module_exit(exit_ntfs_fs);
3157 
3158 MODULE_AUTHOR("Anton Altaparmakov <anton@tuxera.com>"); /* Original read-only NTFS driver */
3159 MODULE_AUTHOR("Namjae Jeon <linkinjeon@kernel.org>"); /* Add write, iomap and various features */
3160 MODULE_DESCRIPTION("NTFS read-write filesystem driver");
3161 MODULE_LICENSE("GPL");
3162 #ifdef DEBUG
3163 module_param(debug_msgs, uint, 0);
3164 MODULE_PARM_DESC(debug_msgs, "Enable debug messages.");
3165 #endif
3166