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