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