2 * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
4 * Copyright (c) 2001-2005 Anton Altaparmakov
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/swap.h>
37 * map_mft_record_page - map the page in which a specific mft record resides
38 * @ni: ntfs inode whose mft record page to map
40 * This maps the page in which the mft record of the ntfs inode @ni is situated
41 * and returns a pointer to the mft record within the mapped page.
43 * Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
44 * contains the negative error code returned.
46 static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
49 ntfs_volume *vol = ni->vol;
50 struct inode *mft_vi = vol->mft_ino;
52 unsigned long index, ofs, end_index;
56 * The index into the page cache and the offset within the page cache
57 * page of the wanted mft record. FIXME: We need to check for
58 * overflowing the unsigned long, but I don't think we would ever get
59 * here if the volume was that big...
61 index = ni->mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
62 ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
64 i_size = i_size_read(mft_vi);
65 /* The maximum valid index into the page cache for $MFT's data. */
66 end_index = i_size >> PAGE_CACHE_SHIFT;
68 /* If the wanted index is out of bounds the mft record doesn't exist. */
69 if (unlikely(index >= end_index)) {
70 if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
71 vol->mft_record_size) {
72 page = ERR_PTR(-ENOENT);
73 ntfs_error(vol->sb, "Attemt to read mft record 0x%lx, "
74 "which is beyond the end of the mft. "
75 "This is probably a bug in the ntfs "
76 "driver.", ni->mft_no);
80 /* Read, map, and pin the page. */
81 page = ntfs_map_page(mft_vi->i_mapping, index);
82 if (likely(!IS_ERR(page))) {
83 /* Catch multi sector transfer fixup errors. */
84 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
88 return page_address(page) + ofs;
90 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
91 "Run chkdsk.", ni->mft_no);
92 ntfs_unmap_page(page);
102 * map_mft_record - map, pin and lock an mft record
103 * @ni: ntfs inode whose MFT record to map
105 * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
106 * for the semaphore if it was already locked by someone else.
108 * The page of the record is mapped using map_mft_record_page() before being
109 * returned to the caller.
111 * This in turn uses ntfs_map_page() to get the page containing the wanted mft
112 * record (it in turn calls read_cache_page() which reads it in from disk if
113 * necessary, increments the use count on the page so that it cannot disappear
114 * under us and returns a reference to the page cache page).
116 * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
117 * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
118 * and the post-read mst fixups on each mft record in the page have been
119 * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
120 * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
121 * ntfs_map_page() waits for PG_locked to become clear and checks if
122 * PG_uptodate is set and returns an error code if not. This provides
123 * sufficient protection against races when reading/using the page.
125 * However there is the write mapping to think about. Doing the above described
126 * checking here will be fine, because when initiating the write we will set
127 * PG_locked and clear PG_uptodate making sure nobody is touching the page
128 * contents. Doing the locking this way means that the commit to disk code in
129 * the page cache code paths is automatically sufficiently locked with us as
130 * we will not touch a page that has been locked or is not uptodate. The only
131 * locking problem then is them locking the page while we are accessing it.
133 * So that code will end up having to own the mrec_lock of all mft
134 * records/inodes present in the page before I/O can proceed. In that case we
135 * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
136 * accessing anything without owning the mrec_lock semaphore. But we do need
137 * to use them because of the read_cache_page() invocation and the code becomes
138 * so much simpler this way that it is well worth it.
140 * The mft record is now ours and we return a pointer to it. You need to check
141 * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
144 * NOTE: Caller is responsible for setting the mft record dirty before calling
145 * unmap_mft_record(). This is obviously only necessary if the caller really
146 * modified the mft record...
147 * Q: Do we want to recycle one of the VFS inode state bits instead?
148 * A: No, the inode ones mean we want to change the mft record, not we want to
151 MFT_RECORD *map_mft_record(ntfs_inode *ni)
155 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
157 /* Make sure the ntfs inode doesn't go away. */
158 atomic_inc(&ni->count);
160 /* Serialize access to this mft record. */
161 down(&ni->mrec_lock);
163 m = map_mft_record_page(ni);
164 if (likely(!IS_ERR(m)))
168 atomic_dec(&ni->count);
169 ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
174 * unmap_mft_record_page - unmap the page in which a specific mft record resides
175 * @ni: ntfs inode whose mft record page to unmap
177 * This unmaps the page in which the mft record of the ntfs inode @ni is
178 * situated and returns. This is a NOOP if highmem is not configured.
180 * The unmap happens via ntfs_unmap_page() which in turn decrements the use
181 * count on the page thus releasing it from the pinned state.
183 * We do not actually unmap the page from memory of course, as that will be
184 * done by the page cache code itself when memory pressure increases or
187 static inline void unmap_mft_record_page(ntfs_inode *ni)
191 // TODO: If dirty, blah...
192 ntfs_unmap_page(ni->page);
199 * unmap_mft_record - release a mapped mft record
200 * @ni: ntfs inode whose MFT record to unmap
202 * We release the page mapping and the mrec_lock mutex which unmaps the mft
203 * record and releases it for others to get hold of. We also release the ntfs
204 * inode by decrementing the ntfs inode reference count.
206 * NOTE: If caller has modified the mft record, it is imperative to set the mft
207 * record dirty BEFORE calling unmap_mft_record().
209 void unmap_mft_record(ntfs_inode *ni)
211 struct page *page = ni->page;
215 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
217 unmap_mft_record_page(ni);
219 atomic_dec(&ni->count);
221 * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
222 * ntfs_clear_extent_inode() in the extent inode case, and to the
223 * caller in the non-extent, yet pure ntfs inode case, to do the actual
224 * tear down of all structures and freeing of all allocated memory.
230 * map_extent_mft_record - load an extent inode and attach it to its base
231 * @base_ni: base ntfs inode
232 * @mref: mft reference of the extent inode to load
233 * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
235 * Load the extent mft record @mref and attach it to its base inode @base_ni.
236 * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
237 * PTR_ERR(result) gives the negative error code.
239 * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
240 * structure of the mapped extent inode.
242 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
243 ntfs_inode **ntfs_ino)
246 ntfs_inode *ni = NULL;
247 ntfs_inode **extent_nis = NULL;
249 unsigned long mft_no = MREF(mref);
250 u16 seq_no = MSEQNO(mref);
251 BOOL destroy_ni = FALSE;
253 ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
254 mft_no, base_ni->mft_no);
255 /* Make sure the base ntfs inode doesn't go away. */
256 atomic_inc(&base_ni->count);
258 * Check if this extent inode has already been added to the base inode,
259 * in which case just return it. If not found, add it to the base
260 * inode before returning it.
262 down(&base_ni->extent_lock);
263 if (base_ni->nr_extents > 0) {
264 extent_nis = base_ni->ext.extent_ntfs_inos;
265 for (i = 0; i < base_ni->nr_extents; i++) {
266 if (mft_no != extent_nis[i]->mft_no)
269 /* Make sure the ntfs inode doesn't go away. */
270 atomic_inc(&ni->count);
274 if (likely(ni != NULL)) {
275 up(&base_ni->extent_lock);
276 atomic_dec(&base_ni->count);
277 /* We found the record; just have to map and return it. */
278 m = map_mft_record(ni);
279 /* map_mft_record() has incremented this on success. */
280 atomic_dec(&ni->count);
281 if (likely(!IS_ERR(m))) {
282 /* Verify the sequence number. */
283 if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
284 ntfs_debug("Done 1.");
288 unmap_mft_record(ni);
289 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
290 "reference! Corrupt filesystem. "
292 return ERR_PTR(-EIO);
295 ntfs_error(base_ni->vol->sb, "Failed to map extent "
296 "mft record, error code %ld.", -PTR_ERR(m));
299 /* Record wasn't there. Get a new ntfs inode and initialize it. */
300 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
302 up(&base_ni->extent_lock);
303 atomic_dec(&base_ni->count);
304 return ERR_PTR(-ENOMEM);
306 ni->vol = base_ni->vol;
309 ni->ext.base_ntfs_ino = base_ni;
310 /* Now map the record. */
311 m = map_mft_record(ni);
313 up(&base_ni->extent_lock);
314 atomic_dec(&base_ni->count);
315 ntfs_clear_extent_inode(ni);
318 /* Verify the sequence number if it is present. */
319 if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
320 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
321 "reference! Corrupt filesystem. Run chkdsk.");
326 /* Attach extent inode to base inode, reallocating memory if needed. */
327 if (!(base_ni->nr_extents & 3)) {
329 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
331 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
332 if (unlikely(!tmp)) {
333 ntfs_error(base_ni->vol->sb, "Failed to allocate "
336 m = ERR_PTR(-ENOMEM);
339 if (base_ni->nr_extents) {
340 BUG_ON(!base_ni->ext.extent_ntfs_inos);
341 memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
342 4 * sizeof(ntfs_inode *));
343 kfree(base_ni->ext.extent_ntfs_inos);
345 base_ni->ext.extent_ntfs_inos = tmp;
347 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
348 up(&base_ni->extent_lock);
349 atomic_dec(&base_ni->count);
350 ntfs_debug("Done 2.");
354 unmap_mft_record(ni);
355 up(&base_ni->extent_lock);
356 atomic_dec(&base_ni->count);
358 * If the extent inode was not attached to the base inode we need to
359 * release it or we will leak memory.
362 ntfs_clear_extent_inode(ni);
369 * __mark_mft_record_dirty - set the mft record and the page containing it dirty
370 * @ni: ntfs inode describing the mapped mft record
372 * Internal function. Users should call mark_mft_record_dirty() instead.
374 * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
375 * as well as the page containing the mft record, dirty. Also, mark the base
376 * vfs inode dirty. This ensures that any changes to the mft record are
377 * written out to disk.
379 * NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
380 * on the base vfs inode, because even though file data may have been modified,
381 * it is dirty in the inode meta data rather than the data page cache of the
382 * inode, and thus there are no data pages that need writing out. Therefore, a
383 * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
384 * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
385 * ensure ->write_inode is called from generic_osync_inode() and this needs to
386 * happen or the file data would not necessarily hit the device synchronously,
387 * even though the vfs inode has the O_SYNC flag set. Also, I_DIRTY_DATASYNC
388 * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
389 * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
392 void __mark_mft_record_dirty(ntfs_inode *ni)
396 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
397 BUG_ON(NInoAttr(ni));
398 mark_ntfs_record_dirty(ni->page, ni->page_ofs);
399 /* Determine the base vfs inode and mark it dirty, too. */
400 down(&ni->extent_lock);
401 if (likely(ni->nr_extents >= 0))
404 base_ni = ni->ext.base_ntfs_ino;
405 up(&ni->extent_lock);
406 __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
409 static const char *ntfs_please_email = "Please email "
410 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
411 "this message. Thank you.";
414 * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
415 * @vol: ntfs volume on which the mft record to synchronize resides
416 * @mft_no: mft record number of mft record to synchronize
417 * @m: mapped, mst protected (extent) mft record to synchronize
419 * Write the mapped, mst protected (extent) mft record @m with mft record
420 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
421 * bypassing the page cache and the $MFTMirr inode itself.
423 * This function is only for use at umount time when the mft mirror inode has
424 * already been disposed off. We BUG() if we are called while the mft mirror
425 * inode is still attached to the volume.
427 * On success return 0. On error return -errno.
429 * NOTE: This function is not implemented yet as I am not convinced it can
430 * actually be triggered considering the sequence of commits we do in super.c::
431 * ntfs_put_super(). But just in case we provide this place holder as the
432 * alternative would be either to BUG() or to get a NULL pointer dereference
435 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
436 const unsigned long mft_no, MFT_RECORD *m)
438 BUG_ON(vol->mftmirr_ino);
439 ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
440 "implemented yet. %s", ntfs_please_email);
445 * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
446 * @vol: ntfs volume on which the mft record to synchronize resides
447 * @mft_no: mft record number of mft record to synchronize
448 * @m: mapped, mst protected (extent) mft record to synchronize
449 * @sync: if true, wait for i/o completion
451 * Write the mapped, mst protected (extent) mft record @m with mft record
452 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
454 * On success return 0. On error return -errno and set the volume errors flag
455 * in the ntfs volume @vol.
457 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
459 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
460 * schedule i/o via ->writepage or do it via kntfsd or whatever.
462 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
463 MFT_RECORD *m, int sync)
466 unsigned int blocksize = vol->sb->s_blocksize;
467 int max_bhs = vol->mft_record_size / blocksize;
468 struct buffer_head *bhs[max_bhs];
469 struct buffer_head *bh, *head;
472 unsigned int block_start, block_end, m_start, m_end, page_ofs;
473 int i_bhs, nr_bhs, err = 0;
474 unsigned char blocksize_bits = vol->mftmirr_ino->i_blkbits;
476 ntfs_debug("Entering for inode 0x%lx.", mft_no);
478 if (unlikely(!vol->mftmirr_ino)) {
479 /* This could happen during umount... */
480 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
485 /* Get the page containing the mirror copy of the mft record @m. */
486 page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
487 (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
489 ntfs_error(vol->sb, "Failed to map mft mirror page.");
494 BUG_ON(!PageUptodate(page));
495 ClearPageUptodate(page);
496 /* Offset of the mft mirror record inside the page. */
497 page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
498 /* The address in the page of the mirror copy of the mft record @m. */
499 kmirr = page_address(page) + page_ofs;
500 /* Copy the mst protected mft record to the mirror. */
501 memcpy(kmirr, m, vol->mft_record_size);
502 /* Create uptodate buffers if not present. */
503 if (unlikely(!page_has_buffers(page))) {
504 struct buffer_head *tail;
506 bh = head = alloc_page_buffers(page, blocksize, 1);
508 set_buffer_uptodate(bh);
510 bh = bh->b_this_page;
512 tail->b_this_page = head;
513 attach_page_buffers(page, head);
514 BUG_ON(!page_has_buffers(page));
516 bh = head = page_buffers(page);
521 m_start = kmirr - (u8*)page_address(page);
522 m_end = m_start + vol->mft_record_size;
524 block_end = block_start + blocksize;
525 /* If the buffer is outside the mft record, skip it. */
526 if (block_end <= m_start)
528 if (unlikely(block_start >= m_end))
530 /* Need to map the buffer if it is not mapped already. */
531 if (unlikely(!buffer_mapped(bh))) {
534 unsigned int vcn_ofs;
536 /* Obtain the vcn and offset of the current block. */
537 vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
538 (block_start - m_start);
539 vcn_ofs = vcn & vol->cluster_size_mask;
540 vcn >>= vol->cluster_size_bits;
542 down_read(&NTFS_I(vol->mftmirr_ino)->
544 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
546 * $MFTMirr always has the whole of its runlist
551 /* Seek to element containing target vcn. */
552 while (rl->length && rl[1].vcn <= vcn)
554 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
555 /* For $MFTMirr, only lcn >= 0 is a successful remap. */
556 if (likely(lcn >= 0)) {
557 /* Setup buffer head to correct block. */
558 bh->b_blocknr = ((lcn <<
559 vol->cluster_size_bits) +
560 vcn_ofs) >> blocksize_bits;
561 set_buffer_mapped(bh);
564 ntfs_error(vol->sb, "Cannot write mft mirror "
565 "record 0x%lx because its "
566 "location on disk could not "
567 "be determined (error code "
573 BUG_ON(!buffer_uptodate(bh));
574 BUG_ON(!nr_bhs && (m_start != block_start));
575 BUG_ON(nr_bhs >= max_bhs);
577 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
578 } while (block_start = block_end, (bh = bh->b_this_page) != head);
580 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
582 /* Lock buffers and start synchronous write i/o on them. */
583 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
584 struct buffer_head *tbh = bhs[i_bhs];
586 if (unlikely(test_set_buffer_locked(tbh)))
588 BUG_ON(!buffer_uptodate(tbh));
589 clear_buffer_dirty(tbh);
591 tbh->b_end_io = end_buffer_write_sync;
592 submit_bh(WRITE, tbh);
594 /* Wait on i/o completion of buffers. */
595 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
596 struct buffer_head *tbh = bhs[i_bhs];
599 if (unlikely(!buffer_uptodate(tbh))) {
602 * Set the buffer uptodate so the page and
603 * buffer states do not become out of sync.
605 set_buffer_uptodate(tbh);
608 } else /* if (unlikely(err)) */ {
609 /* Clean the buffers. */
610 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
611 clear_buffer_dirty(bhs[i_bhs]);
613 /* Current state: all buffers are clean, unlocked, and uptodate. */
614 /* Remove the mst protection fixups again. */
615 post_write_mst_fixup((NTFS_RECORD*)kmirr);
616 flush_dcache_page(page);
617 SetPageUptodate(page);
619 ntfs_unmap_page(page);
623 ntfs_error(vol->sb, "I/O error while writing mft mirror "
624 "record 0x%lx!", mft_no);
626 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
627 "code %i). Volume will be left marked dirty "
628 "on umount. Run ntfsfix on the partition "
629 "after umounting to correct this.", -err);
636 * write_mft_record_nolock - write out a mapped (extent) mft record
637 * @ni: ntfs inode describing the mapped (extent) mft record
638 * @m: mapped (extent) mft record to write
639 * @sync: if true, wait for i/o completion
641 * Write the mapped (extent) mft record @m described by the (regular or extent)
642 * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
643 * the mft mirror, that is also updated.
645 * We only write the mft record if the ntfs inode @ni is dirty and the first
646 * buffer belonging to its mft record is dirty, too. We ignore the dirty state
647 * of subsequent buffers because we could have raced with
648 * fs/ntfs/aops.c::mark_ntfs_record_dirty().
650 * On success, clean the mft record and return 0. On error, leave the mft
651 * record dirty and return -errno. The caller should call make_bad_inode() on
652 * the base inode to ensure no more access happens to this inode. We do not do
653 * it here as the caller may want to finish writing other extent mft records
654 * first to minimize on-disk metadata inconsistencies.
656 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
657 * However, if the mft record has a counterpart in the mft mirror and @sync is
658 * true, we write the mft record, wait for i/o completion, and only then write
659 * the mft mirror copy. This ensures that if the system crashes either the mft
660 * or the mft mirror will contain a self-consistent mft record @m. If @sync is
661 * false on the other hand, we start i/o on both and then wait for completion
662 * on them. This provides a speedup but no longer guarantees that you will end
663 * up with a self-consistent mft record in the case of a crash but if you asked
664 * for asynchronous writing you probably do not care about that anyway.
666 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
667 * schedule i/o via ->writepage or do it via kntfsd or whatever.
669 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
671 ntfs_volume *vol = ni->vol;
672 struct page *page = ni->page;
673 unsigned char blocksize_bits = vol->mft_ino->i_blkbits;
674 unsigned int blocksize = 1 << blocksize_bits;
675 int max_bhs = vol->mft_record_size / blocksize;
676 struct buffer_head *bhs[max_bhs];
677 struct buffer_head *bh, *head;
679 unsigned int block_start, block_end, m_start, m_end;
680 int i_bhs, nr_bhs, err = 0;
682 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
683 BUG_ON(NInoAttr(ni));
685 BUG_ON(!PageLocked(page));
687 * If the ntfs_inode is clean no need to do anything. If it is dirty,
688 * mark it as clean now so that it can be redirtied later on if needed.
689 * There is no danger of races since the caller is holding the locks
690 * for the mft record @m and the page it is in.
692 if (!NInoTestClearDirty(ni))
694 BUG_ON(!page_has_buffers(page));
695 bh = head = page_buffers(page);
700 m_start = ni->page_ofs;
701 m_end = m_start + vol->mft_record_size;
703 block_end = block_start + blocksize;
704 /* If the buffer is outside the mft record, skip it. */
705 if (block_end <= m_start)
707 if (unlikely(block_start >= m_end))
710 * If this block is not the first one in the record, we ignore
711 * the buffer's dirty state because we could have raced with a
712 * parallel mark_ntfs_record_dirty().
714 if (block_start == m_start) {
715 /* This block is the first one in the record. */
716 if (!buffer_dirty(bh)) {
718 /* Clean records are not written out. */
722 /* Need to map the buffer if it is not mapped already. */
723 if (unlikely(!buffer_mapped(bh))) {
726 unsigned int vcn_ofs;
728 /* Obtain the vcn and offset of the current block. */
729 vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
730 (block_start - m_start);
731 vcn_ofs = vcn & vol->cluster_size_mask;
732 vcn >>= vol->cluster_size_bits;
734 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
735 rl = NTFS_I(vol->mft_ino)->runlist.rl;
738 /* Seek to element containing target vcn. */
739 while (rl->length && rl[1].vcn <= vcn)
741 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
742 /* For $MFT, only lcn >= 0 is a successful remap. */
743 if (likely(lcn >= 0)) {
744 /* Setup buffer head to correct block. */
745 bh->b_blocknr = ((lcn <<
746 vol->cluster_size_bits) +
747 vcn_ofs) >> blocksize_bits;
748 set_buffer_mapped(bh);
751 ntfs_error(vol->sb, "Cannot write mft record "
752 "0x%lx because its location "
753 "on disk could not be "
754 "determined (error code %lli).",
755 ni->mft_no, (long long)lcn);
759 BUG_ON(!buffer_uptodate(bh));
760 BUG_ON(!nr_bhs && (m_start != block_start));
761 BUG_ON(nr_bhs >= max_bhs);
763 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
764 } while (block_start = block_end, (bh = bh->b_this_page) != head);
766 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
771 /* Apply the mst protection fixups. */
772 err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
774 ntfs_error(vol->sb, "Failed to apply mst fixups!");
777 flush_dcache_mft_record_page(ni);
778 /* Lock buffers and start synchronous write i/o on them. */
779 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
780 struct buffer_head *tbh = bhs[i_bhs];
782 if (unlikely(test_set_buffer_locked(tbh)))
784 BUG_ON(!buffer_uptodate(tbh));
785 clear_buffer_dirty(tbh);
787 tbh->b_end_io = end_buffer_write_sync;
788 submit_bh(WRITE, tbh);
790 /* Synchronize the mft mirror now if not @sync. */
791 if (!sync && ni->mft_no < vol->mftmirr_size)
792 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
793 /* Wait on i/o completion of buffers. */
794 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
795 struct buffer_head *tbh = bhs[i_bhs];
798 if (unlikely(!buffer_uptodate(tbh))) {
801 * Set the buffer uptodate so the page and buffer
802 * states do not become out of sync.
804 if (PageUptodate(page))
805 set_buffer_uptodate(tbh);
808 /* If @sync, now synchronize the mft mirror. */
809 if (sync && ni->mft_no < vol->mftmirr_size)
810 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
811 /* Remove the mst protection fixups again. */
812 post_write_mst_fixup((NTFS_RECORD*)m);
813 flush_dcache_mft_record_page(ni);
815 /* I/O error during writing. This is really bad! */
816 ntfs_error(vol->sb, "I/O error while writing mft record "
817 "0x%lx! Marking base inode as bad. You "
818 "should unmount the volume and run chkdsk.",
826 /* Clean the buffers. */
827 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
828 clear_buffer_dirty(bhs[i_bhs]);
831 * Current state: all buffers are clean, unlocked, and uptodate.
832 * The caller should mark the base inode as bad so that no more i/o
833 * happens. ->clear_inode() will still be invoked so all extent inodes
834 * and other allocated memory will be freed.
836 if (err == -ENOMEM) {
837 ntfs_error(vol->sb, "Not enough memory to write mft record. "
838 "Redirtying so the write is retried later.");
839 mark_mft_record_dirty(ni);
847 * ntfs_may_write_mft_record - check if an mft record may be written out
848 * @vol: [IN] ntfs volume on which the mft record to check resides
849 * @mft_no: [IN] mft record number of the mft record to check
850 * @m: [IN] mapped mft record to check
851 * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
853 * Check if the mapped (base or extent) mft record @m with mft record number
854 * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
855 * and possible the ntfs inode of the mft record is locked and the base vfs
856 * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
857 * caller is responsible for unlocking the ntfs inode and unpinning the base
860 * Return TRUE if the mft record may be written out and FALSE if not.
862 * The caller has locked the page and cleared the uptodate flag on it which
863 * means that we can safely write out any dirty mft records that do not have
864 * their inodes in icache as determined by ilookup5() as anyone
865 * opening/creating such an inode would block when attempting to map the mft
866 * record in read_cache_page() until we are finished with the write out.
868 * Here is a description of the tests we perform:
870 * If the inode is found in icache we know the mft record must be a base mft
871 * record. If it is dirty, we do not write it and return FALSE as the vfs
872 * inode write paths will result in the access times being updated which would
873 * cause the base mft record to be redirtied and written out again. (We know
874 * the access time update will modify the base mft record because Windows
875 * chkdsk complains if the standard information attribute is not in the base
878 * If the inode is in icache and not dirty, we attempt to lock the mft record
879 * and if we find the lock was already taken, it is not safe to write the mft
880 * record and we return FALSE.
882 * If we manage to obtain the lock we have exclusive access to the mft record,
883 * which also allows us safe writeout of the mft record. We then set
884 * @locked_ni to the locked ntfs inode and return TRUE.
886 * Note we cannot just lock the mft record and sleep while waiting for the lock
887 * because this would deadlock due to lock reversal (normally the mft record is
888 * locked before the page is locked but we already have the page locked here
889 * when we try to lock the mft record).
891 * If the inode is not in icache we need to perform further checks.
893 * If the mft record is not a FILE record or it is a base mft record, we can
894 * safely write it and return TRUE.
896 * We now know the mft record is an extent mft record. We check if the inode
897 * corresponding to its base mft record is in icache and obtain a reference to
898 * it if it is. If it is not, we can safely write it and return TRUE.
900 * We now have the base inode for the extent mft record. We check if it has an
901 * ntfs inode for the extent mft record attached and if not it is safe to write
902 * the extent mft record and we return TRUE.
904 * The ntfs inode for the extent mft record is attached to the base inode so we
905 * attempt to lock the extent mft record and if we find the lock was already
906 * taken, it is not safe to write the extent mft record and we return FALSE.
908 * If we manage to obtain the lock we have exclusive access to the extent mft
909 * record, which also allows us safe writeout of the extent mft record. We
910 * set the ntfs inode of the extent mft record clean and then set @locked_ni to
911 * the now locked ntfs inode and return TRUE.
913 * Note, the reason for actually writing dirty mft records here and not just
914 * relying on the vfs inode dirty code paths is that we can have mft records
915 * modified without them ever having actual inodes in memory. Also we can have
916 * dirty mft records with clean ntfs inodes in memory. None of the described
917 * cases would result in the dirty mft records being written out if we only
918 * relied on the vfs inode dirty code paths. And these cases can really occur
919 * during allocation of new mft records and in particular when the
920 * initialized_size of the $MFT/$DATA attribute is extended and the new space
921 * is initialized using ntfs_mft_record_format(). The clean inode can then
922 * appear if the mft record is reused for a new inode before it got written
925 BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
926 const MFT_RECORD *m, ntfs_inode **locked_ni)
928 struct super_block *sb = vol->sb;
929 struct inode *mft_vi = vol->mft_ino;
931 ntfs_inode *ni, *eni, **extent_nis;
935 ntfs_debug("Entering for inode 0x%lx.", mft_no);
937 * Normally we do not return a locked inode so set @locked_ni to NULL.
942 * Check if the inode corresponding to this mft record is in the VFS
943 * inode cache and obtain a reference to it if it is.
945 ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
951 * For inode 0, i.e. $MFT itself, we cannot use ilookup5() from here or
952 * we deadlock because the inode is already locked by the kernel
953 * (fs/fs-writeback.c::__sync_single_inode()) and ilookup5() waits
954 * until the inode is unlocked before returning it and it never gets
955 * unlocked because ntfs_should_write_mft_record() never returns. )-:
956 * Fortunately, we have inode 0 pinned in icache for the duration of
957 * the mount so we can access it directly.
960 /* Balance the below iput(). */
962 BUG_ON(vi != mft_vi);
964 vi = ilookup5(sb, mft_no, (test_t)ntfs_test_inode, &na);
966 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
967 /* The inode is in icache. */
969 /* Take a reference to the ntfs inode. */
970 atomic_inc(&ni->count);
971 /* If the inode is dirty, do not write this record. */
973 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
975 atomic_dec(&ni->count);
979 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
980 /* The inode is not dirty, try to take the mft record lock. */
981 if (unlikely(down_trylock(&ni->mrec_lock))) {
982 ntfs_debug("Mft record 0x%lx is already locked, do "
983 "not write it.", mft_no);
984 atomic_dec(&ni->count);
988 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
991 * The write has to occur while we hold the mft record lock so
992 * return the locked ntfs inode.
997 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
998 /* The inode is not in icache. */
999 /* Write the record if it is not a mft record (type "FILE"). */
1000 if (!ntfs_is_mft_record(m->magic)) {
1001 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1005 /* Write the mft record if it is a base inode. */
1006 if (!m->base_mft_record) {
1007 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1012 * This is an extent mft record. Check if the inode corresponding to
1013 * its base mft record is in icache and obtain a reference to it if it
1016 na.mft_no = MREF_LE(m->base_mft_record);
1017 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1018 "inode 0x%lx in icache.", mft_no, na.mft_no);
1019 vi = ilookup5(sb, na.mft_no, (test_t)ntfs_test_inode, &na);
1022 * The base inode is not in icache, write this extent mft
1025 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1026 "extent record.", na.mft_no);
1029 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1031 * The base inode is in icache. Check if it has the extent inode
1032 * corresponding to this extent mft record attached.
1035 down(&ni->extent_lock);
1036 if (ni->nr_extents <= 0) {
1038 * The base inode has no attached extent inodes, write this
1039 * extent mft record.
1041 up(&ni->extent_lock);
1043 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1044 "write the extent record.", na.mft_no);
1047 /* Iterate over the attached extent inodes. */
1048 extent_nis = ni->ext.extent_ntfs_inos;
1049 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1050 if (mft_no == extent_nis[i]->mft_no) {
1052 * Found the extent inode corresponding to this extent
1055 eni = extent_nis[i];
1060 * If the extent inode was not attached to the base inode, write this
1061 * extent mft record.
1064 up(&ni->extent_lock);
1066 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1067 "inode 0x%lx, write the extent record.",
1071 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1073 /* Take a reference to the extent ntfs inode. */
1074 atomic_inc(&eni->count);
1075 up(&ni->extent_lock);
1077 * Found the extent inode coresponding to this extent mft record.
1078 * Try to take the mft record lock.
1080 if (unlikely(down_trylock(&eni->mrec_lock))) {
1081 atomic_dec(&eni->count);
1083 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1084 "not write it.", mft_no);
1087 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1089 if (NInoTestClearDirty(eni))
1090 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1093 * The write has to occur while we hold the mft record lock so return
1094 * the locked extent ntfs inode.
1100 static const char *es = " Leaving inconsistent metadata. Unmount and run "
1104 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1105 * @vol: volume on which to search for a free mft record
1106 * @base_ni: open base inode if allocating an extent mft record or NULL
1108 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1111 * If @base_ni is NULL start the search at the default allocator position.
1113 * If @base_ni is not NULL start the search at the mft record after the base
1114 * mft record @base_ni.
1116 * Return the free mft record on success and -errno on error. An error code of
1117 * -ENOSPC means that there are no free mft records in the currently
1118 * initialized mft bitmap.
1120 * Locking: Caller must hold vol->mftbmp_lock for writing.
1122 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1123 ntfs_inode *base_ni)
1125 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1126 unsigned long flags;
1127 struct address_space *mftbmp_mapping;
1130 unsigned int page_ofs, size;
1133 ntfs_debug("Searching for free mft record in the currently "
1134 "initialized mft bitmap.");
1135 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1137 * Set the end of the pass making sure we do not overflow the mft
1140 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1141 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1142 vol->mft_record_size_bits;
1143 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1144 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1145 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1146 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1151 data_pos = vol->mft_data_pos;
1153 data_pos = base_ni->mft_no + 1;
1156 if (data_pos >= pass_end) {
1159 /* This happens on a freshly formatted volume. */
1160 if (data_pos >= pass_end)
1163 pass_start = data_pos;
1164 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1165 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1166 (long long)pass_start, (long long)pass_end,
1167 (long long)data_pos);
1168 /* Loop until a free mft record is found. */
1169 for (; pass <= 2;) {
1170 /* Cap size to pass_end. */
1171 ofs = data_pos >> 3;
1172 page_ofs = ofs & ~PAGE_CACHE_MASK;
1173 size = PAGE_CACHE_SIZE - page_ofs;
1174 ll = ((pass_end + 7) >> 3) - ofs;
1179 * If we are still within the active pass, search the next page
1183 page = ntfs_map_page(mftbmp_mapping,
1184 ofs >> PAGE_CACHE_SHIFT);
1185 if (unlikely(IS_ERR(page))) {
1186 ntfs_error(vol->sb, "Failed to read mft "
1187 "bitmap, aborting.");
1188 return PTR_ERR(page);
1190 buf = (u8*)page_address(page) + page_ofs;
1193 ntfs_debug("Before inner for loop: size 0x%x, "
1194 "data_pos 0x%llx, bit 0x%llx", size,
1195 (long long)data_pos, (long long)bit);
1196 for (; bit < size && data_pos + bit < pass_end;
1197 bit &= ~7ull, bit += 8) {
1198 byte = buf + (bit >> 3);
1201 b = ffz((unsigned long)*byte);
1202 if (b < 8 && b >= (bit & 7)) {
1203 ll = data_pos + (bit & ~7ull) + b;
1204 if (unlikely(ll > (1ll << 32))) {
1205 ntfs_unmap_page(page);
1209 flush_dcache_page(page);
1210 set_page_dirty(page);
1211 ntfs_unmap_page(page);
1212 ntfs_debug("Done. (Found and "
1213 "allocated mft record "
1219 ntfs_debug("After inner for loop: size 0x%x, "
1220 "data_pos 0x%llx, bit 0x%llx", size,
1221 (long long)data_pos, (long long)bit);
1223 ntfs_unmap_page(page);
1225 * If the end of the pass has not been reached yet,
1226 * continue searching the mft bitmap for a zero bit.
1228 if (data_pos < pass_end)
1231 /* Do the next pass. */
1234 * Starting the second pass, in which we scan the first
1235 * part of the zone which we omitted earlier.
1237 pass_end = pass_start;
1238 data_pos = pass_start = 24;
1239 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1240 "0x%llx.", pass, (long long)pass_start,
1241 (long long)pass_end);
1242 if (data_pos >= pass_end)
1246 /* No free mft records in currently initialized mft bitmap. */
1247 ntfs_debug("Done. (No free mft records left in currently initialized "
1253 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1254 * @vol: volume on which to extend the mft bitmap attribute
1256 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1258 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1261 * Return 0 on success and -errno on error.
1263 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1264 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1265 * writing and releases it before returning.
1266 * - This function takes vol->lcnbmp_lock for writing and releases it
1269 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1273 unsigned long flags;
1275 ntfs_inode *mft_ni, *mftbmp_ni;
1276 runlist_element *rl, *rl2 = NULL;
1277 ntfs_attr_search_ctx *ctx = NULL;
1279 ATTR_RECORD *a = NULL;
1287 } status = { 0, 0, 0 };
1289 ntfs_debug("Extending mft bitmap allocation.");
1290 mft_ni = NTFS_I(vol->mft_ino);
1291 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1293 * Determine the last lcn of the mft bitmap. The allocated size of the
1294 * mft bitmap cannot be zero so we are ok to do this.
1296 down_write(&mftbmp_ni->runlist.lock);
1297 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1298 ll = mftbmp_ni->allocated_size;
1299 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1300 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1301 (ll - 1) >> vol->cluster_size_bits, TRUE);
1302 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1303 up_write(&mftbmp_ni->runlist.lock);
1304 ntfs_error(vol->sb, "Failed to determine last allocated "
1305 "cluster of mft bitmap attribute.");
1312 lcn = rl->lcn + rl->length;
1313 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1316 * Attempt to get the cluster following the last allocated cluster by
1317 * hand as it may be in the MFT zone so the allocator would not give it
1321 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1322 ll >> PAGE_CACHE_SHIFT);
1324 up_write(&mftbmp_ni->runlist.lock);
1325 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1326 return PTR_ERR(page);
1328 b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1329 tb = 1 << (lcn & 7ull);
1330 down_write(&vol->lcnbmp_lock);
1331 if (*b != 0xff && !(*b & tb)) {
1332 /* Next cluster is free, allocate it. */
1334 flush_dcache_page(page);
1335 set_page_dirty(page);
1336 up_write(&vol->lcnbmp_lock);
1337 ntfs_unmap_page(page);
1338 /* Update the mft bitmap runlist. */
1341 status.added_cluster = 1;
1342 ntfs_debug("Appending one cluster to mft bitmap.");
1344 up_write(&vol->lcnbmp_lock);
1345 ntfs_unmap_page(page);
1346 /* Allocate a cluster from the DATA_ZONE. */
1347 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE);
1349 up_write(&mftbmp_ni->runlist.lock);
1350 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1352 return PTR_ERR(rl2);
1354 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1356 up_write(&mftbmp_ni->runlist.lock);
1357 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1359 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1360 ntfs_error(vol->sb, "Failed to dealocate "
1361 "allocated cluster.%s", es);
1367 mftbmp_ni->runlist.rl = rl;
1368 status.added_run = 1;
1369 ntfs_debug("Adding one run to mft bitmap.");
1370 /* Find the last run in the new runlist. */
1371 for (; rl[1].length; rl++)
1375 * Update the attribute record as well. Note: @rl is the last
1376 * (non-terminator) runlist element of mft bitmap.
1378 mrec = map_mft_record(mft_ni);
1380 ntfs_error(vol->sb, "Failed to map mft record.");
1381 ret = PTR_ERR(mrec);
1384 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1385 if (unlikely(!ctx)) {
1386 ntfs_error(vol->sb, "Failed to get search context.");
1390 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1391 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1393 if (unlikely(ret)) {
1394 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1395 "mft bitmap attribute.");
1401 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1402 /* Search back for the previous last allocated cluster of mft bitmap. */
1403 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1407 BUG_ON(ll < rl2->vcn);
1408 BUG_ON(ll >= rl2->vcn + rl2->length);
1409 /* Get the size for the new mapping pairs array for this extent. */
1410 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll);
1411 if (unlikely(mp_size <= 0)) {
1412 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1413 "mft bitmap attribute extent.");
1419 /* Expand the attribute record if necessary. */
1420 old_alen = le32_to_cpu(a->length);
1421 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1422 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1423 if (unlikely(ret)) {
1424 if (ret != -ENOSPC) {
1425 ntfs_error(vol->sb, "Failed to resize attribute "
1426 "record for mft bitmap attribute.");
1429 // TODO: Deal with this by moving this extent to a new mft
1430 // record or by starting a new extent in a new mft record or by
1431 // moving other attributes out of this mft record.
1432 // Note: It will need to be a special mft record and if none of
1433 // those are available it gets rather complicated...
1434 ntfs_error(vol->sb, "Not enough space in this mft record to "
1435 "accomodate extended mft bitmap attribute "
1436 "extent. Cannot handle this yet.");
1440 status.mp_rebuilt = 1;
1441 /* Generate the mapping pairs array directly into the attr record. */
1442 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1443 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1444 mp_size, rl2, ll, NULL);
1445 if (unlikely(ret)) {
1446 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1447 "mft bitmap attribute.");
1450 /* Update the highest_vcn. */
1451 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1453 * We now have extended the mft bitmap allocated_size by one cluster.
1454 * Reflect this in the ntfs_inode structure and the attribute record.
1456 if (a->data.non_resident.lowest_vcn) {
1458 * We are not in the first attribute extent, switch to it, but
1459 * first ensure the changes will make it to disk later.
1461 flush_dcache_mft_record_page(ctx->ntfs_ino);
1462 mark_mft_record_dirty(ctx->ntfs_ino);
1463 ntfs_attr_reinit_search_ctx(ctx);
1464 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1465 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1467 if (unlikely(ret)) {
1468 ntfs_error(vol->sb, "Failed to find first attribute "
1469 "extent of mft bitmap attribute.");
1470 goto restore_undo_alloc;
1474 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1475 mftbmp_ni->allocated_size += vol->cluster_size;
1476 a->data.non_resident.allocated_size =
1477 cpu_to_sle64(mftbmp_ni->allocated_size);
1478 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1479 /* Ensure the changes make it to disk. */
1480 flush_dcache_mft_record_page(ctx->ntfs_ino);
1481 mark_mft_record_dirty(ctx->ntfs_ino);
1482 ntfs_attr_put_search_ctx(ctx);
1483 unmap_mft_record(mft_ni);
1484 up_write(&mftbmp_ni->runlist.lock);
1485 ntfs_debug("Done.");
1488 ntfs_attr_reinit_search_ctx(ctx);
1489 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1490 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1492 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1493 "mft bitmap attribute.%s", es);
1494 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1495 mftbmp_ni->allocated_size += vol->cluster_size;
1496 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1497 ntfs_attr_put_search_ctx(ctx);
1498 unmap_mft_record(mft_ni);
1499 up_write(&mftbmp_ni->runlist.lock);
1501 * The only thing that is now wrong is ->allocated_size of the
1502 * base attribute extent which chkdsk should be able to fix.
1508 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1510 if (status.added_cluster) {
1511 /* Truncate the last run in the runlist by one cluster. */
1514 } else if (status.added_run) {
1516 /* Remove the last run from the runlist. */
1517 rl->lcn = rl[1].lcn;
1520 /* Deallocate the cluster. */
1521 down_write(&vol->lcnbmp_lock);
1522 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1523 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1526 up_write(&vol->lcnbmp_lock);
1527 if (status.mp_rebuilt) {
1528 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1529 a->data.non_resident.mapping_pairs_offset),
1530 old_alen - le16_to_cpu(
1531 a->data.non_resident.mapping_pairs_offset),
1533 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1537 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1538 ntfs_error(vol->sb, "Failed to restore attribute "
1542 flush_dcache_mft_record_page(ctx->ntfs_ino);
1543 mark_mft_record_dirty(ctx->ntfs_ino);
1546 ntfs_attr_put_search_ctx(ctx);
1548 unmap_mft_record(mft_ni);
1549 up_write(&mftbmp_ni->runlist.lock);
1554 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1555 * @vol: volume on which to extend the mft bitmap attribute
1557 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1558 * volume @vol by 8 bytes.
1560 * Note: Only changes initialized_size and data_size, i.e. requires that
1561 * allocated_size is big enough to fit the new initialized_size.
1563 * Return 0 on success and -error on error.
1565 * Locking: Caller must hold vol->mftbmp_lock for writing.
1567 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1569 s64 old_data_size, old_initialized_size;
1570 unsigned long flags;
1571 struct inode *mftbmp_vi;
1572 ntfs_inode *mft_ni, *mftbmp_ni;
1573 ntfs_attr_search_ctx *ctx;
1578 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1579 mft_ni = NTFS_I(vol->mft_ino);
1580 mftbmp_vi = vol->mftbmp_ino;
1581 mftbmp_ni = NTFS_I(mftbmp_vi);
1582 /* Get the attribute record. */
1583 mrec = map_mft_record(mft_ni);
1585 ntfs_error(vol->sb, "Failed to map mft record.");
1586 return PTR_ERR(mrec);
1588 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1589 if (unlikely(!ctx)) {
1590 ntfs_error(vol->sb, "Failed to get search context.");
1594 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1595 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1596 if (unlikely(ret)) {
1597 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1598 "mft bitmap attribute.");
1604 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1605 old_data_size = i_size_read(mftbmp_vi);
1606 old_initialized_size = mftbmp_ni->initialized_size;
1608 * We can simply update the initialized_size before filling the space
1609 * with zeroes because the caller is holding the mft bitmap lock for
1610 * writing which ensures that no one else is trying to access the data.
1612 mftbmp_ni->initialized_size += 8;
1613 a->data.non_resident.initialized_size =
1614 cpu_to_sle64(mftbmp_ni->initialized_size);
1615 if (mftbmp_ni->initialized_size > old_data_size) {
1616 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1617 a->data.non_resident.data_size =
1618 cpu_to_sle64(mftbmp_ni->initialized_size);
1620 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1621 /* Ensure the changes make it to disk. */
1622 flush_dcache_mft_record_page(ctx->ntfs_ino);
1623 mark_mft_record_dirty(ctx->ntfs_ino);
1624 ntfs_attr_put_search_ctx(ctx);
1625 unmap_mft_record(mft_ni);
1626 /* Initialize the mft bitmap attribute value with zeroes. */
1627 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1629 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1633 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1634 /* Try to recover from the error. */
1635 mrec = map_mft_record(mft_ni);
1637 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1641 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1642 if (unlikely(!ctx)) {
1643 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1647 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1648 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1649 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1650 "mft bitmap attribute.%s", es);
1653 ntfs_attr_put_search_ctx(ctx);
1655 unmap_mft_record(mft_ni);
1659 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1660 mftbmp_ni->initialized_size = old_initialized_size;
1661 a->data.non_resident.initialized_size =
1662 cpu_to_sle64(old_initialized_size);
1663 if (i_size_read(mftbmp_vi) != old_data_size) {
1664 i_size_write(mftbmp_vi, old_data_size);
1665 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1667 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1668 flush_dcache_mft_record_page(ctx->ntfs_ino);
1669 mark_mft_record_dirty(ctx->ntfs_ino);
1670 ntfs_attr_put_search_ctx(ctx);
1671 unmap_mft_record(mft_ni);
1673 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1674 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1675 "data_size 0x%llx, initialized_size 0x%llx.",
1676 (long long)mftbmp_ni->allocated_size,
1677 (long long)i_size_read(mftbmp_vi),
1678 (long long)mftbmp_ni->initialized_size);
1679 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1686 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1687 * @vol: volume on which to extend the mft data attribute
1689 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1690 * worth of clusters or if not enough space for this by one mft record worth
1693 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1696 * Return 0 on success and -errno on error.
1698 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1699 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1700 * writing and releases it before returning.
1701 * - This function calls functions which take vol->lcnbmp_lock for
1702 * writing and release it before returning.
1704 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1709 unsigned long flags;
1711 runlist_element *rl, *rl2;
1712 ntfs_attr_search_ctx *ctx = NULL;
1714 ATTR_RECORD *a = NULL;
1717 BOOL mp_rebuilt = FALSE;
1719 ntfs_debug("Extending mft data allocation.");
1720 mft_ni = NTFS_I(vol->mft_ino);
1722 * Determine the preferred allocation location, i.e. the last lcn of
1723 * the mft data attribute. The allocated size of the mft data
1724 * attribute cannot be zero so we are ok to do this.
1726 down_write(&mft_ni->runlist.lock);
1727 read_lock_irqsave(&mft_ni->size_lock, flags);
1728 ll = mft_ni->allocated_size;
1729 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1730 rl = ntfs_attr_find_vcn_nolock(mft_ni,
1731 (ll - 1) >> vol->cluster_size_bits, TRUE);
1732 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1733 up_write(&mft_ni->runlist.lock);
1734 ntfs_error(vol->sb, "Failed to determine last allocated "
1735 "cluster of mft data attribute.");
1742 lcn = rl->lcn + rl->length;
1743 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1744 /* Minimum allocation is one mft record worth of clusters. */
1745 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1748 /* Want to allocate 16 mft records worth of clusters. */
1749 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1752 /* Ensure we do not go above 2^32-1 mft records. */
1753 read_lock_irqsave(&mft_ni->size_lock, flags);
1754 ll = mft_ni->allocated_size;
1755 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1756 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1757 vol->mft_record_size_bits >= (1ll << 32))) {
1759 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1760 vol->mft_record_size_bits >= (1ll << 32))) {
1761 ntfs_warning(vol->sb, "Cannot allocate mft record "
1762 "because the maximum number of inodes "
1763 "(2^32) has already been reached.");
1764 up_write(&mft_ni->runlist.lock);
1768 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1769 nr > min_nr ? "default" : "minimal", (long long)nr);
1770 old_last_vcn = rl[1].vcn;
1772 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1773 if (likely(!IS_ERR(rl2)))
1775 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1776 ntfs_error(vol->sb, "Failed to allocate the minimal "
1777 "number of clusters (%lli) for the "
1778 "mft data attribute.", (long long)nr);
1779 up_write(&mft_ni->runlist.lock);
1780 return PTR_ERR(rl2);
1783 * There is not enough space to do the allocation, but there
1784 * might be enough space to do a minimal allocation so try that
1788 ntfs_debug("Retrying mft data allocation with minimal cluster "
1789 "count %lli.", (long long)nr);
1791 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1793 up_write(&mft_ni->runlist.lock);
1794 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1796 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1797 ntfs_error(vol->sb, "Failed to dealocate clusters "
1798 "from the mft data attribute.%s", es);
1804 mft_ni->runlist.rl = rl;
1805 ntfs_debug("Allocated %lli clusters.", (long long)nr);
1806 /* Find the last run in the new runlist. */
1807 for (; rl[1].length; rl++)
1809 /* Update the attribute record as well. */
1810 mrec = map_mft_record(mft_ni);
1812 ntfs_error(vol->sb, "Failed to map mft record.");
1813 ret = PTR_ERR(mrec);
1816 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1817 if (unlikely(!ctx)) {
1818 ntfs_error(vol->sb, "Failed to get search context.");
1822 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1823 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1824 if (unlikely(ret)) {
1825 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1826 "mft data attribute.");
1832 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1833 /* Search back for the previous last allocated cluster of mft bitmap. */
1834 for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1838 BUG_ON(ll < rl2->vcn);
1839 BUG_ON(ll >= rl2->vcn + rl2->length);
1840 /* Get the size for the new mapping pairs array for this extent. */
1841 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll);
1842 if (unlikely(mp_size <= 0)) {
1843 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1844 "mft data attribute extent.");
1850 /* Expand the attribute record if necessary. */
1851 old_alen = le32_to_cpu(a->length);
1852 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1853 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1854 if (unlikely(ret)) {
1855 if (ret != -ENOSPC) {
1856 ntfs_error(vol->sb, "Failed to resize attribute "
1857 "record for mft data attribute.");
1860 // TODO: Deal with this by moving this extent to a new mft
1861 // record or by starting a new extent in a new mft record or by
1862 // moving other attributes out of this mft record.
1863 // Note: Use the special reserved mft records and ensure that
1864 // this extent is not required to find the mft record in
1865 // question. If no free special records left we would need to
1866 // move an existing record away, insert ours in its place, and
1867 // then place the moved record into the newly allocated space
1868 // and we would then need to update all references to this mft
1869 // record appropriately. This is rather complicated...
1870 ntfs_error(vol->sb, "Not enough space in this mft record to "
1871 "accomodate extended mft data attribute "
1872 "extent. Cannot handle this yet.");
1877 /* Generate the mapping pairs array directly into the attr record. */
1878 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1879 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1880 mp_size, rl2, ll, NULL);
1881 if (unlikely(ret)) {
1882 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1883 "mft data attribute.");
1886 /* Update the highest_vcn. */
1887 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1889 * We now have extended the mft data allocated_size by nr clusters.
1890 * Reflect this in the ntfs_inode structure and the attribute record.
1891 * @rl is the last (non-terminator) runlist element of mft data
1894 if (a->data.non_resident.lowest_vcn) {
1896 * We are not in the first attribute extent, switch to it, but
1897 * first ensure the changes will make it to disk later.
1899 flush_dcache_mft_record_page(ctx->ntfs_ino);
1900 mark_mft_record_dirty(ctx->ntfs_ino);
1901 ntfs_attr_reinit_search_ctx(ctx);
1902 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1903 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1905 if (unlikely(ret)) {
1906 ntfs_error(vol->sb, "Failed to find first attribute "
1907 "extent of mft data attribute.");
1908 goto restore_undo_alloc;
1912 write_lock_irqsave(&mft_ni->size_lock, flags);
1913 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1914 a->data.non_resident.allocated_size =
1915 cpu_to_sle64(mft_ni->allocated_size);
1916 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1917 /* Ensure the changes make it to disk. */
1918 flush_dcache_mft_record_page(ctx->ntfs_ino);
1919 mark_mft_record_dirty(ctx->ntfs_ino);
1920 ntfs_attr_put_search_ctx(ctx);
1921 unmap_mft_record(mft_ni);
1922 up_write(&mft_ni->runlist.lock);
1923 ntfs_debug("Done.");
1926 ntfs_attr_reinit_search_ctx(ctx);
1927 if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1928 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1929 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1930 "mft data attribute.%s", es);
1931 write_lock_irqsave(&mft_ni->size_lock, flags);
1932 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1933 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1934 ntfs_attr_put_search_ctx(ctx);
1935 unmap_mft_record(mft_ni);
1936 up_write(&mft_ni->runlist.lock);
1938 * The only thing that is now wrong is ->allocated_size of the
1939 * base attribute extent which chkdsk should be able to fix.
1945 a->data.non_resident.highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1947 if (ntfs_cluster_free(vol->mft_ino, old_last_vcn, -1) < 0) {
1948 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1949 "attribute.%s", es);
1952 if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1953 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1958 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1959 a->data.non_resident.mapping_pairs_offset),
1960 old_alen - le16_to_cpu(
1961 a->data.non_resident.mapping_pairs_offset),
1963 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1967 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1968 ntfs_error(vol->sb, "Failed to restore attribute "
1972 flush_dcache_mft_record_page(ctx->ntfs_ino);
1973 mark_mft_record_dirty(ctx->ntfs_ino);
1976 ntfs_attr_put_search_ctx(ctx);
1978 unmap_mft_record(mft_ni);
1979 up_write(&mft_ni->runlist.lock);
1984 * ntfs_mft_record_layout - layout an mft record into a memory buffer
1985 * @vol: volume to which the mft record will belong
1986 * @mft_no: mft reference specifying the mft record number
1987 * @m: destination buffer of size >= @vol->mft_record_size bytes
1989 * Layout an empty, unused mft record with the mft record number @mft_no into
1990 * the buffer @m. The volume @vol is needed because the mft record structure
1991 * was modified in NTFS 3.1 so we need to know which volume version this mft
1992 * record will be used on.
1994 * Return 0 on success and -errno on error.
1996 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2001 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2002 if (mft_no >= (1ll << 32)) {
2003 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2004 "maximum of 2^32.", (long long)mft_no);
2007 /* Start by clearing the whole mft record to gives us a clean slate. */
2008 memset(m, 0, vol->mft_record_size);
2009 /* Aligned to 2-byte boundary. */
2010 if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2011 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2013 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2015 * Set the NTFS 3.1+ specific fields while we know that the
2016 * volume version is 3.1+.
2019 m->mft_record_number = cpu_to_le32((u32)mft_no);
2021 m->magic = magic_FILE;
2022 if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2023 m->usa_count = cpu_to_le16(vol->mft_record_size /
2024 NTFS_BLOCK_SIZE + 1);
2026 m->usa_count = cpu_to_le16(1);
2027 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2028 "size. Setting usa_count to 1. If chkdsk "
2029 "reports this as corruption, please email "
2030 "linux-ntfs-dev@lists.sourceforge.net stating "
2031 "that you saw this message and that the "
2032 "modified filesystem created was corrupt. "
2035 /* Set the update sequence number to 1. */
2036 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2038 m->sequence_number = cpu_to_le16(1);
2041 * Place the attributes straight after the update sequence array,
2042 * aligned to 8-byte boundary.
2044 m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2045 (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2048 * Using attrs_offset plus eight bytes (for the termination attribute).
2049 * attrs_offset is already aligned to 8-byte boundary, so no need to
2052 m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2053 m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2054 m->base_mft_record = 0;
2055 m->next_attr_instance = 0;
2056 /* Add the termination attribute. */
2057 a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2060 ntfs_debug("Done.");
2065 * ntfs_mft_record_format - format an mft record on an ntfs volume
2066 * @vol: volume on which to format the mft record
2067 * @mft_no: mft record number to format
2069 * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2070 * mft record into the appropriate place of the mft data attribute. This is
2071 * used when extending the mft data attribute.
2073 * Return 0 on success and -errno on error.
2075 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2078 struct inode *mft_vi = vol->mft_ino;
2081 pgoff_t index, end_index;
2085 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2087 * The index into the page cache and the offset within the page cache
2088 * page of the wanted mft record.
2090 index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2091 ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2092 /* The maximum valid index into the page cache for $MFT's data. */
2093 i_size = i_size_read(mft_vi);
2094 end_index = i_size >> PAGE_CACHE_SHIFT;
2095 if (unlikely(index >= end_index)) {
2096 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2097 (i_size & ~PAGE_CACHE_MASK))) {
2098 ntfs_error(vol->sb, "Tried to format non-existing mft "
2099 "record 0x%llx.", (long long)mft_no);
2103 /* Read, map, and pin the page containing the mft record. */
2104 page = ntfs_map_page(mft_vi->i_mapping, index);
2105 if (unlikely(IS_ERR(page))) {
2106 ntfs_error(vol->sb, "Failed to map page containing mft record "
2107 "to format 0x%llx.", (long long)mft_no);
2108 return PTR_ERR(page);
2111 BUG_ON(!PageUptodate(page));
2112 ClearPageUptodate(page);
2113 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2114 err = ntfs_mft_record_layout(vol, mft_no, m);
2115 if (unlikely(err)) {
2116 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2118 SetPageUptodate(page);
2120 ntfs_unmap_page(page);
2123 flush_dcache_page(page);
2124 SetPageUptodate(page);
2127 * Make sure the mft record is written out to disk. We could use
2128 * ilookup5() to check if an inode is in icache and so on but this is
2129 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2131 mark_ntfs_record_dirty(page, ofs);
2132 ntfs_unmap_page(page);
2133 ntfs_debug("Done.");
2138 * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2139 * @vol: [IN] volume on which to allocate the mft record
2140 * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
2141 * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
2142 * @mrec: [OUT] on successful return this is the mapped mft record
2144 * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2146 * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2147 * direvctory inode, and allocate it at the default allocator position. In
2148 * this case @mode is the file mode as given to us by the caller. We in
2149 * particular use @mode to distinguish whether a file or a directory is being
2150 * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2152 * If @base_ni is not NULL make the allocated mft record an extent record,
2153 * allocate it starting at the mft record after the base mft record and attach
2154 * the allocated and opened ntfs inode to the base inode @base_ni. In this
2155 * case @mode must be 0 as it is meaningless for extent inodes.
2157 * You need to check the return value with IS_ERR(). If false, the function
2158 * was successful and the return value is the now opened ntfs inode of the
2159 * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
2160 * and locked mft record. If IS_ERR() is true, the function failed and the
2161 * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
2164 * Allocation strategy:
2166 * To find a free mft record, we scan the mft bitmap for a zero bit. To
2167 * optimize this we start scanning at the place specified by @base_ni or if
2168 * @base_ni is NULL we start where we last stopped and we perform wrap around
2169 * when we reach the end. Note, we do not try to allocate mft records below
2170 * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2171 * to 24 are special in that they are used for storing extension mft records
2172 * for the $DATA attribute of $MFT. This is required to avoid the possibility
2173 * of creating a runlist with a circular dependency which once written to disk
2174 * can never be read in again. Windows will only use records 16 to 24 for
2175 * normal files if the volume is completely out of space. We never use them
2176 * which means that when the volume is really out of space we cannot create any
2177 * more files while Windows can still create up to 8 small files. We can start
2178 * doing this at some later time, it does not matter much for now.
2180 * When scanning the mft bitmap, we only search up to the last allocated mft
2181 * record. If there are no free records left in the range 24 to number of
2182 * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2183 * create free mft records. We extend the allocated size of $MFT/$DATA by 16
2184 * records at a time or one cluster, if cluster size is above 16kiB. If there
2185 * is not sufficient space to do this, we try to extend by a single mft record
2186 * or one cluster, if cluster size is above the mft record size.
2188 * No matter how many mft records we allocate, we initialize only the first
2189 * allocated mft record, incrementing mft data size and initialized size
2190 * accordingly, open an ntfs_inode for it and return it to the caller, unless
2191 * there are less than 24 mft records, in which case we allocate and initialize
2192 * mft records until we reach record 24 which we consider as the first free mft
2193 * record for use by normal files.
2195 * If during any stage we overflow the initialized data in the mft bitmap, we
2196 * extend the initialized size (and data size) by 8 bytes, allocating another
2197 * cluster if required. The bitmap data size has to be at least equal to the
2198 * number of mft records in the mft, but it can be bigger, in which case the
2199 * superflous bits are padded with zeroes.
2201 * Thus, when we return successfully (IS_ERR() is false), we will have:
2202 * - initialized / extended the mft bitmap if necessary,
2203 * - initialized / extended the mft data if necessary,
2204 * - set the bit corresponding to the mft record being allocated in the
2206 * - opened an ntfs_inode for the allocated mft record, and we will have
2207 * - returned the ntfs_inode as well as the allocated mapped, pinned, and
2208 * locked mft record.
2210 * On error, the volume will be left in a consistent state and no record will
2211 * be allocated. If rolling back a partial operation fails, we may leave some
2212 * inconsistent metadata in which case we set NVolErrors() so the volume is
2213 * left dirty when unmounted.
2215 * Note, this function cannot make use of most of the normal functions, like
2216 * for example for attribute resizing, etc, because when the run list overflows
2217 * the base mft record and an attribute list is used, it is very important that
2218 * the extension mft records used to store the $DATA attribute of $MFT can be
2219 * reached without having to read the information contained inside them, as
2220 * this would make it impossible to find them in the first place after the
2221 * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
2222 * rule because the bitmap is not essential for finding the mft records, but on
2223 * the other hand, handling the bitmap in this special way would make life
2224 * easier because otherwise there might be circular invocations of functions
2225 * when reading the bitmap.
2227 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2228 ntfs_inode *base_ni, MFT_RECORD **mrec)
2230 s64 ll, bit, old_data_initialized, old_data_size;
2231 unsigned long flags;
2234 ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2235 ntfs_attr_search_ctx *ctx;
2242 BOOL record_formatted = FALSE;
2245 ntfs_debug("Entering (allocating an extent mft record for "
2246 "base mft record 0x%llx).",
2247 (long long)base_ni->mft_no);
2248 /* @mode and @base_ni are mutually exclusive. */
2251 ntfs_debug("Entering (allocating a base mft record).");
2253 /* @mode and @base_ni are mutually exclusive. */
2255 /* We only support creation of normal files and directories. */
2256 if (!S_ISREG(mode) && !S_ISDIR(mode))
2257 return ERR_PTR(-EOPNOTSUPP);
2260 mft_ni = NTFS_I(vol->mft_ino);
2261 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2262 down_write(&vol->mftbmp_lock);
2263 bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2265 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2267 goto have_alloc_rec;
2269 if (bit != -ENOSPC) {
2270 up_write(&vol->mftbmp_lock);
2271 return ERR_PTR(bit);
2274 * No free mft records left. If the mft bitmap already covers more
2275 * than the currently used mft records, the next records are all free,
2276 * so we can simply allocate the first unused mft record.
2277 * Note: We also have to make sure that the mft bitmap at least covers
2278 * the first 24 mft records as they are special and whilst they may not
2279 * be in use, we do not allocate from them.
2281 read_lock_irqsave(&mft_ni->size_lock, flags);
2282 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2283 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2284 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2285 old_data_initialized = mftbmp_ni->initialized_size;
2286 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2287 if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2291 if (unlikely(bit >= (1ll << 32)))
2293 ntfs_debug("Found free record (#2), bit 0x%llx.",
2295 goto found_free_rec;
2298 * The mft bitmap needs to be expanded until it covers the first unused
2299 * mft record that we can allocate.
2300 * Note: The smallest mft record we allocate is mft record 24.
2302 bit = old_data_initialized << 3;
2303 if (unlikely(bit >= (1ll << 32)))
2305 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2306 old_data_size = mftbmp_ni->allocated_size;
2307 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2308 "data_size 0x%llx, initialized_size 0x%llx.",
2309 (long long)old_data_size,
2310 (long long)i_size_read(vol->mftbmp_ino),
2311 (long long)old_data_initialized);
2312 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2313 if (old_data_initialized + 8 > old_data_size) {
2314 /* Need to extend bitmap by one more cluster. */
2315 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2316 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2317 if (unlikely(err)) {
2318 up_write(&vol->mftbmp_lock);
2322 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2323 ntfs_debug("Status of mftbmp after allocation extension: "
2324 "allocated_size 0x%llx, data_size 0x%llx, "
2325 "initialized_size 0x%llx.",
2326 (long long)mftbmp_ni->allocated_size,
2327 (long long)i_size_read(vol->mftbmp_ino),
2328 (long long)mftbmp_ni->initialized_size);
2329 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2333 * We now have sufficient allocated space, extend the initialized_size
2334 * as well as the data_size if necessary and fill the new space with
2337 err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2338 if (unlikely(err)) {
2339 up_write(&vol->mftbmp_lock);
2343 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2344 ntfs_debug("Status of mftbmp after initialized extention: "
2345 "allocated_size 0x%llx, data_size 0x%llx, "
2346 "initialized_size 0x%llx.",
2347 (long long)mftbmp_ni->allocated_size,
2348 (long long)i_size_read(vol->mftbmp_ino),
2349 (long long)mftbmp_ni->initialized_size);
2350 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2352 ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2354 /* @bit is the found free mft record, allocate it in the mft bitmap. */
2355 ntfs_debug("At found_free_rec.");
2356 err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2357 if (unlikely(err)) {
2358 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2359 up_write(&vol->mftbmp_lock);
2362 ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2365 * The mft bitmap is now uptodate. Deal with mft data attribute now.
2366 * Note, we keep hold of the mft bitmap lock for writing until all
2367 * modifications to the mft data attribute are complete, too, as they
2368 * will impact decisions for mft bitmap and mft record allocation done
2369 * by a parallel allocation and if the lock is not maintained a
2370 * parallel allocation could allocate the same mft record as this one.
2372 ll = (bit + 1) << vol->mft_record_size_bits;
2373 read_lock_irqsave(&mft_ni->size_lock, flags);
2374 old_data_initialized = mft_ni->initialized_size;
2375 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2376 if (ll <= old_data_initialized) {
2377 ntfs_debug("Allocated mft record already initialized.");
2378 goto mft_rec_already_initialized;
2380 ntfs_debug("Initializing allocated mft record.");
2382 * The mft record is outside the initialized data. Extend the mft data
2383 * attribute until it covers the allocated record. The loop is only
2384 * actually traversed more than once when a freshly formatted volume is
2385 * first written to so it optimizes away nicely in the common case.
2387 read_lock_irqsave(&mft_ni->size_lock, flags);
2388 ntfs_debug("Status of mft data before extension: "
2389 "allocated_size 0x%llx, data_size 0x%llx, "
2390 "initialized_size 0x%llx.",
2391 (long long)mft_ni->allocated_size,
2392 (long long)i_size_read(vol->mft_ino),
2393 (long long)mft_ni->initialized_size);
2394 while (ll > mft_ni->allocated_size) {
2395 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2396 err = ntfs_mft_data_extend_allocation_nolock(vol);
2397 if (unlikely(err)) {
2398 ntfs_error(vol->sb, "Failed to extend mft data "
2400 goto undo_mftbmp_alloc_nolock;
2402 read_lock_irqsave(&mft_ni->size_lock, flags);
2403 ntfs_debug("Status of mft data after allocation extension: "
2404 "allocated_size 0x%llx, data_size 0x%llx, "
2405 "initialized_size 0x%llx.",
2406 (long long)mft_ni->allocated_size,
2407 (long long)i_size_read(vol->mft_ino),
2408 (long long)mft_ni->initialized_size);
2410 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2412 * Extend mft data initialized size (and data size of course) to reach
2413 * the allocated mft record, formatting the mft records allong the way.
2414 * Note: We only modify the ntfs_inode structure as that is all that is
2415 * needed by ntfs_mft_record_format(). We will update the attribute
2416 * record itself in one fell swoop later on.
2418 write_lock_irqsave(&mft_ni->size_lock, flags);
2419 old_data_initialized = mft_ni->initialized_size;
2420 old_data_size = vol->mft_ino->i_size;
2421 while (ll > mft_ni->initialized_size) {
2422 s64 new_initialized_size, mft_no;
2424 new_initialized_size = mft_ni->initialized_size +
2425 vol->mft_record_size;
2426 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2427 if (new_initialized_size > i_size_read(vol->mft_ino))
2428 i_size_write(vol->mft_ino, new_initialized_size);
2429 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2430 ntfs_debug("Initializing mft record 0x%llx.",
2432 err = ntfs_mft_record_format(vol, mft_no);
2433 if (unlikely(err)) {
2434 ntfs_error(vol->sb, "Failed to format mft record.");
2435 goto undo_data_init;
2437 write_lock_irqsave(&mft_ni->size_lock, flags);
2438 mft_ni->initialized_size = new_initialized_size;
2440 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2441 record_formatted = TRUE;
2442 /* Update the mft data attribute record to reflect the new sizes. */
2443 m = map_mft_record(mft_ni);
2445 ntfs_error(vol->sb, "Failed to map mft record.");
2447 goto undo_data_init;
2449 ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2450 if (unlikely(!ctx)) {
2451 ntfs_error(vol->sb, "Failed to get search context.");
2453 unmap_mft_record(mft_ni);
2454 goto undo_data_init;
2456 err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2457 CASE_SENSITIVE, 0, NULL, 0, ctx);
2458 if (unlikely(err)) {
2459 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2460 "mft data attribute.");
2461 ntfs_attr_put_search_ctx(ctx);
2462 unmap_mft_record(mft_ni);
2463 goto undo_data_init;
2466 read_lock_irqsave(&mft_ni->size_lock, flags);
2467 a->data.non_resident.initialized_size =
2468 cpu_to_sle64(mft_ni->initialized_size);
2469 a->data.non_resident.data_size =
2470 cpu_to_sle64(i_size_read(vol->mft_ino));
2471 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2472 /* Ensure the changes make it to disk. */
2473 flush_dcache_mft_record_page(ctx->ntfs_ino);
2474 mark_mft_record_dirty(ctx->ntfs_ino);
2475 ntfs_attr_put_search_ctx(ctx);
2476 unmap_mft_record(mft_ni);
2477 read_lock_irqsave(&mft_ni->size_lock, flags);
2478 ntfs_debug("Status of mft data after mft record initialization: "
2479 "allocated_size 0x%llx, data_size 0x%llx, "
2480 "initialized_size 0x%llx.",
2481 (long long)mft_ni->allocated_size,
2482 (long long)i_size_read(vol->mft_ino),
2483 (long long)mft_ni->initialized_size);
2484 BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2485 BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2486 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2487 mft_rec_already_initialized:
2489 * We can finally drop the mft bitmap lock as the mft data attribute
2490 * has been fully updated. The only disparity left is that the
2491 * allocated mft record still needs to be marked as in use to match the
2492 * set bit in the mft bitmap but this is actually not a problem since
2493 * this mft record is not referenced from anywhere yet and the fact
2494 * that it is allocated in the mft bitmap means that no-one will try to
2495 * allocate it either.
2497 up_write(&vol->mftbmp_lock);
2499 * We now have allocated and initialized the mft record. Calculate the
2500 * index of and the offset within the page cache page the record is in.
2502 index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2503 ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2504 /* Read, map, and pin the page containing the mft record. */
2505 page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2506 if (unlikely(IS_ERR(page))) {
2507 ntfs_error(vol->sb, "Failed to map page containing allocated "
2508 "mft record 0x%llx.", (long long)bit);
2509 err = PTR_ERR(page);
2510 goto undo_mftbmp_alloc;
2513 BUG_ON(!PageUptodate(page));
2514 ClearPageUptodate(page);
2515 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2516 /* If we just formatted the mft record no need to do it again. */
2517 if (!record_formatted) {
2518 /* Sanity check that the mft record is really not in use. */
2519 if (ntfs_is_file_record(m->magic) &&
2520 (m->flags & MFT_RECORD_IN_USE)) {
2521 ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2522 "free in mft bitmap but is marked "
2523 "used itself. Corrupt filesystem. "
2524 "Unmount and run chkdsk.",
2527 SetPageUptodate(page);
2529 ntfs_unmap_page(page);
2531 goto undo_mftbmp_alloc;
2534 * We need to (re-)format the mft record, preserving the
2535 * sequence number if it is not zero as well as the update
2536 * sequence number if it is not zero or -1 (0xffff). This
2537 * means we do not need to care whether or not something went
2538 * wrong with the previous mft record.
2540 seq_no = m->sequence_number;
2541 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2542 err = ntfs_mft_record_layout(vol, bit, m);
2543 if (unlikely(err)) {
2544 ntfs_error(vol->sb, "Failed to layout allocated mft "
2545 "record 0x%llx.", (long long)bit);
2546 SetPageUptodate(page);
2548 ntfs_unmap_page(page);
2549 goto undo_mftbmp_alloc;
2552 m->sequence_number = seq_no;
2553 if (usn && le16_to_cpu(usn) != 0xffff)
2554 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2556 /* Set the mft record itself in use. */
2557 m->flags |= MFT_RECORD_IN_USE;
2559 m->flags |= MFT_RECORD_IS_DIRECTORY;
2560 flush_dcache_page(page);
2561 SetPageUptodate(page);
2564 * Setup the base mft record in the extent mft record. This
2565 * completes initialization of the allocated extent mft record
2566 * and we can simply use it with map_extent_mft_record().
2568 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2571 * Allocate an extent inode structure for the new mft record,
2572 * attach it to the base inode @base_ni and map, pin, and lock
2573 * its, i.e. the allocated, mft record.
2575 m = map_extent_mft_record(base_ni, bit, &ni);
2577 ntfs_error(vol->sb, "Failed to map allocated extent "
2578 "mft record 0x%llx.", (long long)bit);
2580 /* Set the mft record itself not in use. */
2581 m->flags &= cpu_to_le16(
2582 ~le16_to_cpu(MFT_RECORD_IN_USE));
2583 flush_dcache_page(page);
2584 /* Make sure the mft record is written out to disk. */
2585 mark_ntfs_record_dirty(page, ofs);
2587 ntfs_unmap_page(page);
2588 goto undo_mftbmp_alloc;
2591 * Make sure the allocated mft record is written out to disk.
2592 * No need to set the inode dirty because the caller is going
2593 * to do that anyway after finishing with the new extent mft
2594 * record (e.g. at a minimum a new attribute will be added to
2597 mark_ntfs_record_dirty(page, ofs);
2600 * Need to unmap the page since map_extent_mft_record() mapped
2601 * it as well so we have it mapped twice at the moment.
2603 ntfs_unmap_page(page);
2606 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2607 * is set to 1 but the mft record->link_count is 0. The caller
2608 * needs to bear this in mind.
2610 vi = new_inode(vol->sb);
2611 if (unlikely(!vi)) {
2613 /* Set the mft record itself not in use. */
2614 m->flags &= cpu_to_le16(
2615 ~le16_to_cpu(MFT_RECORD_IN_USE));
2616 flush_dcache_page(page);
2617 /* Make sure the mft record is written out to disk. */
2618 mark_ntfs_record_dirty(page, ofs);
2620 ntfs_unmap_page(page);
2621 goto undo_mftbmp_alloc;
2625 * This is the optimal IO size (for stat), not the fs block
2628 vi->i_blksize = PAGE_CACHE_SIZE;
2630 * This is for checking whether an inode has changed w.r.t. a
2631 * file so that the file can be updated if necessary (compare
2636 /* The owner and group come from the ntfs volume. */
2637 vi->i_uid = vol->uid;
2638 vi->i_gid = vol->gid;
2640 /* Initialize the ntfs specific part of @vi. */
2641 ntfs_init_big_inode(vi);
2644 * Set the appropriate mode, attribute type, and name. For
2645 * directories, also setup the index values to the defaults.
2647 if (S_ISDIR(mode)) {
2648 vi->i_mode = S_IFDIR | S_IRWXUGO;
2649 vi->i_mode &= ~vol->dmask;
2651 NInoSetMstProtected(ni);
2652 ni->type = AT_INDEX_ALLOCATION;
2656 ni->itype.index.block_size = 4096;
2657 ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2658 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2659 if (vol->cluster_size <= ni->itype.index.block_size) {
2660 ni->itype.index.vcn_size = vol->cluster_size;
2661 ni->itype.index.vcn_size_bits =
2662 vol->cluster_size_bits;
2664 ni->itype.index.vcn_size = vol->sector_size;
2665 ni->itype.index.vcn_size_bits =
2666 vol->sector_size_bits;
2669 vi->i_mode = S_IFREG | S_IRWXUGO;
2670 vi->i_mode &= ~vol->fmask;
2677 vi->i_mode &= ~S_IWUGO;
2679 /* Set the inode times to the current time. */
2680 vi->i_atime = vi->i_mtime = vi->i_ctime =
2681 current_fs_time(vi->i_sb);
2683 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2684 * the call to ntfs_init_big_inode() below.
2689 /* Set the sequence number. */
2690 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2692 * Manually map, pin, and lock the mft record as we already
2693 * have its page mapped and it is very easy to do.
2695 atomic_inc(&ni->count);
2696 down(&ni->mrec_lock);
2700 * Make sure the allocated mft record is written out to disk.
2701 * NOTE: We do not set the ntfs inode dirty because this would
2702 * fail in ntfs_write_inode() because the inode does not have a
2703 * standard information attribute yet. Also, there is no need
2704 * to set the inode dirty because the caller is going to do
2705 * that anyway after finishing with the new mft record (e.g. at
2706 * a minimum some new attributes will be added to the mft
2709 mark_ntfs_record_dirty(page, ofs);
2712 /* Add the inode to the inode hash for the superblock. */
2713 insert_inode_hash(vi);
2715 /* Update the default mft allocation position. */
2716 vol->mft_data_pos = bit + 1;
2719 * Return the opened, allocated inode of the allocated mft record as
2720 * well as the mapped, pinned, and locked mft record.
2722 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2723 base_ni ? "extent " : "", (long long)bit);
2727 write_lock_irqsave(&mft_ni->size_lock, flags);
2728 mft_ni->initialized_size = old_data_initialized;
2729 i_size_write(vol->mft_ino, old_data_size);
2730 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2731 goto undo_mftbmp_alloc_nolock;
2733 down_write(&vol->mftbmp_lock);
2734 undo_mftbmp_alloc_nolock:
2735 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2736 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2739 up_write(&vol->mftbmp_lock);
2741 return ERR_PTR(err);
2743 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2744 "number of inodes (2^32) has already been reached.");
2745 up_write(&vol->mftbmp_lock);
2746 return ERR_PTR(-ENOSPC);
2750 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2751 * @ni: ntfs inode of the mapped extent mft record to free
2752 * @m: mapped extent mft record of the ntfs inode @ni
2754 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2756 * Note that this function unmaps the mft record and closes and destroys @ni
2757 * internally and hence you cannot use either @ni nor @m any more after this
2758 * function returns success.
2760 * On success return 0 and on error return -errno. @ni and @m are still valid
2761 * in this case and have not been freed.
2763 * For some errors an error message is displayed and the success code 0 is
2764 * returned and the volume is then left dirty on umount. This makes sense in
2765 * case we could not rollback the changes that were already done since the
2766 * caller no longer wants to reference this mft record so it does not matter to
2767 * the caller if something is wrong with it as long as it is properly detached
2768 * from the base inode.
2770 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2772 unsigned long mft_no = ni->mft_no;
2773 ntfs_volume *vol = ni->vol;
2774 ntfs_inode *base_ni;
2775 ntfs_inode **extent_nis;
2780 BUG_ON(NInoAttr(ni));
2781 BUG_ON(ni->nr_extents != -1);
2783 down(&ni->extent_lock);
2784 base_ni = ni->ext.base_ntfs_ino;
2785 up(&ni->extent_lock);
2787 BUG_ON(base_ni->nr_extents <= 0);
2789 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2790 mft_no, base_ni->mft_no);
2792 down(&base_ni->extent_lock);
2794 /* Make sure we are holding the only reference to the extent inode. */
2795 if (atomic_read(&ni->count) > 2) {
2796 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2797 "not freeing.", base_ni->mft_no);
2798 up(&base_ni->extent_lock);
2802 /* Dissociate the ntfs inode from the base inode. */
2803 extent_nis = base_ni->ext.extent_ntfs_inos;
2805 for (i = 0; i < base_ni->nr_extents; i++) {
2806 if (ni != extent_nis[i])
2809 base_ni->nr_extents--;
2810 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2811 sizeof(ntfs_inode*));
2816 up(&base_ni->extent_lock);
2818 if (unlikely(err)) {
2819 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2820 "its base inode 0x%lx.", mft_no,
2826 * The extent inode is no longer attached to the base inode so no one
2827 * can get a reference to it any more.
2830 /* Mark the mft record as not in use. */
2831 m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2833 /* Increment the sequence number, skipping zero, if it is not zero. */
2834 old_seq_no = m->sequence_number;
2835 seq_no = le16_to_cpu(old_seq_no);
2836 if (seq_no == 0xffff)
2840 m->sequence_number = cpu_to_le16(seq_no);
2843 * Set the ntfs inode dirty and write it out. We do not need to worry
2844 * about the base inode here since whatever caused the extent mft
2845 * record to be freed is guaranteed to do it already.
2848 err = write_mft_record(ni, m, 0);
2849 if (unlikely(err)) {
2850 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2851 "freeing.", mft_no);
2855 /* Unmap and throw away the now freed extent inode. */
2856 unmap_extent_mft_record(ni);
2857 ntfs_clear_extent_inode(ni);
2859 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2860 down_write(&vol->mftbmp_lock);
2861 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2862 up_write(&vol->mftbmp_lock);
2863 if (unlikely(err)) {
2865 * The extent inode is gone but we failed to deallocate it in
2866 * the mft bitmap. Just emit a warning and leave the volume
2869 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2874 /* Rollback what we did... */
2875 down(&base_ni->extent_lock);
2876 extent_nis = base_ni->ext.extent_ntfs_inos;
2877 if (!(base_ni->nr_extents & 3)) {
2878 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2880 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2881 if (unlikely(!extent_nis)) {
2882 ntfs_error(vol->sb, "Failed to allocate internal "
2883 "buffer during rollback.%s", es);
2884 up(&base_ni->extent_lock);
2886 goto rollback_error;
2888 if (base_ni->nr_extents) {
2889 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2890 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2891 new_size - 4 * sizeof(ntfs_inode*));
2892 kfree(base_ni->ext.extent_ntfs_inos);
2894 base_ni->ext.extent_ntfs_inos = extent_nis;
2896 m->flags |= MFT_RECORD_IN_USE;
2897 m->sequence_number = old_seq_no;
2898 extent_nis[base_ni->nr_extents++] = ni;
2899 up(&base_ni->extent_lock);
2900 mark_mft_record_dirty(ni);
2903 #endif /* NTFS_RW */