2 * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
4 * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
5 * Copyright (c) 2002 Richard Russon
7 * This program/include file is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program/include file is distributed in the hope that it will be
13 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program (in the main directory of the Linux-NTFS
19 * distribution in the file COPYING); if not, write to the Free Software
20 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <linux/buffer_head.h>
24 #include <linux/slab.h>
25 #include <linux/swap.h>
26 #include <linux/bio.h>
38 #define MAX_BHS (PAGE_SIZE / NTFS_BLOCK_SIZE)
41 * map_mft_record_page - map the page in which a specific mft record resides
42 * @ni: ntfs inode whose mft record page to map
44 * This maps the page in which the mft record of the ntfs inode @ni is situated
45 * and returns a pointer to the mft record within the mapped page.
47 * Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
48 * contains the negative error code returned.
50 static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
53 ntfs_volume *vol = ni->vol;
54 struct inode *mft_vi = vol->mft_ino;
56 unsigned long index, end_index;
61 * The index into the page cache and the offset within the page cache
62 * page of the wanted mft record. FIXME: We need to check for
63 * overflowing the unsigned long, but I don't think we would ever get
64 * here if the volume was that big...
66 index = (u64)ni->mft_no << vol->mft_record_size_bits >>
68 ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
70 i_size = i_size_read(mft_vi);
71 /* The maximum valid index into the page cache for $MFT's data. */
72 end_index = i_size >> PAGE_SHIFT;
74 /* If the wanted index is out of bounds the mft record doesn't exist. */
75 if (unlikely(index >= end_index)) {
76 if (index > end_index || (i_size & ~PAGE_MASK) < ofs +
77 vol->mft_record_size) {
78 page = ERR_PTR(-ENOENT);
79 ntfs_error(vol->sb, "Attempt to read mft record 0x%lx, "
80 "which is beyond the end of the mft. "
81 "This is probably a bug in the ntfs "
82 "driver.", ni->mft_no);
86 /* Read, map, and pin the page. */
87 page = ntfs_map_page(mft_vi->i_mapping, index);
88 if (likely(!IS_ERR(page))) {
89 /* Catch multi sector transfer fixup errors. */
90 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
94 return page_address(page) + ofs;
96 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
97 "Run chkdsk.", ni->mft_no);
98 ntfs_unmap_page(page);
109 * map_mft_record - map, pin and lock an mft record
110 * @ni: ntfs inode whose MFT record to map
112 * First, take the mrec_lock mutex. We might now be sleeping, while waiting
113 * for the mutex if it was already locked by someone else.
115 * The page of the record is mapped using map_mft_record_page() before being
116 * returned to the caller.
118 * This in turn uses ntfs_map_page() to get the page containing the wanted mft
119 * record (it in turn calls read_cache_page() which reads it in from disk if
120 * necessary, increments the use count on the page so that it cannot disappear
121 * under us and returns a reference to the page cache page).
123 * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
124 * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
125 * and the post-read mst fixups on each mft record in the page have been
126 * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
127 * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
128 * ntfs_map_page() waits for PG_locked to become clear and checks if
129 * PG_uptodate is set and returns an error code if not. This provides
130 * sufficient protection against races when reading/using the page.
132 * However there is the write mapping to think about. Doing the above described
133 * checking here will be fine, because when initiating the write we will set
134 * PG_locked and clear PG_uptodate making sure nobody is touching the page
135 * contents. Doing the locking this way means that the commit to disk code in
136 * the page cache code paths is automatically sufficiently locked with us as
137 * we will not touch a page that has been locked or is not uptodate. The only
138 * locking problem then is them locking the page while we are accessing it.
140 * So that code will end up having to own the mrec_lock of all mft
141 * records/inodes present in the page before I/O can proceed. In that case we
142 * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
143 * accessing anything without owning the mrec_lock mutex. But we do need to
144 * use them because of the read_cache_page() invocation and the code becomes so
145 * much simpler this way that it is well worth it.
147 * The mft record is now ours and we return a pointer to it. You need to check
148 * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
151 * NOTE: Caller is responsible for setting the mft record dirty before calling
152 * unmap_mft_record(). This is obviously only necessary if the caller really
153 * modified the mft record...
154 * Q: Do we want to recycle one of the VFS inode state bits instead?
155 * A: No, the inode ones mean we want to change the mft record, not we want to
158 MFT_RECORD *map_mft_record(ntfs_inode *ni)
162 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
164 /* Make sure the ntfs inode doesn't go away. */
165 atomic_inc(&ni->count);
167 /* Serialize access to this mft record. */
168 mutex_lock(&ni->mrec_lock);
170 m = map_mft_record_page(ni);
171 if (likely(!IS_ERR(m)))
174 mutex_unlock(&ni->mrec_lock);
175 atomic_dec(&ni->count);
176 ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
181 * unmap_mft_record_page - unmap the page in which a specific mft record resides
182 * @ni: ntfs inode whose mft record page to unmap
184 * This unmaps the page in which the mft record of the ntfs inode @ni is
185 * situated and returns. This is a NOOP if highmem is not configured.
187 * The unmap happens via ntfs_unmap_page() which in turn decrements the use
188 * count on the page thus releasing it from the pinned state.
190 * We do not actually unmap the page from memory of course, as that will be
191 * done by the page cache code itself when memory pressure increases or
194 static inline void unmap_mft_record_page(ntfs_inode *ni)
198 // TODO: If dirty, blah...
199 ntfs_unmap_page(ni->page);
206 * unmap_mft_record - release a mapped mft record
207 * @ni: ntfs inode whose MFT record to unmap
209 * We release the page mapping and the mrec_lock mutex which unmaps the mft
210 * record and releases it for others to get hold of. We also release the ntfs
211 * inode by decrementing the ntfs inode reference count.
213 * NOTE: If caller has modified the mft record, it is imperative to set the mft
214 * record dirty BEFORE calling unmap_mft_record().
216 void unmap_mft_record(ntfs_inode *ni)
218 struct page *page = ni->page;
222 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
224 unmap_mft_record_page(ni);
225 mutex_unlock(&ni->mrec_lock);
226 atomic_dec(&ni->count);
228 * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
229 * ntfs_clear_extent_inode() in the extent inode case, and to the
230 * caller in the non-extent, yet pure ntfs inode case, to do the actual
231 * tear down of all structures and freeing of all allocated memory.
237 * map_extent_mft_record - load an extent inode and attach it to its base
238 * @base_ni: base ntfs inode
239 * @mref: mft reference of the extent inode to load
240 * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
242 * Load the extent mft record @mref and attach it to its base inode @base_ni.
243 * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
244 * PTR_ERR(result) gives the negative error code.
246 * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
247 * structure of the mapped extent inode.
249 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
250 ntfs_inode **ntfs_ino)
253 ntfs_inode *ni = NULL;
254 ntfs_inode **extent_nis = NULL;
256 unsigned long mft_no = MREF(mref);
257 u16 seq_no = MSEQNO(mref);
258 bool destroy_ni = false;
260 ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
261 mft_no, base_ni->mft_no);
262 /* Make sure the base ntfs inode doesn't go away. */
263 atomic_inc(&base_ni->count);
265 * Check if this extent inode has already been added to the base inode,
266 * in which case just return it. If not found, add it to the base
267 * inode before returning it.
269 mutex_lock(&base_ni->extent_lock);
270 if (base_ni->nr_extents > 0) {
271 extent_nis = base_ni->ext.extent_ntfs_inos;
272 for (i = 0; i < base_ni->nr_extents; i++) {
273 if (mft_no != extent_nis[i]->mft_no)
276 /* Make sure the ntfs inode doesn't go away. */
277 atomic_inc(&ni->count);
281 if (likely(ni != NULL)) {
282 mutex_unlock(&base_ni->extent_lock);
283 atomic_dec(&base_ni->count);
284 /* We found the record; just have to map and return it. */
285 m = map_mft_record(ni);
286 /* map_mft_record() has incremented this on success. */
287 atomic_dec(&ni->count);
288 if (likely(!IS_ERR(m))) {
289 /* Verify the sequence number. */
290 if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
291 ntfs_debug("Done 1.");
295 unmap_mft_record(ni);
296 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
297 "reference! Corrupt filesystem. "
299 return ERR_PTR(-EIO);
302 ntfs_error(base_ni->vol->sb, "Failed to map extent "
303 "mft record, error code %ld.", -PTR_ERR(m));
306 /* Record wasn't there. Get a new ntfs inode and initialize it. */
307 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
309 mutex_unlock(&base_ni->extent_lock);
310 atomic_dec(&base_ni->count);
311 return ERR_PTR(-ENOMEM);
313 ni->vol = base_ni->vol;
316 ni->ext.base_ntfs_ino = base_ni;
317 /* Now map the record. */
318 m = map_mft_record(ni);
320 mutex_unlock(&base_ni->extent_lock);
321 atomic_dec(&base_ni->count);
322 ntfs_clear_extent_inode(ni);
325 /* Verify the sequence number if it is present. */
326 if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
327 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
328 "reference! Corrupt filesystem. Run chkdsk.");
333 /* Attach extent inode to base inode, reallocating memory if needed. */
334 if (!(base_ni->nr_extents & 3)) {
336 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
338 tmp = kmalloc(new_size, GFP_NOFS);
339 if (unlikely(!tmp)) {
340 ntfs_error(base_ni->vol->sb, "Failed to allocate "
343 m = ERR_PTR(-ENOMEM);
346 if (base_ni->nr_extents) {
347 BUG_ON(!base_ni->ext.extent_ntfs_inos);
348 memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
349 4 * sizeof(ntfs_inode *));
350 kfree(base_ni->ext.extent_ntfs_inos);
352 base_ni->ext.extent_ntfs_inos = tmp;
354 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
355 mutex_unlock(&base_ni->extent_lock);
356 atomic_dec(&base_ni->count);
357 ntfs_debug("Done 2.");
361 unmap_mft_record(ni);
362 mutex_unlock(&base_ni->extent_lock);
363 atomic_dec(&base_ni->count);
365 * If the extent inode was not attached to the base inode we need to
366 * release it or we will leak memory.
369 ntfs_clear_extent_inode(ni);
376 * __mark_mft_record_dirty - set the mft record and the page containing it dirty
377 * @ni: ntfs inode describing the mapped mft record
379 * Internal function. Users should call mark_mft_record_dirty() instead.
381 * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
382 * as well as the page containing the mft record, dirty. Also, mark the base
383 * vfs inode dirty. This ensures that any changes to the mft record are
384 * written out to disk.
386 * NOTE: We only set I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
387 * on the base vfs inode, because even though file data may have been modified,
388 * it is dirty in the inode meta data rather than the data page cache of the
389 * inode, and thus there are no data pages that need writing out. Therefore, a
390 * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
391 * other hand, is not sufficient, because ->write_inode needs to be called even
392 * in case of fdatasync. This needs to happen or the file data would not
393 * necessarily hit the device synchronously, even though the vfs inode has the
394 * O_SYNC flag set. Also, I_DIRTY_DATASYNC simply "feels" better than just
395 * I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
396 * which is not what I_DIRTY_SYNC on its own would suggest.
398 void __mark_mft_record_dirty(ntfs_inode *ni)
402 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
403 BUG_ON(NInoAttr(ni));
404 mark_ntfs_record_dirty(ni->page, ni->page_ofs);
405 /* Determine the base vfs inode and mark it dirty, too. */
406 mutex_lock(&ni->extent_lock);
407 if (likely(ni->nr_extents >= 0))
410 base_ni = ni->ext.base_ntfs_ino;
411 mutex_unlock(&ni->extent_lock);
412 __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_DATASYNC);
415 static const char *ntfs_please_email = "Please email "
417 "this message. Thank you.";
420 * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
421 * @vol: ntfs volume on which the mft record to synchronize resides
422 * @mft_no: mft record number of mft record to synchronize
423 * @m: mapped, mst protected (extent) mft record to synchronize
425 * Write the mapped, mst protected (extent) mft record @m with mft record
426 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
427 * bypassing the page cache and the $MFTMirr inode itself.
429 * This function is only for use at umount time when the mft mirror inode has
430 * already been disposed off. We BUG() if we are called while the mft mirror
431 * inode is still attached to the volume.
433 * On success return 0. On error return -errno.
435 * NOTE: This function is not implemented yet as I am not convinced it can
436 * actually be triggered considering the sequence of commits we do in super.c::
437 * ntfs_put_super(). But just in case we provide this place holder as the
438 * alternative would be either to BUG() or to get a NULL pointer dereference
441 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
442 const unsigned long mft_no, MFT_RECORD *m)
444 BUG_ON(vol->mftmirr_ino);
445 ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
446 "implemented yet. %s", ntfs_please_email);
451 * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
452 * @vol: ntfs volume on which the mft record to synchronize resides
453 * @mft_no: mft record number of mft record to synchronize
454 * @m: mapped, mst protected (extent) mft record to synchronize
455 * @sync: if true, wait for i/o completion
457 * Write the mapped, mst protected (extent) mft record @m with mft record
458 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
460 * On success return 0. On error return -errno and set the volume errors flag
461 * in the ntfs volume @vol.
463 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
465 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
466 * schedule i/o via ->writepage or do it via kntfsd or whatever.
468 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
469 MFT_RECORD *m, int sync)
472 unsigned int blocksize = vol->sb->s_blocksize;
473 int max_bhs = vol->mft_record_size / blocksize;
474 struct buffer_head *bhs[MAX_BHS];
475 struct buffer_head *bh, *head;
478 unsigned int block_start, block_end, m_start, m_end, page_ofs;
479 int i_bhs, nr_bhs, err = 0;
480 unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
482 ntfs_debug("Entering for inode 0x%lx.", mft_no);
484 if (WARN_ON(max_bhs > MAX_BHS))
486 if (unlikely(!vol->mftmirr_ino)) {
487 /* This could happen during umount... */
488 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
493 /* Get the page containing the mirror copy of the mft record @m. */
494 page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
495 (PAGE_SHIFT - vol->mft_record_size_bits));
497 ntfs_error(vol->sb, "Failed to map mft mirror page.");
502 BUG_ON(!PageUptodate(page));
503 ClearPageUptodate(page);
504 /* Offset of the mft mirror record inside the page. */
505 page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
506 /* The address in the page of the mirror copy of the mft record @m. */
507 kmirr = page_address(page) + page_ofs;
508 /* Copy the mst protected mft record to the mirror. */
509 memcpy(kmirr, m, vol->mft_record_size);
510 /* Create uptodate buffers if not present. */
511 if (unlikely(!page_has_buffers(page))) {
512 struct buffer_head *tail;
514 bh = head = alloc_page_buffers(page, blocksize, true);
516 set_buffer_uptodate(bh);
518 bh = bh->b_this_page;
520 tail->b_this_page = head;
521 attach_page_buffers(page, head);
523 bh = head = page_buffers(page);
528 m_start = kmirr - (u8*)page_address(page);
529 m_end = m_start + vol->mft_record_size;
531 block_end = block_start + blocksize;
532 /* If the buffer is outside the mft record, skip it. */
533 if (block_end <= m_start)
535 if (unlikely(block_start >= m_end))
537 /* Need to map the buffer if it is not mapped already. */
538 if (unlikely(!buffer_mapped(bh))) {
541 unsigned int vcn_ofs;
543 bh->b_bdev = vol->sb->s_bdev;
544 /* Obtain the vcn and offset of the current block. */
545 vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
546 (block_start - m_start);
547 vcn_ofs = vcn & vol->cluster_size_mask;
548 vcn >>= vol->cluster_size_bits;
550 down_read(&NTFS_I(vol->mftmirr_ino)->
552 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
554 * $MFTMirr always has the whole of its runlist
559 /* Seek to element containing target vcn. */
560 while (rl->length && rl[1].vcn <= vcn)
562 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
563 /* For $MFTMirr, only lcn >= 0 is a successful remap. */
564 if (likely(lcn >= 0)) {
565 /* Setup buffer head to correct block. */
566 bh->b_blocknr = ((lcn <<
567 vol->cluster_size_bits) +
568 vcn_ofs) >> blocksize_bits;
569 set_buffer_mapped(bh);
572 ntfs_error(vol->sb, "Cannot write mft mirror "
573 "record 0x%lx because its "
574 "location on disk could not "
575 "be determined (error code "
581 BUG_ON(!buffer_uptodate(bh));
582 BUG_ON(!nr_bhs && (m_start != block_start));
583 BUG_ON(nr_bhs >= max_bhs);
585 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
586 } while (block_start = block_end, (bh = bh->b_this_page) != head);
588 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
590 /* Lock buffers and start synchronous write i/o on them. */
591 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
592 struct buffer_head *tbh = bhs[i_bhs];
594 if (!trylock_buffer(tbh))
596 BUG_ON(!buffer_uptodate(tbh));
597 clear_buffer_dirty(tbh);
599 tbh->b_end_io = end_buffer_write_sync;
600 submit_bh(REQ_OP_WRITE, 0, tbh);
602 /* Wait on i/o completion of buffers. */
603 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
604 struct buffer_head *tbh = bhs[i_bhs];
607 if (unlikely(!buffer_uptodate(tbh))) {
610 * Set the buffer uptodate so the page and
611 * buffer states do not become out of sync.
613 set_buffer_uptodate(tbh);
616 } else /* if (unlikely(err)) */ {
617 /* Clean the buffers. */
618 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
619 clear_buffer_dirty(bhs[i_bhs]);
621 /* Current state: all buffers are clean, unlocked, and uptodate. */
622 /* Remove the mst protection fixups again. */
623 post_write_mst_fixup((NTFS_RECORD*)kmirr);
624 flush_dcache_page(page);
625 SetPageUptodate(page);
627 ntfs_unmap_page(page);
631 ntfs_error(vol->sb, "I/O error while writing mft mirror "
632 "record 0x%lx!", mft_no);
634 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
635 "code %i). Volume will be left marked dirty "
636 "on umount. Run ntfsfix on the partition "
637 "after umounting to correct this.", -err);
644 * write_mft_record_nolock - write out a mapped (extent) mft record
645 * @ni: ntfs inode describing the mapped (extent) mft record
646 * @m: mapped (extent) mft record to write
647 * @sync: if true, wait for i/o completion
649 * Write the mapped (extent) mft record @m described by the (regular or extent)
650 * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
651 * the mft mirror, that is also updated.
653 * We only write the mft record if the ntfs inode @ni is dirty and the first
654 * buffer belonging to its mft record is dirty, too. We ignore the dirty state
655 * of subsequent buffers because we could have raced with
656 * fs/ntfs/aops.c::mark_ntfs_record_dirty().
658 * On success, clean the mft record and return 0. On error, leave the mft
659 * record dirty and return -errno.
661 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
662 * However, if the mft record has a counterpart in the mft mirror and @sync is
663 * true, we write the mft record, wait for i/o completion, and only then write
664 * the mft mirror copy. This ensures that if the system crashes either the mft
665 * or the mft mirror will contain a self-consistent mft record @m. If @sync is
666 * false on the other hand, we start i/o on both and then wait for completion
667 * on them. This provides a speedup but no longer guarantees that you will end
668 * up with a self-consistent mft record in the case of a crash but if you asked
669 * for asynchronous writing you probably do not care about that anyway.
671 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
672 * schedule i/o via ->writepage or do it via kntfsd or whatever.
674 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
676 ntfs_volume *vol = ni->vol;
677 struct page *page = ni->page;
678 unsigned int blocksize = vol->sb->s_blocksize;
679 unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
680 int max_bhs = vol->mft_record_size / blocksize;
681 struct buffer_head *bhs[MAX_BHS];
682 struct buffer_head *bh, *head;
684 unsigned int block_start, block_end, m_start, m_end;
685 int i_bhs, nr_bhs, err = 0;
687 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
688 BUG_ON(NInoAttr(ni));
690 BUG_ON(!PageLocked(page));
691 if (WARN_ON(max_bhs > MAX_BHS)) {
696 * If the ntfs_inode is clean no need to do anything. If it is dirty,
697 * mark it as clean now so that it can be redirtied later on if needed.
698 * There is no danger of races since the caller is holding the locks
699 * for the mft record @m and the page it is in.
701 if (!NInoTestClearDirty(ni))
703 bh = head = page_buffers(page);
708 m_start = ni->page_ofs;
709 m_end = m_start + vol->mft_record_size;
711 block_end = block_start + blocksize;
712 /* If the buffer is outside the mft record, skip it. */
713 if (block_end <= m_start)
715 if (unlikely(block_start >= m_end))
718 * If this block is not the first one in the record, we ignore
719 * the buffer's dirty state because we could have raced with a
720 * parallel mark_ntfs_record_dirty().
722 if (block_start == m_start) {
723 /* This block is the first one in the record. */
724 if (!buffer_dirty(bh)) {
726 /* Clean records are not written out. */
730 /* Need to map the buffer if it is not mapped already. */
731 if (unlikely(!buffer_mapped(bh))) {
734 unsigned int vcn_ofs;
736 bh->b_bdev = vol->sb->s_bdev;
737 /* Obtain the vcn and offset of the current block. */
738 vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
739 (block_start - m_start);
740 vcn_ofs = vcn & vol->cluster_size_mask;
741 vcn >>= vol->cluster_size_bits;
743 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
744 rl = NTFS_I(vol->mft_ino)->runlist.rl;
747 /* Seek to element containing target vcn. */
748 while (rl->length && rl[1].vcn <= vcn)
750 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
751 /* For $MFT, only lcn >= 0 is a successful remap. */
752 if (likely(lcn >= 0)) {
753 /* Setup buffer head to correct block. */
754 bh->b_blocknr = ((lcn <<
755 vol->cluster_size_bits) +
756 vcn_ofs) >> blocksize_bits;
757 set_buffer_mapped(bh);
760 ntfs_error(vol->sb, "Cannot write mft record "
761 "0x%lx because its location "
762 "on disk could not be "
763 "determined (error code %lli).",
764 ni->mft_no, (long long)lcn);
768 BUG_ON(!buffer_uptodate(bh));
769 BUG_ON(!nr_bhs && (m_start != block_start));
770 BUG_ON(nr_bhs >= max_bhs);
772 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
773 } while (block_start = block_end, (bh = bh->b_this_page) != head);
775 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
780 /* Apply the mst protection fixups. */
781 err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
783 ntfs_error(vol->sb, "Failed to apply mst fixups!");
786 flush_dcache_mft_record_page(ni);
787 /* Lock buffers and start synchronous write i/o on them. */
788 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
789 struct buffer_head *tbh = bhs[i_bhs];
791 if (!trylock_buffer(tbh))
793 BUG_ON(!buffer_uptodate(tbh));
794 clear_buffer_dirty(tbh);
796 tbh->b_end_io = end_buffer_write_sync;
797 submit_bh(REQ_OP_WRITE, 0, tbh);
799 /* Synchronize the mft mirror now if not @sync. */
800 if (!sync && ni->mft_no < vol->mftmirr_size)
801 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
802 /* Wait on i/o completion of buffers. */
803 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
804 struct buffer_head *tbh = bhs[i_bhs];
807 if (unlikely(!buffer_uptodate(tbh))) {
810 * Set the buffer uptodate so the page and buffer
811 * states do not become out of sync.
813 if (PageUptodate(page))
814 set_buffer_uptodate(tbh);
817 /* If @sync, now synchronize the mft mirror. */
818 if (sync && ni->mft_no < vol->mftmirr_size)
819 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
820 /* Remove the mst protection fixups again. */
821 post_write_mst_fixup((NTFS_RECORD*)m);
822 flush_dcache_mft_record_page(ni);
824 /* I/O error during writing. This is really bad! */
825 ntfs_error(vol->sb, "I/O error while writing mft record "
826 "0x%lx! Marking base inode as bad. You "
827 "should unmount the volume and run chkdsk.",
835 /* Clean the buffers. */
836 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
837 clear_buffer_dirty(bhs[i_bhs]);
840 * Current state: all buffers are clean, unlocked, and uptodate.
841 * The caller should mark the base inode as bad so that no more i/o
842 * happens. ->clear_inode() will still be invoked so all extent inodes
843 * and other allocated memory will be freed.
845 if (err == -ENOMEM) {
846 ntfs_error(vol->sb, "Not enough memory to write mft record. "
847 "Redirtying so the write is retried later.");
848 mark_mft_record_dirty(ni);
856 * ntfs_may_write_mft_record - check if an mft record may be written out
857 * @vol: [IN] ntfs volume on which the mft record to check resides
858 * @mft_no: [IN] mft record number of the mft record to check
859 * @m: [IN] mapped mft record to check
860 * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
862 * Check if the mapped (base or extent) mft record @m with mft record number
863 * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
864 * and possible the ntfs inode of the mft record is locked and the base vfs
865 * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
866 * caller is responsible for unlocking the ntfs inode and unpinning the base
869 * Return 'true' if the mft record may be written out and 'false' if not.
871 * The caller has locked the page and cleared the uptodate flag on it which
872 * means that we can safely write out any dirty mft records that do not have
873 * their inodes in icache as determined by ilookup5() as anyone
874 * opening/creating such an inode would block when attempting to map the mft
875 * record in read_cache_page() until we are finished with the write out.
877 * Here is a description of the tests we perform:
879 * If the inode is found in icache we know the mft record must be a base mft
880 * record. If it is dirty, we do not write it and return 'false' as the vfs
881 * inode write paths will result in the access times being updated which would
882 * cause the base mft record to be redirtied and written out again. (We know
883 * the access time update will modify the base mft record because Windows
884 * chkdsk complains if the standard information attribute is not in the base
887 * If the inode is in icache and not dirty, we attempt to lock the mft record
888 * and if we find the lock was already taken, it is not safe to write the mft
889 * record and we return 'false'.
891 * If we manage to obtain the lock we have exclusive access to the mft record,
892 * which also allows us safe writeout of the mft record. We then set
893 * @locked_ni to the locked ntfs inode and return 'true'.
895 * Note we cannot just lock the mft record and sleep while waiting for the lock
896 * because this would deadlock due to lock reversal (normally the mft record is
897 * locked before the page is locked but we already have the page locked here
898 * when we try to lock the mft record).
900 * If the inode is not in icache we need to perform further checks.
902 * If the mft record is not a FILE record or it is a base mft record, we can
903 * safely write it and return 'true'.
905 * We now know the mft record is an extent mft record. We check if the inode
906 * corresponding to its base mft record is in icache and obtain a reference to
907 * it if it is. If it is not, we can safely write it and return 'true'.
909 * We now have the base inode for the extent mft record. We check if it has an
910 * ntfs inode for the extent mft record attached and if not it is safe to write
911 * the extent mft record and we return 'true'.
913 * The ntfs inode for the extent mft record is attached to the base inode so we
914 * attempt to lock the extent mft record and if we find the lock was already
915 * taken, it is not safe to write the extent mft record and we return 'false'.
917 * If we manage to obtain the lock we have exclusive access to the extent mft
918 * record, which also allows us safe writeout of the extent mft record. We
919 * set the ntfs inode of the extent mft record clean and then set @locked_ni to
920 * the now locked ntfs inode and return 'true'.
922 * Note, the reason for actually writing dirty mft records here and not just
923 * relying on the vfs inode dirty code paths is that we can have mft records
924 * modified without them ever having actual inodes in memory. Also we can have
925 * dirty mft records with clean ntfs inodes in memory. None of the described
926 * cases would result in the dirty mft records being written out if we only
927 * relied on the vfs inode dirty code paths. And these cases can really occur
928 * during allocation of new mft records and in particular when the
929 * initialized_size of the $MFT/$DATA attribute is extended and the new space
930 * is initialized using ntfs_mft_record_format(). The clean inode can then
931 * appear if the mft record is reused for a new inode before it got written
934 bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
935 const MFT_RECORD *m, ntfs_inode **locked_ni)
937 struct super_block *sb = vol->sb;
938 struct inode *mft_vi = vol->mft_ino;
940 ntfs_inode *ni, *eni, **extent_nis;
944 ntfs_debug("Entering for inode 0x%lx.", mft_no);
946 * Normally we do not return a locked inode so set @locked_ni to NULL.
951 * Check if the inode corresponding to this mft record is in the VFS
952 * inode cache and obtain a reference to it if it is.
954 ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
960 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
961 * we get here for it rather often.
964 /* Balance the below iput(). */
966 BUG_ON(vi != mft_vi);
969 * Have to use ilookup5_nowait() since ilookup5() waits for the
970 * inode lock which causes ntfs to deadlock when a concurrent
971 * inode write via the inode dirty code paths and the page
972 * dirty code path of the inode dirty code path when writing
975 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
978 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
979 /* The inode is in icache. */
981 /* Take a reference to the ntfs inode. */
982 atomic_inc(&ni->count);
983 /* If the inode is dirty, do not write this record. */
985 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
987 atomic_dec(&ni->count);
991 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
992 /* The inode is not dirty, try to take the mft record lock. */
993 if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
994 ntfs_debug("Mft record 0x%lx is already locked, do "
995 "not write it.", mft_no);
996 atomic_dec(&ni->count);
1000 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
1003 * The write has to occur while we hold the mft record lock so
1004 * return the locked ntfs inode.
1009 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1010 /* The inode is not in icache. */
1011 /* Write the record if it is not a mft record (type "FILE"). */
1012 if (!ntfs_is_mft_record(m->magic)) {
1013 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1017 /* Write the mft record if it is a base inode. */
1018 if (!m->base_mft_record) {
1019 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1024 * This is an extent mft record. Check if the inode corresponding to
1025 * its base mft record is in icache and obtain a reference to it if it
1028 na.mft_no = MREF_LE(m->base_mft_record);
1029 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1030 "inode 0x%lx in icache.", mft_no, na.mft_no);
1032 /* Balance the below iput(). */
1034 BUG_ON(vi != mft_vi);
1036 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1040 * The base inode is not in icache, write this extent mft
1043 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1044 "extent record.", na.mft_no);
1047 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1049 * The base inode is in icache. Check if it has the extent inode
1050 * corresponding to this extent mft record attached.
1053 mutex_lock(&ni->extent_lock);
1054 if (ni->nr_extents <= 0) {
1056 * The base inode has no attached extent inodes, write this
1057 * extent mft record.
1059 mutex_unlock(&ni->extent_lock);
1061 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1062 "write the extent record.", na.mft_no);
1065 /* Iterate over the attached extent inodes. */
1066 extent_nis = ni->ext.extent_ntfs_inos;
1067 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1068 if (mft_no == extent_nis[i]->mft_no) {
1070 * Found the extent inode corresponding to this extent
1073 eni = extent_nis[i];
1078 * If the extent inode was not attached to the base inode, write this
1079 * extent mft record.
1082 mutex_unlock(&ni->extent_lock);
1084 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1085 "inode 0x%lx, write the extent record.",
1089 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1091 /* Take a reference to the extent ntfs inode. */
1092 atomic_inc(&eni->count);
1093 mutex_unlock(&ni->extent_lock);
1095 * Found the extent inode coresponding to this extent mft record.
1096 * Try to take the mft record lock.
1098 if (unlikely(!mutex_trylock(&eni->mrec_lock))) {
1099 atomic_dec(&eni->count);
1101 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1102 "not write it.", mft_no);
1105 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1107 if (NInoTestClearDirty(eni))
1108 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1111 * The write has to occur while we hold the mft record lock so return
1112 * the locked extent ntfs inode.
1118 static const char *es = " Leaving inconsistent metadata. Unmount and run "
1122 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1123 * @vol: volume on which to search for a free mft record
1124 * @base_ni: open base inode if allocating an extent mft record or NULL
1126 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1129 * If @base_ni is NULL start the search at the default allocator position.
1131 * If @base_ni is not NULL start the search at the mft record after the base
1132 * mft record @base_ni.
1134 * Return the free mft record on success and -errno on error. An error code of
1135 * -ENOSPC means that there are no free mft records in the currently
1136 * initialized mft bitmap.
1138 * Locking: Caller must hold vol->mftbmp_lock for writing.
1140 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1141 ntfs_inode *base_ni)
1143 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1144 unsigned long flags;
1145 struct address_space *mftbmp_mapping;
1148 unsigned int page_ofs, size;
1151 ntfs_debug("Searching for free mft record in the currently "
1152 "initialized mft bitmap.");
1153 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1155 * Set the end of the pass making sure we do not overflow the mft
1158 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1159 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1160 vol->mft_record_size_bits;
1161 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1162 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1163 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1164 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1169 data_pos = vol->mft_data_pos;
1171 data_pos = base_ni->mft_no + 1;
1174 if (data_pos >= pass_end) {
1177 /* This happens on a freshly formatted volume. */
1178 if (data_pos >= pass_end)
1181 pass_start = data_pos;
1182 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1183 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1184 (long long)pass_start, (long long)pass_end,
1185 (long long)data_pos);
1186 /* Loop until a free mft record is found. */
1187 for (; pass <= 2;) {
1188 /* Cap size to pass_end. */
1189 ofs = data_pos >> 3;
1190 page_ofs = ofs & ~PAGE_MASK;
1191 size = PAGE_SIZE - page_ofs;
1192 ll = ((pass_end + 7) >> 3) - ofs;
1197 * If we are still within the active pass, search the next page
1201 page = ntfs_map_page(mftbmp_mapping,
1204 ntfs_error(vol->sb, "Failed to read mft "
1205 "bitmap, aborting.");
1206 return PTR_ERR(page);
1208 buf = (u8*)page_address(page) + page_ofs;
1211 ntfs_debug("Before inner for loop: size 0x%x, "
1212 "data_pos 0x%llx, bit 0x%llx", size,
1213 (long long)data_pos, (long long)bit);
1214 for (; bit < size && data_pos + bit < pass_end;
1215 bit &= ~7ull, bit += 8) {
1216 byte = buf + (bit >> 3);
1219 b = ffz((unsigned long)*byte);
1220 if (b < 8 && b >= (bit & 7)) {
1221 ll = data_pos + (bit & ~7ull) + b;
1222 if (unlikely(ll > (1ll << 32))) {
1223 ntfs_unmap_page(page);
1227 flush_dcache_page(page);
1228 set_page_dirty(page);
1229 ntfs_unmap_page(page);
1230 ntfs_debug("Done. (Found and "
1231 "allocated mft record "
1237 ntfs_debug("After inner for loop: size 0x%x, "
1238 "data_pos 0x%llx, bit 0x%llx", size,
1239 (long long)data_pos, (long long)bit);
1241 ntfs_unmap_page(page);
1243 * If the end of the pass has not been reached yet,
1244 * continue searching the mft bitmap for a zero bit.
1246 if (data_pos < pass_end)
1249 /* Do the next pass. */
1252 * Starting the second pass, in which we scan the first
1253 * part of the zone which we omitted earlier.
1255 pass_end = pass_start;
1256 data_pos = pass_start = 24;
1257 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1258 "0x%llx.", pass, (long long)pass_start,
1259 (long long)pass_end);
1260 if (data_pos >= pass_end)
1264 /* No free mft records in currently initialized mft bitmap. */
1265 ntfs_debug("Done. (No free mft records left in currently initialized "
1271 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1272 * @vol: volume on which to extend the mft bitmap attribute
1274 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1276 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1279 * Return 0 on success and -errno on error.
1281 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1282 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1283 * writing and releases it before returning.
1284 * - This function takes vol->lcnbmp_lock for writing and releases it
1287 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1291 unsigned long flags;
1293 ntfs_inode *mft_ni, *mftbmp_ni;
1294 runlist_element *rl, *rl2 = NULL;
1295 ntfs_attr_search_ctx *ctx = NULL;
1297 ATTR_RECORD *a = NULL;
1305 } status = { 0, 0, 0 };
1307 ntfs_debug("Extending mft bitmap allocation.");
1308 mft_ni = NTFS_I(vol->mft_ino);
1309 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1311 * Determine the last lcn of the mft bitmap. The allocated size of the
1312 * mft bitmap cannot be zero so we are ok to do this.
1314 down_write(&mftbmp_ni->runlist.lock);
1315 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1316 ll = mftbmp_ni->allocated_size;
1317 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1318 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1319 (ll - 1) >> vol->cluster_size_bits, NULL);
1320 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1321 up_write(&mftbmp_ni->runlist.lock);
1322 ntfs_error(vol->sb, "Failed to determine last allocated "
1323 "cluster of mft bitmap attribute.");
1330 lcn = rl->lcn + rl->length;
1331 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1334 * Attempt to get the cluster following the last allocated cluster by
1335 * hand as it may be in the MFT zone so the allocator would not give it
1339 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1342 up_write(&mftbmp_ni->runlist.lock);
1343 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1344 return PTR_ERR(page);
1346 b = (u8*)page_address(page) + (ll & ~PAGE_MASK);
1347 tb = 1 << (lcn & 7ull);
1348 down_write(&vol->lcnbmp_lock);
1349 if (*b != 0xff && !(*b & tb)) {
1350 /* Next cluster is free, allocate it. */
1352 flush_dcache_page(page);
1353 set_page_dirty(page);
1354 up_write(&vol->lcnbmp_lock);
1355 ntfs_unmap_page(page);
1356 /* Update the mft bitmap runlist. */
1359 status.added_cluster = 1;
1360 ntfs_debug("Appending one cluster to mft bitmap.");
1362 up_write(&vol->lcnbmp_lock);
1363 ntfs_unmap_page(page);
1364 /* Allocate a cluster from the DATA_ZONE. */
1365 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
1368 up_write(&mftbmp_ni->runlist.lock);
1369 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1371 return PTR_ERR(rl2);
1373 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1375 up_write(&mftbmp_ni->runlist.lock);
1376 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1378 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1379 ntfs_error(vol->sb, "Failed to deallocate "
1380 "allocated cluster.%s", es);
1386 mftbmp_ni->runlist.rl = rl;
1387 status.added_run = 1;
1388 ntfs_debug("Adding one run to mft bitmap.");
1389 /* Find the last run in the new runlist. */
1390 for (; rl[1].length; rl++)
1394 * Update the attribute record as well. Note: @rl is the last
1395 * (non-terminator) runlist element of mft bitmap.
1397 mrec = map_mft_record(mft_ni);
1399 ntfs_error(vol->sb, "Failed to map mft record.");
1400 ret = PTR_ERR(mrec);
1403 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1404 if (unlikely(!ctx)) {
1405 ntfs_error(vol->sb, "Failed to get search context.");
1409 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1410 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1412 if (unlikely(ret)) {
1413 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1414 "mft bitmap attribute.");
1420 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1421 /* Search back for the previous last allocated cluster of mft bitmap. */
1422 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1426 BUG_ON(ll < rl2->vcn);
1427 BUG_ON(ll >= rl2->vcn + rl2->length);
1428 /* Get the size for the new mapping pairs array for this extent. */
1429 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1430 if (unlikely(mp_size <= 0)) {
1431 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1432 "mft bitmap attribute extent.");
1438 /* Expand the attribute record if necessary. */
1439 old_alen = le32_to_cpu(a->length);
1440 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1441 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1442 if (unlikely(ret)) {
1443 if (ret != -ENOSPC) {
1444 ntfs_error(vol->sb, "Failed to resize attribute "
1445 "record for mft bitmap attribute.");
1448 // TODO: Deal with this by moving this extent to a new mft
1449 // record or by starting a new extent in a new mft record or by
1450 // moving other attributes out of this mft record.
1451 // Note: It will need to be a special mft record and if none of
1452 // those are available it gets rather complicated...
1453 ntfs_error(vol->sb, "Not enough space in this mft record to "
1454 "accommodate extended mft bitmap attribute "
1455 "extent. Cannot handle this yet.");
1459 status.mp_rebuilt = 1;
1460 /* Generate the mapping pairs array directly into the attr record. */
1461 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1462 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1463 mp_size, rl2, ll, -1, NULL);
1464 if (unlikely(ret)) {
1465 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1466 "mft bitmap attribute.");
1469 /* Update the highest_vcn. */
1470 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1472 * We now have extended the mft bitmap allocated_size by one cluster.
1473 * Reflect this in the ntfs_inode structure and the attribute record.
1475 if (a->data.non_resident.lowest_vcn) {
1477 * We are not in the first attribute extent, switch to it, but
1478 * first ensure the changes will make it to disk later.
1480 flush_dcache_mft_record_page(ctx->ntfs_ino);
1481 mark_mft_record_dirty(ctx->ntfs_ino);
1482 ntfs_attr_reinit_search_ctx(ctx);
1483 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1484 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1486 if (unlikely(ret)) {
1487 ntfs_error(vol->sb, "Failed to find first attribute "
1488 "extent of mft bitmap attribute.");
1489 goto restore_undo_alloc;
1493 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1494 mftbmp_ni->allocated_size += vol->cluster_size;
1495 a->data.non_resident.allocated_size =
1496 cpu_to_sle64(mftbmp_ni->allocated_size);
1497 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1498 /* Ensure the changes make it to disk. */
1499 flush_dcache_mft_record_page(ctx->ntfs_ino);
1500 mark_mft_record_dirty(ctx->ntfs_ino);
1501 ntfs_attr_put_search_ctx(ctx);
1502 unmap_mft_record(mft_ni);
1503 up_write(&mftbmp_ni->runlist.lock);
1504 ntfs_debug("Done.");
1507 ntfs_attr_reinit_search_ctx(ctx);
1508 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1509 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1511 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1512 "mft bitmap attribute.%s", es);
1513 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1514 mftbmp_ni->allocated_size += vol->cluster_size;
1515 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1516 ntfs_attr_put_search_ctx(ctx);
1517 unmap_mft_record(mft_ni);
1518 up_write(&mftbmp_ni->runlist.lock);
1520 * The only thing that is now wrong is ->allocated_size of the
1521 * base attribute extent which chkdsk should be able to fix.
1527 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1529 if (status.added_cluster) {
1530 /* Truncate the last run in the runlist by one cluster. */
1533 } else if (status.added_run) {
1535 /* Remove the last run from the runlist. */
1536 rl->lcn = rl[1].lcn;
1539 /* Deallocate the cluster. */
1540 down_write(&vol->lcnbmp_lock);
1541 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1542 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1545 up_write(&vol->lcnbmp_lock);
1546 if (status.mp_rebuilt) {
1547 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1548 a->data.non_resident.mapping_pairs_offset),
1549 old_alen - le16_to_cpu(
1550 a->data.non_resident.mapping_pairs_offset),
1551 rl2, ll, -1, NULL)) {
1552 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1556 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1557 ntfs_error(vol->sb, "Failed to restore attribute "
1561 flush_dcache_mft_record_page(ctx->ntfs_ino);
1562 mark_mft_record_dirty(ctx->ntfs_ino);
1565 ntfs_attr_put_search_ctx(ctx);
1567 unmap_mft_record(mft_ni);
1568 up_write(&mftbmp_ni->runlist.lock);
1573 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1574 * @vol: volume on which to extend the mft bitmap attribute
1576 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1577 * volume @vol by 8 bytes.
1579 * Note: Only changes initialized_size and data_size, i.e. requires that
1580 * allocated_size is big enough to fit the new initialized_size.
1582 * Return 0 on success and -error on error.
1584 * Locking: Caller must hold vol->mftbmp_lock for writing.
1586 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1588 s64 old_data_size, old_initialized_size;
1589 unsigned long flags;
1590 struct inode *mftbmp_vi;
1591 ntfs_inode *mft_ni, *mftbmp_ni;
1592 ntfs_attr_search_ctx *ctx;
1597 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1598 mft_ni = NTFS_I(vol->mft_ino);
1599 mftbmp_vi = vol->mftbmp_ino;
1600 mftbmp_ni = NTFS_I(mftbmp_vi);
1601 /* Get the attribute record. */
1602 mrec = map_mft_record(mft_ni);
1604 ntfs_error(vol->sb, "Failed to map mft record.");
1605 return PTR_ERR(mrec);
1607 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1608 if (unlikely(!ctx)) {
1609 ntfs_error(vol->sb, "Failed to get search context.");
1613 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1614 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1615 if (unlikely(ret)) {
1616 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1617 "mft bitmap attribute.");
1623 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1624 old_data_size = i_size_read(mftbmp_vi);
1625 old_initialized_size = mftbmp_ni->initialized_size;
1627 * We can simply update the initialized_size before filling the space
1628 * with zeroes because the caller is holding the mft bitmap lock for
1629 * writing which ensures that no one else is trying to access the data.
1631 mftbmp_ni->initialized_size += 8;
1632 a->data.non_resident.initialized_size =
1633 cpu_to_sle64(mftbmp_ni->initialized_size);
1634 if (mftbmp_ni->initialized_size > old_data_size) {
1635 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1636 a->data.non_resident.data_size =
1637 cpu_to_sle64(mftbmp_ni->initialized_size);
1639 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1640 /* Ensure the changes make it to disk. */
1641 flush_dcache_mft_record_page(ctx->ntfs_ino);
1642 mark_mft_record_dirty(ctx->ntfs_ino);
1643 ntfs_attr_put_search_ctx(ctx);
1644 unmap_mft_record(mft_ni);
1645 /* Initialize the mft bitmap attribute value with zeroes. */
1646 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1648 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1652 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1653 /* Try to recover from the error. */
1654 mrec = map_mft_record(mft_ni);
1656 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1660 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1661 if (unlikely(!ctx)) {
1662 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1666 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1667 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1668 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1669 "mft bitmap attribute.%s", es);
1672 ntfs_attr_put_search_ctx(ctx);
1674 unmap_mft_record(mft_ni);
1678 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1679 mftbmp_ni->initialized_size = old_initialized_size;
1680 a->data.non_resident.initialized_size =
1681 cpu_to_sle64(old_initialized_size);
1682 if (i_size_read(mftbmp_vi) != old_data_size) {
1683 i_size_write(mftbmp_vi, old_data_size);
1684 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1686 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1687 flush_dcache_mft_record_page(ctx->ntfs_ino);
1688 mark_mft_record_dirty(ctx->ntfs_ino);
1689 ntfs_attr_put_search_ctx(ctx);
1690 unmap_mft_record(mft_ni);
1692 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1693 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1694 "data_size 0x%llx, initialized_size 0x%llx.",
1695 (long long)mftbmp_ni->allocated_size,
1696 (long long)i_size_read(mftbmp_vi),
1697 (long long)mftbmp_ni->initialized_size);
1698 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1705 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1706 * @vol: volume on which to extend the mft data attribute
1708 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1709 * worth of clusters or if not enough space for this by one mft record worth
1712 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1715 * Return 0 on success and -errno on error.
1717 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1718 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1719 * writing and releases it before returning.
1720 * - This function calls functions which take vol->lcnbmp_lock for
1721 * writing and release it before returning.
1723 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1728 unsigned long flags;
1730 runlist_element *rl, *rl2;
1731 ntfs_attr_search_ctx *ctx = NULL;
1733 ATTR_RECORD *a = NULL;
1736 bool mp_rebuilt = false;
1738 ntfs_debug("Extending mft data allocation.");
1739 mft_ni = NTFS_I(vol->mft_ino);
1741 * Determine the preferred allocation location, i.e. the last lcn of
1742 * the mft data attribute. The allocated size of the mft data
1743 * attribute cannot be zero so we are ok to do this.
1745 down_write(&mft_ni->runlist.lock);
1746 read_lock_irqsave(&mft_ni->size_lock, flags);
1747 ll = mft_ni->allocated_size;
1748 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1749 rl = ntfs_attr_find_vcn_nolock(mft_ni,
1750 (ll - 1) >> vol->cluster_size_bits, NULL);
1751 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1752 up_write(&mft_ni->runlist.lock);
1753 ntfs_error(vol->sb, "Failed to determine last allocated "
1754 "cluster of mft data attribute.");
1761 lcn = rl->lcn + rl->length;
1762 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1763 /* Minimum allocation is one mft record worth of clusters. */
1764 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1767 /* Want to allocate 16 mft records worth of clusters. */
1768 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1771 /* Ensure we do not go above 2^32-1 mft records. */
1772 read_lock_irqsave(&mft_ni->size_lock, flags);
1773 ll = mft_ni->allocated_size;
1774 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1775 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1776 vol->mft_record_size_bits >= (1ll << 32))) {
1778 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1779 vol->mft_record_size_bits >= (1ll << 32))) {
1780 ntfs_warning(vol->sb, "Cannot allocate mft record "
1781 "because the maximum number of inodes "
1782 "(2^32) has already been reached.");
1783 up_write(&mft_ni->runlist.lock);
1787 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1788 nr > min_nr ? "default" : "minimal", (long long)nr);
1789 old_last_vcn = rl[1].vcn;
1791 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
1793 if (likely(!IS_ERR(rl2)))
1795 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1796 ntfs_error(vol->sb, "Failed to allocate the minimal "
1797 "number of clusters (%lli) for the "
1798 "mft data attribute.", (long long)nr);
1799 up_write(&mft_ni->runlist.lock);
1800 return PTR_ERR(rl2);
1803 * There is not enough space to do the allocation, but there
1804 * might be enough space to do a minimal allocation so try that
1808 ntfs_debug("Retrying mft data allocation with minimal cluster "
1809 "count %lli.", (long long)nr);
1811 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1813 up_write(&mft_ni->runlist.lock);
1814 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1816 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1817 ntfs_error(vol->sb, "Failed to deallocate clusters "
1818 "from the mft data attribute.%s", es);
1824 mft_ni->runlist.rl = rl;
1825 ntfs_debug("Allocated %lli clusters.", (long long)nr);
1826 /* Find the last run in the new runlist. */
1827 for (; rl[1].length; rl++)
1829 /* Update the attribute record as well. */
1830 mrec = map_mft_record(mft_ni);
1832 ntfs_error(vol->sb, "Failed to map mft record.");
1833 ret = PTR_ERR(mrec);
1836 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1837 if (unlikely(!ctx)) {
1838 ntfs_error(vol->sb, "Failed to get search context.");
1842 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1843 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1844 if (unlikely(ret)) {
1845 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1846 "mft data attribute.");
1852 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1853 /* Search back for the previous last allocated cluster of mft bitmap. */
1854 for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1858 BUG_ON(ll < rl2->vcn);
1859 BUG_ON(ll >= rl2->vcn + rl2->length);
1860 /* Get the size for the new mapping pairs array for this extent. */
1861 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1862 if (unlikely(mp_size <= 0)) {
1863 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1864 "mft data attribute extent.");
1870 /* Expand the attribute record if necessary. */
1871 old_alen = le32_to_cpu(a->length);
1872 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1873 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1874 if (unlikely(ret)) {
1875 if (ret != -ENOSPC) {
1876 ntfs_error(vol->sb, "Failed to resize attribute "
1877 "record for mft data attribute.");
1880 // TODO: Deal with this by moving this extent to a new mft
1881 // record or by starting a new extent in a new mft record or by
1882 // moving other attributes out of this mft record.
1883 // Note: Use the special reserved mft records and ensure that
1884 // this extent is not required to find the mft record in
1885 // question. If no free special records left we would need to
1886 // move an existing record away, insert ours in its place, and
1887 // then place the moved record into the newly allocated space
1888 // and we would then need to update all references to this mft
1889 // record appropriately. This is rather complicated...
1890 ntfs_error(vol->sb, "Not enough space in this mft record to "
1891 "accommodate extended mft data attribute "
1892 "extent. Cannot handle this yet.");
1897 /* Generate the mapping pairs array directly into the attr record. */
1898 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1899 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1900 mp_size, rl2, ll, -1, NULL);
1901 if (unlikely(ret)) {
1902 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1903 "mft data attribute.");
1906 /* Update the highest_vcn. */
1907 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1909 * We now have extended the mft data allocated_size by nr clusters.
1910 * Reflect this in the ntfs_inode structure and the attribute record.
1911 * @rl is the last (non-terminator) runlist element of mft data
1914 if (a->data.non_resident.lowest_vcn) {
1916 * We are not in the first attribute extent, switch to it, but
1917 * first ensure the changes will make it to disk later.
1919 flush_dcache_mft_record_page(ctx->ntfs_ino);
1920 mark_mft_record_dirty(ctx->ntfs_ino);
1921 ntfs_attr_reinit_search_ctx(ctx);
1922 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1923 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1925 if (unlikely(ret)) {
1926 ntfs_error(vol->sb, "Failed to find first attribute "
1927 "extent of mft data attribute.");
1928 goto restore_undo_alloc;
1932 write_lock_irqsave(&mft_ni->size_lock, flags);
1933 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1934 a->data.non_resident.allocated_size =
1935 cpu_to_sle64(mft_ni->allocated_size);
1936 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1937 /* Ensure the changes make it to disk. */
1938 flush_dcache_mft_record_page(ctx->ntfs_ino);
1939 mark_mft_record_dirty(ctx->ntfs_ino);
1940 ntfs_attr_put_search_ctx(ctx);
1941 unmap_mft_record(mft_ni);
1942 up_write(&mft_ni->runlist.lock);
1943 ntfs_debug("Done.");
1946 ntfs_attr_reinit_search_ctx(ctx);
1947 if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1948 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1949 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1950 "mft data attribute.%s", es);
1951 write_lock_irqsave(&mft_ni->size_lock, flags);
1952 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1953 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1954 ntfs_attr_put_search_ctx(ctx);
1955 unmap_mft_record(mft_ni);
1956 up_write(&mft_ni->runlist.lock);
1958 * The only thing that is now wrong is ->allocated_size of the
1959 * base attribute extent which chkdsk should be able to fix.
1964 ctx->attr->data.non_resident.highest_vcn =
1965 cpu_to_sle64(old_last_vcn - 1);
1967 if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
1968 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1969 "attribute.%s", es);
1973 if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1974 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1978 if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
1979 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1980 a->data.non_resident.mapping_pairs_offset),
1981 old_alen - le16_to_cpu(
1982 a->data.non_resident.mapping_pairs_offset),
1983 rl2, ll, -1, NULL)) {
1984 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1988 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1989 ntfs_error(vol->sb, "Failed to restore attribute "
1993 flush_dcache_mft_record_page(ctx->ntfs_ino);
1994 mark_mft_record_dirty(ctx->ntfs_ino);
1995 } else if (IS_ERR(ctx->mrec)) {
1996 ntfs_error(vol->sb, "Failed to restore attribute search "
2001 ntfs_attr_put_search_ctx(ctx);
2003 unmap_mft_record(mft_ni);
2004 up_write(&mft_ni->runlist.lock);
2009 * ntfs_mft_record_layout - layout an mft record into a memory buffer
2010 * @vol: volume to which the mft record will belong
2011 * @mft_no: mft reference specifying the mft record number
2012 * @m: destination buffer of size >= @vol->mft_record_size bytes
2014 * Layout an empty, unused mft record with the mft record number @mft_no into
2015 * the buffer @m. The volume @vol is needed because the mft record structure
2016 * was modified in NTFS 3.1 so we need to know which volume version this mft
2017 * record will be used on.
2019 * Return 0 on success and -errno on error.
2021 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2026 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2027 if (mft_no >= (1ll << 32)) {
2028 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2029 "maximum of 2^32.", (long long)mft_no);
2032 /* Start by clearing the whole mft record to gives us a clean slate. */
2033 memset(m, 0, vol->mft_record_size);
2034 /* Aligned to 2-byte boundary. */
2035 if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2036 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2038 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2040 * Set the NTFS 3.1+ specific fields while we know that the
2041 * volume version is 3.1+.
2044 m->mft_record_number = cpu_to_le32((u32)mft_no);
2046 m->magic = magic_FILE;
2047 if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2048 m->usa_count = cpu_to_le16(vol->mft_record_size /
2049 NTFS_BLOCK_SIZE + 1);
2051 m->usa_count = cpu_to_le16(1);
2052 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2053 "size. Setting usa_count to 1. If chkdsk "
2054 "reports this as corruption, please email "
2056 "that you saw this message and that the "
2057 "modified filesystem created was corrupt. "
2060 /* Set the update sequence number to 1. */
2061 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2063 m->sequence_number = cpu_to_le16(1);
2066 * Place the attributes straight after the update sequence array,
2067 * aligned to 8-byte boundary.
2069 m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2070 (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2073 * Using attrs_offset plus eight bytes (for the termination attribute).
2074 * attrs_offset is already aligned to 8-byte boundary, so no need to
2077 m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2078 m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2079 m->base_mft_record = 0;
2080 m->next_attr_instance = 0;
2081 /* Add the termination attribute. */
2082 a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2085 ntfs_debug("Done.");
2090 * ntfs_mft_record_format - format an mft record on an ntfs volume
2091 * @vol: volume on which to format the mft record
2092 * @mft_no: mft record number to format
2094 * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2095 * mft record into the appropriate place of the mft data attribute. This is
2096 * used when extending the mft data attribute.
2098 * Return 0 on success and -errno on error.
2100 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2103 struct inode *mft_vi = vol->mft_ino;
2106 pgoff_t index, end_index;
2110 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2112 * The index into the page cache and the offset within the page cache
2113 * page of the wanted mft record.
2115 index = mft_no << vol->mft_record_size_bits >> PAGE_SHIFT;
2116 ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK;
2117 /* The maximum valid index into the page cache for $MFT's data. */
2118 i_size = i_size_read(mft_vi);
2119 end_index = i_size >> PAGE_SHIFT;
2120 if (unlikely(index >= end_index)) {
2121 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2122 (i_size & ~PAGE_MASK))) {
2123 ntfs_error(vol->sb, "Tried to format non-existing mft "
2124 "record 0x%llx.", (long long)mft_no);
2128 /* Read, map, and pin the page containing the mft record. */
2129 page = ntfs_map_page(mft_vi->i_mapping, index);
2131 ntfs_error(vol->sb, "Failed to map page containing mft record "
2132 "to format 0x%llx.", (long long)mft_no);
2133 return PTR_ERR(page);
2136 BUG_ON(!PageUptodate(page));
2137 ClearPageUptodate(page);
2138 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2139 err = ntfs_mft_record_layout(vol, mft_no, m);
2140 if (unlikely(err)) {
2141 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2143 SetPageUptodate(page);
2145 ntfs_unmap_page(page);
2148 flush_dcache_page(page);
2149 SetPageUptodate(page);
2152 * Make sure the mft record is written out to disk. We could use
2153 * ilookup5() to check if an inode is in icache and so on but this is
2154 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2156 mark_ntfs_record_dirty(page, ofs);
2157 ntfs_unmap_page(page);
2158 ntfs_debug("Done.");
2163 * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2164 * @vol: [IN] volume on which to allocate the mft record
2165 * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
2166 * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
2167 * @mrec: [OUT] on successful return this is the mapped mft record
2169 * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2171 * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2172 * direvctory inode, and allocate it at the default allocator position. In
2173 * this case @mode is the file mode as given to us by the caller. We in
2174 * particular use @mode to distinguish whether a file or a directory is being
2175 * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2177 * If @base_ni is not NULL make the allocated mft record an extent record,
2178 * allocate it starting at the mft record after the base mft record and attach
2179 * the allocated and opened ntfs inode to the base inode @base_ni. In this
2180 * case @mode must be 0 as it is meaningless for extent inodes.
2182 * You need to check the return value with IS_ERR(). If false, the function
2183 * was successful and the return value is the now opened ntfs inode of the
2184 * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
2185 * and locked mft record. If IS_ERR() is true, the function failed and the
2186 * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
2189 * Allocation strategy:
2191 * To find a free mft record, we scan the mft bitmap for a zero bit. To
2192 * optimize this we start scanning at the place specified by @base_ni or if
2193 * @base_ni is NULL we start where we last stopped and we perform wrap around
2194 * when we reach the end. Note, we do not try to allocate mft records below
2195 * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2196 * to 24 are special in that they are used for storing extension mft records
2197 * for the $DATA attribute of $MFT. This is required to avoid the possibility
2198 * of creating a runlist with a circular dependency which once written to disk
2199 * can never be read in again. Windows will only use records 16 to 24 for
2200 * normal files if the volume is completely out of space. We never use them
2201 * which means that when the volume is really out of space we cannot create any
2202 * more files while Windows can still create up to 8 small files. We can start
2203 * doing this at some later time, it does not matter much for now.
2205 * When scanning the mft bitmap, we only search up to the last allocated mft
2206 * record. If there are no free records left in the range 24 to number of
2207 * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2208 * create free mft records. We extend the allocated size of $MFT/$DATA by 16
2209 * records at a time or one cluster, if cluster size is above 16kiB. If there
2210 * is not sufficient space to do this, we try to extend by a single mft record
2211 * or one cluster, if cluster size is above the mft record size.
2213 * No matter how many mft records we allocate, we initialize only the first
2214 * allocated mft record, incrementing mft data size and initialized size
2215 * accordingly, open an ntfs_inode for it and return it to the caller, unless
2216 * there are less than 24 mft records, in which case we allocate and initialize
2217 * mft records until we reach record 24 which we consider as the first free mft
2218 * record for use by normal files.
2220 * If during any stage we overflow the initialized data in the mft bitmap, we
2221 * extend the initialized size (and data size) by 8 bytes, allocating another
2222 * cluster if required. The bitmap data size has to be at least equal to the
2223 * number of mft records in the mft, but it can be bigger, in which case the
2224 * superflous bits are padded with zeroes.
2226 * Thus, when we return successfully (IS_ERR() is false), we will have:
2227 * - initialized / extended the mft bitmap if necessary,
2228 * - initialized / extended the mft data if necessary,
2229 * - set the bit corresponding to the mft record being allocated in the
2231 * - opened an ntfs_inode for the allocated mft record, and we will have
2232 * - returned the ntfs_inode as well as the allocated mapped, pinned, and
2233 * locked mft record.
2235 * On error, the volume will be left in a consistent state and no record will
2236 * be allocated. If rolling back a partial operation fails, we may leave some
2237 * inconsistent metadata in which case we set NVolErrors() so the volume is
2238 * left dirty when unmounted.
2240 * Note, this function cannot make use of most of the normal functions, like
2241 * for example for attribute resizing, etc, because when the run list overflows
2242 * the base mft record and an attribute list is used, it is very important that
2243 * the extension mft records used to store the $DATA attribute of $MFT can be
2244 * reached without having to read the information contained inside them, as
2245 * this would make it impossible to find them in the first place after the
2246 * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
2247 * rule because the bitmap is not essential for finding the mft records, but on
2248 * the other hand, handling the bitmap in this special way would make life
2249 * easier because otherwise there might be circular invocations of functions
2250 * when reading the bitmap.
2252 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2253 ntfs_inode *base_ni, MFT_RECORD **mrec)
2255 s64 ll, bit, old_data_initialized, old_data_size;
2256 unsigned long flags;
2259 ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2260 ntfs_attr_search_ctx *ctx;
2267 bool record_formatted = false;
2270 ntfs_debug("Entering (allocating an extent mft record for "
2271 "base mft record 0x%llx).",
2272 (long long)base_ni->mft_no);
2273 /* @mode and @base_ni are mutually exclusive. */
2276 ntfs_debug("Entering (allocating a base mft record).");
2278 /* @mode and @base_ni are mutually exclusive. */
2280 /* We only support creation of normal files and directories. */
2281 if (!S_ISREG(mode) && !S_ISDIR(mode))
2282 return ERR_PTR(-EOPNOTSUPP);
2285 mft_ni = NTFS_I(vol->mft_ino);
2286 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2287 down_write(&vol->mftbmp_lock);
2288 bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2290 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2292 goto have_alloc_rec;
2294 if (bit != -ENOSPC) {
2295 up_write(&vol->mftbmp_lock);
2296 return ERR_PTR(bit);
2299 * No free mft records left. If the mft bitmap already covers more
2300 * than the currently used mft records, the next records are all free,
2301 * so we can simply allocate the first unused mft record.
2302 * Note: We also have to make sure that the mft bitmap at least covers
2303 * the first 24 mft records as they are special and whilst they may not
2304 * be in use, we do not allocate from them.
2306 read_lock_irqsave(&mft_ni->size_lock, flags);
2307 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2308 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2309 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2310 old_data_initialized = mftbmp_ni->initialized_size;
2311 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2312 if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2316 if (unlikely(bit >= (1ll << 32)))
2318 ntfs_debug("Found free record (#2), bit 0x%llx.",
2320 goto found_free_rec;
2323 * The mft bitmap needs to be expanded until it covers the first unused
2324 * mft record that we can allocate.
2325 * Note: The smallest mft record we allocate is mft record 24.
2327 bit = old_data_initialized << 3;
2328 if (unlikely(bit >= (1ll << 32)))
2330 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2331 old_data_size = mftbmp_ni->allocated_size;
2332 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2333 "data_size 0x%llx, initialized_size 0x%llx.",
2334 (long long)old_data_size,
2335 (long long)i_size_read(vol->mftbmp_ino),
2336 (long long)old_data_initialized);
2337 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2338 if (old_data_initialized + 8 > old_data_size) {
2339 /* Need to extend bitmap by one more cluster. */
2340 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2341 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2342 if (unlikely(err)) {
2343 up_write(&vol->mftbmp_lock);
2347 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2348 ntfs_debug("Status of mftbmp after allocation extension: "
2349 "allocated_size 0x%llx, data_size 0x%llx, "
2350 "initialized_size 0x%llx.",
2351 (long long)mftbmp_ni->allocated_size,
2352 (long long)i_size_read(vol->mftbmp_ino),
2353 (long long)mftbmp_ni->initialized_size);
2354 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2358 * We now have sufficient allocated space, extend the initialized_size
2359 * as well as the data_size if necessary and fill the new space with
2362 err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2363 if (unlikely(err)) {
2364 up_write(&vol->mftbmp_lock);
2368 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2369 ntfs_debug("Status of mftbmp after initialized extension: "
2370 "allocated_size 0x%llx, data_size 0x%llx, "
2371 "initialized_size 0x%llx.",
2372 (long long)mftbmp_ni->allocated_size,
2373 (long long)i_size_read(vol->mftbmp_ino),
2374 (long long)mftbmp_ni->initialized_size);
2375 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2377 ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2379 /* @bit is the found free mft record, allocate it in the mft bitmap. */
2380 ntfs_debug("At found_free_rec.");
2381 err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2382 if (unlikely(err)) {
2383 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2384 up_write(&vol->mftbmp_lock);
2387 ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2390 * The mft bitmap is now uptodate. Deal with mft data attribute now.
2391 * Note, we keep hold of the mft bitmap lock for writing until all
2392 * modifications to the mft data attribute are complete, too, as they
2393 * will impact decisions for mft bitmap and mft record allocation done
2394 * by a parallel allocation and if the lock is not maintained a
2395 * parallel allocation could allocate the same mft record as this one.
2397 ll = (bit + 1) << vol->mft_record_size_bits;
2398 read_lock_irqsave(&mft_ni->size_lock, flags);
2399 old_data_initialized = mft_ni->initialized_size;
2400 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2401 if (ll <= old_data_initialized) {
2402 ntfs_debug("Allocated mft record already initialized.");
2403 goto mft_rec_already_initialized;
2405 ntfs_debug("Initializing allocated mft record.");
2407 * The mft record is outside the initialized data. Extend the mft data
2408 * attribute until it covers the allocated record. The loop is only
2409 * actually traversed more than once when a freshly formatted volume is
2410 * first written to so it optimizes away nicely in the common case.
2412 read_lock_irqsave(&mft_ni->size_lock, flags);
2413 ntfs_debug("Status of mft data before extension: "
2414 "allocated_size 0x%llx, data_size 0x%llx, "
2415 "initialized_size 0x%llx.",
2416 (long long)mft_ni->allocated_size,
2417 (long long)i_size_read(vol->mft_ino),
2418 (long long)mft_ni->initialized_size);
2419 while (ll > mft_ni->allocated_size) {
2420 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2421 err = ntfs_mft_data_extend_allocation_nolock(vol);
2422 if (unlikely(err)) {
2423 ntfs_error(vol->sb, "Failed to extend mft data "
2425 goto undo_mftbmp_alloc_nolock;
2427 read_lock_irqsave(&mft_ni->size_lock, flags);
2428 ntfs_debug("Status of mft data after allocation extension: "
2429 "allocated_size 0x%llx, data_size 0x%llx, "
2430 "initialized_size 0x%llx.",
2431 (long long)mft_ni->allocated_size,
2432 (long long)i_size_read(vol->mft_ino),
2433 (long long)mft_ni->initialized_size);
2435 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2437 * Extend mft data initialized size (and data size of course) to reach
2438 * the allocated mft record, formatting the mft records allong the way.
2439 * Note: We only modify the ntfs_inode structure as that is all that is
2440 * needed by ntfs_mft_record_format(). We will update the attribute
2441 * record itself in one fell swoop later on.
2443 write_lock_irqsave(&mft_ni->size_lock, flags);
2444 old_data_initialized = mft_ni->initialized_size;
2445 old_data_size = vol->mft_ino->i_size;
2446 while (ll > mft_ni->initialized_size) {
2447 s64 new_initialized_size, mft_no;
2449 new_initialized_size = mft_ni->initialized_size +
2450 vol->mft_record_size;
2451 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2452 if (new_initialized_size > i_size_read(vol->mft_ino))
2453 i_size_write(vol->mft_ino, new_initialized_size);
2454 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2455 ntfs_debug("Initializing mft record 0x%llx.",
2457 err = ntfs_mft_record_format(vol, mft_no);
2458 if (unlikely(err)) {
2459 ntfs_error(vol->sb, "Failed to format mft record.");
2460 goto undo_data_init;
2462 write_lock_irqsave(&mft_ni->size_lock, flags);
2463 mft_ni->initialized_size = new_initialized_size;
2465 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2466 record_formatted = true;
2467 /* Update the mft data attribute record to reflect the new sizes. */
2468 m = map_mft_record(mft_ni);
2470 ntfs_error(vol->sb, "Failed to map mft record.");
2472 goto undo_data_init;
2474 ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2475 if (unlikely(!ctx)) {
2476 ntfs_error(vol->sb, "Failed to get search context.");
2478 unmap_mft_record(mft_ni);
2479 goto undo_data_init;
2481 err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2482 CASE_SENSITIVE, 0, NULL, 0, ctx);
2483 if (unlikely(err)) {
2484 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2485 "mft data attribute.");
2486 ntfs_attr_put_search_ctx(ctx);
2487 unmap_mft_record(mft_ni);
2488 goto undo_data_init;
2491 read_lock_irqsave(&mft_ni->size_lock, flags);
2492 a->data.non_resident.initialized_size =
2493 cpu_to_sle64(mft_ni->initialized_size);
2494 a->data.non_resident.data_size =
2495 cpu_to_sle64(i_size_read(vol->mft_ino));
2496 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2497 /* Ensure the changes make it to disk. */
2498 flush_dcache_mft_record_page(ctx->ntfs_ino);
2499 mark_mft_record_dirty(ctx->ntfs_ino);
2500 ntfs_attr_put_search_ctx(ctx);
2501 unmap_mft_record(mft_ni);
2502 read_lock_irqsave(&mft_ni->size_lock, flags);
2503 ntfs_debug("Status of mft data after mft record initialization: "
2504 "allocated_size 0x%llx, data_size 0x%llx, "
2505 "initialized_size 0x%llx.",
2506 (long long)mft_ni->allocated_size,
2507 (long long)i_size_read(vol->mft_ino),
2508 (long long)mft_ni->initialized_size);
2509 BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2510 BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2511 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2512 mft_rec_already_initialized:
2514 * We can finally drop the mft bitmap lock as the mft data attribute
2515 * has been fully updated. The only disparity left is that the
2516 * allocated mft record still needs to be marked as in use to match the
2517 * set bit in the mft bitmap but this is actually not a problem since
2518 * this mft record is not referenced from anywhere yet and the fact
2519 * that it is allocated in the mft bitmap means that no-one will try to
2520 * allocate it either.
2522 up_write(&vol->mftbmp_lock);
2524 * We now have allocated and initialized the mft record. Calculate the
2525 * index of and the offset within the page cache page the record is in.
2527 index = bit << vol->mft_record_size_bits >> PAGE_SHIFT;
2528 ofs = (bit << vol->mft_record_size_bits) & ~PAGE_MASK;
2529 /* Read, map, and pin the page containing the mft record. */
2530 page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2532 ntfs_error(vol->sb, "Failed to map page containing allocated "
2533 "mft record 0x%llx.", (long long)bit);
2534 err = PTR_ERR(page);
2535 goto undo_mftbmp_alloc;
2538 BUG_ON(!PageUptodate(page));
2539 ClearPageUptodate(page);
2540 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2541 /* If we just formatted the mft record no need to do it again. */
2542 if (!record_formatted) {
2543 /* Sanity check that the mft record is really not in use. */
2544 if (ntfs_is_file_record(m->magic) &&
2545 (m->flags & MFT_RECORD_IN_USE)) {
2546 ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2547 "free in mft bitmap but is marked "
2548 "used itself. Corrupt filesystem. "
2549 "Unmount and run chkdsk.",
2552 SetPageUptodate(page);
2554 ntfs_unmap_page(page);
2556 goto undo_mftbmp_alloc;
2559 * We need to (re-)format the mft record, preserving the
2560 * sequence number if it is not zero as well as the update
2561 * sequence number if it is not zero or -1 (0xffff). This
2562 * means we do not need to care whether or not something went
2563 * wrong with the previous mft record.
2565 seq_no = m->sequence_number;
2566 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2567 err = ntfs_mft_record_layout(vol, bit, m);
2568 if (unlikely(err)) {
2569 ntfs_error(vol->sb, "Failed to layout allocated mft "
2570 "record 0x%llx.", (long long)bit);
2571 SetPageUptodate(page);
2573 ntfs_unmap_page(page);
2574 goto undo_mftbmp_alloc;
2577 m->sequence_number = seq_no;
2578 if (usn && le16_to_cpu(usn) != 0xffff)
2579 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2581 /* Set the mft record itself in use. */
2582 m->flags |= MFT_RECORD_IN_USE;
2584 m->flags |= MFT_RECORD_IS_DIRECTORY;
2585 flush_dcache_page(page);
2586 SetPageUptodate(page);
2591 * Setup the base mft record in the extent mft record. This
2592 * completes initialization of the allocated extent mft record
2593 * and we can simply use it with map_extent_mft_record().
2595 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2598 * Allocate an extent inode structure for the new mft record,
2599 * attach it to the base inode @base_ni and map, pin, and lock
2600 * its, i.e. the allocated, mft record.
2602 m_tmp = map_extent_mft_record(base_ni, bit, &ni);
2603 if (IS_ERR(m_tmp)) {
2604 ntfs_error(vol->sb, "Failed to map allocated extent "
2605 "mft record 0x%llx.", (long long)bit);
2606 err = PTR_ERR(m_tmp);
2607 /* Set the mft record itself not in use. */
2608 m->flags &= cpu_to_le16(
2609 ~le16_to_cpu(MFT_RECORD_IN_USE));
2610 flush_dcache_page(page);
2611 /* Make sure the mft record is written out to disk. */
2612 mark_ntfs_record_dirty(page, ofs);
2614 ntfs_unmap_page(page);
2615 goto undo_mftbmp_alloc;
2619 * Make sure the allocated mft record is written out to disk.
2620 * No need to set the inode dirty because the caller is going
2621 * to do that anyway after finishing with the new extent mft
2622 * record (e.g. at a minimum a new attribute will be added to
2625 mark_ntfs_record_dirty(page, ofs);
2628 * Need to unmap the page since map_extent_mft_record() mapped
2629 * it as well so we have it mapped twice at the moment.
2631 ntfs_unmap_page(page);
2634 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2635 * is set to 1 but the mft record->link_count is 0. The caller
2636 * needs to bear this in mind.
2638 vi = new_inode(vol->sb);
2639 if (unlikely(!vi)) {
2641 /* Set the mft record itself not in use. */
2642 m->flags &= cpu_to_le16(
2643 ~le16_to_cpu(MFT_RECORD_IN_USE));
2644 flush_dcache_page(page);
2645 /* Make sure the mft record is written out to disk. */
2646 mark_ntfs_record_dirty(page, ofs);
2648 ntfs_unmap_page(page);
2649 goto undo_mftbmp_alloc;
2653 /* The owner and group come from the ntfs volume. */
2654 vi->i_uid = vol->uid;
2655 vi->i_gid = vol->gid;
2657 /* Initialize the ntfs specific part of @vi. */
2658 ntfs_init_big_inode(vi);
2661 * Set the appropriate mode, attribute type, and name. For
2662 * directories, also setup the index values to the defaults.
2664 if (S_ISDIR(mode)) {
2665 vi->i_mode = S_IFDIR | S_IRWXUGO;
2666 vi->i_mode &= ~vol->dmask;
2668 NInoSetMstProtected(ni);
2669 ni->type = AT_INDEX_ALLOCATION;
2673 ni->itype.index.block_size = 4096;
2674 ni->itype.index.block_size_bits = ntfs_ffs(4096) - 1;
2675 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2676 if (vol->cluster_size <= ni->itype.index.block_size) {
2677 ni->itype.index.vcn_size = vol->cluster_size;
2678 ni->itype.index.vcn_size_bits =
2679 vol->cluster_size_bits;
2681 ni->itype.index.vcn_size = vol->sector_size;
2682 ni->itype.index.vcn_size_bits =
2683 vol->sector_size_bits;
2686 vi->i_mode = S_IFREG | S_IRWXUGO;
2687 vi->i_mode &= ~vol->fmask;
2694 vi->i_mode &= ~S_IWUGO;
2696 /* Set the inode times to the current time. */
2697 vi->i_atime = vi->i_mtime = vi->i_ctime =
2700 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2701 * the call to ntfs_init_big_inode() below.
2706 /* Set the sequence number. */
2707 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2709 * Manually map, pin, and lock the mft record as we already
2710 * have its page mapped and it is very easy to do.
2712 atomic_inc(&ni->count);
2713 mutex_lock(&ni->mrec_lock);
2717 * Make sure the allocated mft record is written out to disk.
2718 * NOTE: We do not set the ntfs inode dirty because this would
2719 * fail in ntfs_write_inode() because the inode does not have a
2720 * standard information attribute yet. Also, there is no need
2721 * to set the inode dirty because the caller is going to do
2722 * that anyway after finishing with the new mft record (e.g. at
2723 * a minimum some new attributes will be added to the mft
2726 mark_ntfs_record_dirty(page, ofs);
2729 /* Add the inode to the inode hash for the superblock. */
2730 insert_inode_hash(vi);
2732 /* Update the default mft allocation position. */
2733 vol->mft_data_pos = bit + 1;
2736 * Return the opened, allocated inode of the allocated mft record as
2737 * well as the mapped, pinned, and locked mft record.
2739 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2740 base_ni ? "extent " : "", (long long)bit);
2744 write_lock_irqsave(&mft_ni->size_lock, flags);
2745 mft_ni->initialized_size = old_data_initialized;
2746 i_size_write(vol->mft_ino, old_data_size);
2747 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2748 goto undo_mftbmp_alloc_nolock;
2750 down_write(&vol->mftbmp_lock);
2751 undo_mftbmp_alloc_nolock:
2752 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2753 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2756 up_write(&vol->mftbmp_lock);
2758 return ERR_PTR(err);
2760 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2761 "number of inodes (2^32) has already been reached.");
2762 up_write(&vol->mftbmp_lock);
2763 return ERR_PTR(-ENOSPC);
2767 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2768 * @ni: ntfs inode of the mapped extent mft record to free
2769 * @m: mapped extent mft record of the ntfs inode @ni
2771 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2773 * Note that this function unmaps the mft record and closes and destroys @ni
2774 * internally and hence you cannot use either @ni nor @m any more after this
2775 * function returns success.
2777 * On success return 0 and on error return -errno. @ni and @m are still valid
2778 * in this case and have not been freed.
2780 * For some errors an error message is displayed and the success code 0 is
2781 * returned and the volume is then left dirty on umount. This makes sense in
2782 * case we could not rollback the changes that were already done since the
2783 * caller no longer wants to reference this mft record so it does not matter to
2784 * the caller if something is wrong with it as long as it is properly detached
2785 * from the base inode.
2787 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2789 unsigned long mft_no = ni->mft_no;
2790 ntfs_volume *vol = ni->vol;
2791 ntfs_inode *base_ni;
2792 ntfs_inode **extent_nis;
2797 BUG_ON(NInoAttr(ni));
2798 BUG_ON(ni->nr_extents != -1);
2800 mutex_lock(&ni->extent_lock);
2801 base_ni = ni->ext.base_ntfs_ino;
2802 mutex_unlock(&ni->extent_lock);
2804 BUG_ON(base_ni->nr_extents <= 0);
2806 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2807 mft_no, base_ni->mft_no);
2809 mutex_lock(&base_ni->extent_lock);
2811 /* Make sure we are holding the only reference to the extent inode. */
2812 if (atomic_read(&ni->count) > 2) {
2813 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2814 "not freeing.", base_ni->mft_no);
2815 mutex_unlock(&base_ni->extent_lock);
2819 /* Dissociate the ntfs inode from the base inode. */
2820 extent_nis = base_ni->ext.extent_ntfs_inos;
2822 for (i = 0; i < base_ni->nr_extents; i++) {
2823 if (ni != extent_nis[i])
2826 base_ni->nr_extents--;
2827 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2828 sizeof(ntfs_inode*));
2833 mutex_unlock(&base_ni->extent_lock);
2835 if (unlikely(err)) {
2836 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2837 "its base inode 0x%lx.", mft_no,
2843 * The extent inode is no longer attached to the base inode so no one
2844 * can get a reference to it any more.
2847 /* Mark the mft record as not in use. */
2848 m->flags &= ~MFT_RECORD_IN_USE;
2850 /* Increment the sequence number, skipping zero, if it is not zero. */
2851 old_seq_no = m->sequence_number;
2852 seq_no = le16_to_cpu(old_seq_no);
2853 if (seq_no == 0xffff)
2857 m->sequence_number = cpu_to_le16(seq_no);
2860 * Set the ntfs inode dirty and write it out. We do not need to worry
2861 * about the base inode here since whatever caused the extent mft
2862 * record to be freed is guaranteed to do it already.
2865 err = write_mft_record(ni, m, 0);
2866 if (unlikely(err)) {
2867 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2868 "freeing.", mft_no);
2872 /* Unmap and throw away the now freed extent inode. */
2873 unmap_extent_mft_record(ni);
2874 ntfs_clear_extent_inode(ni);
2876 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2877 down_write(&vol->mftbmp_lock);
2878 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2879 up_write(&vol->mftbmp_lock);
2880 if (unlikely(err)) {
2882 * The extent inode is gone but we failed to deallocate it in
2883 * the mft bitmap. Just emit a warning and leave the volume
2886 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2891 /* Rollback what we did... */
2892 mutex_lock(&base_ni->extent_lock);
2893 extent_nis = base_ni->ext.extent_ntfs_inos;
2894 if (!(base_ni->nr_extents & 3)) {
2895 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2897 extent_nis = kmalloc(new_size, GFP_NOFS);
2898 if (unlikely(!extent_nis)) {
2899 ntfs_error(vol->sb, "Failed to allocate internal "
2900 "buffer during rollback.%s", es);
2901 mutex_unlock(&base_ni->extent_lock);
2903 goto rollback_error;
2905 if (base_ni->nr_extents) {
2906 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2907 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2908 new_size - 4 * sizeof(ntfs_inode*));
2909 kfree(base_ni->ext.extent_ntfs_inos);
2911 base_ni->ext.extent_ntfs_inos = extent_nis;
2913 m->flags |= MFT_RECORD_IN_USE;
2914 m->sequence_number = old_seq_no;
2915 extent_nis[base_ni->nr_extents++] = ni;
2916 mutex_unlock(&base_ni->extent_lock);
2917 mark_mft_record_dirty(ni);
2920 #endif /* NTFS_RW */