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);
515 bh = head = page_buffers(page);
520 m_start = kmirr - (u8*)page_address(page);
521 m_end = m_start + vol->mft_record_size;
523 block_end = block_start + blocksize;
524 /* If the buffer is outside the mft record, skip it. */
525 if (block_end <= m_start)
527 if (unlikely(block_start >= m_end))
529 /* Need to map the buffer if it is not mapped already. */
530 if (unlikely(!buffer_mapped(bh))) {
533 unsigned int vcn_ofs;
535 bh->b_bdev = vol->sb->s_bdev;
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 bh = head = page_buffers(page);
699 m_start = ni->page_ofs;
700 m_end = m_start + vol->mft_record_size;
702 block_end = block_start + blocksize;
703 /* If the buffer is outside the mft record, skip it. */
704 if (block_end <= m_start)
706 if (unlikely(block_start >= m_end))
709 * If this block is not the first one in the record, we ignore
710 * the buffer's dirty state because we could have raced with a
711 * parallel mark_ntfs_record_dirty().
713 if (block_start == m_start) {
714 /* This block is the first one in the record. */
715 if (!buffer_dirty(bh)) {
717 /* Clean records are not written out. */
721 /* Need to map the buffer if it is not mapped already. */
722 if (unlikely(!buffer_mapped(bh))) {
725 unsigned int vcn_ofs;
727 bh->b_bdev = vol->sb->s_bdev;
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 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
952 * we get here for it rather often.
955 /* Balance the below iput(). */
957 BUG_ON(vi != mft_vi);
960 * Have to use ilookup5_nowait() since ilookup5() waits for the
961 * inode lock which causes ntfs to deadlock when a concurrent
962 * inode write via the inode dirty code paths and the page
963 * dirty code path of the inode dirty code path when writing
966 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
969 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
970 /* The inode is in icache. */
972 /* Take a reference to the ntfs inode. */
973 atomic_inc(&ni->count);
974 /* If the inode is dirty, do not write this record. */
976 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
978 atomic_dec(&ni->count);
982 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
983 /* The inode is not dirty, try to take the mft record lock. */
984 if (unlikely(down_trylock(&ni->mrec_lock))) {
985 ntfs_debug("Mft record 0x%lx is already locked, do "
986 "not write it.", mft_no);
987 atomic_dec(&ni->count);
991 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
994 * The write has to occur while we hold the mft record lock so
995 * return the locked ntfs inode.
1000 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1001 /* The inode is not in icache. */
1002 /* Write the record if it is not a mft record (type "FILE"). */
1003 if (!ntfs_is_mft_record(m->magic)) {
1004 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1008 /* Write the mft record if it is a base inode. */
1009 if (!m->base_mft_record) {
1010 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1015 * This is an extent mft record. Check if the inode corresponding to
1016 * its base mft record is in icache and obtain a reference to it if it
1019 na.mft_no = MREF_LE(m->base_mft_record);
1020 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1021 "inode 0x%lx in icache.", mft_no, na.mft_no);
1023 /* Balance the below iput(). */
1025 BUG_ON(vi != mft_vi);
1027 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1031 * The base inode is not in icache, write this extent mft
1034 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1035 "extent record.", na.mft_no);
1038 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1040 * The base inode is in icache. Check if it has the extent inode
1041 * corresponding to this extent mft record attached.
1044 down(&ni->extent_lock);
1045 if (ni->nr_extents <= 0) {
1047 * The base inode has no attached extent inodes, write this
1048 * extent mft record.
1050 up(&ni->extent_lock);
1052 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1053 "write the extent record.", na.mft_no);
1056 /* Iterate over the attached extent inodes. */
1057 extent_nis = ni->ext.extent_ntfs_inos;
1058 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1059 if (mft_no == extent_nis[i]->mft_no) {
1061 * Found the extent inode corresponding to this extent
1064 eni = extent_nis[i];
1069 * If the extent inode was not attached to the base inode, write this
1070 * extent mft record.
1073 up(&ni->extent_lock);
1075 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1076 "inode 0x%lx, write the extent record.",
1080 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1082 /* Take a reference to the extent ntfs inode. */
1083 atomic_inc(&eni->count);
1084 up(&ni->extent_lock);
1086 * Found the extent inode coresponding to this extent mft record.
1087 * Try to take the mft record lock.
1089 if (unlikely(down_trylock(&eni->mrec_lock))) {
1090 atomic_dec(&eni->count);
1092 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1093 "not write it.", mft_no);
1096 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1098 if (NInoTestClearDirty(eni))
1099 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1102 * The write has to occur while we hold the mft record lock so return
1103 * the locked extent ntfs inode.
1109 static const char *es = " Leaving inconsistent metadata. Unmount and run "
1113 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1114 * @vol: volume on which to search for a free mft record
1115 * @base_ni: open base inode if allocating an extent mft record or NULL
1117 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1120 * If @base_ni is NULL start the search at the default allocator position.
1122 * If @base_ni is not NULL start the search at the mft record after the base
1123 * mft record @base_ni.
1125 * Return the free mft record on success and -errno on error. An error code of
1126 * -ENOSPC means that there are no free mft records in the currently
1127 * initialized mft bitmap.
1129 * Locking: Caller must hold vol->mftbmp_lock for writing.
1131 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1132 ntfs_inode *base_ni)
1134 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1135 unsigned long flags;
1136 struct address_space *mftbmp_mapping;
1139 unsigned int page_ofs, size;
1142 ntfs_debug("Searching for free mft record in the currently "
1143 "initialized mft bitmap.");
1144 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1146 * Set the end of the pass making sure we do not overflow the mft
1149 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1150 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1151 vol->mft_record_size_bits;
1152 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1153 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1154 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1155 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1160 data_pos = vol->mft_data_pos;
1162 data_pos = base_ni->mft_no + 1;
1165 if (data_pos >= pass_end) {
1168 /* This happens on a freshly formatted volume. */
1169 if (data_pos >= pass_end)
1172 pass_start = data_pos;
1173 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1174 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1175 (long long)pass_start, (long long)pass_end,
1176 (long long)data_pos);
1177 /* Loop until a free mft record is found. */
1178 for (; pass <= 2;) {
1179 /* Cap size to pass_end. */
1180 ofs = data_pos >> 3;
1181 page_ofs = ofs & ~PAGE_CACHE_MASK;
1182 size = PAGE_CACHE_SIZE - page_ofs;
1183 ll = ((pass_end + 7) >> 3) - ofs;
1188 * If we are still within the active pass, search the next page
1192 page = ntfs_map_page(mftbmp_mapping,
1193 ofs >> PAGE_CACHE_SHIFT);
1194 if (unlikely(IS_ERR(page))) {
1195 ntfs_error(vol->sb, "Failed to read mft "
1196 "bitmap, aborting.");
1197 return PTR_ERR(page);
1199 buf = (u8*)page_address(page) + page_ofs;
1202 ntfs_debug("Before inner for loop: size 0x%x, "
1203 "data_pos 0x%llx, bit 0x%llx", size,
1204 (long long)data_pos, (long long)bit);
1205 for (; bit < size && data_pos + bit < pass_end;
1206 bit &= ~7ull, bit += 8) {
1207 byte = buf + (bit >> 3);
1210 b = ffz((unsigned long)*byte);
1211 if (b < 8 && b >= (bit & 7)) {
1212 ll = data_pos + (bit & ~7ull) + b;
1213 if (unlikely(ll > (1ll << 32))) {
1214 ntfs_unmap_page(page);
1218 flush_dcache_page(page);
1219 set_page_dirty(page);
1220 ntfs_unmap_page(page);
1221 ntfs_debug("Done. (Found and "
1222 "allocated mft record "
1228 ntfs_debug("After inner for loop: size 0x%x, "
1229 "data_pos 0x%llx, bit 0x%llx", size,
1230 (long long)data_pos, (long long)bit);
1232 ntfs_unmap_page(page);
1234 * If the end of the pass has not been reached yet,
1235 * continue searching the mft bitmap for a zero bit.
1237 if (data_pos < pass_end)
1240 /* Do the next pass. */
1243 * Starting the second pass, in which we scan the first
1244 * part of the zone which we omitted earlier.
1246 pass_end = pass_start;
1247 data_pos = pass_start = 24;
1248 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1249 "0x%llx.", pass, (long long)pass_start,
1250 (long long)pass_end);
1251 if (data_pos >= pass_end)
1255 /* No free mft records in currently initialized mft bitmap. */
1256 ntfs_debug("Done. (No free mft records left in currently initialized "
1262 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1263 * @vol: volume on which to extend the mft bitmap attribute
1265 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1267 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1270 * Return 0 on success and -errno on error.
1272 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1273 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1274 * writing and releases it before returning.
1275 * - This function takes vol->lcnbmp_lock for writing and releases it
1278 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1282 unsigned long flags;
1284 ntfs_inode *mft_ni, *mftbmp_ni;
1285 runlist_element *rl, *rl2 = NULL;
1286 ntfs_attr_search_ctx *ctx = NULL;
1288 ATTR_RECORD *a = NULL;
1296 } status = { 0, 0, 0 };
1298 ntfs_debug("Extending mft bitmap allocation.");
1299 mft_ni = NTFS_I(vol->mft_ino);
1300 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1302 * Determine the last lcn of the mft bitmap. The allocated size of the
1303 * mft bitmap cannot be zero so we are ok to do this.
1305 down_write(&mftbmp_ni->runlist.lock);
1306 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1307 ll = mftbmp_ni->allocated_size;
1308 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1309 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1310 (ll - 1) >> vol->cluster_size_bits, TRUE);
1311 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1312 up_write(&mftbmp_ni->runlist.lock);
1313 ntfs_error(vol->sb, "Failed to determine last allocated "
1314 "cluster of mft bitmap attribute.");
1321 lcn = rl->lcn + rl->length;
1322 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1325 * Attempt to get the cluster following the last allocated cluster by
1326 * hand as it may be in the MFT zone so the allocator would not give it
1330 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1331 ll >> PAGE_CACHE_SHIFT);
1333 up_write(&mftbmp_ni->runlist.lock);
1334 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1335 return PTR_ERR(page);
1337 b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1338 tb = 1 << (lcn & 7ull);
1339 down_write(&vol->lcnbmp_lock);
1340 if (*b != 0xff && !(*b & tb)) {
1341 /* Next cluster is free, allocate it. */
1343 flush_dcache_page(page);
1344 set_page_dirty(page);
1345 up_write(&vol->lcnbmp_lock);
1346 ntfs_unmap_page(page);
1347 /* Update the mft bitmap runlist. */
1350 status.added_cluster = 1;
1351 ntfs_debug("Appending one cluster to mft bitmap.");
1353 up_write(&vol->lcnbmp_lock);
1354 ntfs_unmap_page(page);
1355 /* Allocate a cluster from the DATA_ZONE. */
1356 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE);
1358 up_write(&mftbmp_ni->runlist.lock);
1359 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1361 return PTR_ERR(rl2);
1363 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1365 up_write(&mftbmp_ni->runlist.lock);
1366 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1368 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1369 ntfs_error(vol->sb, "Failed to dealocate "
1370 "allocated cluster.%s", es);
1376 mftbmp_ni->runlist.rl = rl;
1377 status.added_run = 1;
1378 ntfs_debug("Adding one run to mft bitmap.");
1379 /* Find the last run in the new runlist. */
1380 for (; rl[1].length; rl++)
1384 * Update the attribute record as well. Note: @rl is the last
1385 * (non-terminator) runlist element of mft bitmap.
1387 mrec = map_mft_record(mft_ni);
1389 ntfs_error(vol->sb, "Failed to map mft record.");
1390 ret = PTR_ERR(mrec);
1393 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1394 if (unlikely(!ctx)) {
1395 ntfs_error(vol->sb, "Failed to get search context.");
1399 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1400 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1402 if (unlikely(ret)) {
1403 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1404 "mft bitmap attribute.");
1410 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1411 /* Search back for the previous last allocated cluster of mft bitmap. */
1412 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1416 BUG_ON(ll < rl2->vcn);
1417 BUG_ON(ll >= rl2->vcn + rl2->length);
1418 /* Get the size for the new mapping pairs array for this extent. */
1419 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1420 if (unlikely(mp_size <= 0)) {
1421 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1422 "mft bitmap attribute extent.");
1428 /* Expand the attribute record if necessary. */
1429 old_alen = le32_to_cpu(a->length);
1430 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1431 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1432 if (unlikely(ret)) {
1433 if (ret != -ENOSPC) {
1434 ntfs_error(vol->sb, "Failed to resize attribute "
1435 "record for mft bitmap attribute.");
1438 // TODO: Deal with this by moving this extent to a new mft
1439 // record or by starting a new extent in a new mft record or by
1440 // moving other attributes out of this mft record.
1441 // Note: It will need to be a special mft record and if none of
1442 // those are available it gets rather complicated...
1443 ntfs_error(vol->sb, "Not enough space in this mft record to "
1444 "accomodate extended mft bitmap attribute "
1445 "extent. Cannot handle this yet.");
1449 status.mp_rebuilt = 1;
1450 /* Generate the mapping pairs array directly into the attr record. */
1451 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1452 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1453 mp_size, rl2, ll, -1, NULL);
1454 if (unlikely(ret)) {
1455 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1456 "mft bitmap attribute.");
1459 /* Update the highest_vcn. */
1460 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1462 * We now have extended the mft bitmap allocated_size by one cluster.
1463 * Reflect this in the ntfs_inode structure and the attribute record.
1465 if (a->data.non_resident.lowest_vcn) {
1467 * We are not in the first attribute extent, switch to it, but
1468 * first ensure the changes will make it to disk later.
1470 flush_dcache_mft_record_page(ctx->ntfs_ino);
1471 mark_mft_record_dirty(ctx->ntfs_ino);
1472 ntfs_attr_reinit_search_ctx(ctx);
1473 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1474 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1476 if (unlikely(ret)) {
1477 ntfs_error(vol->sb, "Failed to find first attribute "
1478 "extent of mft bitmap attribute.");
1479 goto restore_undo_alloc;
1483 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1484 mftbmp_ni->allocated_size += vol->cluster_size;
1485 a->data.non_resident.allocated_size =
1486 cpu_to_sle64(mftbmp_ni->allocated_size);
1487 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1488 /* Ensure the changes make it to disk. */
1489 flush_dcache_mft_record_page(ctx->ntfs_ino);
1490 mark_mft_record_dirty(ctx->ntfs_ino);
1491 ntfs_attr_put_search_ctx(ctx);
1492 unmap_mft_record(mft_ni);
1493 up_write(&mftbmp_ni->runlist.lock);
1494 ntfs_debug("Done.");
1497 ntfs_attr_reinit_search_ctx(ctx);
1498 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1499 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1501 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1502 "mft bitmap attribute.%s", es);
1503 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1504 mftbmp_ni->allocated_size += vol->cluster_size;
1505 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1506 ntfs_attr_put_search_ctx(ctx);
1507 unmap_mft_record(mft_ni);
1508 up_write(&mftbmp_ni->runlist.lock);
1510 * The only thing that is now wrong is ->allocated_size of the
1511 * base attribute extent which chkdsk should be able to fix.
1517 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1519 if (status.added_cluster) {
1520 /* Truncate the last run in the runlist by one cluster. */
1523 } else if (status.added_run) {
1525 /* Remove the last run from the runlist. */
1526 rl->lcn = rl[1].lcn;
1529 /* Deallocate the cluster. */
1530 down_write(&vol->lcnbmp_lock);
1531 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1532 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1535 up_write(&vol->lcnbmp_lock);
1536 if (status.mp_rebuilt) {
1537 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1538 a->data.non_resident.mapping_pairs_offset),
1539 old_alen - le16_to_cpu(
1540 a->data.non_resident.mapping_pairs_offset),
1541 rl2, ll, -1, NULL)) {
1542 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1546 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1547 ntfs_error(vol->sb, "Failed to restore attribute "
1551 flush_dcache_mft_record_page(ctx->ntfs_ino);
1552 mark_mft_record_dirty(ctx->ntfs_ino);
1555 ntfs_attr_put_search_ctx(ctx);
1557 unmap_mft_record(mft_ni);
1558 up_write(&mftbmp_ni->runlist.lock);
1563 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1564 * @vol: volume on which to extend the mft bitmap attribute
1566 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1567 * volume @vol by 8 bytes.
1569 * Note: Only changes initialized_size and data_size, i.e. requires that
1570 * allocated_size is big enough to fit the new initialized_size.
1572 * Return 0 on success and -error on error.
1574 * Locking: Caller must hold vol->mftbmp_lock for writing.
1576 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1578 s64 old_data_size, old_initialized_size;
1579 unsigned long flags;
1580 struct inode *mftbmp_vi;
1581 ntfs_inode *mft_ni, *mftbmp_ni;
1582 ntfs_attr_search_ctx *ctx;
1587 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1588 mft_ni = NTFS_I(vol->mft_ino);
1589 mftbmp_vi = vol->mftbmp_ino;
1590 mftbmp_ni = NTFS_I(mftbmp_vi);
1591 /* Get the attribute record. */
1592 mrec = map_mft_record(mft_ni);
1594 ntfs_error(vol->sb, "Failed to map mft record.");
1595 return PTR_ERR(mrec);
1597 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1598 if (unlikely(!ctx)) {
1599 ntfs_error(vol->sb, "Failed to get search context.");
1603 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1604 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1605 if (unlikely(ret)) {
1606 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1607 "mft bitmap attribute.");
1613 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1614 old_data_size = i_size_read(mftbmp_vi);
1615 old_initialized_size = mftbmp_ni->initialized_size;
1617 * We can simply update the initialized_size before filling the space
1618 * with zeroes because the caller is holding the mft bitmap lock for
1619 * writing which ensures that no one else is trying to access the data.
1621 mftbmp_ni->initialized_size += 8;
1622 a->data.non_resident.initialized_size =
1623 cpu_to_sle64(mftbmp_ni->initialized_size);
1624 if (mftbmp_ni->initialized_size > old_data_size) {
1625 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1626 a->data.non_resident.data_size =
1627 cpu_to_sle64(mftbmp_ni->initialized_size);
1629 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1630 /* Ensure the changes make it to disk. */
1631 flush_dcache_mft_record_page(ctx->ntfs_ino);
1632 mark_mft_record_dirty(ctx->ntfs_ino);
1633 ntfs_attr_put_search_ctx(ctx);
1634 unmap_mft_record(mft_ni);
1635 /* Initialize the mft bitmap attribute value with zeroes. */
1636 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1638 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1642 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1643 /* Try to recover from the error. */
1644 mrec = map_mft_record(mft_ni);
1646 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1650 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1651 if (unlikely(!ctx)) {
1652 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1656 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1657 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1658 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1659 "mft bitmap attribute.%s", es);
1662 ntfs_attr_put_search_ctx(ctx);
1664 unmap_mft_record(mft_ni);
1668 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1669 mftbmp_ni->initialized_size = old_initialized_size;
1670 a->data.non_resident.initialized_size =
1671 cpu_to_sle64(old_initialized_size);
1672 if (i_size_read(mftbmp_vi) != old_data_size) {
1673 i_size_write(mftbmp_vi, old_data_size);
1674 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1676 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1677 flush_dcache_mft_record_page(ctx->ntfs_ino);
1678 mark_mft_record_dirty(ctx->ntfs_ino);
1679 ntfs_attr_put_search_ctx(ctx);
1680 unmap_mft_record(mft_ni);
1682 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1683 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1684 "data_size 0x%llx, initialized_size 0x%llx.",
1685 (long long)mftbmp_ni->allocated_size,
1686 (long long)i_size_read(mftbmp_vi),
1687 (long long)mftbmp_ni->initialized_size);
1688 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1695 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1696 * @vol: volume on which to extend the mft data attribute
1698 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1699 * worth of clusters or if not enough space for this by one mft record worth
1702 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1705 * Return 0 on success and -errno on error.
1707 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1708 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1709 * writing and releases it before returning.
1710 * - This function calls functions which take vol->lcnbmp_lock for
1711 * writing and release it before returning.
1713 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1718 unsigned long flags;
1720 runlist_element *rl, *rl2;
1721 ntfs_attr_search_ctx *ctx = NULL;
1723 ATTR_RECORD *a = NULL;
1726 BOOL mp_rebuilt = FALSE;
1728 ntfs_debug("Extending mft data allocation.");
1729 mft_ni = NTFS_I(vol->mft_ino);
1731 * Determine the preferred allocation location, i.e. the last lcn of
1732 * the mft data attribute. The allocated size of the mft data
1733 * attribute cannot be zero so we are ok to do this.
1735 down_write(&mft_ni->runlist.lock);
1736 read_lock_irqsave(&mft_ni->size_lock, flags);
1737 ll = mft_ni->allocated_size;
1738 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1739 rl = ntfs_attr_find_vcn_nolock(mft_ni,
1740 (ll - 1) >> vol->cluster_size_bits, TRUE);
1741 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1742 up_write(&mft_ni->runlist.lock);
1743 ntfs_error(vol->sb, "Failed to determine last allocated "
1744 "cluster of mft data attribute.");
1751 lcn = rl->lcn + rl->length;
1752 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1753 /* Minimum allocation is one mft record worth of clusters. */
1754 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1757 /* Want to allocate 16 mft records worth of clusters. */
1758 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1761 /* Ensure we do not go above 2^32-1 mft records. */
1762 read_lock_irqsave(&mft_ni->size_lock, flags);
1763 ll = mft_ni->allocated_size;
1764 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1765 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1766 vol->mft_record_size_bits >= (1ll << 32))) {
1768 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1769 vol->mft_record_size_bits >= (1ll << 32))) {
1770 ntfs_warning(vol->sb, "Cannot allocate mft record "
1771 "because the maximum number of inodes "
1772 "(2^32) has already been reached.");
1773 up_write(&mft_ni->runlist.lock);
1777 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1778 nr > min_nr ? "default" : "minimal", (long long)nr);
1779 old_last_vcn = rl[1].vcn;
1781 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1782 if (likely(!IS_ERR(rl2)))
1784 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1785 ntfs_error(vol->sb, "Failed to allocate the minimal "
1786 "number of clusters (%lli) for the "
1787 "mft data attribute.", (long long)nr);
1788 up_write(&mft_ni->runlist.lock);
1789 return PTR_ERR(rl2);
1792 * There is not enough space to do the allocation, but there
1793 * might be enough space to do a minimal allocation so try that
1797 ntfs_debug("Retrying mft data allocation with minimal cluster "
1798 "count %lli.", (long long)nr);
1800 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1802 up_write(&mft_ni->runlist.lock);
1803 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1805 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1806 ntfs_error(vol->sb, "Failed to dealocate clusters "
1807 "from the mft data attribute.%s", es);
1813 mft_ni->runlist.rl = rl;
1814 ntfs_debug("Allocated %lli clusters.", (long long)nr);
1815 /* Find the last run in the new runlist. */
1816 for (; rl[1].length; rl++)
1818 /* Update the attribute record as well. */
1819 mrec = map_mft_record(mft_ni);
1821 ntfs_error(vol->sb, "Failed to map mft record.");
1822 ret = PTR_ERR(mrec);
1825 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1826 if (unlikely(!ctx)) {
1827 ntfs_error(vol->sb, "Failed to get search context.");
1831 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1832 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1833 if (unlikely(ret)) {
1834 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1835 "mft data attribute.");
1841 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1842 /* Search back for the previous last allocated cluster of mft bitmap. */
1843 for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1847 BUG_ON(ll < rl2->vcn);
1848 BUG_ON(ll >= rl2->vcn + rl2->length);
1849 /* Get the size for the new mapping pairs array for this extent. */
1850 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1851 if (unlikely(mp_size <= 0)) {
1852 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1853 "mft data attribute extent.");
1859 /* Expand the attribute record if necessary. */
1860 old_alen = le32_to_cpu(a->length);
1861 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1862 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1863 if (unlikely(ret)) {
1864 if (ret != -ENOSPC) {
1865 ntfs_error(vol->sb, "Failed to resize attribute "
1866 "record for mft data attribute.");
1869 // TODO: Deal with this by moving this extent to a new mft
1870 // record or by starting a new extent in a new mft record or by
1871 // moving other attributes out of this mft record.
1872 // Note: Use the special reserved mft records and ensure that
1873 // this extent is not required to find the mft record in
1874 // question. If no free special records left we would need to
1875 // move an existing record away, insert ours in its place, and
1876 // then place the moved record into the newly allocated space
1877 // and we would then need to update all references to this mft
1878 // record appropriately. This is rather complicated...
1879 ntfs_error(vol->sb, "Not enough space in this mft record to "
1880 "accomodate extended mft data attribute "
1881 "extent. Cannot handle this yet.");
1886 /* Generate the mapping pairs array directly into the attr record. */
1887 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1888 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1889 mp_size, rl2, ll, -1, NULL);
1890 if (unlikely(ret)) {
1891 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1892 "mft data attribute.");
1895 /* Update the highest_vcn. */
1896 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1898 * We now have extended the mft data allocated_size by nr clusters.
1899 * Reflect this in the ntfs_inode structure and the attribute record.
1900 * @rl is the last (non-terminator) runlist element of mft data
1903 if (a->data.non_resident.lowest_vcn) {
1905 * We are not in the first attribute extent, switch to it, but
1906 * first ensure the changes will make it to disk later.
1908 flush_dcache_mft_record_page(ctx->ntfs_ino);
1909 mark_mft_record_dirty(ctx->ntfs_ino);
1910 ntfs_attr_reinit_search_ctx(ctx);
1911 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1912 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1914 if (unlikely(ret)) {
1915 ntfs_error(vol->sb, "Failed to find first attribute "
1916 "extent of mft data attribute.");
1917 goto restore_undo_alloc;
1921 write_lock_irqsave(&mft_ni->size_lock, flags);
1922 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1923 a->data.non_resident.allocated_size =
1924 cpu_to_sle64(mft_ni->allocated_size);
1925 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1926 /* Ensure the changes make it to disk. */
1927 flush_dcache_mft_record_page(ctx->ntfs_ino);
1928 mark_mft_record_dirty(ctx->ntfs_ino);
1929 ntfs_attr_put_search_ctx(ctx);
1930 unmap_mft_record(mft_ni);
1931 up_write(&mft_ni->runlist.lock);
1932 ntfs_debug("Done.");
1935 ntfs_attr_reinit_search_ctx(ctx);
1936 if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1937 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1938 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1939 "mft data attribute.%s", es);
1940 write_lock_irqsave(&mft_ni->size_lock, flags);
1941 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1942 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1943 ntfs_attr_put_search_ctx(ctx);
1944 unmap_mft_record(mft_ni);
1945 up_write(&mft_ni->runlist.lock);
1947 * The only thing that is now wrong is ->allocated_size of the
1948 * base attribute extent which chkdsk should be able to fix.
1954 a->data.non_resident.highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1956 if (ntfs_cluster_free(mft_ni, old_last_vcn, -1) < 0) {
1957 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1958 "attribute.%s", es);
1961 if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1962 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1967 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1968 a->data.non_resident.mapping_pairs_offset),
1969 old_alen - le16_to_cpu(
1970 a->data.non_resident.mapping_pairs_offset),
1971 rl2, ll, -1, NULL)) {
1972 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1976 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1977 ntfs_error(vol->sb, "Failed to restore attribute "
1981 flush_dcache_mft_record_page(ctx->ntfs_ino);
1982 mark_mft_record_dirty(ctx->ntfs_ino);
1985 ntfs_attr_put_search_ctx(ctx);
1987 unmap_mft_record(mft_ni);
1988 up_write(&mft_ni->runlist.lock);
1993 * ntfs_mft_record_layout - layout an mft record into a memory buffer
1994 * @vol: volume to which the mft record will belong
1995 * @mft_no: mft reference specifying the mft record number
1996 * @m: destination buffer of size >= @vol->mft_record_size bytes
1998 * Layout an empty, unused mft record with the mft record number @mft_no into
1999 * the buffer @m. The volume @vol is needed because the mft record structure
2000 * was modified in NTFS 3.1 so we need to know which volume version this mft
2001 * record will be used on.
2003 * Return 0 on success and -errno on error.
2005 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2010 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2011 if (mft_no >= (1ll << 32)) {
2012 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2013 "maximum of 2^32.", (long long)mft_no);
2016 /* Start by clearing the whole mft record to gives us a clean slate. */
2017 memset(m, 0, vol->mft_record_size);
2018 /* Aligned to 2-byte boundary. */
2019 if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2020 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2022 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2024 * Set the NTFS 3.1+ specific fields while we know that the
2025 * volume version is 3.1+.
2028 m->mft_record_number = cpu_to_le32((u32)mft_no);
2030 m->magic = magic_FILE;
2031 if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2032 m->usa_count = cpu_to_le16(vol->mft_record_size /
2033 NTFS_BLOCK_SIZE + 1);
2035 m->usa_count = cpu_to_le16(1);
2036 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2037 "size. Setting usa_count to 1. If chkdsk "
2038 "reports this as corruption, please email "
2039 "linux-ntfs-dev@lists.sourceforge.net stating "
2040 "that you saw this message and that the "
2041 "modified filesystem created was corrupt. "
2044 /* Set the update sequence number to 1. */
2045 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2047 m->sequence_number = cpu_to_le16(1);
2050 * Place the attributes straight after the update sequence array,
2051 * aligned to 8-byte boundary.
2053 m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2054 (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2057 * Using attrs_offset plus eight bytes (for the termination attribute).
2058 * attrs_offset is already aligned to 8-byte boundary, so no need to
2061 m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2062 m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2063 m->base_mft_record = 0;
2064 m->next_attr_instance = 0;
2065 /* Add the termination attribute. */
2066 a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2069 ntfs_debug("Done.");
2074 * ntfs_mft_record_format - format an mft record on an ntfs volume
2075 * @vol: volume on which to format the mft record
2076 * @mft_no: mft record number to format
2078 * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2079 * mft record into the appropriate place of the mft data attribute. This is
2080 * used when extending the mft data attribute.
2082 * Return 0 on success and -errno on error.
2084 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2087 struct inode *mft_vi = vol->mft_ino;
2090 pgoff_t index, end_index;
2094 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2096 * The index into the page cache and the offset within the page cache
2097 * page of the wanted mft record.
2099 index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2100 ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2101 /* The maximum valid index into the page cache for $MFT's data. */
2102 i_size = i_size_read(mft_vi);
2103 end_index = i_size >> PAGE_CACHE_SHIFT;
2104 if (unlikely(index >= end_index)) {
2105 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2106 (i_size & ~PAGE_CACHE_MASK))) {
2107 ntfs_error(vol->sb, "Tried to format non-existing mft "
2108 "record 0x%llx.", (long long)mft_no);
2112 /* Read, map, and pin the page containing the mft record. */
2113 page = ntfs_map_page(mft_vi->i_mapping, index);
2114 if (unlikely(IS_ERR(page))) {
2115 ntfs_error(vol->sb, "Failed to map page containing mft record "
2116 "to format 0x%llx.", (long long)mft_no);
2117 return PTR_ERR(page);
2120 BUG_ON(!PageUptodate(page));
2121 ClearPageUptodate(page);
2122 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2123 err = ntfs_mft_record_layout(vol, mft_no, m);
2124 if (unlikely(err)) {
2125 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2127 SetPageUptodate(page);
2129 ntfs_unmap_page(page);
2132 flush_dcache_page(page);
2133 SetPageUptodate(page);
2136 * Make sure the mft record is written out to disk. We could use
2137 * ilookup5() to check if an inode is in icache and so on but this is
2138 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2140 mark_ntfs_record_dirty(page, ofs);
2141 ntfs_unmap_page(page);
2142 ntfs_debug("Done.");
2147 * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2148 * @vol: [IN] volume on which to allocate the mft record
2149 * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
2150 * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
2151 * @mrec: [OUT] on successful return this is the mapped mft record
2153 * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2155 * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2156 * direvctory inode, and allocate it at the default allocator position. In
2157 * this case @mode is the file mode as given to us by the caller. We in
2158 * particular use @mode to distinguish whether a file or a directory is being
2159 * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2161 * If @base_ni is not NULL make the allocated mft record an extent record,
2162 * allocate it starting at the mft record after the base mft record and attach
2163 * the allocated and opened ntfs inode to the base inode @base_ni. In this
2164 * case @mode must be 0 as it is meaningless for extent inodes.
2166 * You need to check the return value with IS_ERR(). If false, the function
2167 * was successful and the return value is the now opened ntfs inode of the
2168 * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
2169 * and locked mft record. If IS_ERR() is true, the function failed and the
2170 * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
2173 * Allocation strategy:
2175 * To find a free mft record, we scan the mft bitmap for a zero bit. To
2176 * optimize this we start scanning at the place specified by @base_ni or if
2177 * @base_ni is NULL we start where we last stopped and we perform wrap around
2178 * when we reach the end. Note, we do not try to allocate mft records below
2179 * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2180 * to 24 are special in that they are used for storing extension mft records
2181 * for the $DATA attribute of $MFT. This is required to avoid the possibility
2182 * of creating a runlist with a circular dependency which once written to disk
2183 * can never be read in again. Windows will only use records 16 to 24 for
2184 * normal files if the volume is completely out of space. We never use them
2185 * which means that when the volume is really out of space we cannot create any
2186 * more files while Windows can still create up to 8 small files. We can start
2187 * doing this at some later time, it does not matter much for now.
2189 * When scanning the mft bitmap, we only search up to the last allocated mft
2190 * record. If there are no free records left in the range 24 to number of
2191 * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2192 * create free mft records. We extend the allocated size of $MFT/$DATA by 16
2193 * records at a time or one cluster, if cluster size is above 16kiB. If there
2194 * is not sufficient space to do this, we try to extend by a single mft record
2195 * or one cluster, if cluster size is above the mft record size.
2197 * No matter how many mft records we allocate, we initialize only the first
2198 * allocated mft record, incrementing mft data size and initialized size
2199 * accordingly, open an ntfs_inode for it and return it to the caller, unless
2200 * there are less than 24 mft records, in which case we allocate and initialize
2201 * mft records until we reach record 24 which we consider as the first free mft
2202 * record for use by normal files.
2204 * If during any stage we overflow the initialized data in the mft bitmap, we
2205 * extend the initialized size (and data size) by 8 bytes, allocating another
2206 * cluster if required. The bitmap data size has to be at least equal to the
2207 * number of mft records in the mft, but it can be bigger, in which case the
2208 * superflous bits are padded with zeroes.
2210 * Thus, when we return successfully (IS_ERR() is false), we will have:
2211 * - initialized / extended the mft bitmap if necessary,
2212 * - initialized / extended the mft data if necessary,
2213 * - set the bit corresponding to the mft record being allocated in the
2215 * - opened an ntfs_inode for the allocated mft record, and we will have
2216 * - returned the ntfs_inode as well as the allocated mapped, pinned, and
2217 * locked mft record.
2219 * On error, the volume will be left in a consistent state and no record will
2220 * be allocated. If rolling back a partial operation fails, we may leave some
2221 * inconsistent metadata in which case we set NVolErrors() so the volume is
2222 * left dirty when unmounted.
2224 * Note, this function cannot make use of most of the normal functions, like
2225 * for example for attribute resizing, etc, because when the run list overflows
2226 * the base mft record and an attribute list is used, it is very important that
2227 * the extension mft records used to store the $DATA attribute of $MFT can be
2228 * reached without having to read the information contained inside them, as
2229 * this would make it impossible to find them in the first place after the
2230 * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
2231 * rule because the bitmap is not essential for finding the mft records, but on
2232 * the other hand, handling the bitmap in this special way would make life
2233 * easier because otherwise there might be circular invocations of functions
2234 * when reading the bitmap.
2236 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2237 ntfs_inode *base_ni, MFT_RECORD **mrec)
2239 s64 ll, bit, old_data_initialized, old_data_size;
2240 unsigned long flags;
2243 ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2244 ntfs_attr_search_ctx *ctx;
2251 BOOL record_formatted = FALSE;
2254 ntfs_debug("Entering (allocating an extent mft record for "
2255 "base mft record 0x%llx).",
2256 (long long)base_ni->mft_no);
2257 /* @mode and @base_ni are mutually exclusive. */
2260 ntfs_debug("Entering (allocating a base mft record).");
2262 /* @mode and @base_ni are mutually exclusive. */
2264 /* We only support creation of normal files and directories. */
2265 if (!S_ISREG(mode) && !S_ISDIR(mode))
2266 return ERR_PTR(-EOPNOTSUPP);
2269 mft_ni = NTFS_I(vol->mft_ino);
2270 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2271 down_write(&vol->mftbmp_lock);
2272 bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2274 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2276 goto have_alloc_rec;
2278 if (bit != -ENOSPC) {
2279 up_write(&vol->mftbmp_lock);
2280 return ERR_PTR(bit);
2283 * No free mft records left. If the mft bitmap already covers more
2284 * than the currently used mft records, the next records are all free,
2285 * so we can simply allocate the first unused mft record.
2286 * Note: We also have to make sure that the mft bitmap at least covers
2287 * the first 24 mft records as they are special and whilst they may not
2288 * be in use, we do not allocate from them.
2290 read_lock_irqsave(&mft_ni->size_lock, flags);
2291 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2292 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2293 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2294 old_data_initialized = mftbmp_ni->initialized_size;
2295 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2296 if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2300 if (unlikely(bit >= (1ll << 32)))
2302 ntfs_debug("Found free record (#2), bit 0x%llx.",
2304 goto found_free_rec;
2307 * The mft bitmap needs to be expanded until it covers the first unused
2308 * mft record that we can allocate.
2309 * Note: The smallest mft record we allocate is mft record 24.
2311 bit = old_data_initialized << 3;
2312 if (unlikely(bit >= (1ll << 32)))
2314 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2315 old_data_size = mftbmp_ni->allocated_size;
2316 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2317 "data_size 0x%llx, initialized_size 0x%llx.",
2318 (long long)old_data_size,
2319 (long long)i_size_read(vol->mftbmp_ino),
2320 (long long)old_data_initialized);
2321 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2322 if (old_data_initialized + 8 > old_data_size) {
2323 /* Need to extend bitmap by one more cluster. */
2324 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2325 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2326 if (unlikely(err)) {
2327 up_write(&vol->mftbmp_lock);
2331 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2332 ntfs_debug("Status of mftbmp after allocation extension: "
2333 "allocated_size 0x%llx, data_size 0x%llx, "
2334 "initialized_size 0x%llx.",
2335 (long long)mftbmp_ni->allocated_size,
2336 (long long)i_size_read(vol->mftbmp_ino),
2337 (long long)mftbmp_ni->initialized_size);
2338 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2342 * We now have sufficient allocated space, extend the initialized_size
2343 * as well as the data_size if necessary and fill the new space with
2346 err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2347 if (unlikely(err)) {
2348 up_write(&vol->mftbmp_lock);
2352 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2353 ntfs_debug("Status of mftbmp after initialized extention: "
2354 "allocated_size 0x%llx, data_size 0x%llx, "
2355 "initialized_size 0x%llx.",
2356 (long long)mftbmp_ni->allocated_size,
2357 (long long)i_size_read(vol->mftbmp_ino),
2358 (long long)mftbmp_ni->initialized_size);
2359 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2361 ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2363 /* @bit is the found free mft record, allocate it in the mft bitmap. */
2364 ntfs_debug("At found_free_rec.");
2365 err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2366 if (unlikely(err)) {
2367 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2368 up_write(&vol->mftbmp_lock);
2371 ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2374 * The mft bitmap is now uptodate. Deal with mft data attribute now.
2375 * Note, we keep hold of the mft bitmap lock for writing until all
2376 * modifications to the mft data attribute are complete, too, as they
2377 * will impact decisions for mft bitmap and mft record allocation done
2378 * by a parallel allocation and if the lock is not maintained a
2379 * parallel allocation could allocate the same mft record as this one.
2381 ll = (bit + 1) << vol->mft_record_size_bits;
2382 read_lock_irqsave(&mft_ni->size_lock, flags);
2383 old_data_initialized = mft_ni->initialized_size;
2384 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2385 if (ll <= old_data_initialized) {
2386 ntfs_debug("Allocated mft record already initialized.");
2387 goto mft_rec_already_initialized;
2389 ntfs_debug("Initializing allocated mft record.");
2391 * The mft record is outside the initialized data. Extend the mft data
2392 * attribute until it covers the allocated record. The loop is only
2393 * actually traversed more than once when a freshly formatted volume is
2394 * first written to so it optimizes away nicely in the common case.
2396 read_lock_irqsave(&mft_ni->size_lock, flags);
2397 ntfs_debug("Status of mft data before extension: "
2398 "allocated_size 0x%llx, data_size 0x%llx, "
2399 "initialized_size 0x%llx.",
2400 (long long)mft_ni->allocated_size,
2401 (long long)i_size_read(vol->mft_ino),
2402 (long long)mft_ni->initialized_size);
2403 while (ll > mft_ni->allocated_size) {
2404 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2405 err = ntfs_mft_data_extend_allocation_nolock(vol);
2406 if (unlikely(err)) {
2407 ntfs_error(vol->sb, "Failed to extend mft data "
2409 goto undo_mftbmp_alloc_nolock;
2411 read_lock_irqsave(&mft_ni->size_lock, flags);
2412 ntfs_debug("Status of mft data after allocation extension: "
2413 "allocated_size 0x%llx, data_size 0x%llx, "
2414 "initialized_size 0x%llx.",
2415 (long long)mft_ni->allocated_size,
2416 (long long)i_size_read(vol->mft_ino),
2417 (long long)mft_ni->initialized_size);
2419 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2421 * Extend mft data initialized size (and data size of course) to reach
2422 * the allocated mft record, formatting the mft records allong the way.
2423 * Note: We only modify the ntfs_inode structure as that is all that is
2424 * needed by ntfs_mft_record_format(). We will update the attribute
2425 * record itself in one fell swoop later on.
2427 write_lock_irqsave(&mft_ni->size_lock, flags);
2428 old_data_initialized = mft_ni->initialized_size;
2429 old_data_size = vol->mft_ino->i_size;
2430 while (ll > mft_ni->initialized_size) {
2431 s64 new_initialized_size, mft_no;
2433 new_initialized_size = mft_ni->initialized_size +
2434 vol->mft_record_size;
2435 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2436 if (new_initialized_size > i_size_read(vol->mft_ino))
2437 i_size_write(vol->mft_ino, new_initialized_size);
2438 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2439 ntfs_debug("Initializing mft record 0x%llx.",
2441 err = ntfs_mft_record_format(vol, mft_no);
2442 if (unlikely(err)) {
2443 ntfs_error(vol->sb, "Failed to format mft record.");
2444 goto undo_data_init;
2446 write_lock_irqsave(&mft_ni->size_lock, flags);
2447 mft_ni->initialized_size = new_initialized_size;
2449 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2450 record_formatted = TRUE;
2451 /* Update the mft data attribute record to reflect the new sizes. */
2452 m = map_mft_record(mft_ni);
2454 ntfs_error(vol->sb, "Failed to map mft record.");
2456 goto undo_data_init;
2458 ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2459 if (unlikely(!ctx)) {
2460 ntfs_error(vol->sb, "Failed to get search context.");
2462 unmap_mft_record(mft_ni);
2463 goto undo_data_init;
2465 err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2466 CASE_SENSITIVE, 0, NULL, 0, ctx);
2467 if (unlikely(err)) {
2468 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2469 "mft data attribute.");
2470 ntfs_attr_put_search_ctx(ctx);
2471 unmap_mft_record(mft_ni);
2472 goto undo_data_init;
2475 read_lock_irqsave(&mft_ni->size_lock, flags);
2476 a->data.non_resident.initialized_size =
2477 cpu_to_sle64(mft_ni->initialized_size);
2478 a->data.non_resident.data_size =
2479 cpu_to_sle64(i_size_read(vol->mft_ino));
2480 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2481 /* Ensure the changes make it to disk. */
2482 flush_dcache_mft_record_page(ctx->ntfs_ino);
2483 mark_mft_record_dirty(ctx->ntfs_ino);
2484 ntfs_attr_put_search_ctx(ctx);
2485 unmap_mft_record(mft_ni);
2486 read_lock_irqsave(&mft_ni->size_lock, flags);
2487 ntfs_debug("Status of mft data after mft record initialization: "
2488 "allocated_size 0x%llx, data_size 0x%llx, "
2489 "initialized_size 0x%llx.",
2490 (long long)mft_ni->allocated_size,
2491 (long long)i_size_read(vol->mft_ino),
2492 (long long)mft_ni->initialized_size);
2493 BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2494 BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2495 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2496 mft_rec_already_initialized:
2498 * We can finally drop the mft bitmap lock as the mft data attribute
2499 * has been fully updated. The only disparity left is that the
2500 * allocated mft record still needs to be marked as in use to match the
2501 * set bit in the mft bitmap but this is actually not a problem since
2502 * this mft record is not referenced from anywhere yet and the fact
2503 * that it is allocated in the mft bitmap means that no-one will try to
2504 * allocate it either.
2506 up_write(&vol->mftbmp_lock);
2508 * We now have allocated and initialized the mft record. Calculate the
2509 * index of and the offset within the page cache page the record is in.
2511 index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2512 ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2513 /* Read, map, and pin the page containing the mft record. */
2514 page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2515 if (unlikely(IS_ERR(page))) {
2516 ntfs_error(vol->sb, "Failed to map page containing allocated "
2517 "mft record 0x%llx.", (long long)bit);
2518 err = PTR_ERR(page);
2519 goto undo_mftbmp_alloc;
2522 BUG_ON(!PageUptodate(page));
2523 ClearPageUptodate(page);
2524 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2525 /* If we just formatted the mft record no need to do it again. */
2526 if (!record_formatted) {
2527 /* Sanity check that the mft record is really not in use. */
2528 if (ntfs_is_file_record(m->magic) &&
2529 (m->flags & MFT_RECORD_IN_USE)) {
2530 ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2531 "free in mft bitmap but is marked "
2532 "used itself. Corrupt filesystem. "
2533 "Unmount and run chkdsk.",
2536 SetPageUptodate(page);
2538 ntfs_unmap_page(page);
2540 goto undo_mftbmp_alloc;
2543 * We need to (re-)format the mft record, preserving the
2544 * sequence number if it is not zero as well as the update
2545 * sequence number if it is not zero or -1 (0xffff). This
2546 * means we do not need to care whether or not something went
2547 * wrong with the previous mft record.
2549 seq_no = m->sequence_number;
2550 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2551 err = ntfs_mft_record_layout(vol, bit, m);
2552 if (unlikely(err)) {
2553 ntfs_error(vol->sb, "Failed to layout allocated mft "
2554 "record 0x%llx.", (long long)bit);
2555 SetPageUptodate(page);
2557 ntfs_unmap_page(page);
2558 goto undo_mftbmp_alloc;
2561 m->sequence_number = seq_no;
2562 if (usn && le16_to_cpu(usn) != 0xffff)
2563 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2565 /* Set the mft record itself in use. */
2566 m->flags |= MFT_RECORD_IN_USE;
2568 m->flags |= MFT_RECORD_IS_DIRECTORY;
2569 flush_dcache_page(page);
2570 SetPageUptodate(page);
2573 * Setup the base mft record in the extent mft record. This
2574 * completes initialization of the allocated extent mft record
2575 * and we can simply use it with map_extent_mft_record().
2577 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2580 * Allocate an extent inode structure for the new mft record,
2581 * attach it to the base inode @base_ni and map, pin, and lock
2582 * its, i.e. the allocated, mft record.
2584 m = map_extent_mft_record(base_ni, bit, &ni);
2586 ntfs_error(vol->sb, "Failed to map allocated extent "
2587 "mft record 0x%llx.", (long long)bit);
2589 /* Set the mft record itself not in use. */
2590 m->flags &= cpu_to_le16(
2591 ~le16_to_cpu(MFT_RECORD_IN_USE));
2592 flush_dcache_page(page);
2593 /* Make sure the mft record is written out to disk. */
2594 mark_ntfs_record_dirty(page, ofs);
2596 ntfs_unmap_page(page);
2597 goto undo_mftbmp_alloc;
2600 * Make sure the allocated mft record is written out to disk.
2601 * No need to set the inode dirty because the caller is going
2602 * to do that anyway after finishing with the new extent mft
2603 * record (e.g. at a minimum a new attribute will be added to
2606 mark_ntfs_record_dirty(page, ofs);
2609 * Need to unmap the page since map_extent_mft_record() mapped
2610 * it as well so we have it mapped twice at the moment.
2612 ntfs_unmap_page(page);
2615 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2616 * is set to 1 but the mft record->link_count is 0. The caller
2617 * needs to bear this in mind.
2619 vi = new_inode(vol->sb);
2620 if (unlikely(!vi)) {
2622 /* Set the mft record itself not in use. */
2623 m->flags &= cpu_to_le16(
2624 ~le16_to_cpu(MFT_RECORD_IN_USE));
2625 flush_dcache_page(page);
2626 /* Make sure the mft record is written out to disk. */
2627 mark_ntfs_record_dirty(page, ofs);
2629 ntfs_unmap_page(page);
2630 goto undo_mftbmp_alloc;
2634 * This is the optimal IO size (for stat), not the fs block
2637 vi->i_blksize = PAGE_CACHE_SIZE;
2639 * This is for checking whether an inode has changed w.r.t. a
2640 * file so that the file can be updated if necessary (compare
2645 /* The owner and group come from the ntfs volume. */
2646 vi->i_uid = vol->uid;
2647 vi->i_gid = vol->gid;
2649 /* Initialize the ntfs specific part of @vi. */
2650 ntfs_init_big_inode(vi);
2653 * Set the appropriate mode, attribute type, and name. For
2654 * directories, also setup the index values to the defaults.
2656 if (S_ISDIR(mode)) {
2657 vi->i_mode = S_IFDIR | S_IRWXUGO;
2658 vi->i_mode &= ~vol->dmask;
2660 NInoSetMstProtected(ni);
2661 ni->type = AT_INDEX_ALLOCATION;
2665 ni->itype.index.block_size = 4096;
2666 ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2667 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2668 if (vol->cluster_size <= ni->itype.index.block_size) {
2669 ni->itype.index.vcn_size = vol->cluster_size;
2670 ni->itype.index.vcn_size_bits =
2671 vol->cluster_size_bits;
2673 ni->itype.index.vcn_size = vol->sector_size;
2674 ni->itype.index.vcn_size_bits =
2675 vol->sector_size_bits;
2678 vi->i_mode = S_IFREG | S_IRWXUGO;
2679 vi->i_mode &= ~vol->fmask;
2686 vi->i_mode &= ~S_IWUGO;
2688 /* Set the inode times to the current time. */
2689 vi->i_atime = vi->i_mtime = vi->i_ctime =
2690 current_fs_time(vi->i_sb);
2692 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2693 * the call to ntfs_init_big_inode() below.
2698 /* Set the sequence number. */
2699 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2701 * Manually map, pin, and lock the mft record as we already
2702 * have its page mapped and it is very easy to do.
2704 atomic_inc(&ni->count);
2705 down(&ni->mrec_lock);
2709 * Make sure the allocated mft record is written out to disk.
2710 * NOTE: We do not set the ntfs inode dirty because this would
2711 * fail in ntfs_write_inode() because the inode does not have a
2712 * standard information attribute yet. Also, there is no need
2713 * to set the inode dirty because the caller is going to do
2714 * that anyway after finishing with the new mft record (e.g. at
2715 * a minimum some new attributes will be added to the mft
2718 mark_ntfs_record_dirty(page, ofs);
2721 /* Add the inode to the inode hash for the superblock. */
2722 insert_inode_hash(vi);
2724 /* Update the default mft allocation position. */
2725 vol->mft_data_pos = bit + 1;
2728 * Return the opened, allocated inode of the allocated mft record as
2729 * well as the mapped, pinned, and locked mft record.
2731 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2732 base_ni ? "extent " : "", (long long)bit);
2736 write_lock_irqsave(&mft_ni->size_lock, flags);
2737 mft_ni->initialized_size = old_data_initialized;
2738 i_size_write(vol->mft_ino, old_data_size);
2739 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2740 goto undo_mftbmp_alloc_nolock;
2742 down_write(&vol->mftbmp_lock);
2743 undo_mftbmp_alloc_nolock:
2744 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2745 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2748 up_write(&vol->mftbmp_lock);
2750 return ERR_PTR(err);
2752 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2753 "number of inodes (2^32) has already been reached.");
2754 up_write(&vol->mftbmp_lock);
2755 return ERR_PTR(-ENOSPC);
2759 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2760 * @ni: ntfs inode of the mapped extent mft record to free
2761 * @m: mapped extent mft record of the ntfs inode @ni
2763 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2765 * Note that this function unmaps the mft record and closes and destroys @ni
2766 * internally and hence you cannot use either @ni nor @m any more after this
2767 * function returns success.
2769 * On success return 0 and on error return -errno. @ni and @m are still valid
2770 * in this case and have not been freed.
2772 * For some errors an error message is displayed and the success code 0 is
2773 * returned and the volume is then left dirty on umount. This makes sense in
2774 * case we could not rollback the changes that were already done since the
2775 * caller no longer wants to reference this mft record so it does not matter to
2776 * the caller if something is wrong with it as long as it is properly detached
2777 * from the base inode.
2779 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2781 unsigned long mft_no = ni->mft_no;
2782 ntfs_volume *vol = ni->vol;
2783 ntfs_inode *base_ni;
2784 ntfs_inode **extent_nis;
2789 BUG_ON(NInoAttr(ni));
2790 BUG_ON(ni->nr_extents != -1);
2792 down(&ni->extent_lock);
2793 base_ni = ni->ext.base_ntfs_ino;
2794 up(&ni->extent_lock);
2796 BUG_ON(base_ni->nr_extents <= 0);
2798 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2799 mft_no, base_ni->mft_no);
2801 down(&base_ni->extent_lock);
2803 /* Make sure we are holding the only reference to the extent inode. */
2804 if (atomic_read(&ni->count) > 2) {
2805 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2806 "not freeing.", base_ni->mft_no);
2807 up(&base_ni->extent_lock);
2811 /* Dissociate the ntfs inode from the base inode. */
2812 extent_nis = base_ni->ext.extent_ntfs_inos;
2814 for (i = 0; i < base_ni->nr_extents; i++) {
2815 if (ni != extent_nis[i])
2818 base_ni->nr_extents--;
2819 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2820 sizeof(ntfs_inode*));
2825 up(&base_ni->extent_lock);
2827 if (unlikely(err)) {
2828 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2829 "its base inode 0x%lx.", mft_no,
2835 * The extent inode is no longer attached to the base inode so no one
2836 * can get a reference to it any more.
2839 /* Mark the mft record as not in use. */
2840 m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2842 /* Increment the sequence number, skipping zero, if it is not zero. */
2843 old_seq_no = m->sequence_number;
2844 seq_no = le16_to_cpu(old_seq_no);
2845 if (seq_no == 0xffff)
2849 m->sequence_number = cpu_to_le16(seq_no);
2852 * Set the ntfs inode dirty and write it out. We do not need to worry
2853 * about the base inode here since whatever caused the extent mft
2854 * record to be freed is guaranteed to do it already.
2857 err = write_mft_record(ni, m, 0);
2858 if (unlikely(err)) {
2859 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2860 "freeing.", mft_no);
2864 /* Unmap and throw away the now freed extent inode. */
2865 unmap_extent_mft_record(ni);
2866 ntfs_clear_extent_inode(ni);
2868 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2869 down_write(&vol->mftbmp_lock);
2870 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2871 up_write(&vol->mftbmp_lock);
2872 if (unlikely(err)) {
2874 * The extent inode is gone but we failed to deallocate it in
2875 * the mft bitmap. Just emit a warning and leave the volume
2878 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2883 /* Rollback what we did... */
2884 down(&base_ni->extent_lock);
2885 extent_nis = base_ni->ext.extent_ntfs_inos;
2886 if (!(base_ni->nr_extents & 3)) {
2887 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2889 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2890 if (unlikely(!extent_nis)) {
2891 ntfs_error(vol->sb, "Failed to allocate internal "
2892 "buffer during rollback.%s", es);
2893 up(&base_ni->extent_lock);
2895 goto rollback_error;
2897 if (base_ni->nr_extents) {
2898 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2899 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2900 new_size - 4 * sizeof(ntfs_inode*));
2901 kfree(base_ni->ext.extent_ntfs_inos);
2903 base_ni->ext.extent_ntfs_inos = extent_nis;
2905 m->flags |= MFT_RECORD_IN_USE;
2906 m->sequence_number = old_seq_no;
2907 extent_nis[base_ni->nr_extents++] = ni;
2908 up(&base_ni->extent_lock);
2909 mark_mft_record_dirty(ni);
2912 #endif /* NTFS_RW */