xref: /linux/fs/ntfs/mft.c (revision 69ba74e8a5dfc6fd7ba3588e81d53e965566f3a4)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NTFS kernel mft record operations.
4  * Part of this file is based on code from the NTFS-3G.
5  *
6  * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
7  * Copyright (c) 2002 Richard Russon
8  * Copyright (c) 2025 LG Electronics Co., Ltd.
9  */
10 
11 #include <linux/writeback.h>
12 #include <linux/bio.h>
13 #include <linux/blkdev.h>
14 #include <linux/completion.h>
15 #include <linux/iomap.h>
16 #include <linux/math64.h>
17 
18 #include "bitmap.h"
19 #include "lcnalloc.h"
20 #include "mft.h"
21 #include "ntfs.h"
22 
23 /*
24  * ntfs_mft_record_check - Check the consistency of an MFT record
25  *
26  * Make sure its general fields are safe, then examine all its
27  * attributes and apply generic checks to them.
28  *
29  * Returns 0 if the checks are successful. If not, return -EIO.
30  */
31 int ntfs_mft_record_check(const struct ntfs_volume *vol, struct mft_record *m,
32 		u64 mft_no)
33 {
34 	struct attr_record *a;
35 	struct super_block *sb = vol->sb;
36 	u16 attrs_offset;
37 	u32 bytes_in_use;
38 
39 	if (!ntfs_is_file_record(m->magic)) {
40 		ntfs_error(sb, "Record %llu has no FILE magic (0x%x)\n",
41 				mft_no, le32_to_cpu(*(__le32 *)m));
42 		goto err_out;
43 	}
44 
45 	if (le16_to_cpu(m->usa_ofs) & 0x1 ||
46 	    (vol->mft_record_size >> NTFS_BLOCK_SIZE_BITS) + 1 != le16_to_cpu(m->usa_count) ||
47 	    le16_to_cpu(m->usa_ofs) + le16_to_cpu(m->usa_count) * 2 > vol->mft_record_size) {
48 		ntfs_error(sb, "Record %llu has corrupt fix-up values fields\n",
49 				mft_no);
50 		goto err_out;
51 	}
52 
53 	if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) {
54 		ntfs_error(sb, "Record %llu has corrupt allocation size (%u <> %u)\n",
55 				mft_no, vol->mft_record_size,
56 				le32_to_cpu(m->bytes_allocated));
57 		goto err_out;
58 	}
59 
60 	if (le32_to_cpu(m->bytes_in_use) > vol->mft_record_size) {
61 		ntfs_error(sb, "Record %llu has corrupt in-use size (%u > %u)\n",
62 				mft_no, le32_to_cpu(m->bytes_in_use),
63 				vol->mft_record_size);
64 		goto err_out;
65 	}
66 
67 	if (le16_to_cpu(m->attrs_offset) & 7) {
68 		ntfs_error(sb, "Attributes badly aligned in record %llu\n",
69 				mft_no);
70 		goto err_out;
71 	}
72 
73 	attrs_offset = le16_to_cpu(m->attrs_offset);
74 	bytes_in_use = le32_to_cpu(m->bytes_in_use);
75 
76 	if (attrs_offset > bytes_in_use ||
77 	    bytes_in_use - attrs_offset < sizeof_field(struct attr_record, type)) {
78 		ntfs_error(sb, "Record %llu has corrupt attribute offset\n", mft_no);
79 		goto err_out;
80 	}
81 
82 	a = (struct attr_record *)((char *)m + attrs_offset);
83 	if ((char *)a < (char *)m || (char *)a > (char *)m + vol->mft_record_size) {
84 		ntfs_error(sb, "Record %llu is corrupt\n", mft_no);
85 		goto err_out;
86 	}
87 
88 	return 0;
89 
90 err_out:
91 	return -EIO;
92 }
93 
94 /*
95  * map_mft_record_folio - map the folio in which a specific mft record resides
96  * @ni:		ntfs inode whose mft record page to map
97  *
98  * This maps the folio in which the mft record of the ntfs inode @ni is
99  * situated.
100  *
101  * This allocates a new buffer (@ni->mrec), copies the MFT record data from
102  * the mapped folio into this buffer, and applies the MST (Multi Sector
103  * Transfer) fixups on the copy.
104  *
105  * The folio is pinned (referenced) in @ni->folio to ensure the data remains
106  * valid in the page cache, but the returned pointer is the allocated copy.
107  *
108  * Return: A pointer to the allocated and fixed-up mft record (@ni->mrec).
109  * The return value needs to be checked with IS_ERR(). If it is true,
110  * PTR_ERR() contains the negative error code.
111  */
112 static inline struct mft_record *map_mft_record_folio(struct ntfs_inode *ni)
113 {
114 	loff_t i_size;
115 	struct ntfs_volume *vol = ni->vol;
116 	struct inode *mft_vi = vol->mft_ino;
117 	struct folio *folio;
118 	unsigned long index, end_index;
119 	unsigned int ofs;
120 
121 	WARN_ON(ni->folio);
122 	/*
123 	 * The index into the page cache and the offset within the page cache
124 	 * page of the wanted mft record.
125 	 */
126 	index = NTFS_MFT_NR_TO_PIDX(vol, ni->mft_no);
127 	ofs = NTFS_MFT_NR_TO_POFS(vol, ni->mft_no);
128 
129 	i_size = i_size_read(mft_vi);
130 	/* The maximum valid index into the page cache for $MFT's data. */
131 	end_index = i_size >> PAGE_SHIFT;
132 
133 	/* If the wanted index is out of bounds the mft record doesn't exist. */
134 	if (unlikely(index >= end_index)) {
135 		if (index > end_index || (i_size & ~PAGE_MASK) < ofs +
136 				vol->mft_record_size) {
137 			folio = ERR_PTR(-ENOENT);
138 			ntfs_error(vol->sb,
139 				"Attempt to read mft record 0x%llx, which is beyond the end of the mft. This is probably a bug in the ntfs driver.",
140 				ni->mft_no);
141 			goto err_out;
142 		}
143 	}
144 
145 	/* Read, map, and pin the folio. */
146 	folio = read_mapping_folio(mft_vi->i_mapping, index, NULL);
147 	if (!IS_ERR(folio)) {
148 		u8 *addr;
149 
150 		ni->mrec = kmalloc(vol->mft_record_size, GFP_NOFS);
151 		if (!ni->mrec) {
152 			folio_put(folio);
153 			folio = ERR_PTR(-ENOMEM);
154 			goto err_out;
155 		}
156 
157 		addr = kmap_local_folio(folio, 0);
158 		memcpy(ni->mrec, addr + ofs, vol->mft_record_size);
159 		post_read_mst_fixup((struct ntfs_record *)ni->mrec, vol->mft_record_size);
160 
161 		/* Catch multi sector transfer fixup errors. */
162 		if (!ntfs_mft_record_check(vol, (struct mft_record *)ni->mrec, ni->mft_no)) {
163 			kunmap_local(addr);
164 			ni->folio = folio;
165 			ni->folio_ofs = ofs;
166 			return ni->mrec;
167 		}
168 		kunmap_local(addr);
169 		folio_put(folio);
170 		kfree(ni->mrec);
171 		ni->mrec = NULL;
172 		folio = ERR_PTR(-EIO);
173 		NVolSetErrors(vol);
174 	}
175 err_out:
176 	ni->folio = NULL;
177 	ni->folio_ofs = 0;
178 	return (struct mft_record *)folio;
179 }
180 
181 /*
182  * map_mft_record - map and pin an mft record
183  * @ni:		ntfs inode whose MFT record to map
184  *
185  * This function ensures the MFT record for the given inode is mapped and
186  * accessible.
187  *
188  * It increments the reference count of the ntfs inode. If the record is
189  * already mapped (@ni->folio is set), it returns the cached record
190  * immediately.
191  *
192  * Otherwise, it calls map_mft_record_folio() to read the folio from disk
193  * (if necessary via read_mapping_folio), allocate a buffer, and copy the
194  * record data.
195  *
196  * Return: A pointer to the mft record. You need to check the returned
197  * pointer with IS_ERR().
198  */
199 struct mft_record *map_mft_record(struct ntfs_inode *ni)
200 {
201 	struct mft_record *m;
202 
203 	if (!ni)
204 		return ERR_PTR(-EINVAL);
205 
206 	ntfs_debug("Entering for mft_no 0x%llx.", ni->mft_no);
207 
208 	/* Make sure the ntfs inode doesn't go away. */
209 	atomic_inc(&ni->count);
210 
211 	if (ni->folio)
212 		return (struct mft_record *)ni->mrec;
213 
214 	m = map_mft_record_folio(ni);
215 	if (!IS_ERR(m))
216 		return m;
217 
218 	atomic_dec(&ni->count);
219 	if (PTR_ERR(m) != -EINTR && PTR_ERR(m) != -ERESTARTSYS)
220 		ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
221 	return m;
222 }
223 
224 /*
225  * unmap_mft_record - release a reference to a mapped mft record
226  * @ni:		ntfs inode whose MFT record to unmap
227  *
228  * This decrements the reference count of the ntfs inode.
229  *
230  * It releases the caller's hold on the inode. If the reference count indicates
231  * that there are still other users (count > 1), the function returns
232  * immediately, keeping the resources (folio and mrec buffer) pinned for
233  * those users.
234  *
235  * NOTE: If caller has modified the mft record, it is imperative to set the mft
236  * record dirty BEFORE calling unmap_mft_record().
237  */
238 void unmap_mft_record(struct ntfs_inode *ni)
239 {
240 	struct folio *folio;
241 
242 	if (!ni)
243 		return;
244 
245 	ntfs_debug("Entering for mft_no 0x%llx.", ni->mft_no);
246 
247 	folio = ni->folio;
248 	if (atomic_dec_return(&ni->count) > 1)
249 		return;
250 	WARN_ON(!folio);
251 }
252 
253 /*
254  * map_extent_mft_record - load an extent inode and attach it to its base
255  * @base_ni:	base ntfs inode
256  * @mref:	mft reference of the extent inode to load
257  * @ntfs_ino:	on successful return, pointer to the struct ntfs_inode structure
258  *
259  * Load the extent mft record @mref and attach it to its base inode @base_ni.
260  * Return the mapped extent mft record if IS_ERR(result) is false.  Otherwise
261  * PTR_ERR(result) gives the negative error code.
262  *
263  * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
264  * structure of the mapped extent inode.
265  */
266 struct mft_record *map_extent_mft_record(struct ntfs_inode *base_ni, u64 mref,
267 		struct ntfs_inode **ntfs_ino)
268 {
269 	struct mft_record *m;
270 	struct ntfs_inode *ni = NULL;
271 	struct ntfs_inode **extent_nis = NULL;
272 	int i;
273 	u64 mft_no = MREF(mref);
274 	u16 seq_no = MSEQNO(mref);
275 	bool destroy_ni = false;
276 
277 	ntfs_debug("Mapping extent mft record 0x%llx (base mft record 0x%llx).",
278 			mft_no, base_ni->mft_no);
279 	/* Make sure the base ntfs inode doesn't go away. */
280 	atomic_inc(&base_ni->count);
281 	/*
282 	 * Check if this extent inode has already been added to the base inode,
283 	 * in which case just return it. If not found, add it to the base
284 	 * inode before returning it.
285 	 */
286 retry:
287 	mutex_lock(&base_ni->extent_lock);
288 	if (base_ni->nr_extents > 0) {
289 		extent_nis = base_ni->ext.extent_ntfs_inos;
290 		for (i = 0; i < base_ni->nr_extents; i++) {
291 			if (mft_no != extent_nis[i]->mft_no)
292 				continue;
293 			ni = extent_nis[i];
294 			/* Make sure the ntfs inode doesn't go away. */
295 			atomic_inc(&ni->count);
296 			break;
297 		}
298 	}
299 	if (likely(ni != NULL)) {
300 		mutex_unlock(&base_ni->extent_lock);
301 		atomic_dec(&base_ni->count);
302 		/* We found the record; just have to map and return it. */
303 		m = map_mft_record(ni);
304 		/* map_mft_record() has incremented this on success. */
305 		atomic_dec(&ni->count);
306 		if (!IS_ERR(m)) {
307 			/* Verify the sequence number. */
308 			if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
309 				ntfs_debug("Done 1.");
310 				*ntfs_ino = ni;
311 				return m;
312 			}
313 			unmap_mft_record(ni);
314 			ntfs_error(base_ni->vol->sb,
315 					"Found stale extent mft reference! Corrupt filesystem. Run chkdsk.");
316 			return ERR_PTR(-EIO);
317 		}
318 map_err_out:
319 		ntfs_error(base_ni->vol->sb,
320 				"Failed to map extent mft record, error code %ld.",
321 				-PTR_ERR(m));
322 		return m;
323 	}
324 	mutex_unlock(&base_ni->extent_lock);
325 
326 	/* Record wasn't there. Get a new ntfs inode and initialize it. */
327 	ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
328 	if (unlikely(!ni)) {
329 		atomic_dec(&base_ni->count);
330 		return ERR_PTR(-ENOMEM);
331 	}
332 	ni->vol = base_ni->vol;
333 	ni->seq_no = seq_no;
334 	ni->nr_extents = -1;
335 	ni->ext.base_ntfs_ino = base_ni;
336 	/* Now map the record. */
337 	m = map_mft_record(ni);
338 	if (IS_ERR(m)) {
339 		atomic_dec(&base_ni->count);
340 		ntfs_clear_extent_inode(ni);
341 		goto map_err_out;
342 	}
343 	/* Verify the sequence number if it is present. */
344 	if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
345 		ntfs_error(base_ni->vol->sb,
346 				"Found stale extent mft reference! Corrupt filesystem. Run chkdsk.");
347 		destroy_ni = true;
348 		m = ERR_PTR(-EIO);
349 		goto unm_nolock_err_out;
350 	}
351 
352 	mutex_lock(&base_ni->extent_lock);
353 	for (i = 0; i < base_ni->nr_extents; i++) {
354 		if (mft_no == extent_nis[i]->mft_no) {
355 			mutex_unlock(&base_ni->extent_lock);
356 			ntfs_clear_extent_inode(ni);
357 			goto retry;
358 		}
359 	}
360 	/* Attach extent inode to base inode, reallocating memory if needed. */
361 	if (!(base_ni->nr_extents & 3)) {
362 		struct ntfs_inode **tmp;
363 		int new_size = (base_ni->nr_extents + 4) * sizeof(struct ntfs_inode *);
364 
365 		tmp = kvzalloc(new_size, GFP_NOFS);
366 		if (unlikely(!tmp)) {
367 			ntfs_error(base_ni->vol->sb, "Failed to allocate internal buffer.");
368 			destroy_ni = true;
369 			m = ERR_PTR(-ENOMEM);
370 			goto unm_err_out;
371 		}
372 		if (base_ni->nr_extents) {
373 			WARN_ON(!base_ni->ext.extent_ntfs_inos);
374 			memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
375 					4 * sizeof(struct ntfs_inode *));
376 			kvfree(base_ni->ext.extent_ntfs_inos);
377 		}
378 		base_ni->ext.extent_ntfs_inos = tmp;
379 	}
380 	base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
381 	mutex_unlock(&base_ni->extent_lock);
382 	atomic_dec(&base_ni->count);
383 	ntfs_debug("Done 2.");
384 	*ntfs_ino = ni;
385 	return m;
386 unm_err_out:
387 	mutex_unlock(&base_ni->extent_lock);
388 unm_nolock_err_out:
389 	unmap_mft_record(ni);
390 	atomic_dec(&base_ni->count);
391 	/*
392 	 * If the extent inode was not attached to the base inode we need to
393 	 * release it or we will leak memory.
394 	 */
395 	if (destroy_ni)
396 		ntfs_clear_extent_inode(ni);
397 	return m;
398 }
399 
400 /*
401  * __mark_mft_record_dirty - mark the base vfs inode dirty
402  * @ni:		ntfs inode describing the mapped mft record
403  *
404  * Internal function.  Users should call mark_mft_record_dirty() instead.
405  *
406  * This function determines the base ntfs inode (in case @ni is an extent
407  * inode) and marks the corresponding VFS inode dirty.
408  *
409  * NOTE:  We only set I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
410  * on the base vfs inode, because even though file data may have been modified,
411  * it is dirty in the inode meta data rather than the data page cache of the
412  * inode, and thus there are no data pages that need writing out.  Therefore, a
413  * full mark_inode_dirty() is overkill.  A mark_inode_dirty_sync(), on the
414  * other hand, is not sufficient, because ->write_inode needs to be called even
415  * in case of fdatasync. This needs to happen or the file data would not
416  * necessarily hit the device synchronously, even though the vfs inode has the
417  * O_SYNC flag set.  Also, I_DIRTY_DATASYNC simply "feels" better than just
418  * I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
419  * which is not what I_DIRTY_SYNC on its own would suggest.
420  */
421 void __mark_mft_record_dirty(struct ntfs_inode *ni)
422 {
423 	struct ntfs_inode *base_ni;
424 
425 	ntfs_debug("Entering for inode 0x%llx.", ni->mft_no);
426 	WARN_ON(NInoAttr(ni));
427 	/* Determine the base vfs inode and mark it dirty, too. */
428 	if (likely(ni->nr_extents >= 0))
429 		base_ni = ni;
430 	else
431 		base_ni = ni->ext.base_ntfs_ino;
432 	__mark_inode_dirty(VFS_I(base_ni), I_DIRTY_DATASYNC);
433 }
434 
435 struct ntfs_mft_io_unit {
436 	sector_t sector;
437 	unsigned int folio_ofs;
438 	unsigned int len;
439 };
440 
441 struct ntfs_mft_write_ctx {
442 	struct folio *folio;
443 	struct address_space *mapping;
444 	struct ntfs_volume *vol;
445 	struct completion *done;
446 	int error;
447 	bool writeback_started;
448 	struct bio bio;
449 };
450 
451 static struct bio_set ntfs_mft_bioset;
452 
453 int ntfs_mft_bioset_init(void)
454 {
455 	return bioset_init(&ntfs_mft_bioset, BIO_POOL_SIZE,
456 			   offsetof(struct ntfs_mft_write_ctx, bio),
457 			   BIOSET_NEED_BVECS);
458 }
459 
460 void ntfs_mft_bioset_exit(void)
461 {
462 	bioset_exit(&ntfs_mft_bioset);
463 }
464 
465 static void ntfs_mft_end_io(struct bio *bio)
466 {
467 	struct ntfs_mft_write_ctx *ctx =
468 		container_of(bio, struct ntfs_mft_write_ctx, bio);
469 	struct folio *folio = ctx->folio;
470 	struct completion *done = ctx->done;
471 	int err;
472 
473 	if (bio->bi_status)
474 		err = blk_status_to_errno(bio->bi_status);
475 	else
476 		err = ctx->error;
477 	if (err) {
478 		mapping_set_error(ctx->mapping, err);
479 		NVolSetErrors(ctx->vol);
480 		ntfs_error(ctx->vol->sb, "I/O error while writing MFT: %d",
481 			   err);
482 	}
483 
484 	if (!done)
485 		bio_put(bio);
486 	folio_end_writeback(folio);
487 	folio_put(folio);
488 	if (done)
489 		complete(done);
490 }
491 
492 static void ntfs_start_mft_writeback(struct ntfs_mft_write_ctx *ctx)
493 {
494 	if (ctx->writeback_started)
495 		return;
496 
497 	inode_attach_wb(ctx->mapping->host, NULL);
498 	folio_get(ctx->folio);
499 	folio_start_writeback(ctx->folio);
500 	ctx->writeback_started = true;
501 }
502 
503 static struct bio *ntfs_alloc_mft_parent_bio(struct ntfs_volume *vol,
504 					     struct folio *folio,
505 					     struct completion *done)
506 {
507 	struct ntfs_mft_write_ctx *ctx;
508 	struct bio *parent;
509 
510 	parent = bio_alloc_bioset(vol->sb->s_bdev, 1, REQ_OP_WRITE, GFP_NOIO,
511 				  &ntfs_mft_bioset);
512 	if (!parent)
513 		return NULL;
514 
515 	ctx = container_of(parent, struct ntfs_mft_write_ctx, bio);
516 	ctx->folio = folio;
517 	ctx->mapping = folio->mapping;
518 	ctx->vol = vol;
519 	ctx->done = done;
520 	ctx->error = 0;
521 	ctx->writeback_started = false;
522 	parent->bi_end_io = ntfs_mft_end_io;
523 	return parent;
524 }
525 
526 /*
527  * Write one MFT I/O unit to $MFTMirr.  The source folio contains the MST
528  * protected image that will be written to $MFT.
529  */
530 static int ntfs_sync_mft_mirror_unit(struct ntfs_volume *vol,
531 				     struct folio *source, u64 mirror_file_ofs,
532 				     const struct ntfs_mft_io_unit *unit)
533 {
534 	struct folio *mirror;
535 	struct bio_vec bvec;
536 	struct bio bio;
537 	u64 mirror_size;
538 	unsigned int mirror_ofs;
539 	u8 *src, *dst;
540 	int err;
541 
542 	if (unlikely(!vol->mftmirr_ino))
543 		return -EIO;
544 
545 	mirror_size = (u64)vol->mftmirr_size * vol->mft_record_size;
546 	if (mirror_file_ofs >= mirror_size ||
547 	    unit->len > mirror_size - mirror_file_ofs)
548 		return -EIO;
549 	if (unit->folio_ofs + unit->len > folio_size(source))
550 		return -EIO;
551 
552 	mirror = read_mapping_folio(vol->mftmirr_ino->i_mapping,
553 				    mirror_file_ofs >> PAGE_SHIFT, NULL);
554 	if (IS_ERR(mirror))
555 		return PTR_ERR(mirror);
556 
557 	folio_lock(mirror);
558 	if (folio_test_writeback(mirror))
559 		folio_wait_writeback(mirror);
560 	mirror_ofs = mirror_file_ofs - folio_pos(mirror);
561 	if (mirror_ofs + unit->len > folio_size(mirror)) {
562 		err = -EIO;
563 		goto out_unlock;
564 	}
565 
566 	folio_clear_uptodate(mirror);
567 	src = kmap_local_folio(source, unit->folio_ofs);
568 	dst = kmap_local_folio(mirror, mirror_ofs);
569 	memcpy(dst, src, unit->len);
570 	kunmap_local(dst);
571 	kunmap_local(src);
572 
573 	bio_init(&bio, vol->sb->s_bdev, &bvec, 1, REQ_OP_WRITE);
574 	bio.bi_iter.bi_sector = ntfs_bytes_to_bio_sector(
575 		NTFS_CLU_TO_B(vol, vol->mftmirr_lcn) + mirror_file_ofs);
576 	if (!bio_add_folio(&bio, mirror, unit->len, mirror_ofs))
577 		err = -EIO;
578 	else
579 		err = submit_bio_wait(&bio);
580 	bio_uninit(&bio);
581 
582 	/*
583 	 * The in-memory mirror is now valid because we just memcpy()'d the
584 	 * mst-protected mft record into it.  Mark the folio uptodate even on
585 	 * write error so a subsequent read_mapping_folio() does not refetch
586 	 * the stale on-disk mirror and overwrite this copy.  The error is
587 	 * propagated to the caller via @err.
588 	 */
589 	folio_mark_uptodate(mirror);
590 
591 out_unlock:
592 	folio_unlock(mirror);
593 	folio_put(mirror);
594 	return err;
595 }
596 
597 static int ntfs_sync_mft_mirror_record(struct ntfs_volume *vol,
598 				       struct folio *source, const u64 mft_no)
599 {
600 	u64 mirror_file_ofs = (u64)mft_no * vol->mft_record_size;
601 	struct ntfs_mft_io_unit unit = {
602 		.folio_ofs = NTFS_MFT_NR_TO_POFS(vol, mft_no),
603 		.len = vol->mft_record_size,
604 	};
605 
606 	mirror_file_ofs =
607 		round_down(mirror_file_ofs, (u64)vol->mft_io_unit_size);
608 	unit.folio_ofs = round_down(unit.folio_ofs, vol->mft_io_unit_size);
609 	unit.len = vol->mft_io_unit_size;
610 
611 	return ntfs_sync_mft_mirror_unit(vol, source, mirror_file_ofs, &unit);
612 }
613 
614 static int ntfs_prepare_mft_record_io_units(struct ntfs_inode *ni,
615 					    struct ntfs_mft_io_unit units[2])
616 {
617 	struct ntfs_volume *vol = ni->vol;
618 	u64 record_byte = (u64)ni->mft_no * vol->mft_record_size;
619 	u64 disk_byte;
620 	unsigned int nr_units = ni->mft_lcn_count;
621 	unsigned int cluster_ofs;
622 	unsigned int i;
623 
624 	if (!nr_units || nr_units > ARRAY_SIZE(ni->mft_lcn))
625 		return -EIO;
626 	for (i = 0; i < nr_units; i++)
627 		if (ni->mft_lcn[i] < 0)
628 			return -EIO;
629 
630 	cluster_ofs = ntfs_bytes_to_cluster_off(vol, record_byte);
631 	if (vol->mft_io_unit_size > vol->mft_record_size) {
632 		cluster_ofs = round_down(cluster_ofs, vol->mft_io_unit_size);
633 		disk_byte = NTFS_CLU_TO_B(vol, ni->mft_lcn[0]) + cluster_ofs;
634 		units[0] = (struct ntfs_mft_io_unit){
635 			.sector = ntfs_bytes_to_bio_sector(disk_byte),
636 			.folio_ofs = round_down(ni->folio_ofs,
637 						vol->mft_io_unit_size),
638 			.len = vol->mft_io_unit_size,
639 		};
640 		return 1;
641 	}
642 
643 	disk_byte = NTFS_CLU_TO_B(vol, ni->mft_lcn[0]) + cluster_ofs;
644 	units[0] = (struct ntfs_mft_io_unit){
645 		.sector = ntfs_bytes_to_bio_sector(disk_byte),
646 		.folio_ofs = ni->folio_ofs,
647 		.len = vol->mft_record_size,
648 	};
649 	if (nr_units == 1)
650 		return 1;
651 
652 	units[0].len = vol->cluster_size;
653 	disk_byte = NTFS_CLU_TO_B(vol, ni->mft_lcn[1]);
654 	units[1] = (struct ntfs_mft_io_unit){
655 		.sector = ntfs_bytes_to_bio_sector(disk_byte),
656 		.folio_ofs = ni->folio_ofs + vol->cluster_size,
657 		.len = vol->mft_record_size - vol->cluster_size,
658 	};
659 	return 2;
660 }
661 
662 /*
663  * write_mft_record_nolock - write out a mapped (extent) mft record
664  * @ni:		ntfs inode describing the mapped (extent) mft record
665  * @m:		mapped (extent) mft record to write
666  * @sync:	if true, wait for i/o completion
667  *
668  * Write the mapped (extent) mft record @m described by the (regular or extent)
669  * ntfs inode @ni to backing store.  If the mft record @m has a counterpart in
670  * the mft mirror, that is also updated.
671  *
672  * We only write the mft record if the ntfs inode @ni is dirty.
673  *
674  * On success, clean the mft record and return 0.  On ENOMEM, redirty the
675  * record so it can be retried.  Asynchronous callers return success after
676  * redirtying while synchronous callers receive the error.  For other errors,
677  * mark the volume with errors.
678  *
679  * If @sync is false, PG_writeback keeps the folio stable and serializes later
680  * writers until the I/O completes.
681  */
682 int write_mft_record_nolock(struct ntfs_inode *ni, struct mft_record *m, int sync)
683 {
684 	struct ntfs_volume *vol = ni->vol;
685 	struct folio *folio = ni->folio;
686 	DECLARE_COMPLETION_ONSTACK(done);
687 	struct ntfs_mft_io_unit units[2];
688 	struct ntfs_mft_write_ctx *ctx;
689 	struct bio *parent, *child = NULL;
690 	unsigned int nr_units;
691 	int err = 0;
692 	u8 *kaddr;
693 	struct mft_record *fixup_m;
694 
695 	ntfs_debug("Entering for inode 0x%llx.", ni->mft_no);
696 
697 	WARN_ON(NInoAttr(ni));
698 	WARN_ON(!folio_test_locked(folio));
699 
700 	if (folio_test_writeback(folio))
701 		folio_wait_writeback(folio);
702 
703 	/*
704 	 * If the struct ntfs_inode is clean no need to do anything.  If it is dirty,
705 	 * mark it as clean now so that it can be redirtied later on if needed.
706 	 * There is no danger of races since the caller is holding the locks
707 	 * for the mft record @m and the page it is in.
708 	 */
709 	if (!NInoTestClearDirty(ni))
710 		goto done;
711 
712 	err = ntfs_prepare_mft_record_io_units(ni, units);
713 	if (err < 0)
714 		goto err_out;
715 	nr_units = err;
716 
717 	kaddr = kmap_local_folio(folio, 0);
718 	fixup_m = (struct mft_record *)(kaddr + ni->folio_ofs);
719 	memcpy(fixup_m, m, vol->mft_record_size);
720 
721 	/* Apply the mst protection fixups. */
722 	err = pre_write_mst_fixup((struct ntfs_record *)fixup_m, vol->mft_record_size);
723 	if (err) {
724 		ntfs_error(vol->sb, "Failed to apply mst fixups!");
725 		goto unmap_err_out;
726 	}
727 
728 	parent = ntfs_alloc_mft_parent_bio(vol, folio, sync ? &done : NULL);
729 	if (!parent) {
730 		err = -ENOMEM;
731 		goto unmap_err_out;
732 	}
733 	ctx = container_of(parent, struct ntfs_mft_write_ctx, bio);
734 
735 	parent->bi_iter.bi_sector = units[0].sector;
736 	if (!bio_add_folio(parent, folio, units[0].len, units[0].folio_ofs)) {
737 		err = -EIO;
738 		goto put_bios_out;
739 	}
740 
741 	if (nr_units == 2) {
742 		if (bio_end_sector(parent) != units[1].sector ||
743 		    !bio_add_folio(parent, folio, units[1].len,
744 				   units[1].folio_ofs)) {
745 			child = bio_alloc(vol->sb->s_bdev, 1, REQ_OP_WRITE,
746 					  GFP_NOIO);
747 			if (!child) {
748 				err = -ENOMEM;
749 				goto put_bios_out;
750 			}
751 			child->bi_iter.bi_sector = units[1].sector;
752 			if (!bio_add_folio(child, folio, units[1].len,
753 					   units[1].folio_ofs)) {
754 				err = -EIO;
755 				goto put_bios_out;
756 			}
757 		}
758 	}
759 
760 	if (ni->mft_no < vol->mftmirr_size) {
761 		err = ntfs_sync_mft_mirror_record(vol, folio, ni->mft_no);
762 		if (err)
763 			ctx->error = err;
764 	}
765 
766 	kunmap_local(kaddr);
767 
768 	ntfs_start_mft_writeback(ctx);
769 	if (child) {
770 		bio_chain(child, parent);
771 		submit_bio(child);
772 	}
773 	submit_bio(parent);
774 
775 	if (sync) {
776 		wait_for_completion(&done);
777 		if (!err && parent->bi_status)
778 			err = blk_status_to_errno(parent->bi_status);
779 		bio_put(parent);
780 	}
781 
782 	if (unlikely(err)) {
783 		/* I/O error during writing.  This is really bad! */
784 		ntfs_error(vol->sb,
785 			"I/O error while writing mft record 0x%llx!  Marking base inode as bad.  You should unmount the volume and run chkdsk.",
786 			ni->mft_no);
787 		return err;
788 	}
789 done:
790 	ntfs_debug("Done.");
791 	return 0;
792 put_bios_out:
793 	if (child)
794 		bio_put(child);
795 	bio_put(parent);
796 unmap_err_out:
797 	kunmap_local(kaddr);
798 err_out:
799 	/*
800 	 * The caller should mark the base inode as bad so no more I/O
801 	 * happens. ->drop_inode() will still be invoked so all extent inodes
802 	 * and other allocated memory will be freed. ENOMEM is retried by
803 	 * redirtying the mft record below.
804 	 */
805 	if (err == -ENOMEM) {
806 		ntfs_error(vol->sb,
807 			"Not enough memory to write mft record. Redirtying so the write is retried later.");
808 		mark_mft_record_dirty(ni);
809 		if (!sync)
810 			err = 0;
811 	} else
812 		NVolSetErrors(vol);
813 	return err;
814 }
815 
816 static int ntfs_test_inode_wb(struct inode *vi, u64 ino, void *data)
817 {
818 	struct ntfs_attr *na = data;
819 
820 	if (!ntfs_test_inode(vi, na))
821 		return 0;
822 
823 	/*
824 	 * Without this, ntfs_write_mst_block() could call iput_final()
825 	 * , and ntfs_evict_big_inode() could try to unlink this inode
826 	 * and the contex could be blocked infinitly in map_mft_record().
827 	 */
828 	if (NInoBeingDeleted(NTFS_I(vi))) {
829 		na->state = NI_BeingDeleted;
830 		return -1;
831 	}
832 
833 	/*
834 	 * This condition can prevent ntfs_write_mst_block()
835 	 * from applying/undo fixups while ntfs_create() being
836 	 * called
837 	 */
838 	spin_lock(&vi->i_lock);
839 	if (inode_state_read_once(vi) & I_CREATING) {
840 		spin_unlock(&vi->i_lock);
841 		na->state = NI_BeingCreated;
842 		return -1;
843 	}
844 	spin_unlock(&vi->i_lock);
845 
846 	return igrab(vi) ? 1 : -1;
847 }
848 
849 /*
850  * ntfs_may_write_mft_record - check if an mft record may be written out
851  * @vol:	[IN]  ntfs volume on which the mft record to check resides
852  * @mft_no:	[IN]  mft record number of the mft record to check
853  * @m:		[IN]  mapped mft record to check
854  * @locked_ni:	[OUT] caller has to unlock this ntfs inode if one is returned
855  * @ref_vi:	[OUT] caller has to drop this vfs inode if one is returned
856  *
857  * Check if the mapped (base or extent) mft record @m with mft record number
858  * @mft_no belonging to the ntfs volume @vol may be written out.  If necessary
859  * and possible the ntfs inode of the mft record is locked and the base vfs
860  * inode is pinned.  The locked ntfs inode is then returned in @locked_ni.  The
861  * caller is responsible for unlocking the ntfs inode and unpinning the base
862  * vfs inode.
863  *
864  * To avoid deadlock when the caller holds a folio lock, if the function
865  * returns @ref_vi it defers dropping the vfs inode reference by returning
866  * it in @ref_vi instead of calling iput() directly.  The caller must call
867  * iput() on @ref_vi after releasing the folio lock.
868  *
869  * Return 'true' if the mft record may be written out by this path and 'false'
870  * if direct inode writeback owns it.
871  *
872  * The caller has locked the page and cleared the uptodate flag on it which
873  * means that we can safely write out any dirty mft records that do not have
874  * their inodes in icache as determined by find_inode_nowait().
875  *
876  * Here is a description of the tests we perform:
877  *
878  * If the inode is found in icache we know the mft record must be a base mft
879  * record.  If it is dirty, we do not write it and return 'false' as the vfs
880  * inode write paths will result in the access times being updated which would
881  * cause the base mft record to be redirtied and written out again.
882  *
883  * If the inode is in icache and not dirty, we attempt to lock the mft record
884  * and if we find the lock was already taken, it is not safe to write the mft
885  * record and we return 'false'.
886  *
887  * If we manage to obtain the lock we have exclusive access to the mft record,
888  * which also allows us safe writeout of the mft record.  We then set
889  * @locked_ni to the locked ntfs inode and return 'true'.
890  *
891  * Note we cannot just lock the mft record and sleep while waiting for the lock
892  * because this would deadlock due to lock reversal.
893  *
894  * If the inode is not in icache we need to perform further checks.
895  *
896  * If the mft record is not a FILE record or it is a base mft record, we can
897  * safely write it and return 'true'.
898  */
899 static bool ntfs_may_write_mft_record(struct ntfs_volume *vol, const u64 mft_no,
900 		const struct mft_record *m, struct ntfs_inode **locked_ni,
901 		struct inode **ref_vi)
902 {
903 	struct super_block *sb = vol->sb;
904 	struct inode *mft_vi = vol->mft_ino;
905 	struct inode *vi;
906 	struct ntfs_inode *ni;
907 	struct ntfs_attr na = {0};
908 
909 	ntfs_debug("Entering for inode 0x%llx.", mft_no);
910 	/*
911 	 * Normally we do not return a locked inode so set @locked_ni to NULL.
912 	 */
913 	*locked_ni = NULL;
914 	*ref_vi = NULL;
915 
916 	/*
917 	 * Check if the inode corresponding to this mft record is in the VFS
918 	 * inode cache and obtain a reference to it if it is.
919 	 */
920 	ntfs_debug("Looking for inode 0x%llx in icache.", mft_no);
921 	na.mft_no = mft_no;
922 	na.type = AT_UNUSED;
923 	/*
924 	 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
925 	 * we get here for it rather often.
926 	 */
927 	if (!mft_no) {
928 		/* Balance the below iput(). */
929 		vi = igrab(mft_vi);
930 		WARN_ON(vi != mft_vi);
931 	} else {
932 		/*
933 		 * Have to use find_inode_nowait() since ilookup5_nowait()
934 		 * waits for inode with I_FREEING, which causes ntfs to deadlock
935 		 * when inodes are unlinked concurrently
936 		 */
937 		vi = find_inode_nowait(sb, mft_no, ntfs_test_inode_wb, &na);
938 		if (na.state == NI_BeingDeleted || na.state == NI_BeingCreated)
939 			return false;
940 	}
941 	if (vi) {
942 		ntfs_debug("Base inode 0x%llx is in icache.", mft_no);
943 		/* The inode is in icache. */
944 		ni = NTFS_I(vi);
945 		/* Take a reference to the ntfs inode. */
946 		atomic_inc(&ni->count);
947 		/* If the inode is dirty, do not write this record. */
948 		if (NInoDirty(ni)) {
949 			ntfs_debug("Inode 0x%llx is dirty, do not write it.",
950 					mft_no);
951 			atomic_dec(&ni->count);
952 			*ref_vi = vi;
953 			return false;
954 		}
955 		ntfs_debug("Inode 0x%llx is not dirty.", mft_no);
956 		/* The inode is not dirty, try to take the mft record lock. */
957 		if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
958 			ntfs_debug("Mft record 0x%llx is already locked, do not write it.", mft_no);
959 			atomic_dec(&ni->count);
960 			*ref_vi = vi;
961 			return false;
962 		}
963 		ntfs_debug("Managed to lock mft record 0x%llx, write it.",
964 				mft_no);
965 		/*
966 		 * The write has to occur while we hold the mft record lock so
967 		 * return the locked ntfs inode and its vfs inode reference.
968 		 */
969 		*locked_ni = ni;
970 		*ref_vi = vi;
971 		return true;
972 	}
973 	ntfs_debug("Inode 0x%llx is not in icache.", mft_no);
974 	/* The inode is not in icache. */
975 	/* Write the record if it is not a mft record (type "FILE"). */
976 	if (!ntfs_is_mft_record(m->magic)) {
977 		ntfs_debug("Mft record 0x%llx is not a FILE record, write it.",
978 				mft_no);
979 		return true;
980 	}
981 	/* Write the mft record if it is a base inode. */
982 	if (!m->base_mft_record) {
983 		ntfs_debug("Mft record 0x%llx is a base record, write it.",
984 				mft_no);
985 		return true;
986 	}
987 
988 	ntfs_debug("Mft record 0x%llx is an extent record, skip it.",
989 		   mft_no);
990 	return false;
991 }
992 
993 static const char *es = "  Leaving inconsistent metadata.  Unmount and run chkdsk.";
994 
995 #define FIRST_NORMAL_MFT_RECORD	24
996 #define MFT_RECORD_RESERVE	4
997 
998 /*
999  * Records 12-15 are marked in use by Windows but normally have no name
1000  * and no links. Keep them as the last bootstrap option when a volume
1001  * mounted without an in-memory tail reserve needs its first $MFT metadata
1002  * extent.
1003  */
1004 static bool mft_reserved_is_free(struct ntfs_volume *vol,
1005 		struct ntfs_inode *mft_ni, s64 mft_no)
1006 {
1007 	struct attr_record *a;
1008 	struct mft_record *m;
1009 	struct folio *folio;
1010 	void *mapped;
1011 	pgoff_t index = NTFS_MFT_NR_TO_PIDX(vol, mft_no);
1012 	unsigned int ofs = NTFS_MFT_NR_TO_POFS(vol, mft_no);
1013 	u32 attrs_offset, bytes_in_use;
1014 	bool available = false, have_std = false;
1015 	int i;
1016 
1017 	for (i = 0; i < mft_ni->nr_extents; i++) {
1018 		if (mft_ni->ext.extent_ntfs_inos[i] &&
1019 		    mft_ni->ext.extent_ntfs_inos[i]->mft_no == mft_no)
1020 			return false;
1021 	}
1022 	m = kmalloc(vol->mft_record_size, GFP_NOFS);
1023 	if (!m)
1024 		return false;
1025 
1026 	folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL);
1027 	if (IS_ERR(folio))
1028 		goto free_m;
1029 
1030 	folio_lock(folio);
1031 	mapped = kmap_local_folio(folio, 0);
1032 	memcpy(m, (u8 *)mapped + ofs, vol->mft_record_size);
1033 	kunmap_local(mapped);
1034 	folio_unlock(folio);
1035 	folio_put(folio);
1036 	if (post_read_mst_fixup((struct ntfs_record *)m, vol->mft_record_size))
1037 		goto free_m;
1038 
1039 	if (!ntfs_is_mft_record(m->magic) ||
1040 	    !(m->flags & MFT_RECORD_IN_USE) || m->base_mft_record ||
1041 	    m->link_count)
1042 		goto out;
1043 
1044 	attrs_offset = le16_to_cpu(m->attrs_offset);
1045 	bytes_in_use = le32_to_cpu(m->bytes_in_use);
1046 	if (attrs_offset > bytes_in_use || bytes_in_use > vol->mft_record_size ||
1047 	    bytes_in_use - attrs_offset < sizeof(a->type))
1048 		goto out;
1049 
1050 	for (a = (struct attr_record *)((u8 *)m + attrs_offset);
1051 	     (u8 *)a + sizeof(a->type) <= (u8 *)m + bytes_in_use;) {
1052 		u32 len;
1053 
1054 		if (a->type == AT_END) {
1055 			if ((u8 *)a + sizeof(a->type) + sizeof(a->length) >
1056 			    (u8 *)m + bytes_in_use)
1057 				break;
1058 			/* Also accept a record emptied by an earlier bootstrap. */
1059 			available = have_std ||
1060 				    (u8 *)a == (u8 *)m + attrs_offset;
1061 			break;
1062 		}
1063 		if (a->type == AT_FILE_NAME)
1064 			break;
1065 		len = le32_to_cpu(a->length);
1066 		if (len < offsetof(struct attr_record, data) ||
1067 		    (u8 *)a + len > (u8 *)m + bytes_in_use)
1068 			break;
1069 		if (a->type == AT_STANDARD_INFORMATION) {
1070 			u32 value_len, value_ofs;
1071 
1072 			if (have_std || a->non_resident ||
1073 			    len < offsetof(struct attr_record,
1074 					   data.resident.reserved) + 1)
1075 				break;
1076 			value_len = le32_to_cpu(a->data.resident.value_length);
1077 			value_ofs = le16_to_cpu(a->data.resident.value_offset);
1078 			if (value_ofs > len || value_len > len - value_ofs)
1079 				break;
1080 			have_std = true;
1081 		}
1082 		a = (struct attr_record *)((u8 *)a + len);
1083 	}
1084 out:
1085 	kfree(m);
1086 	return available;
1087 free_m:
1088 	kfree(m);
1089 	return false;
1090 }
1091 
1092 static s64 mft_reserve_end(const u8 *buf, s64 buf_start, s64 buf_end,
1093 			   s64 start, s64 pass_end, s64 initialized_mft_records)
1094 {
1095 	s64 end = start + 1;
1096 	s64 limit = min_t(s64, start + MFT_RECORD_RESERVE, pass_end);
1097 
1098 	if (limit > initialized_mft_records)
1099 		limit = initialized_mft_records;
1100 	if (limit > buf_end)
1101 		limit = buf_end;
1102 	while (end < limit &&
1103 	       !(buf[(end - buf_start) >> 3] &
1104 		 (1 << ((end - buf_start) & 7))))
1105 		end++;
1106 	return end;
1107 }
1108 
1109 /*
1110  * mft_bitmap_alloc_free_rec - find and allocate a free MFT record
1111  * @vol:	volume on which to search for a free mft record
1112  * @base_ni:	open base inode if allocating an extent mft record or NULL
1113  * @max_mft_no:	first record which must not be allocated, or -1
1114  * @new_reserve_end: if not NULL, end of a free run starting after the result
1115  *
1116  * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1117  * @vol.
1118  *
1119  * If @base_ni is NULL start the search at the default allocator position.
1120  *
1121  * If @base_ni is not NULL start the search at the mft record after the base
1122  * mft record @base_ni.
1123  *
1124  * Return the free mft record on success and -errno on error.  An error code of
1125  * -ENOSPC means that there are no free mft records in the currently
1126  * initialized mft bitmap.
1127  *
1128  * Locking: Caller must hold vol->mftbmp_lock for writing.
1129  */
1130 static s64 mft_bitmap_alloc_free_rec(struct ntfs_volume *vol,
1131 				     struct ntfs_inode *base_ni,
1132 				     s64 max_mft_no, s64 *new_reserve_end)
1133 {
1134 	s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1135 	s64 initialized_mft_records;
1136 	unsigned long flags;
1137 	struct address_space *mftbmp_mapping;
1138 	u8 *buf = NULL, *byte;
1139 	struct folio *folio;
1140 	unsigned int folio_ofs, size;
1141 	u8 pass, b;
1142 
1143 	ntfs_debug("Searching for free mft record in the currently initialized mft bitmap.");
1144 	mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1145 	/*
1146 	 * Set the end of the pass making sure we do not overflow the mft
1147 	 * bitmap.
1148 	 */
1149 	read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1150 	pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1151 			vol->mft_record_size_bits;
1152 	initialized_mft_records = NTFS_I(vol->mft_ino)->initialized_size >>
1153 			vol->mft_record_size_bits;
1154 	read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1155 	read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1156 	ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1157 	read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1158 	if (pass_end > ll)
1159 		pass_end = ll;
1160 	if (max_mft_no >= 0 && pass_end > max_mft_no)
1161 		pass_end = max_mft_no;
1162 	if (base_ni && base_ni->mft_no == FILE_MFT) {
1163 		data_pos = FILE_first_user;
1164 		pass = 2;
1165 		if (data_pos >= pass_end)
1166 			return -ENOSPC;
1167 	} else {
1168 		pass = 1;
1169 		if (!base_ni)
1170 			data_pos = vol->mft_data_pos;
1171 		else
1172 			data_pos = base_ni->mft_no + 1;
1173 		if (data_pos < FIRST_NORMAL_MFT_RECORD)
1174 			data_pos = FIRST_NORMAL_MFT_RECORD;
1175 		if (data_pos >= pass_end) {
1176 			data_pos = FIRST_NORMAL_MFT_RECORD;
1177 			pass = 2;
1178 			/* This happens on a freshly formatted volume. */
1179 			if (data_pos >= pass_end)
1180 				return -ENOSPC;
1181 		}
1182 	}
1183 
1184 	pass_start = data_pos;
1185 	ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, pass_end 0x%llx, data_pos 0x%llx.",
1186 			pass, pass_start, pass_end, data_pos);
1187 	/* Loop until a free mft record is found. */
1188 	for (; pass <= 2;) {
1189 		/* Cap size to pass_end. */
1190 		ofs = data_pos >> 3;
1191 		folio_ofs = ofs & ~PAGE_MASK;
1192 		size = PAGE_SIZE - folio_ofs;
1193 		ll = ((pass_end + 7) >> 3) - ofs;
1194 		if (size > ll)
1195 			size = ll;
1196 		size <<= 3;
1197 		/*
1198 		 * If we are still within the active pass, search the next page
1199 		 * for a zero bit.
1200 		 */
1201 		if (size) {
1202 			folio = read_mapping_folio(mftbmp_mapping,
1203 					ofs >> PAGE_SHIFT, NULL);
1204 			if (IS_ERR(folio)) {
1205 				ntfs_error(vol->sb, "Failed to read mft bitmap, aborting.");
1206 				return PTR_ERR(folio);
1207 			}
1208 			folio_lock(folio);
1209 			buf = (u8 *)kmap_local_folio(folio, 0) + folio_ofs;
1210 			bit = data_pos & 7;
1211 			data_pos &= ~7ull;
1212 			ntfs_debug("Before inner for loop: size 0x%x, data_pos 0x%llx, bit 0x%llx",
1213 					size, data_pos, bit);
1214 			for (; bit < size && data_pos + bit < pass_end;
1215 					bit &= ~7ull, bit += 8) {
1216 				byte = buf + (bit >> 3);
1217 				if (*byte == 0xff)
1218 					continue;
1219 				b = bit & 7;
1220 				for (; b < 8; b++) {
1221 					if (*byte & (1 << b))
1222 						continue;
1223 					ll = data_pos + (bit & ~7ull) + b;
1224 					if (ll >= pass_end)
1225 						break;
1226 					/* Keep the dynamic tail reserve for $MFT metadata. */
1227 					if ((!base_ni || base_ni->mft_no != FILE_MFT) &&
1228 					    ll >= vol->mft_record_reserve_pos &&
1229 					    ll < vol->mft_record_reserve_end)
1230 						continue;
1231 					if (unlikely(ll >= (1ll << 32))) {
1232 						folio_unlock(folio);
1233 						kunmap_local(buf);
1234 						folio_put(folio);
1235 						return -ENOSPC;
1236 					}
1237 					goto found;
1238 				}
1239 			}
1240 			ntfs_debug("After inner for loop: size 0x%x, data_pos 0x%llx, bit 0x%llx",
1241 					size, data_pos, bit);
1242 			data_pos += size;
1243 			folio_unlock(folio);
1244 			kunmap_local(buf);
1245 			folio_put(folio);
1246 			/*
1247 			 * If the end of the pass has not been reached yet,
1248 			 * continue searching the mft bitmap for a zero bit.
1249 			 */
1250 			if (data_pos < pass_end)
1251 				continue;
1252 		}
1253 		/* Do the next pass. */
1254 		if (++pass == 2) {
1255 			/*
1256 			 * Starting the second pass, in which we scan the first
1257 			 * part of the zone which we omitted earlier.
1258 			 */
1259 			pass_end = pass_start;
1260 			data_pos = FIRST_NORMAL_MFT_RECORD;
1261 			pass_start = FIRST_NORMAL_MFT_RECORD;
1262 			ntfs_debug("pass %i, pass_start 0x%llx, pass_end 0x%llx.",
1263 					pass, pass_start, pass_end);
1264 			if (data_pos >= pass_end)
1265 				break;
1266 		}
1267 	}
1268 	/* No free mft records in currently initialized mft bitmap. */
1269 	ntfs_debug("Done.  (No free mft records left in currently initialized mft bitmap.)");
1270 	return -ENOSPC;
1271 found:
1272 	if (new_reserve_end)
1273 		*new_reserve_end = mft_reserve_end(buf, data_pos,
1274 						   data_pos + size, ll, pass_end,
1275 						   initialized_mft_records);
1276 	*byte |= 1 << b;
1277 	folio_mark_dirty(folio);
1278 	folio_unlock(folio);
1279 	kunmap_local(buf);
1280 	folio_put(folio);
1281 	ntfs_debug("Done.  (Found and allocated mft record 0x%llx.)", ll);
1282 	return ll;
1283 }
1284 
1285 static int ntfs_mft_attr_extend(struct ntfs_inode *ni,
1286 				struct ntfs_inode *locked_ni)
1287 {
1288 	int ret = 0;
1289 	struct ntfs_inode *base_ni;
1290 
1291 	if (NInoAttr(ni))
1292 		base_ni = ni->ext.base_ntfs_ino;
1293 	else
1294 		base_ni = ni;
1295 
1296 	if (!NInoAttrList(base_ni)) {
1297 		ret = ntfs_inode_add_attrlist(base_ni);
1298 		if (ret) {
1299 			pr_err("Can not add attrlist\n");
1300 			goto out;
1301 		} else {
1302 			ret = -EAGAIN;
1303 			goto out;
1304 		}
1305 	}
1306 
1307 	ret = ntfs_attr_update_mapping_pairs_locked(ni, 0, locked_ni);
1308 	if (ret)
1309 		pr_err("MP update failed\n");
1310 
1311 out:
1312 	return ret;
1313 }
1314 
1315 /*
1316  * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1317  * @vol:	volume on which to extend the mft bitmap attribute
1318  *
1319  * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1320  *
1321  * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1322  * data_size.
1323  *
1324  * Return 0 on success and -errno on error.
1325  *
1326  * Locking: - Caller must hold vol->mftbmp_lock for writing.
1327  *	    - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1328  *	      writing and releases it before returning.
1329  *	    - This function takes vol->lcnbmp_lock for writing and releases it
1330  *	      before returning.
1331  */
1332 static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol)
1333 {
1334 	s64 lcn;
1335 	s64 ll;
1336 	unsigned long flags;
1337 	struct folio *folio;
1338 	struct ntfs_inode *mft_ni, *mftbmp_ni;
1339 	struct runlist_element *rl, *rl2 = NULL;
1340 	struct ntfs_attr_search_ctx *ctx = NULL;
1341 	struct mft_record *mrec;
1342 	struct attr_record *a = NULL;
1343 	int ret, mp_size;
1344 	u32 old_alen = 0;
1345 	u8 *b, tb;
1346 	struct {
1347 		u8 added_cluster:1;
1348 		u8 added_run:1;
1349 		u8 mp_rebuilt:1;
1350 		u8 mp_extended:1;
1351 	} status = { 0, 0, 0, 0 };
1352 	size_t new_rl_count;
1353 
1354 	ntfs_debug("Extending mft bitmap allocation.");
1355 	/* The initial bitmap scan must finish before we lock or change a folio. */
1356 	if (!NVolFreeClusterKnown(vol))
1357 		wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
1358 
1359 	mft_ni = NTFS_I(vol->mft_ino);
1360 	mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1361 	/*
1362 	 * Determine the last lcn of the mft bitmap.  The allocated size of the
1363 	 * mft bitmap cannot be zero so we are ok to do this.
1364 	 */
1365 	down_write(&mftbmp_ni->runlist.lock);
1366 	read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1367 	ll = mftbmp_ni->allocated_size;
1368 	read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1369 	rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1370 			NTFS_B_TO_CLU(vol, ll - 1), NULL);
1371 	if (IS_ERR(rl) || unlikely(!rl->length || rl->lcn < 0)) {
1372 		up_write(&mftbmp_ni->runlist.lock);
1373 		ntfs_error(vol->sb,
1374 			"Failed to determine last allocated cluster of mft bitmap attribute.");
1375 		if (!IS_ERR(rl))
1376 			ret = -EIO;
1377 		else
1378 			ret = PTR_ERR(rl);
1379 		return ret;
1380 	}
1381 	lcn = rl->lcn + rl->length;
1382 	ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1383 			(long long)lcn);
1384 	/* There is no adjacent cluster if the last run ends at the volume end. */
1385 	if (lcn >= vol->nr_clusters) {
1386 		lcn = -1;
1387 		goto alloc_cluster;
1388 	}
1389 	/*
1390 	 * Attempt to get the cluster following the last allocated cluster by
1391 	 * hand as it may be in the MFT zone so the allocator would not give it
1392 	 * to us.
1393 	 */
1394 	ll = lcn >> 3;
1395 	folio = read_mapping_folio(vol->lcnbmp_ino->i_mapping,
1396 			ll >> PAGE_SHIFT, NULL);
1397 	if (IS_ERR(folio)) {
1398 		up_write(&mftbmp_ni->runlist.lock);
1399 		ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1400 		return PTR_ERR(folio);
1401 	}
1402 
1403 	down_write(&vol->lcnbmp_lock);
1404 	folio_lock(folio);
1405 	b = (u8 *)kmap_local_folio(folio, 0) + (ll & ~PAGE_MASK);
1406 	tb = 1 << (lcn & 7ull);
1407 	/*
1408 	 * A page skipped by the initial scan has no free bits recorded.
1409 	 * Honor that and the space reserved for delayed allocation.
1410 	 */
1411 	if (*b != 0xff && !(*b & tb) &&
1412 	    vol->lcn_empty_bits_per_page[ll >> PAGE_SHIFT] &&
1413 	    ntfs_available_clusters_count(vol, 1) > 0) {
1414 		/* Next cluster is free, allocate it. */
1415 		*b |= tb;
1416 		folio_mark_dirty(folio);
1417 		ntfs_dec_free_clusters(vol, 1);
1418 		ntfs_set_lcn_empty_bits(vol, ll >> PAGE_SHIFT, 1, 1);
1419 		folio_unlock(folio);
1420 		kunmap_local(b);
1421 		folio_put(folio);
1422 		up_write(&vol->lcnbmp_lock);
1423 		/* Update the mft bitmap runlist. */
1424 		rl->length++;
1425 		rl[1].vcn++;
1426 		status.added_cluster = 1;
1427 		ntfs_debug("Appending one cluster to mft bitmap.");
1428 	} else {
1429 		folio_unlock(folio);
1430 		kunmap_local(b);
1431 		folio_put(folio);
1432 		up_write(&vol->lcnbmp_lock);
1433 alloc_cluster:
1434 		/* Allocate a cluster from the DATA_ZONE. */
1435 		rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
1436 				true, false, false);
1437 		if (IS_ERR(rl2)) {
1438 			up_write(&mftbmp_ni->runlist.lock);
1439 			ntfs_error(vol->sb,
1440 					"Failed to allocate a cluster for the mft bitmap.");
1441 			return PTR_ERR(rl2);
1442 		}
1443 		/* The adjacent cluster may have become available while unlocked. */
1444 		status.added_cluster = rl2->lcn == lcn;
1445 		rl = ntfs_runlists_merge(&mftbmp_ni->runlist, rl2, 0, &new_rl_count);
1446 		if (IS_ERR(rl)) {
1447 			up_write(&mftbmp_ni->runlist.lock);
1448 			ntfs_error(vol->sb, "Failed to merge runlists for mft bitmap.");
1449 			if (ntfs_cluster_free_from_rl(vol, rl2)) {
1450 				ntfs_error(vol->sb, "Failed to deallocate allocated cluster.%s",
1451 						es);
1452 				NVolSetErrors(vol);
1453 			}
1454 			kvfree(rl2);
1455 			return PTR_ERR(rl);
1456 		}
1457 		mftbmp_ni->runlist.rl = rl;
1458 		mftbmp_ni->runlist.count = new_rl_count;
1459 		status.added_run = !status.added_cluster;
1460 		ntfs_debug("Allocated one cluster for mft bitmap.");
1461 		/* Find the last run in the new runlist. */
1462 		for (; rl[1].length; rl++)
1463 			;
1464 	}
1465 	/*
1466 	 * Update the attribute record as well.  Note: @rl is the last
1467 	 * (non-terminator) runlist element of mft bitmap.
1468 	 */
1469 	mrec = map_mft_record(mft_ni);
1470 	if (IS_ERR(mrec)) {
1471 		ntfs_error(vol->sb, "Failed to map mft record.");
1472 		ret = PTR_ERR(mrec);
1473 		goto undo_alloc;
1474 	}
1475 	ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1476 	if (unlikely(!ctx)) {
1477 		ntfs_error(vol->sb, "Failed to get search context.");
1478 		ret = -ENOMEM;
1479 		goto undo_alloc;
1480 	}
1481 	ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1482 			mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1483 			0, ctx);
1484 	if (unlikely(ret)) {
1485 		ntfs_error(vol->sb,
1486 			"Failed to find last attribute extent of mft bitmap attribute.");
1487 		if (ret == -ENOENT)
1488 			ret = -EIO;
1489 		goto undo_alloc;
1490 	}
1491 	a = ctx->attr;
1492 	ll = le64_to_cpu(a->data.non_resident.lowest_vcn);
1493 	/* Search back for the previous last allocated cluster of mft bitmap. */
1494 	for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1495 		if (ll >= rl2->vcn)
1496 			break;
1497 	}
1498 	WARN_ON(ll < rl2->vcn);
1499 	WARN_ON(ll >= rl2->vcn + rl2->length);
1500 	/* Get the size for the new mapping pairs array for this extent. */
1501 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1, -1);
1502 	if (unlikely(mp_size <= 0)) {
1503 		ntfs_error(vol->sb,
1504 			"Get size for mapping pairs failed for mft bitmap attribute extent.");
1505 		ret = mp_size;
1506 		if (!ret)
1507 			ret = -EIO;
1508 		goto undo_alloc;
1509 	}
1510 	/* Expand the attribute record if necessary. */
1511 	old_alen = le32_to_cpu(a->length);
1512 	ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1513 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1514 	if (unlikely(ret)) {
1515 		ret = ntfs_mft_attr_extend(mftbmp_ni, mftbmp_ni);
1516 		if (!ret)
1517 			goto extended_ok;
1518 		if (ret != -EAGAIN)
1519 			status.mp_extended = 1;
1520 		goto undo_alloc;
1521 	}
1522 	status.mp_rebuilt = 1;
1523 	/* Generate the mapping pairs array directly into the attr record. */
1524 	ret = ntfs_mapping_pairs_build(vol, (u8 *)a +
1525 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1526 			mp_size, rl2, ll, -1, NULL, NULL, NULL);
1527 	if (unlikely(ret)) {
1528 		ntfs_error(vol->sb,
1529 			"Failed to build mapping pairs array for mft bitmap attribute.");
1530 		goto undo_alloc;
1531 	}
1532 	/* Update the highest_vcn. */
1533 	a->data.non_resident.highest_vcn = cpu_to_le64(rl[1].vcn - 1);
1534 	/*
1535 	 * We now have extended the mft bitmap allocated_size by one cluster.
1536 	 * Reflect this in the struct ntfs_inode structure and the attribute record.
1537 	 */
1538 	if (a->data.non_resident.lowest_vcn) {
1539 		/*
1540 		 * We are not in the first attribute extent, switch to it, but
1541 		 * first ensure the changes will make it to disk later.
1542 		 */
1543 		mark_mft_record_dirty(ctx->ntfs_ino);
1544 extended_ok:
1545 		ntfs_attr_reinit_search_ctx(ctx);
1546 		ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1547 				mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1548 				0, ctx);
1549 		if (unlikely(ret)) {
1550 			ntfs_error(vol->sb,
1551 				"Failed to find first attribute extent of mft bitmap attribute.");
1552 			goto restore_undo_alloc;
1553 		}
1554 		a = ctx->attr;
1555 	}
1556 
1557 	write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1558 	mftbmp_ni->allocated_size += vol->cluster_size;
1559 	a->data.non_resident.allocated_size =
1560 			cpu_to_le64(mftbmp_ni->allocated_size);
1561 	write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1562 	/* Ensure the changes make it to disk. */
1563 	mark_mft_record_dirty(ctx->ntfs_ino);
1564 	ntfs_attr_put_search_ctx(ctx);
1565 	unmap_mft_record(mft_ni);
1566 	up_write(&mftbmp_ni->runlist.lock);
1567 	ntfs_debug("Done.");
1568 	return 0;
1569 
1570 restore_undo_alloc:
1571 	ntfs_attr_reinit_search_ctx(ctx);
1572 	if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1573 			mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1574 			0, ctx)) {
1575 		ntfs_error(vol->sb,
1576 			"Failed to find last attribute extent of mft bitmap attribute.%s", es);
1577 		write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1578 		mftbmp_ni->allocated_size += vol->cluster_size;
1579 		write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1580 		ntfs_attr_put_search_ctx(ctx);
1581 		unmap_mft_record(mft_ni);
1582 		up_write(&mftbmp_ni->runlist.lock);
1583 		/*
1584 		 * The only thing that is now wrong is ->allocated_size of the
1585 		 * base attribute extent which chkdsk should be able to fix.
1586 		 */
1587 		NVolSetErrors(vol);
1588 		return ret;
1589 	}
1590 	a = ctx->attr;
1591 	a->data.non_resident.highest_vcn = cpu_to_le64(rl[1].vcn - 2);
1592 undo_alloc:
1593 	if (status.added_cluster) {
1594 		/* Truncate the last run in the runlist by one cluster. */
1595 		rl->length--;
1596 		rl[1].vcn--;
1597 	} else if (status.added_run) {
1598 		lcn = rl->lcn;
1599 		/* Remove the last run from the runlist. */
1600 		rl->lcn = rl[1].lcn;
1601 		rl->length = 0;
1602 		mftbmp_ni->runlist.count--;
1603 	}
1604 	/* Deallocate the cluster. */
1605 	down_write(&vol->lcnbmp_lock);
1606 	if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1607 		ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1608 		NVolSetErrors(vol);
1609 	} else
1610 		ntfs_inc_free_clusters(vol, 1);
1611 	up_write(&vol->lcnbmp_lock);
1612 	if (status.mp_rebuilt) {
1613 		if (ntfs_mapping_pairs_build(vol, (u8 *)a + le16_to_cpu(
1614 				a->data.non_resident.mapping_pairs_offset),
1615 				old_alen - le16_to_cpu(
1616 				a->data.non_resident.mapping_pairs_offset),
1617 				rl2, ll, -1, NULL, NULL, NULL)) {
1618 			ntfs_error(vol->sb, "Failed to restore mapping pairs array.%s", es);
1619 			NVolSetErrors(vol);
1620 		}
1621 		if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1622 			ntfs_error(vol->sb, "Failed to restore attribute record.%s", es);
1623 			NVolSetErrors(vol);
1624 		}
1625 		mark_mft_record_dirty(ctx->ntfs_ino);
1626 	} else if (status.mp_extended &&
1627 		   ntfs_attr_update_mapping_pairs_locked(mftbmp_ni, 0,
1628 							  mftbmp_ni)) {
1629 		ntfs_error(vol->sb, "Failed to restore mapping pairs.%s", es);
1630 		NVolSetErrors(vol);
1631 	}
1632 	if (ctx)
1633 		ntfs_attr_put_search_ctx(ctx);
1634 	if (!IS_ERR(mrec))
1635 		unmap_mft_record(mft_ni);
1636 	up_write(&mftbmp_ni->runlist.lock);
1637 	return ret;
1638 }
1639 
1640 /*
1641  * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1642  * @vol:	volume on which to extend the mft bitmap attribute
1643  *
1644  * Extend the initialized portion of the mft bitmap attribute on the ntfs
1645  * volume @vol by 8 bytes.
1646  *
1647  * Note:  Only changes initialized_size and data_size, i.e. requires that
1648  * allocated_size is big enough to fit the new initialized_size.
1649  *
1650  * Return 0 on success and -error on error.
1651  *
1652  * Locking: Caller must hold vol->mftbmp_lock for writing.
1653  */
1654 static int ntfs_mft_bitmap_extend_initialized_nolock(struct ntfs_volume *vol)
1655 {
1656 	s64 old_data_size, old_initialized_size;
1657 	unsigned long flags;
1658 	struct inode *mftbmp_vi;
1659 	struct ntfs_inode *mft_ni, *mftbmp_ni;
1660 	struct ntfs_attr_search_ctx *ctx;
1661 	struct mft_record *mrec;
1662 	struct attr_record *a;
1663 	int ret;
1664 
1665 	ntfs_debug("Extending mft bitmap initialized (and data) size.");
1666 	mft_ni = NTFS_I(vol->mft_ino);
1667 	mftbmp_vi = vol->mftbmp_ino;
1668 	mftbmp_ni = NTFS_I(mftbmp_vi);
1669 	/* Get the attribute record. */
1670 	mrec = map_mft_record(mft_ni);
1671 	if (IS_ERR(mrec)) {
1672 		ntfs_error(vol->sb, "Failed to map mft record.");
1673 		return PTR_ERR(mrec);
1674 	}
1675 	ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1676 	if (unlikely(!ctx)) {
1677 		ntfs_error(vol->sb, "Failed to get search context.");
1678 		ret = -ENOMEM;
1679 		goto unm_err_out;
1680 	}
1681 	ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1682 			mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1683 	if (unlikely(ret)) {
1684 		ntfs_error(vol->sb,
1685 			"Failed to find first attribute extent of mft bitmap attribute.");
1686 		if (ret == -ENOENT)
1687 			ret = -EIO;
1688 		goto put_err_out;
1689 	}
1690 	a = ctx->attr;
1691 	write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1692 	old_data_size = i_size_read(mftbmp_vi);
1693 	old_initialized_size = mftbmp_ni->initialized_size;
1694 	/*
1695 	 * We can simply update the initialized_size before filling the space
1696 	 * with zeroes because the caller is holding the mft bitmap lock for
1697 	 * writing which ensures that no one else is trying to access the data.
1698 	 */
1699 	mftbmp_ni->initialized_size += 8;
1700 	a->data.non_resident.initialized_size =
1701 			cpu_to_le64(mftbmp_ni->initialized_size);
1702 	if (mftbmp_ni->initialized_size > old_data_size) {
1703 		i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1704 		a->data.non_resident.data_size =
1705 				cpu_to_le64(mftbmp_ni->initialized_size);
1706 	}
1707 	write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1708 	/* Ensure the changes make it to disk. */
1709 	mark_mft_record_dirty(ctx->ntfs_ino);
1710 	ntfs_attr_put_search_ctx(ctx);
1711 	unmap_mft_record(mft_ni);
1712 	/* Initialize the mft bitmap attribute value with zeroes. */
1713 	ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1714 	if (likely(!ret)) {
1715 		ntfs_debug("Done.  (Wrote eight initialized bytes to mft bitmap.");
1716 		return 0;
1717 	}
1718 	ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1719 	/* Try to recover from the error. */
1720 	mrec = map_mft_record(mft_ni);
1721 	if (IS_ERR(mrec)) {
1722 		ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1723 		NVolSetErrors(vol);
1724 		return ret;
1725 	}
1726 	ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1727 	if (unlikely(!ctx)) {
1728 		ntfs_error(vol->sb, "Failed to get search context.%s", es);
1729 		NVolSetErrors(vol);
1730 		goto unm_err_out;
1731 	}
1732 	if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1733 			mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1734 		ntfs_error(vol->sb,
1735 			"Failed to find first attribute extent of mft bitmap attribute.%s", es);
1736 		NVolSetErrors(vol);
1737 put_err_out:
1738 		ntfs_attr_put_search_ctx(ctx);
1739 unm_err_out:
1740 		unmap_mft_record(mft_ni);
1741 		goto err_out;
1742 	}
1743 	a = ctx->attr;
1744 	write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1745 	mftbmp_ni->initialized_size = old_initialized_size;
1746 	a->data.non_resident.initialized_size =
1747 			cpu_to_le64(old_initialized_size);
1748 	if (i_size_read(mftbmp_vi) != old_data_size) {
1749 		i_size_write(mftbmp_vi, old_data_size);
1750 		a->data.non_resident.data_size = cpu_to_le64(old_data_size);
1751 	}
1752 	write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1753 	mark_mft_record_dirty(ctx->ntfs_ino);
1754 	ntfs_attr_put_search_ctx(ctx);
1755 	unmap_mft_record(mft_ni);
1756 #ifdef DEBUG
1757 	read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1758 	ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
1759 			mftbmp_ni->allocated_size, i_size_read(mftbmp_vi),
1760 			mftbmp_ni->initialized_size);
1761 	read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1762 #endif /* DEBUG */
1763 err_out:
1764 	return ret;
1765 }
1766 
1767 /*
1768  * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1769  * @vol:	volume on which to extend the mft data attribute
1770  *
1771  * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1772  * worth of clusters or if not enough space for this by two mft records worth
1773  * of clusters. Keeping at least two new records breaks the recursion between
1774  * extending $MFT and allocating a record for a new $MFT attribute extent.
1775  *
1776  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
1777  * data_size.
1778  *
1779  * Return 0 on success and -errno on error.
1780  *
1781  * Locking: - Caller must hold vol->mftbmp_lock for writing.
1782  *	    - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1783  *	      writing and releases it before returning.
1784  *	    - This function calls functions which take vol->lcnbmp_lock for
1785  *	      writing and release it before returning.
1786  */
1787 static int ntfs_mft_data_extend_allocation_nolock(struct ntfs_volume *vol)
1788 {
1789 	s64 lcn;
1790 	s64 old_last_vcn;
1791 	s64 min_nr, nr, ll;
1792 	unsigned long flags;
1793 	struct ntfs_inode *mft_ni;
1794 	struct runlist_element *rl, *rl2, *alloc_rl;
1795 	struct ntfs_attr_search_ctx *ctx = NULL;
1796 	struct mft_record *mrec;
1797 	struct attr_record *a = NULL;
1798 	int ret, mp_size;
1799 	u32 old_alen = 0;
1800 	bool mp_rebuilt = false, mp_extended = false;
1801 	size_t new_rl_count;
1802 
1803 	ntfs_debug("Extending mft data allocation.");
1804 	mft_ni = NTFS_I(vol->mft_ino);
1805 	/*
1806 	 * Determine the preferred allocation location, i.e. the last lcn of
1807 	 * the mft data attribute.  The allocated size of the mft data
1808 	 * attribute cannot be zero so we are ok to do this.
1809 	 */
1810 	down_write(&mft_ni->runlist.lock);
1811 	read_lock_irqsave(&mft_ni->size_lock, flags);
1812 	ll = mft_ni->allocated_size;
1813 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
1814 	rl = ntfs_attr_find_vcn_nolock(mft_ni,
1815 			NTFS_B_TO_CLU(vol, ll - 1), NULL);
1816 	if (IS_ERR(rl) || unlikely(!rl->length || rl->lcn < 0)) {
1817 		up_write(&mft_ni->runlist.lock);
1818 		ntfs_error(vol->sb,
1819 			"Failed to determine last allocated cluster of mft data attribute.");
1820 		if (!IS_ERR(rl))
1821 			ret = -EIO;
1822 		else
1823 			ret = PTR_ERR(rl);
1824 		return ret;
1825 	}
1826 	lcn = rl->lcn + rl->length;
1827 	ntfs_debug("Last lcn of mft data attribute is 0x%llx.", lcn);
1828 	/* Keep room for the allocating record and at least one MFT reserve. */
1829 	min_nr = DIV_ROUND_UP_ULL((u64)vol->mft_record_size * 2, vol->cluster_size);
1830 	/* Want to allocate 16 mft records worth of clusters. */
1831 	nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1832 	if (!nr)
1833 		nr = min_nr;
1834 	/* Ensure we do not go above 2^32-1 mft records. */
1835 	read_lock_irqsave(&mft_ni->size_lock, flags);
1836 	ll = mft_ni->allocated_size;
1837 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
1838 	if (unlikely((ll + NTFS_CLU_TO_B(vol, nr)) >>
1839 			vol->mft_record_size_bits >= (1ll << 32))) {
1840 		nr = min_nr;
1841 		if (unlikely((ll + NTFS_CLU_TO_B(vol, nr)) >>
1842 				vol->mft_record_size_bits >= (1ll << 32))) {
1843 			ntfs_warning(vol->sb,
1844 				"Cannot allocate mft record because the maximum number of inodes (2^32) has already been reached.");
1845 			up_write(&mft_ni->runlist.lock);
1846 			return -ENOSPC;
1847 		}
1848 	}
1849 	ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1850 			nr > min_nr ? "default" : "minimal", (long long)nr);
1851 	old_last_vcn = rl[1].vcn;
1852 	/*
1853 	 * We can release the mft_ni runlist lock, Because this function is
1854 	 * the only one that expends $MFT data attribute and is called with
1855 	 * mft_ni->mrec_lock.
1856 	 * This is required for the lock order, vol->lcnbmp_lock =>
1857 	 * mft_ni->runlist.lock.
1858 	 */
1859 	up_write(&mft_ni->runlist.lock);
1860 
1861 	do {
1862 		alloc_rl = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn,
1863 				MFT_ZONE, true, false, false);
1864 		if (!IS_ERR(alloc_rl))
1865 			break;
1866 		if (PTR_ERR(alloc_rl) != -ENOSPC || nr == min_nr) {
1867 			ntfs_error(vol->sb,
1868 				"Failed to allocate the minimal number of clusters (%lli) for the mft data attribute.",
1869 				nr);
1870 			return PTR_ERR(alloc_rl);
1871 		}
1872 		/*
1873 		 * There is not enough space to do the allocation, but there
1874 		 * might be enough space to do a minimal allocation so try that
1875 		 * before failing.
1876 		 */
1877 		nr = min_nr;
1878 		ntfs_debug("Retrying mft data allocation with minimal cluster count %lli.", nr);
1879 	} while (1);
1880 
1881 	/*
1882 	 * Keep @alloc_rl until the extension is complete: it describes exactly
1883 	 * the new clusters, which undo_alloc frees if a later step fails.
1884 	 */
1885 	down_write(&mft_ni->runlist.lock);
1886 	rl = ntfs_runlists_merge_keep_src(&mft_ni->runlist, alloc_rl, 0,
1887 			&new_rl_count);
1888 	if (IS_ERR(rl)) {
1889 		up_write(&mft_ni->runlist.lock);
1890 		ntfs_error(vol->sb, "Failed to merge runlists for mft data attribute.");
1891 		if (ntfs_cluster_free_from_rl(vol, alloc_rl)) {
1892 			ntfs_error(vol->sb,
1893 				"Failed to deallocate clusters from the mft data attribute.%s", es);
1894 			NVolSetErrors(vol);
1895 		}
1896 		kvfree(alloc_rl);
1897 		return PTR_ERR(rl);
1898 	}
1899 	mft_ni->runlist.rl = rl;
1900 	mft_ni->runlist.count = new_rl_count;
1901 	ntfs_debug("Allocated %lli clusters.", (long long)nr);
1902 	/* Find the last run in the new runlist. */
1903 	for (; rl[1].length; rl++)
1904 		;
1905 	up_write(&mft_ni->runlist.lock);
1906 
1907 	/* Update the attribute record as well. */
1908 	mrec = map_mft_record(mft_ni);
1909 	if (IS_ERR(mrec)) {
1910 		ntfs_error(vol->sb, "Failed to map mft record.");
1911 		ret = PTR_ERR(mrec);
1912 		goto undo_alloc;
1913 	}
1914 	ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1915 	if (unlikely(!ctx)) {
1916 		ntfs_error(vol->sb, "Failed to get search context.");
1917 		ret = -ENOMEM;
1918 		goto undo_alloc;
1919 	}
1920 	ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1921 			CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1922 	if (unlikely(ret)) {
1923 		ntfs_error(vol->sb, "Failed to find last attribute extent of mft data attribute.");
1924 		if (ret == -ENOENT)
1925 			ret = -EIO;
1926 		goto undo_alloc;
1927 	}
1928 	a = ctx->attr;
1929 	ll = le64_to_cpu(a->data.non_resident.lowest_vcn);
1930 
1931 	down_write(&mft_ni->runlist.lock);
1932 	/* Search back for the previous last allocated cluster of mft bitmap. */
1933 	for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1934 		if (ll >= rl2->vcn)
1935 			break;
1936 	}
1937 	WARN_ON(ll < rl2->vcn);
1938 	WARN_ON(ll >= rl2->vcn + rl2->length);
1939 	/* Get the size for the new mapping pairs array for this extent. */
1940 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1, -1);
1941 	if (unlikely(mp_size <= 0)) {
1942 		ntfs_error(vol->sb,
1943 			"Get size for mapping pairs failed for mft data attribute extent.");
1944 		ret = mp_size;
1945 		if (!ret)
1946 			ret = -EIO;
1947 		up_write(&mft_ni->runlist.lock);
1948 		goto undo_alloc;
1949 	}
1950 	up_write(&mft_ni->runlist.lock);
1951 
1952 	/* Expand the attribute record if necessary. */
1953 	old_alen = le32_to_cpu(a->length);
1954 	ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1955 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1956 	if (unlikely(ret)) {
1957 		ret = ntfs_mft_attr_extend(mft_ni, NULL);
1958 		if (!ret)
1959 			goto extended_ok;
1960 		if (ret != -EAGAIN)
1961 			mp_extended = true;
1962 		goto undo_alloc;
1963 	}
1964 	mp_rebuilt = true;
1965 	/* Generate the mapping pairs array directly into the attr record. */
1966 	ret = ntfs_mapping_pairs_build(vol, (u8 *)a +
1967 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1968 			mp_size, rl2, ll, -1, NULL, NULL, NULL);
1969 	if (unlikely(ret)) {
1970 		ntfs_error(vol->sb, "Failed to build mapping pairs array of mft data attribute.");
1971 		goto undo_alloc;
1972 	}
1973 	/* Update the highest_vcn. */
1974 	a->data.non_resident.highest_vcn = cpu_to_le64(rl[1].vcn - 1);
1975 	/*
1976 	 * We now have extended the mft data allocated_size by nr clusters.
1977 	 * Reflect this in the struct ntfs_inode structure and the attribute record.
1978 	 * @rl is the last (non-terminator) runlist element of mft data
1979 	 * attribute.
1980 	 */
1981 	if (a->data.non_resident.lowest_vcn) {
1982 		/*
1983 		 * We are not in the first attribute extent, switch to it, but
1984 		 * first ensure the changes will make it to disk later.
1985 		 */
1986 		mark_mft_record_dirty(ctx->ntfs_ino);
1987 extended_ok:
1988 		ntfs_attr_reinit_search_ctx(ctx);
1989 		ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1990 				mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1991 				ctx);
1992 		if (unlikely(ret)) {
1993 			ntfs_error(vol->sb,
1994 				"Failed to find first attribute extent of mft data attribute.");
1995 			goto restore_undo_alloc;
1996 		}
1997 		a = ctx->attr;
1998 	}
1999 
2000 	write_lock_irqsave(&mft_ni->size_lock, flags);
2001 	mft_ni->allocated_size += NTFS_CLU_TO_B(vol, nr);
2002 	a->data.non_resident.allocated_size =
2003 			cpu_to_le64(mft_ni->allocated_size);
2004 	write_unlock_irqrestore(&mft_ni->size_lock, flags);
2005 	/* Ensure the changes make it to disk. */
2006 	mark_mft_record_dirty(ctx->ntfs_ino);
2007 	ntfs_attr_put_search_ctx(ctx);
2008 	unmap_mft_record(mft_ni);
2009 	kvfree(alloc_rl);
2010 	ntfs_debug("Done.");
2011 	return 0;
2012 restore_undo_alloc:
2013 	ntfs_attr_reinit_search_ctx(ctx);
2014 	if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2015 			CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
2016 		ntfs_error(vol->sb,
2017 			"Failed to find last attribute extent of mft data attribute.%s", es);
2018 		write_lock_irqsave(&mft_ni->size_lock, flags);
2019 		mft_ni->allocated_size += NTFS_CLU_TO_B(vol, nr);
2020 		write_unlock_irqrestore(&mft_ni->size_lock, flags);
2021 		ntfs_attr_put_search_ctx(ctx);
2022 		unmap_mft_record(mft_ni);
2023 		kvfree(alloc_rl);
2024 		/*
2025 		 * The only thing that is now wrong is ->allocated_size of the
2026 		 * base attribute extent which chkdsk should be able to fix.
2027 		 */
2028 		NVolSetErrors(vol);
2029 		return ret;
2030 	}
2031 	ctx->attr->data.non_resident.highest_vcn =
2032 			cpu_to_le64(old_last_vcn - 1);
2033 undo_alloc:
2034 	/*
2035 	 * Entered without the runlist lock.  Take the new runs off the
2036 	 * runlist under it, and free their clusters from @alloc_rl once it
2037 	 * is dropped, as lcnbmp_lock nests outside it (see above).
2038 	 */
2039 	down_write(&mft_ni->runlist.lock);
2040 	if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
2041 		ntfs_error(vol->sb, "Failed to truncate mft data attribute runlist.%s", es);
2042 		NVolSetErrors(vol);
2043 		/*
2044 		 * The runlist may still reference the clusters, so leave them
2045 		 * allocated until chkdsk.
2046 		 */
2047 		kvfree(alloc_rl);
2048 		alloc_rl = NULL;
2049 	}
2050 	up_write(&mft_ni->runlist.lock);
2051 	if (ntfs_cluster_free_from_rl(vol, alloc_rl)) {
2052 		ntfs_error(vol->sb, "Failed to free clusters from mft data attribute.%s", es);
2053 		NVolSetErrors(vol);
2054 	}
2055 	kvfree(alloc_rl);
2056 	if (mp_extended && ntfs_attr_update_mapping_pairs(mft_ni, 0)) {
2057 		ntfs_error(vol->sb, "Failed to restore mapping pairs.%s",
2058 			   es);
2059 		NVolSetErrors(vol);
2060 	}
2061 	if (ctx) {
2062 		a = ctx->attr;
2063 		if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
2064 			int err;
2065 
2066 			down_read(&mft_ni->runlist.lock);
2067 			err = ntfs_mapping_pairs_build(vol, (u8 *)a + le16_to_cpu(
2068 				a->data.non_resident.mapping_pairs_offset),
2069 				old_alen - le16_to_cpu(
2070 					a->data.non_resident.mapping_pairs_offset),
2071 				mft_ni->runlist.rl, ll, -1, NULL, NULL, NULL);
2072 			up_read(&mft_ni->runlist.lock);
2073 			if (err) {
2074 				ntfs_error(vol->sb, "Failed to restore mapping pairs array.%s", es);
2075 				NVolSetErrors(vol);
2076 			}
2077 			if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
2078 				ntfs_error(vol->sb, "Failed to restore attribute record.%s", es);
2079 				NVolSetErrors(vol);
2080 			}
2081 			mark_mft_record_dirty(ctx->ntfs_ino);
2082 		} else if (IS_ERR(ctx->mrec)) {
2083 			ntfs_error(vol->sb, "Failed to restore attribute search context.%s", es);
2084 			NVolSetErrors(vol);
2085 		}
2086 		ntfs_attr_put_search_ctx(ctx);
2087 	}
2088 	if (!IS_ERR(mrec))
2089 		unmap_mft_record(mft_ni);
2090 	return ret;
2091 }
2092 
2093 /*
2094  * ntfs_mft_record_layout - layout an mft record into a memory buffer
2095  * @vol:	volume to which the mft record will belong
2096  * @mft_no:	mft reference specifying the mft record number
2097  * @m:		destination buffer of size >= @vol->mft_record_size bytes
2098  *
2099  * Layout an empty, unused mft record with the mft record number @mft_no into
2100  * the buffer @m.  The volume @vol is needed because the mft record structure
2101  * was modified in NTFS 3.1 so we need to know which volume version this mft
2102  * record will be used on.
2103  *
2104  * Return 0 on success and -errno on error.
2105  */
2106 static int ntfs_mft_record_layout(const struct ntfs_volume *vol, const s64 mft_no,
2107 		struct mft_record *m)
2108 {
2109 	struct attr_record *a;
2110 
2111 	ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2112 	if (mft_no >= (1ll << 32)) {
2113 		ntfs_error(vol->sb, "Mft record number 0x%llx exceeds maximum of 2^32.",
2114 				(long long)mft_no);
2115 		return -ERANGE;
2116 	}
2117 	/* Start by clearing the whole mft record to gives us a clean slate. */
2118 	memset(m, 0, vol->mft_record_size);
2119 	/* Aligned to 2-byte boundary. */
2120 	if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2121 		m->usa_ofs = cpu_to_le16((sizeof(struct mft_record_old) + 1) & ~1);
2122 	else {
2123 		m->usa_ofs = cpu_to_le16((sizeof(struct mft_record) + 1) & ~1);
2124 		/*
2125 		 * Set the NTFS 3.1+ specific fields while we know that the
2126 		 * volume version is 3.1+.
2127 		 */
2128 		m->reserved = 0;
2129 		m->mft_record_number = cpu_to_le32((u32)mft_no);
2130 	}
2131 	m->magic = magic_FILE;
2132 	if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2133 		m->usa_count = cpu_to_le16(vol->mft_record_size /
2134 				NTFS_BLOCK_SIZE + 1);
2135 	else {
2136 		m->usa_count = cpu_to_le16(1);
2137 		ntfs_warning(vol->sb,
2138 			"Sector size is bigger than mft record size.  Setting usa_count to 1.  If chkdsk reports this as corruption");
2139 	}
2140 	/* Set the update sequence number to 1. */
2141 	*(__le16 *)((u8 *)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2142 	m->lsn = 0;
2143 	m->sequence_number = cpu_to_le16(1);
2144 	m->link_count = 0;
2145 	/*
2146 	 * Place the attributes straight after the update sequence array,
2147 	 * aligned to 8-byte boundary.
2148 	 */
2149 	m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2150 			(le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2151 	m->flags = 0;
2152 	/*
2153 	 * Using attrs_offset plus eight bytes (for the termination attribute).
2154 	 * attrs_offset is already aligned to 8-byte boundary, so no need to
2155 	 * align again.
2156 	 */
2157 	m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2158 	m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2159 	m->base_mft_record = 0;
2160 	m->next_attr_instance = 0;
2161 	/* Add the termination attribute. */
2162 	a = (struct attr_record *)((u8 *)m + le16_to_cpu(m->attrs_offset));
2163 	a->type = AT_END;
2164 	a->length = 0;
2165 	ntfs_debug("Done.");
2166 	return 0;
2167 }
2168 
2169 /*
2170  * ntfs_mft_record_format - format an mft record on an ntfs volume
2171  * @vol:	volume on which to format the mft record
2172  * @mft_no:	mft record number to format
2173  *
2174  * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2175  * mft record into the appropriate place of the mft data attribute.  This is
2176  * used when extending the mft data attribute.
2177  *
2178  * Return 0 on success and -errno on error.
2179  */
2180 static int ntfs_mft_record_format(const struct ntfs_volume *vol, const s64 mft_no)
2181 {
2182 	loff_t i_size;
2183 	struct inode *mft_vi = vol->mft_ino;
2184 	struct folio *folio;
2185 	struct mft_record *m;
2186 	pgoff_t index, end_index;
2187 	unsigned int ofs;
2188 	int err;
2189 
2190 	ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2191 	/*
2192 	 * The index into the page cache and the offset within the page cache
2193 	 * page of the wanted mft record.
2194 	 */
2195 	index = NTFS_MFT_NR_TO_PIDX(vol, mft_no);
2196 	ofs = NTFS_MFT_NR_TO_POFS(vol, mft_no);
2197 	/* The maximum valid index into the page cache for $MFT's data. */
2198 	i_size = i_size_read(mft_vi);
2199 	end_index = i_size >> PAGE_SHIFT;
2200 	if (unlikely(index >= end_index)) {
2201 		if (unlikely(index > end_index ||
2202 			     ofs + vol->mft_record_size > (i_size & ~PAGE_MASK))) {
2203 			ntfs_error(vol->sb, "Tried to format non-existing mft record 0x%llx.",
2204 					(long long)mft_no);
2205 			return -ENOENT;
2206 		}
2207 	}
2208 
2209 	/* Read, map, and pin the folio containing the mft record. */
2210 	folio = read_mapping_folio(mft_vi->i_mapping, index, NULL);
2211 	if (IS_ERR(folio)) {
2212 		ntfs_error(vol->sb, "Failed to map page containing mft record to format 0x%llx.",
2213 				(long long)mft_no);
2214 		return PTR_ERR(folio);
2215 	}
2216 	folio_lock(folio);
2217 	if (folio_test_writeback(folio))
2218 		folio_wait_writeback(folio);
2219 	folio_clear_uptodate(folio);
2220 	m = (struct mft_record *)((u8 *)kmap_local_folio(folio, 0) + ofs);
2221 	err = ntfs_mft_record_layout(vol, mft_no, m);
2222 	if (unlikely(err)) {
2223 		ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2224 				(long long)mft_no);
2225 		folio_mark_uptodate(folio);
2226 		folio_unlock(folio);
2227 		kunmap_local(m);
2228 		folio_put(folio);
2229 		return err;
2230 	}
2231 	pre_write_mst_fixup((struct ntfs_record *)m, vol->mft_record_size);
2232 	folio_mark_uptodate(folio);
2233 	/*
2234 	 * Make sure the mft record is written out to disk.  We could use
2235 	 * ilookup5() to check if an inode is in icache and so on but this is
2236 	 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2237 	 */
2238 	ntfs_mft_mark_dirty(folio);
2239 	folio_unlock(folio);
2240 	kunmap_local(m);
2241 	folio_put(folio);
2242 	ntfs_debug("Done.");
2243 	return 0;
2244 }
2245 
2246 /*
2247  * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2248  * @vol:	[IN]  volume on which to allocate the mft record
2249  * @mode:	[IN]  mode if want a file or directory, i.e. base inode or 0
2250  * @ni:		[OUT] on success, set to the allocated ntfs inode
2251  * @base_ni:	[IN]  open base inode if allocating an extent mft record or NULL
2252  * @ni_mrec:	[OUT] on successful return this is the mapped mft record
2253  * @mft_data_vcn: [IN] lowest VCN of a new $MFT/$DATA extent, or -1
2254  *
2255  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2256  *
2257  * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2258  * direvctory inode, and allocate it at the default allocator position.  In
2259  * this case @mode is the file mode as given to us by the caller.  We in
2260  * particular use @mode to distinguish whether a file or a directory is being
2261  * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2262  *
2263  * If @base_ni is not NULL make the allocated mft record an extent record,
2264  * allocate it starting at the mft record after the base mft record and attach
2265  * the allocated and opened ntfs inode to the base inode @base_ni.  In this
2266  * case @mode must be 0 as it is meaningless for extent inodes.
2267  *
2268  * You need to check the return value with IS_ERR().  If false, the function
2269  * was successful and the return value is the now opened ntfs inode of the
2270  * allocated mft record.  *@mrec is then set to the allocated, mapped, pinned,
2271  * and locked mft record.  If IS_ERR() is true, the function failed and the
2272  * error code is obtained from PTR_ERR(return value).  *@mrec is undefined in
2273  * this case.
2274  *
2275  * Allocation strategy:
2276  *
2277  * To find a free mft record, we scan the mft bitmap for a zero bit.  To
2278  * optimize this we start scanning at the place specified by @base_ni or if
2279  * @base_ni is NULL we start where we last stopped and we perform wrap around
2280  * when we reach the end.  Note, we do not try to allocate mft records below
2281  * number 24 because numbers 0 to 15 are the defined system files and records
2282  * 16 to 23 are kept for metadata compatibility. Records reserved dynamically
2283  * at the initialized MFT tail are skipped by normal allocation and consumed by
2284  * $MFT metadata extent allocation.
2285  *
2286  * When scanning the mft bitmap, we only search up to the last allocated mft
2287  * record.  If there are no free records left in the range 24 to number of
2288  * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2289  * create free mft records.  We extend the allocated size of $MFT/$DATA by 16
2290  * records at a time or one cluster, if cluster size is above 16kiB.  If there
2291  * is not sufficient space to do this, we try to extend by two mft records or
2292  * one cluster, if a cluster already contains at least two mft records.
2293  *
2294  * When extending the initialized MFT tail, we also initialize up to four
2295  * additional records and reserve them in memory for future $MFT metadata
2296  * extents.  If there are less than 24 mft records, records are initialized
2297  * until record 24, which is the first record used for normal files.
2298  *
2299  * If during any stage we overflow the initialized data in the mft bitmap, we
2300  * extend the initialized size (and data size) by 8 bytes, allocating another
2301  * cluster if required.  The bitmap data size has to be at least equal to the
2302  * number of mft records in the mft, but it can be bigger, in which case the
2303  * superfluous bits are padded with zeroes.
2304  *
2305  * Thus, when we return successfully (IS_ERR() is false), we will have:
2306  *	- initialized / extended the mft bitmap if necessary,
2307  *	- initialized / extended the mft data if necessary,
2308  *	- set the bit corresponding to the mft record being allocated in the
2309  *	  mft bitmap,
2310  *	- opened an struct ntfs_inode for the allocated mft record, and we will have
2311  *	- returned the struct ntfs_inode as well as the allocated mapped, pinned, and
2312  *	  locked mft record.
2313  *
2314  * On error, the volume will be left in a consistent state and no record will
2315  * be allocated.  If rolling back a partial operation fails, we may leave some
2316  * inconsistent metadata in which case we set NVolErrors() so the volume is
2317  * left dirty when unmounted.
2318  *
2319  * Note, this function cannot make use of most of the normal functions, like
2320  * for example for attribute resizing, etc, because when the run list overflows
2321  * the base mft record and an attribute list is used, it is very important that
2322  * the extension mft records used to store the $DATA attribute of $MFT can be
2323  * reached without having to read the information contained inside them, as
2324  * this would make it impossible to find them in the first place after the
2325  * volume is unmounted.  $MFT/$BITMAP probably does not need to follow this
2326  * rule because the bitmap is not essential for finding the mft records, but on
2327  * the other hand, handling the bitmap in this special way would make life
2328  * easier because otherwise there might be circular invocations of functions
2329  * when reading the bitmap.
2330  */
2331 int ntfs_mft_record_alloc(struct ntfs_volume *vol, const int mode,
2332 			  struct ntfs_inode **ni, struct ntfs_inode *base_ni,
2333 			  struct mft_record **ni_mrec, const s64 mft_data_vcn)
2334 {
2335 	s64 ll, bit, old_data_initialized, old_data_size;
2336 	s64 nr_new_mft_records = 0;
2337 	s64 max_mft_no = -1, reserve_start = -1, reserve_end = -1;
2338 	s64 candidate_reserve_end = -1;
2339 	s64 *reserve_endp;
2340 	unsigned long flags;
2341 	struct folio *folio;
2342 	struct ntfs_inode *mft_ni, *mftbmp_ni;
2343 	struct ntfs_attr_search_ctx *ctx;
2344 	struct mft_record *m = NULL;
2345 	struct attr_record *a;
2346 	pgoff_t index;
2347 	unsigned int ofs;
2348 	int err;
2349 	__le16 seq_no, usn;
2350 	bool record_formatted = false, from_reserve = false, tail_alloc = false;
2351 	bool reserve_created = false;
2352 	bool forced_reserved_record = false;
2353 	unsigned int memalloc_flags;
2354 
2355 	if (base_ni && *ni)
2356 		return -EINVAL;
2357 
2358 	/* @mode and @base_ni are mutually exclusive. */
2359 	if (mode && base_ni)
2360 		return -EINVAL;
2361 	if (mft_data_vcn >= 0 &&
2362 	    (!base_ni || base_ni->mft_no != FILE_MFT))
2363 		return -EINVAL;
2364 	if (mft_data_vcn >= 0) {
2365 		u64 vbo;
2366 
2367 		if ((u64)mft_data_vcn > (U64_MAX >> vol->cluster_size_bits))
2368 			return -EOVERFLOW;
2369 		vbo = (u64)mft_data_vcn << vol->cluster_size_bits;
2370 		/*
2371 		 * The whole extent record must be reachable without this
2372 		 * extent, including when an MFT record spans multiple clusters.
2373 		 */
2374 		max_mft_no = vbo >> vol->mft_record_size_bits;
2375 	}
2376 
2377 	if (base_ni)
2378 		ntfs_debug("Entering (allocating an extent mft record for base mft record 0x%llx).",
2379 				(long long)base_ni->mft_no);
2380 	else
2381 		ntfs_debug("Entering (allocating a base mft record).");
2382 
2383 	memalloc_flags = memalloc_nofs_save();
2384 
2385 	mft_ni = NTFS_I(vol->mft_ino);
2386 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2387 		mutex_lock(&mft_ni->mrec_lock);
2388 	mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2389 search_free_rec:
2390 	from_reserve = false;
2391 	reserve_created = false;
2392 	candidate_reserve_end = -1;
2393 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2394 		down_write(&vol->mftbmp_lock);
2395 	if (base_ni && base_ni->mft_no == FILE_MFT &&
2396 	    vol->mft_record_reserve_pos < vol->mft_record_reserve_end &&
2397 	    (max_mft_no < 0 || vol->mft_record_reserve_pos < max_mft_no)) {
2398 		bit = vol->mft_record_reserve_pos;
2399 		err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2400 		if (unlikely(err)) {
2401 			ntfs_error(vol->sb,
2402 				   "Failed to allocate reserved MFT record 0x%llx.",
2403 				   bit);
2404 			goto err_out;
2405 		}
2406 		vol->mft_record_reserve_pos++;
2407 		from_reserve = true;
2408 		ntfs_debug("Allocated MFT metadata record 0x%llx from tail reserve.",
2409 			   bit);
2410 		goto have_alloc_rec;
2411 	}
2412 	reserve_endp = vol->mft_record_reserve_pos >=
2413 			vol->mft_record_reserve_end ? &candidate_reserve_end : NULL;
2414 	bit = mft_bitmap_alloc_free_rec(vol, base_ni, max_mft_no, reserve_endp);
2415 	if (bit >= 0) {
2416 		if (candidate_reserve_end > bit + 1) {
2417 			vol->mft_record_reserve_pos = bit + 1;
2418 			vol->mft_record_reserve_end = candidate_reserve_end;
2419 			reserve_created = true;
2420 			ntfs_debug("Reserved free MFT records [0x%llx, 0x%llx) for metadata.",
2421 				   bit + 1, candidate_reserve_end);
2422 		}
2423 		ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2424 				(long long)bit);
2425 		goto have_alloc_rec;
2426 	}
2427 	if (bit != -ENOSPC) {
2428 		if (!base_ni || base_ni->mft_no != FILE_MFT) {
2429 			up_write(&vol->mftbmp_lock);
2430 			mutex_unlock(&mft_ni->mrec_lock);
2431 		}
2432 		memalloc_nofs_restore(memalloc_flags);
2433 		return bit;
2434 	}
2435 
2436 	if (base_ni && base_ni->mft_no == FILE_MFT) {
2437 		static const u8 bootstrap_records[] = {
2438 			FILE_reserved15, FILE_reserved12, FILE_reserved13,
2439 			FILE_reserved14,
2440 		};
2441 		int i;
2442 
2443 		for (i = 0; i < ARRAY_SIZE(bootstrap_records); i++) {
2444 			if (max_mft_no >= 0 && bootstrap_records[i] >= max_mft_no)
2445 				continue;
2446 			if (!mft_reserved_is_free(vol, mft_ni,
2447 						  bootstrap_records[i]))
2448 				continue;
2449 			bit = bootstrap_records[i];
2450 			forced_reserved_record = true;
2451 			ntfs_debug("Using reserved MFT record %lld to bootstrap metadata extension.",
2452 				   bit);
2453 			goto have_alloc_rec;
2454 		}
2455 		memalloc_nofs_restore(memalloc_flags);
2456 		return bit;
2457 	}
2458 
2459 	/*
2460 	 * No free mft records left.  If the mft bitmap already covers more
2461 	 * than the currently used mft records, the next records are all free,
2462 	 * so we can simply allocate the first unused mft record.
2463 	 * Note: We also have to make sure that the mft bitmap at least covers
2464 	 * the first 24 mft records as they are special and whilst they may not
2465 	 * be in use, we do not allocate from them.
2466 	 */
2467 	read_lock_irqsave(&mft_ni->size_lock, flags);
2468 	ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2469 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
2470 	read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2471 	old_data_initialized = mftbmp_ni->initialized_size;
2472 	read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2473 	if (old_data_initialized << 3 > ll &&
2474 	    old_data_initialized << 3 > FIRST_NORMAL_MFT_RECORD) {
2475 		bit = ll;
2476 		if (bit < FIRST_NORMAL_MFT_RECORD)
2477 			bit = FIRST_NORMAL_MFT_RECORD;
2478 		if (unlikely(bit >= (1ll << 32)))
2479 			goto max_err_out;
2480 		ntfs_debug("Found free record (#2), bit 0x%llx.",
2481 				(long long)bit);
2482 		goto found_free_rec;
2483 	}
2484 	/*
2485 	 * The mft bitmap needs to be expanded until it covers the first unused
2486 	 * mft record that we can allocate.
2487 	 * Note: The smallest mft record we allocate is mft record 24.
2488 	 */
2489 	bit = old_data_initialized << 3;
2490 	if (unlikely(bit >= (1ll << 32)))
2491 		goto max_err_out;
2492 	read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2493 	old_data_size = mftbmp_ni->allocated_size;
2494 	ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2495 			old_data_size, i_size_read(vol->mftbmp_ino),
2496 			old_data_initialized);
2497 	read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2498 	if (old_data_initialized + 8 > old_data_size) {
2499 		/* Need to extend bitmap by one more cluster. */
2500 		ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2501 		err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2502 		if (err == -EAGAIN)
2503 			err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2504 
2505 		if (unlikely(err)) {
2506 			if (!base_ni || base_ni->mft_no != FILE_MFT)
2507 				up_write(&vol->mftbmp_lock);
2508 			goto err_out;
2509 		}
2510 #ifdef DEBUG
2511 		read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2512 		ntfs_debug("Status of mftbmp after allocation extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2513 				mftbmp_ni->allocated_size,
2514 				i_size_read(vol->mftbmp_ino),
2515 				mftbmp_ni->initialized_size);
2516 		read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2517 #endif /* DEBUG */
2518 	}
2519 	/*
2520 	 * We now have sufficient allocated space, extend the initialized_size
2521 	 * as well as the data_size if necessary and fill the new space with
2522 	 * zeroes.
2523 	 */
2524 	err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2525 	if (unlikely(err)) {
2526 		if (!base_ni || base_ni->mft_no != FILE_MFT)
2527 			up_write(&vol->mftbmp_lock);
2528 		goto err_out;
2529 	}
2530 #ifdef DEBUG
2531 	read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2532 	ntfs_debug("Status of mftbmp after initialized extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2533 			mftbmp_ni->allocated_size,
2534 			i_size_read(vol->mftbmp_ino),
2535 			mftbmp_ni->initialized_size);
2536 	read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2537 #endif /* DEBUG */
2538 	ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2539 found_free_rec:
2540 	/* @bit is the found free mft record, allocate it in the mft bitmap. */
2541 	ntfs_debug("At found_free_rec.");
2542 	err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2543 	if (unlikely(err)) {
2544 		ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2545 		if (!base_ni || base_ni->mft_no != FILE_MFT)
2546 			up_write(&vol->mftbmp_lock);
2547 		goto err_out;
2548 	}
2549 	ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2550 have_alloc_rec:
2551 	/*
2552 	 * The mft bitmap is now uptodate.  Deal with mft data attribute now.
2553 	 * Note, we keep hold of the mft bitmap lock for writing until all
2554 	 * modifications to the mft data attribute are complete, too, as they
2555 	 * will impact decisions for mft bitmap and mft record allocation done
2556 	 * by a parallel allocation and if the lock is not maintained a
2557 	 * parallel allocation could allocate the same mft record as this one.
2558 	 */
2559 	ll = (bit + 1) << vol->mft_record_size_bits;
2560 	read_lock_irqsave(&mft_ni->size_lock, flags);
2561 	old_data_initialized = mft_ni->initialized_size;
2562 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
2563 	tail_alloc = (!base_ni || base_ni->mft_no != FILE_MFT) &&
2564 			bit >= (old_data_initialized >> vol->mft_record_size_bits) &&
2565 			vol->mft_record_reserve_pos >= vol->mft_record_reserve_end;
2566 	if (tail_alloc)
2567 		ll = (bit + 2) << vol->mft_record_size_bits;
2568 	if (ll <= old_data_initialized) {
2569 		ntfs_debug("Allocated mft record already initialized.");
2570 		goto mft_rec_already_initialized;
2571 	}
2572 	ntfs_debug("Initializing allocated mft record.");
2573 	/*
2574 	 * The mft record is outside the initialized data.  Extend the mft data
2575 	 * attribute until it covers the allocated record.  The loop is only
2576 	 * actually traversed more than once when a freshly formatted volume is
2577 	 * first written to so it optimizes away nicely in the common case.
2578 	 */
2579 	if (!base_ni || base_ni->mft_no != FILE_MFT) {
2580 		read_lock_irqsave(&mft_ni->size_lock, flags);
2581 		ntfs_debug("Status of mft data before extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2582 				mft_ni->allocated_size, i_size_read(vol->mft_ino),
2583 				mft_ni->initialized_size);
2584 		while (ll > mft_ni->allocated_size) {
2585 			read_unlock_irqrestore(&mft_ni->size_lock, flags);
2586 			err = ntfs_mft_data_extend_allocation_nolock(vol);
2587 			if (err == -EAGAIN)
2588 				err = ntfs_mft_data_extend_allocation_nolock(vol);
2589 
2590 			if (unlikely(err)) {
2591 				ntfs_error(vol->sb, "Failed to extend mft data allocation.");
2592 				goto undo_mftbmp_alloc_nolock;
2593 			}
2594 			read_lock_irqsave(&mft_ni->size_lock, flags);
2595 			ntfs_debug("Status of mft data after allocation extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2596 					mft_ni->allocated_size, i_size_read(vol->mft_ino),
2597 					mft_ni->initialized_size);
2598 		}
2599 		read_unlock_irqrestore(&mft_ni->size_lock, flags);
2600 		if (tail_alloc) {
2601 			s64 bitmap_records;
2602 
2603 			read_lock_irqsave(&mft_ni->size_lock, flags);
2604 			reserve_end = mft_ni->allocated_size >>
2605 					vol->mft_record_size_bits;
2606 			read_unlock_irqrestore(&mft_ni->size_lock, flags);
2607 			read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2608 			bitmap_records = mftbmp_ni->initialized_size << 3;
2609 			read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2610 			if (reserve_end > bitmap_records)
2611 				reserve_end = bitmap_records;
2612 			if (reserve_end > bit + 1 + MFT_RECORD_RESERVE)
2613 				reserve_end = bit + 1 + MFT_RECORD_RESERVE;
2614 			reserve_start = bit + 1;
2615 			if (reserve_end > reserve_start) {
2616 				ll = reserve_end << vol->mft_record_size_bits;
2617 			} else {
2618 				reserve_start = -1;
2619 				reserve_end = -1;
2620 				ll = (bit + 1) << vol->mft_record_size_bits;
2621 			}
2622 		}
2623 	} else if (ll > mft_ni->allocated_size) {
2624 		err = -ENOSPC;
2625 		goto undo_mftbmp_alloc_nolock;
2626 	}
2627 	/*
2628 	 * Extend mft data initialized size (and data size of course) to reach
2629 	 * the allocated mft record, formatting the mft records allong the way.
2630 	 * Note: We only modify the struct ntfs_inode structure as that is all that is
2631 	 * needed by ntfs_mft_record_format().  We will update the attribute
2632 	 * record itself in one fell swoop later on.
2633 	 */
2634 	write_lock_irqsave(&mft_ni->size_lock, flags);
2635 	old_data_initialized = mft_ni->initialized_size;
2636 	old_data_size = vol->mft_ino->i_size;
2637 	while (ll > mft_ni->initialized_size) {
2638 		s64 new_initialized_size, mft_no;
2639 
2640 		new_initialized_size = mft_ni->initialized_size +
2641 				vol->mft_record_size;
2642 		mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2643 		if (new_initialized_size > i_size_read(vol->mft_ino))
2644 			i_size_write(vol->mft_ino, new_initialized_size);
2645 		write_unlock_irqrestore(&mft_ni->size_lock, flags);
2646 		ntfs_debug("Initializing mft record 0x%llx.",
2647 				(long long)mft_no);
2648 		err = ntfs_mft_record_format(vol, mft_no);
2649 		if (unlikely(err)) {
2650 			ntfs_error(vol->sb, "Failed to format mft record.");
2651 			goto undo_data_init;
2652 		}
2653 		write_lock_irqsave(&mft_ni->size_lock, flags);
2654 		mft_ni->initialized_size = new_initialized_size;
2655 	}
2656 	write_unlock_irqrestore(&mft_ni->size_lock, flags);
2657 	record_formatted = true;
2658 	/* Update the mft data attribute record to reflect the new sizes. */
2659 	m = map_mft_record(mft_ni);
2660 	if (IS_ERR(m)) {
2661 		ntfs_error(vol->sb, "Failed to map mft record.");
2662 		err = PTR_ERR(m);
2663 		goto undo_data_init;
2664 	}
2665 	ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2666 	if (unlikely(!ctx)) {
2667 		ntfs_error(vol->sb, "Failed to get search context.");
2668 		err = -ENOMEM;
2669 		unmap_mft_record(mft_ni);
2670 		goto undo_data_init;
2671 	}
2672 	err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2673 			CASE_SENSITIVE, 0, NULL, 0, ctx);
2674 	if (unlikely(err)) {
2675 		ntfs_error(vol->sb, "Failed to find first attribute extent of mft data attribute.");
2676 		ntfs_attr_put_search_ctx(ctx);
2677 		unmap_mft_record(mft_ni);
2678 		goto undo_data_init;
2679 	}
2680 	a = ctx->attr;
2681 	read_lock_irqsave(&mft_ni->size_lock, flags);
2682 	a->data.non_resident.initialized_size =
2683 			cpu_to_le64(mft_ni->initialized_size);
2684 	a->data.non_resident.data_size =
2685 			cpu_to_le64(i_size_read(vol->mft_ino));
2686 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
2687 	/* Ensure the changes make it to disk. */
2688 	mark_mft_record_dirty(ctx->ntfs_ino);
2689 	ntfs_attr_put_search_ctx(ctx);
2690 	unmap_mft_record(mft_ni);
2691 	if (reserve_start >= 0 && reserve_end > reserve_start) {
2692 		vol->mft_record_reserve_pos = reserve_start;
2693 		vol->mft_record_reserve_end = reserve_end;
2694 		ntfs_debug("Reserved MFT records [0x%llx, 0x%llx) for metadata.",
2695 			   reserve_start, reserve_end);
2696 	}
2697 	read_lock_irqsave(&mft_ni->size_lock, flags);
2698 	ntfs_debug("Status of mft data after mft record initialization: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx.",
2699 			mft_ni->allocated_size,	i_size_read(vol->mft_ino),
2700 			mft_ni->initialized_size);
2701 	WARN_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2702 	WARN_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2703 	nr_new_mft_records = (i_size_read(vol->mft_ino) - old_data_size) >>
2704 			     vol->mft_record_size_bits;
2705 	read_unlock_irqrestore(&mft_ni->size_lock, flags);
2706 mft_rec_already_initialized:
2707 	/* Account for newly visible MFT records before dropping the lock. */
2708 	if (nr_new_mft_records > 0)
2709 		ntfs_inc_free_mft_records(vol, nr_new_mft_records);
2710 	/*
2711 	 * We can finally drop the mft bitmap lock as the mft data attribute
2712 	 * has been fully updated.  The only disparity left is that the
2713 	 * allocated mft record still needs to be marked as in use to match the
2714 	 * set bit in the mft bitmap but this is actually not a problem since
2715 	 * this mft record is not referenced from anywhere yet and the fact
2716 	 * that it is allocated in the mft bitmap means that no-one will try to
2717 	 * allocate it either.
2718 	 */
2719 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2720 		up_write(&vol->mftbmp_lock);
2721 	/*
2722 	 * We now have allocated and initialized the mft record.  Calculate the
2723 	 * index of and the offset within the page cache page the record is in.
2724 	 */
2725 	index = NTFS_MFT_NR_TO_PIDX(vol, bit);
2726 	ofs = NTFS_MFT_NR_TO_POFS(vol, bit);
2727 	/* Read, map, and pin the folio containing the mft record. */
2728 	folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL);
2729 	if (IS_ERR(folio)) {
2730 		ntfs_error(vol->sb, "Failed to map page containing allocated mft record 0x%llx.",
2731 				bit);
2732 		err = PTR_ERR(folio);
2733 		goto undo_mftbmp_alloc;
2734 	}
2735 	folio_lock(folio);
2736 	if (folio_test_writeback(folio))
2737 		folio_wait_writeback(folio);
2738 	folio_clear_uptodate(folio);
2739 	m = (struct mft_record *)((u8 *)kmap_local_folio(folio, 0) + ofs);
2740 	/* If we just formatted the mft record no need to do it again. */
2741 	if (!record_formatted) {
2742 		/* Sanity check that the mft record is really not in use. */
2743 		if (!forced_reserved_record && ntfs_is_file_record(m->magic) &&
2744 		    (m->flags & MFT_RECORD_IN_USE)) {
2745 			ntfs_warning(vol->sb,
2746 				"Mft record 0x%llx was marked free in mft bitmap but is marked used itself. Unmount and run chkdsk.",
2747 				bit);
2748 			folio_mark_uptodate(folio);
2749 			folio_unlock(folio);
2750 			kunmap_local(m);
2751 			folio_put(folio);
2752 			NVolSetErrors(vol);
2753 			goto search_free_rec;
2754 		}
2755 		/*
2756 		 * We need to (re-)format the mft record, preserving the
2757 		 * sequence number if it is not zero as well as the update
2758 		 * sequence number if it is not zero or -1 (0xffff).  This
2759 		 * means we do not need to care whether or not something went
2760 		 * wrong with the previous mft record.
2761 		 */
2762 		seq_no = m->sequence_number;
2763 		/*
2764 		 * The mft record still holds unvalidated, MST-protected on-disk
2765 		 * bytes, so m->usa_ofs is untrusted here.  Only preserve the old
2766 		 * update sequence number if that offset is in bounds; otherwise
2767 		 * leave usn zero so it is not restored below.
2768 		 */
2769 		if (!(le16_to_cpu(m->usa_ofs) & 1) &&
2770 		    le16_to_cpu(m->usa_ofs) + sizeof(usn) <= vol->mft_record_size)
2771 			usn = *(__le16 *)((u8 *)m + le16_to_cpu(m->usa_ofs));
2772 		else
2773 			usn = 0;
2774 		err = ntfs_mft_record_layout(vol, bit, m);
2775 		if (unlikely(err)) {
2776 			ntfs_error(vol->sb, "Failed to layout allocated mft record 0x%llx.",
2777 					bit);
2778 			folio_mark_uptodate(folio);
2779 			folio_unlock(folio);
2780 			kunmap_local(m);
2781 			folio_put(folio);
2782 			goto undo_mftbmp_alloc;
2783 		}
2784 		if (seq_no)
2785 			m->sequence_number = seq_no;
2786 		if (usn && le16_to_cpu(usn) != 0xffff)
2787 			*(__le16 *)((u8 *)m + le16_to_cpu(m->usa_ofs)) = usn;
2788 		pre_write_mst_fixup((struct ntfs_record *)m, vol->mft_record_size);
2789 	}
2790 	/* Set the mft record itself in use. */
2791 	m->flags |= MFT_RECORD_IN_USE;
2792 	if (S_ISDIR(mode))
2793 		m->flags |= MFT_RECORD_IS_DIRECTORY;
2794 	folio_mark_uptodate(folio);
2795 	if (base_ni) {
2796 		struct mft_record *m_tmp;
2797 
2798 		/*
2799 		 * Setup the base mft record in the extent mft record.  This
2800 		 * completes initialization of the allocated extent mft record
2801 		 * and we can simply use it with map_extent_mft_record().
2802 		 */
2803 		m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2804 				base_ni->seq_no);
2805 		/*
2806 		 * Allocate an extent inode structure for the new mft record,
2807 		 * attach it to the base inode @base_ni and map, pin, and lock
2808 		 * its, i.e. the allocated, mft record.
2809 		 */
2810 		m_tmp = map_extent_mft_record(base_ni,
2811 					      MK_MREF(bit, le16_to_cpu(m->sequence_number)),
2812 					      ni);
2813 		if (IS_ERR(m_tmp)) {
2814 			ntfs_error(vol->sb, "Failed to map allocated extent mft record 0x%llx.",
2815 					bit);
2816 			err = PTR_ERR(m_tmp);
2817 			if (forced_reserved_record) {
2818 				m->base_mft_record = 0;
2819 				m->flags |= MFT_RECORD_IN_USE;
2820 			} else {
2821 				/* Set the mft record itself not in use. */
2822 				m->flags &= cpu_to_le16(~le16_to_cpu(MFT_RECORD_IN_USE));
2823 			}
2824 			/* Make sure the mft record is written out to disk. */
2825 			ntfs_mft_mark_dirty(folio);
2826 			folio_unlock(folio);
2827 			kunmap_local(m);
2828 			folio_put(folio);
2829 			goto undo_mftbmp_alloc;
2830 		}
2831 
2832 		/*
2833 		 * Make sure the allocated mft record is written out to disk.
2834 		 * No need to set the inode dirty because the caller is going
2835 		 * to do that anyway after finishing with the new extent mft
2836 		 * record (e.g. at a minimum a new attribute will be added to
2837 		 * the mft record.
2838 		 */
2839 		ntfs_mft_mark_dirty(folio);
2840 		folio_unlock(folio);
2841 		/*
2842 		 * Need to unmap the page since map_extent_mft_record() mapped
2843 		 * it as well so we have it mapped twice at the moment.
2844 		 */
2845 		kunmap_local(m);
2846 		folio_put(folio);
2847 	} else {
2848 		/*
2849 		 * Manually map, pin, and lock the mft record as we already
2850 		 * have its page mapped and it is very easy to do.
2851 		 */
2852 		(*ni)->seq_no = le16_to_cpu(m->sequence_number);
2853 		/*
2854 		 * Make sure the allocated mft record is written out to disk.
2855 		 * NOTE: We do not set the ntfs inode dirty because this would
2856 		 * fail in ntfs_write_inode() because the inode does not have a
2857 		 * standard information attribute yet.  Also, there is no need
2858 		 * to set the inode dirty because the caller is going to do
2859 		 * that anyway after finishing with the new mft record (e.g. at
2860 		 * a minimum some new attributes will be added to the mft
2861 		 * record.
2862 		 */
2863 
2864 		(*ni)->mrec = kmemdup(m, vol->mft_record_size, GFP_NOFS);
2865 		if (!(*ni)->mrec) {
2866 			folio_unlock(folio);
2867 			kunmap_local(m);
2868 			folio_put(folio);
2869 			err = -ENOMEM;
2870 			goto undo_mftbmp_alloc;
2871 		}
2872 
2873 		post_read_mst_fixup((struct ntfs_record *)(*ni)->mrec, vol->mft_record_size);
2874 		ntfs_mft_mark_dirty(folio);
2875 		folio_unlock(folio);
2876 		(*ni)->folio = folio;
2877 		(*ni)->folio_ofs = ofs;
2878 		atomic_inc(&(*ni)->count);
2879 		/* Update the default mft allocation position. */
2880 		vol->mft_data_pos = bit + 1;
2881 	}
2882 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2883 		mutex_unlock(&mft_ni->mrec_lock);
2884 	memalloc_nofs_restore(memalloc_flags);
2885 
2886 	/*
2887 	 * Return the opened, allocated inode of the allocated mft record as
2888 	 * well as the mapped, pinned, and locked mft record.
2889 	 */
2890 	ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2891 			base_ni ? "extent " : "", bit);
2892 	(*ni)->mft_no = bit;
2893 	if (ni_mrec)
2894 		*ni_mrec = (*ni)->mrec;
2895 	if (!forced_reserved_record)
2896 		ntfs_dec_free_mft_records(vol, 1);
2897 	return 0;
2898 undo_data_init:
2899 	write_lock_irqsave(&mft_ni->size_lock, flags);
2900 	mft_ni->initialized_size = old_data_initialized;
2901 	i_size_write(vol->mft_ino, old_data_size);
2902 	write_unlock_irqrestore(&mft_ni->size_lock, flags);
2903 	goto undo_mftbmp_alloc_nolock;
2904 undo_mftbmp_alloc:
2905 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2906 		down_write(&vol->mftbmp_lock);
2907 undo_mftbmp_alloc_nolock:
2908 	if (!forced_reserved_record && ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2909 		ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2910 		NVolSetErrors(vol);
2911 	}
2912 	if ((from_reserve || reserve_created) &&
2913 	    vol->mft_record_reserve_pos == bit + 1)
2914 		vol->mft_record_reserve_pos = bit;
2915 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2916 		up_write(&vol->mftbmp_lock);
2917 err_out:
2918 	if (!base_ni || base_ni->mft_no != FILE_MFT)
2919 		mutex_unlock(&mft_ni->mrec_lock);
2920 	memalloc_nofs_restore(memalloc_flags);
2921 	return err;
2922 max_err_out:
2923 	ntfs_warning(vol->sb,
2924 		"Cannot allocate mft record because the maximum number of inodes (2^32) has already been reached.");
2925 	if (!base_ni || base_ni->mft_no != FILE_MFT) {
2926 		up_write(&vol->mftbmp_lock);
2927 		mutex_unlock(&mft_ni->mrec_lock);
2928 	}
2929 	memalloc_nofs_restore(memalloc_flags);
2930 	return -ENOSPC;
2931 }
2932 
2933 /*
2934  * ntfs_mft_record_free - free an mft record on an ntfs volume
2935  * @vol:	volume on which to free the mft record
2936  * @ni:		open ntfs inode of the mft record to free
2937  *
2938  * Free the mft record of the open inode @ni on the mounted ntfs volume @vol.
2939  * Note that this function calls ntfs_inode_close() internally and hence you
2940  * cannot use the pointer @ni any more after this function returns success.
2941  *
2942  * On success return 0 and on error return -1 with errno set to the error code.
2943  */
2944 int ntfs_mft_record_free(struct ntfs_volume *vol, struct ntfs_inode *ni)
2945 {
2946 	u64 mft_no;
2947 	int err;
2948 	u16 seq_no;
2949 	__le16 old_seq_no;
2950 	__le64 old_base_mft_record;
2951 	struct mft_record *ni_mrec;
2952 	unsigned int memalloc_flags;
2953 	struct ntfs_inode *base_ni;
2954 	bool keep_reserved;
2955 
2956 	if (!vol || !ni)
2957 		return -EINVAL;
2958 
2959 	ntfs_debug("Entering for inode 0x%llx.\n", (long long)ni->mft_no);
2960 
2961 	ni_mrec = map_mft_record(ni);
2962 	if (IS_ERR(ni_mrec))
2963 		return -EIO;
2964 
2965 	/* Cache the mft reference for later. */
2966 	mft_no = ni->mft_no;
2967 	if (likely(ni->nr_extents >= 0))
2968 		base_ni = ni;
2969 	else
2970 		base_ni = ni->ext.base_ntfs_ino;
2971 	keep_reserved = mft_no >= FILE_reserved12 &&
2972 			mft_no <= FILE_reserved15 &&
2973 			base_ni->mft_no == FILE_MFT;
2974 
2975 	old_base_mft_record = ni_mrec->base_mft_record;
2976 	if (keep_reserved) {
2977 		/* Restore the special, unnamed form used by reserved records. */
2978 		ni_mrec->base_mft_record = 0;
2979 		ni_mrec->flags |= MFT_RECORD_IN_USE;
2980 	} else {
2981 		/* Mark the mft record as not in use. */
2982 		ni_mrec->flags &= ~MFT_RECORD_IN_USE;
2983 	}
2984 
2985 	/* Increment the sequence number, skipping zero, if it is not zero. */
2986 	old_seq_no = ni_mrec->sequence_number;
2987 	seq_no = le16_to_cpu(old_seq_no);
2988 	if (seq_no == 0xffff)
2989 		seq_no = 1;
2990 	else if (seq_no)
2991 		seq_no++;
2992 	ni_mrec->sequence_number = cpu_to_le16(seq_no);
2993 
2994 	down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
2995 	err = ntfs_get_block_mft_record(NTFS_I(vol->mft_ino), ni);
2996 	up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
2997 	if (err) {
2998 		unmap_mft_record(ni);
2999 		return err;
3000 	}
3001 
3002 	/*
3003 	 * Set the ntfs inode dirty and write it out.  We do not need to worry
3004 	 * about the base inode here since whatever caused the extent mft
3005 	 * record to be freed is guaranteed to do it already.
3006 	 */
3007 	NInoSetDirty(ni);
3008 	err = write_mft_record(ni, ni_mrec, 1);
3009 	if (err)
3010 		goto sync_rollback;
3011 
3012 	if (keep_reserved) {
3013 		unmap_mft_record(ni);
3014 		return 0;
3015 	}
3016 
3017 	/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
3018 	memalloc_flags = memalloc_nofs_save();
3019 	if (base_ni->mft_no != FILE_MFT)
3020 		down_write(&vol->mftbmp_lock);
3021 	err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
3022 	if (!err)
3023 		ntfs_inc_free_mft_records(vol, 1);
3024 	if (!err && base_ni->mft_no == FILE_MFT &&
3025 	    mft_no + 1 == vol->mft_record_reserve_pos &&
3026 	    mft_no < vol->mft_record_reserve_end)
3027 		vol->mft_record_reserve_pos = mft_no;
3028 	if (base_ni->mft_no != FILE_MFT)
3029 		up_write(&vol->mftbmp_lock);
3030 	memalloc_nofs_restore(memalloc_flags);
3031 	if (err)
3032 		goto bitmap_rollback;
3033 	unmap_mft_record(ni);
3034 	return 0;
3035 
3036 	/* Rollback what we did... */
3037 bitmap_rollback:
3038 	memalloc_flags = memalloc_nofs_save();
3039 	if (base_ni->mft_no != FILE_MFT)
3040 		down_write(&vol->mftbmp_lock);
3041 	if (ntfs_bitmap_set_bit(vol->mftbmp_ino, mft_no))
3042 		ntfs_error(vol->sb, "ntfs_bitmap_set_bit failed in bitmap_rollback\n");
3043 	if (base_ni->mft_no != FILE_MFT)
3044 		up_write(&vol->mftbmp_lock);
3045 	memalloc_nofs_restore(memalloc_flags);
3046 sync_rollback:
3047 	ntfs_error(vol->sb,
3048 		"Eeek! Rollback failed in %s. Leaving inconsistent metadata!\n", __func__);
3049 	ni_mrec->flags |= MFT_RECORD_IN_USE;
3050 	ni_mrec->sequence_number = old_seq_no;
3051 	ni_mrec->base_mft_record = old_base_mft_record;
3052 	NInoSetDirty(ni);
3053 	write_mft_record(ni, ni_mrec, 0);
3054 	unmap_mft_record(ni);
3055 	return err;
3056 }
3057 
3058 static bool ntfs_add_mft_io_unit(struct bio *bio, struct folio *folio,
3059 				 const struct ntfs_mft_io_unit *unit)
3060 {
3061 	if (!bio->bi_iter.bi_size)
3062 		bio->bi_iter.bi_sector = unit->sector;
3063 	else if (bio_end_sector(bio) != unit->sector)
3064 		return false;
3065 
3066 	return bio_add_folio(bio, folio, unit->len, unit->folio_ofs);
3067 }
3068 
3069 static void ntfs_release_mft_write_refs(struct ntfs_inode **locked_nis,
3070 					unsigned int nr_locked_nis,
3071 					struct inode **ref_inos,
3072 					unsigned int nr_ref_inos)
3073 {
3074 	while (nr_locked_nis-- > 0) {
3075 		struct ntfs_inode *tni = locked_nis[nr_locked_nis];
3076 
3077 		mutex_unlock(&tni->mrec_lock);
3078 		atomic_dec(&tni->count);
3079 	}
3080 
3081 	while (nr_ref_inos-- > 0)
3082 		iput(ref_inos[nr_ref_inos]);
3083 }
3084 
3085 static int ntfs_map_mft_io_locked(struct ntfs_inode *ni, u64 folio_byte,
3086 				  struct ntfs_mft_io_unit *unit)
3087 {
3088 	struct ntfs_volume *vol = ni->vol;
3089 	u64 file_ofs = folio_byte + unit->folio_ofs;
3090 	s64 vcn, lcn;
3091 
3092 	lockdep_assert_held(&ni->runlist.lock);
3093 	if (!ni->runlist.rl)
3094 		return -EIO;
3095 
3096 	vcn = ntfs_bytes_to_cluster(vol, file_ofs);
3097 	/*
3098 	 * $MFT is fully mapped at mount time and extensions merge already
3099 	 * mapped runs under the write lock. Do not remap here: the generic
3100 	 * helper may drop this read lock while upgrading it.
3101 	 */
3102 	lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
3103 	if (lcn == LCN_RL_NOT_MAPPED)
3104 		return -EAGAIN;
3105 	if (lcn < 0)
3106 		return -EIO;
3107 	if (ntfs_bytes_to_cluster_off(vol, file_ofs) + unit->len >
3108 	    vol->cluster_size)
3109 		return -EIO;
3110 
3111 	unit->sector = ntfs_bytes_to_bio_sector(
3112 		NTFS_CLU_TO_B(vol, lcn) +
3113 		ntfs_bytes_to_cluster_off(vol, file_ofs));
3114 	return 0;
3115 }
3116 
3117 static int ntfs_map_mft_io_for_folio(struct ntfs_inode *ni, u64 folio_byte,
3118 				     struct ntfs_mft_io_unit *unit)
3119 {
3120 	int err;
3121 
3122 	if (!down_read_trylock(&ni->runlist.lock))
3123 		return -EAGAIN;
3124 	err = ntfs_map_mft_io_locked(ni, folio_byte, unit);
3125 	up_read(&ni->runlist.lock);
3126 	return err;
3127 }
3128 
3129 static int ntfs_prepare_mft_folio_units(struct ntfs_inode *ni, u64 folio_byte,
3130 					u64 file_limit,
3131 					const unsigned long *record_selected,
3132 					struct ntfs_mft_io_unit *units,
3133 					unsigned int *nr_units,
3134 					unsigned int max_units, bool *defer)
3135 {
3136 	struct ntfs_volume *vol = ni->vol;
3137 	u64 folio_end = folio_byte + PAGE_SIZE;
3138 	u64 unit_byte = folio_byte;
3139 
3140 	while (unit_byte < folio_end && unit_byte < file_limit) {
3141 		struct ntfs_mft_io_unit unit;
3142 		u64 record_byte;
3143 		u64 unit_end;
3144 		u64 io_unit_end;
3145 		u64 cluster_end;
3146 		bool selected = false;
3147 		int err;
3148 
3149 		io_unit_end =
3150 			round_down(unit_byte, (u64)vol->mft_io_unit_size) +
3151 			vol->mft_io_unit_size;
3152 		cluster_end = ntfs_cluster_to_bytes(
3153 			vol, ntfs_bytes_to_cluster(vol, unit_byte) + 1);
3154 		unit_end = min3(io_unit_end, cluster_end, folio_end);
3155 
3156 		record_byte = round_down(unit_byte, (u64)vol->mft_record_size);
3157 		while (record_byte < min(unit_end, file_limit)) {
3158 			unsigned int record;
3159 
3160 			record = div_u64(record_byte - folio_byte,
3161 					 vol->mft_record_size);
3162 			if (test_bit(record, record_selected)) {
3163 				selected = true;
3164 				break;
3165 			}
3166 			record_byte += vol->mft_record_size;
3167 		}
3168 		/*
3169 		 * Direct inode writeback owns unselected records.  Their folio
3170 		 * images are stable while this folio is locked, so a containing
3171 		 * unit can preserve them when writing a selected record.
3172 		 */
3173 		if (!selected)
3174 			goto next;
3175 
3176 		unit = (struct ntfs_mft_io_unit){
3177 			.folio_ofs = unit_byte - folio_byte,
3178 			.len = unit_end - unit_byte,
3179 		};
3180 		err = ntfs_map_mft_io_for_folio(ni, folio_byte, &unit);
3181 		if (err == -EAGAIN) {
3182 			*defer = true;
3183 			goto next;
3184 		}
3185 		if (err)
3186 			return err;
3187 		if (*nr_units >= max_units)
3188 			return -EOVERFLOW;
3189 		units[(*nr_units)++] = unit;
3190 next:
3191 		unit_byte = unit_end;
3192 	}
3193 	return 0;
3194 }
3195 
3196 static void ntfs_mft_write_error(struct ntfs_volume *vol,
3197 				 struct address_space *mapping, int err)
3198 {
3199 	mapping_set_error(mapping, err);
3200 	NVolSetErrors(vol);
3201 	ntfs_error(vol->sb, "Error while writing MFT folio: %d", err);
3202 }
3203 
3204 /*
3205  * ntfs_write_mft_block - Write back a folio containing MFT records
3206  * @folio:	The folio to write back (contains one or more MFT records)
3207  * @wbc:	Writeback control structure
3208  *
3209  * This function is called as part of the address_space_operations
3210  * .writepages implementation for the $MFT inode.  Despite its historical
3211  * name, it handles one folio containing MFT records.
3212  *
3213  * Return: 0 on success, or -errno on error.
3214  */
3215 static int ntfs_write_mft_block(struct folio *folio, struct writeback_control *wbc)
3216 {
3217 	struct address_space *mapping = folio->mapping;
3218 	struct inode *vi = mapping->host;
3219 	struct ntfs_inode *ni = NTFS_I(vi);
3220 	struct ntfs_volume *vol = ni->vol;
3221 	struct ntfs_inode **locked_nis __free(kfree) =
3222 		kmalloc_objs(struct ntfs_inode *, PAGE_SIZE / NTFS_BLOCK_SIZE,
3223 			     GFP_NOFS);
3224 	struct inode **ref_inos __free(kfree) =
3225 		kmalloc_objs(struct inode *, PAGE_SIZE / NTFS_BLOCK_SIZE, GFP_NOFS);
3226 	struct ntfs_mft_io_unit *units __free(kfree) = NULL;
3227 	struct bio *parent = NULL, *child = NULL;
3228 	struct ntfs_mft_write_ctx *ctx = NULL;
3229 	u8 *kaddr = NULL;
3230 	DECLARE_BITMAP(record_selected, PAGE_SIZE / NTFS_BLOCK_SIZE) = {};
3231 	u64 folio_byte, file_limit, folio_end, mirror_size;
3232 	unsigned int nr_records, nr_units = 0, max_units;
3233 	unsigned int nr_locked_nis = 0, nr_ref_inos = 0;
3234 	unsigned int record, unit_idx;
3235 	unsigned long flags;
3236 	loff_t i_size;
3237 	s64 allocated_size;
3238 	bool defer = false, redirty = false;
3239 	int err = 0;
3240 
3241 	read_lock_irqsave(&ni->size_lock, flags);
3242 	i_size = i_size_read(vi);
3243 	allocated_size = ni->allocated_size;
3244 	read_unlock_irqrestore(&ni->size_lock, flags);
3245 
3246 	ntfs_debug("Entering for inode 0x%llx, folio index 0x%lx.", ni->mft_no,
3247 		   folio->index);
3248 	WARN_ON(!folio_test_locked(folio));
3249 
3250 	folio_byte = folio_pos(folio);
3251 	folio_end = folio_byte + PAGE_SIZE;
3252 	mirror_size = (u64)vol->mftmirr_size * vol->mft_record_size;
3253 
3254 	if (i_size <= folio_byte)
3255 		folio_zero_segment(folio, 0, PAGE_SIZE);
3256 	else if ((u64)i_size < folio_end)
3257 		folio_zero_segment(folio, i_size - folio_byte, PAGE_SIZE);
3258 
3259 	file_limit = min_t(u64, i_size, allocated_size);
3260 	nr_records = PAGE_SIZE / vol->mft_record_size;
3261 	max_units = PAGE_SIZE / min(vol->cluster_size, vol->mft_record_size);
3262 	units = kmalloc_array(max_units, sizeof(*units), GFP_NOFS);
3263 	if (!locked_nis || !ref_inos || !units) {
3264 		err = -ENOMEM;
3265 		goto out_noio;
3266 	}
3267 
3268 	kaddr = kmap_local_folio(folio, 0);
3269 	folio_clear_uptodate(folio);
3270 
3271 	for (record = 0; record < nr_records; record++) {
3272 		struct ntfs_inode *tni = NULL;
3273 		struct inode *ref_vi = NULL;
3274 		u64 record_byte =
3275 			folio_byte + (u64)record * vol->mft_record_size;
3276 		u64 mft_no;
3277 
3278 		if (record_byte >= file_limit)
3279 			continue;
3280 		mft_no = record_byte >> vol->mft_record_size_bits;
3281 		if (!ntfs_may_write_mft_record(
3282 			    vol, mft_no,
3283 			    (struct mft_record *)(kaddr +
3284 						  record * vol->mft_record_size),
3285 			    &tni, &ref_vi)) {
3286 			if (ref_vi)
3287 				ref_inos[nr_ref_inos++] = ref_vi;
3288 			continue;
3289 		}
3290 		if (ref_vi)
3291 			ref_inos[nr_ref_inos++] = ref_vi;
3292 		if (tni) {
3293 			locked_nis[nr_locked_nis++] = tni;
3294 			if (tni->nr_extents < 0 &&
3295 			    tni->ext.base_ntfs_ino == NTFS_I(vol->mft_ino))
3296 				continue;
3297 		}
3298 		__set_bit(record, record_selected);
3299 	}
3300 
3301 	err = ntfs_prepare_mft_folio_units(ni, folio_byte, file_limit,
3302 					   record_selected, units, &nr_units,
3303 					   max_units, &defer);
3304 	if (err)
3305 		goto out_noio;
3306 	if (!nr_units) {
3307 		if (defer)
3308 			goto out_noio;
3309 		folio_mark_uptodate(folio);
3310 		kunmap_local(kaddr);
3311 		folio_start_writeback(folio);
3312 		folio_unlock(folio);
3313 		folio_end_writeback(folio);
3314 		ntfs_release_mft_write_refs(locked_nis, nr_locked_nis, ref_inos,
3315 					    nr_ref_inos);
3316 		return 0;
3317 	}
3318 
3319 	parent = ntfs_alloc_mft_parent_bio(vol, folio, NULL);
3320 	if (!parent) {
3321 		err = -ENOMEM;
3322 		goto out_noio;
3323 	}
3324 	ctx = container_of(parent, struct ntfs_mft_write_ctx, bio);
3325 
3326 	if (!ntfs_add_mft_io_unit(parent, folio, &units[0])) {
3327 		err = -EIO;
3328 		goto out_noio;
3329 	}
3330 
3331 	for (unit_idx = 0; unit_idx < nr_units; unit_idx++) {
3332 		struct ntfs_mft_io_unit *unit = &units[unit_idx];
3333 		u64 file_ofs = folio_byte + unit->folio_ofs;
3334 
3335 		if (unit_idx) {
3336 			struct bio *target = child ? child : parent;
3337 
3338 			if (!ntfs_add_mft_io_unit(target, folio, unit)) {
3339 				if (child) {
3340 					ntfs_start_mft_writeback(ctx);
3341 					bio_chain(child, parent);
3342 					submit_bio(child);
3343 					child = NULL;
3344 				}
3345 				child = bio_alloc(vol->sb->s_bdev, 1,
3346 						  REQ_OP_WRITE, GFP_NOIO);
3347 				if (!child) {
3348 					defer = true;
3349 					break;
3350 				}
3351 				if (!ntfs_add_mft_io_unit(child, folio, unit)) {
3352 					bio_put(child);
3353 					child = NULL;
3354 					if (!ctx->error)
3355 						ctx->error = -EIO;
3356 					redirty = true;
3357 					err = -EIO;
3358 					break;
3359 				}
3360 			}
3361 		}
3362 		if (file_ofs < mirror_size) {
3363 			int mirror_err = ntfs_sync_mft_mirror_unit(
3364 				vol, folio, file_ofs, unit);
3365 
3366 			if (mirror_err && !ctx->error)
3367 				ctx->error = mirror_err;
3368 		}
3369 	}
3370 
3371 	if (child) {
3372 		ntfs_start_mft_writeback(ctx);
3373 		bio_chain(child, parent);
3374 		submit_bio(child);
3375 	}
3376 	ntfs_start_mft_writeback(ctx);
3377 	folio_mark_uptodate(folio);
3378 	if (defer || redirty)
3379 		folio_redirty_for_writepage(wbc, folio);
3380 	kunmap_local(kaddr);
3381 	kaddr = NULL;
3382 	folio_unlock(folio);
3383 	submit_bio(parent);
3384 	ntfs_release_mft_write_refs(locked_nis, nr_locked_nis, ref_inos,
3385 				    nr_ref_inos);
3386 
3387 	return 0;
3388 
3389 out_noio:
3390 	if (kaddr) {
3391 		folio_mark_uptodate(folio);
3392 		kunmap_local(kaddr);
3393 	}
3394 	if (err && err != -ENOMEM)
3395 		ntfs_mft_write_error(vol, mapping, err);
3396 	if (parent)
3397 		bio_put(parent);
3398 	if (redirty || defer || err == -ENOMEM)
3399 		folio_redirty_for_writepage(wbc, folio);
3400 	folio_unlock(folio);
3401 	ntfs_release_mft_write_refs(locked_nis, nr_locked_nis, ref_inos,
3402 				    nr_ref_inos);
3403 	if (err == -ENOMEM || (defer && !err))
3404 		return 0;
3405 	return err;
3406 }
3407 
3408 /*
3409  * ntfs_mft_writepages - Write back dirty folios for the $MFT inode
3410  * @mapping:	address space of the $MFT inode
3411  * @wbc:	writeback control
3412  *
3413  * Writeback iterator for MFT records. Iterates over dirty folios and
3414  * delegates actual writing to ntfs_write_mft_block() for each folio.
3415  * Called from the address_space_operations .writepages vector of the
3416  * $MFT inode.
3417  *
3418  * Returns 0 on success, or the first error encountered.
3419  */
3420 int ntfs_mft_writepages(struct address_space *mapping,
3421 		struct writeback_control *wbc)
3422 {
3423 	struct folio *folio = NULL;
3424 	int error;
3425 
3426 	if (NVolShutdown(NTFS_I(mapping->host)->vol))
3427 		return -EIO;
3428 
3429 	while ((folio = writeback_iter(mapping, wbc, folio, &error)))
3430 		error = ntfs_write_mft_block(folio, wbc);
3431 	return error;
3432 }
3433 
3434 void ntfs_mft_mark_dirty(struct folio *folio)
3435 {
3436 	iomap_dirty_folio(folio->mapping, folio);
3437 }
3438