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