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