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 = (u64)ni->mft_no << vol->mft_record_size_bits >>
63 ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
65 i_size = i_size_read(mft_vi);
66 /* The maximum valid index into the page cache for $MFT's data. */
67 end_index = i_size >> PAGE_CACHE_SHIFT;
69 /* If the wanted index is out of bounds the mft record doesn't exist. */
70 if (unlikely(index >= end_index)) {
71 if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
72 vol->mft_record_size) {
73 page = ERR_PTR(-ENOENT);
74 ntfs_error(vol->sb, "Attemt to read mft record 0x%lx, "
75 "which is beyond the end of the mft. "
76 "This is probably a bug in the ntfs "
77 "driver.", ni->mft_no);
81 /* Read, map, and pin the page. */
82 page = ntfs_map_page(mft_vi->i_mapping, index);
83 if (likely(!IS_ERR(page))) {
84 /* Catch multi sector transfer fixup errors. */
85 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
89 return page_address(page) + ofs;
91 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
92 "Run chkdsk.", ni->mft_no);
93 ntfs_unmap_page(page);
103 * map_mft_record - map, pin and lock an mft record
104 * @ni: ntfs inode whose MFT record to map
106 * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
107 * for the semaphore if it was already locked by someone else.
109 * The page of the record is mapped using map_mft_record_page() before being
110 * returned to the caller.
112 * This in turn uses ntfs_map_page() to get the page containing the wanted mft
113 * record (it in turn calls read_cache_page() which reads it in from disk if
114 * necessary, increments the use count on the page so that it cannot disappear
115 * under us and returns a reference to the page cache page).
117 * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
118 * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
119 * and the post-read mst fixups on each mft record in the page have been
120 * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
121 * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
122 * ntfs_map_page() waits for PG_locked to become clear and checks if
123 * PG_uptodate is set and returns an error code if not. This provides
124 * sufficient protection against races when reading/using the page.
126 * However there is the write mapping to think about. Doing the above described
127 * checking here will be fine, because when initiating the write we will set
128 * PG_locked and clear PG_uptodate making sure nobody is touching the page
129 * contents. Doing the locking this way means that the commit to disk code in
130 * the page cache code paths is automatically sufficiently locked with us as
131 * we will not touch a page that has been locked or is not uptodate. The only
132 * locking problem then is them locking the page while we are accessing it.
134 * So that code will end up having to own the mrec_lock of all mft
135 * records/inodes present in the page before I/O can proceed. In that case we
136 * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
137 * accessing anything without owning the mrec_lock semaphore. But we do need
138 * to use them because of the read_cache_page() invocation and the code becomes
139 * so much simpler this way that it is well worth it.
141 * The mft record is now ours and we return a pointer to it. You need to check
142 * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
145 * NOTE: Caller is responsible for setting the mft record dirty before calling
146 * unmap_mft_record(). This is obviously only necessary if the caller really
147 * modified the mft record...
148 * Q: Do we want to recycle one of the VFS inode state bits instead?
149 * A: No, the inode ones mean we want to change the mft record, not we want to
152 MFT_RECORD *map_mft_record(ntfs_inode *ni)
156 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
158 /* Make sure the ntfs inode doesn't go away. */
159 atomic_inc(&ni->count);
161 /* Serialize access to this mft record. */
162 down(&ni->mrec_lock);
164 m = map_mft_record_page(ni);
165 if (likely(!IS_ERR(m)))
169 atomic_dec(&ni->count);
170 ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
175 * unmap_mft_record_page - unmap the page in which a specific mft record resides
176 * @ni: ntfs inode whose mft record page to unmap
178 * This unmaps the page in which the mft record of the ntfs inode @ni is
179 * situated and returns. This is a NOOP if highmem is not configured.
181 * The unmap happens via ntfs_unmap_page() which in turn decrements the use
182 * count on the page thus releasing it from the pinned state.
184 * We do not actually unmap the page from memory of course, as that will be
185 * done by the page cache code itself when memory pressure increases or
188 static inline void unmap_mft_record_page(ntfs_inode *ni)
192 // TODO: If dirty, blah...
193 ntfs_unmap_page(ni->page);
200 * unmap_mft_record - release a mapped mft record
201 * @ni: ntfs inode whose MFT record to unmap
203 * We release the page mapping and the mrec_lock mutex which unmaps the mft
204 * record and releases it for others to get hold of. We also release the ntfs
205 * inode by decrementing the ntfs inode reference count.
207 * NOTE: If caller has modified the mft record, it is imperative to set the mft
208 * record dirty BEFORE calling unmap_mft_record().
210 void unmap_mft_record(ntfs_inode *ni)
212 struct page *page = ni->page;
216 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
218 unmap_mft_record_page(ni);
220 atomic_dec(&ni->count);
222 * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
223 * ntfs_clear_extent_inode() in the extent inode case, and to the
224 * caller in the non-extent, yet pure ntfs inode case, to do the actual
225 * tear down of all structures and freeing of all allocated memory.
231 * map_extent_mft_record - load an extent inode and attach it to its base
232 * @base_ni: base ntfs inode
233 * @mref: mft reference of the extent inode to load
234 * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
236 * Load the extent mft record @mref and attach it to its base inode @base_ni.
237 * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
238 * PTR_ERR(result) gives the negative error code.
240 * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
241 * structure of the mapped extent inode.
243 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
244 ntfs_inode **ntfs_ino)
247 ntfs_inode *ni = NULL;
248 ntfs_inode **extent_nis = NULL;
250 unsigned long mft_no = MREF(mref);
251 u16 seq_no = MSEQNO(mref);
252 BOOL destroy_ni = FALSE;
254 ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
255 mft_no, base_ni->mft_no);
256 /* Make sure the base ntfs inode doesn't go away. */
257 atomic_inc(&base_ni->count);
259 * Check if this extent inode has already been added to the base inode,
260 * in which case just return it. If not found, add it to the base
261 * inode before returning it.
263 down(&base_ni->extent_lock);
264 if (base_ni->nr_extents > 0) {
265 extent_nis = base_ni->ext.extent_ntfs_inos;
266 for (i = 0; i < base_ni->nr_extents; i++) {
267 if (mft_no != extent_nis[i]->mft_no)
270 /* Make sure the ntfs inode doesn't go away. */
271 atomic_inc(&ni->count);
275 if (likely(ni != NULL)) {
276 up(&base_ni->extent_lock);
277 atomic_dec(&base_ni->count);
278 /* We found the record; just have to map and return it. */
279 m = map_mft_record(ni);
280 /* map_mft_record() has incremented this on success. */
281 atomic_dec(&ni->count);
282 if (likely(!IS_ERR(m))) {
283 /* Verify the sequence number. */
284 if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
285 ntfs_debug("Done 1.");
289 unmap_mft_record(ni);
290 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
291 "reference! Corrupt filesystem. "
293 return ERR_PTR(-EIO);
296 ntfs_error(base_ni->vol->sb, "Failed to map extent "
297 "mft record, error code %ld.", -PTR_ERR(m));
300 /* Record wasn't there. Get a new ntfs inode and initialize it. */
301 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
303 up(&base_ni->extent_lock);
304 atomic_dec(&base_ni->count);
305 return ERR_PTR(-ENOMEM);
307 ni->vol = base_ni->vol;
310 ni->ext.base_ntfs_ino = base_ni;
311 /* Now map the record. */
312 m = map_mft_record(ni);
314 up(&base_ni->extent_lock);
315 atomic_dec(&base_ni->count);
316 ntfs_clear_extent_inode(ni);
319 /* Verify the sequence number if it is present. */
320 if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
321 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
322 "reference! Corrupt filesystem. Run chkdsk.");
327 /* Attach extent inode to base inode, reallocating memory if needed. */
328 if (!(base_ni->nr_extents & 3)) {
330 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
332 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
333 if (unlikely(!tmp)) {
334 ntfs_error(base_ni->vol->sb, "Failed to allocate "
337 m = ERR_PTR(-ENOMEM);
340 if (base_ni->nr_extents) {
341 BUG_ON(!base_ni->ext.extent_ntfs_inos);
342 memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
343 4 * sizeof(ntfs_inode *));
344 kfree(base_ni->ext.extent_ntfs_inos);
346 base_ni->ext.extent_ntfs_inos = tmp;
348 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
349 up(&base_ni->extent_lock);
350 atomic_dec(&base_ni->count);
351 ntfs_debug("Done 2.");
355 unmap_mft_record(ni);
356 up(&base_ni->extent_lock);
357 atomic_dec(&base_ni->count);
359 * If the extent inode was not attached to the base inode we need to
360 * release it or we will leak memory.
363 ntfs_clear_extent_inode(ni);
370 * __mark_mft_record_dirty - set the mft record and the page containing it dirty
371 * @ni: ntfs inode describing the mapped mft record
373 * Internal function. Users should call mark_mft_record_dirty() instead.
375 * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
376 * as well as the page containing the mft record, dirty. Also, mark the base
377 * vfs inode dirty. This ensures that any changes to the mft record are
378 * written out to disk.
380 * NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
381 * on the base vfs inode, because even though file data may have been modified,
382 * it is dirty in the inode meta data rather than the data page cache of the
383 * inode, and thus there are no data pages that need writing out. Therefore, a
384 * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
385 * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
386 * ensure ->write_inode is called from generic_osync_inode() and this needs to
387 * happen or the file data would not necessarily hit the device synchronously,
388 * even though the vfs inode has the O_SYNC flag set. Also, I_DIRTY_DATASYNC
389 * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
390 * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
393 void __mark_mft_record_dirty(ntfs_inode *ni)
397 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
398 BUG_ON(NInoAttr(ni));
399 mark_ntfs_record_dirty(ni->page, ni->page_ofs);
400 /* Determine the base vfs inode and mark it dirty, too. */
401 down(&ni->extent_lock);
402 if (likely(ni->nr_extents >= 0))
405 base_ni = ni->ext.base_ntfs_ino;
406 up(&ni->extent_lock);
407 __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
410 static const char *ntfs_please_email = "Please email "
411 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
412 "this message. Thank you.";
415 * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
416 * @vol: ntfs volume on which the mft record to synchronize resides
417 * @mft_no: mft record number of mft record to synchronize
418 * @m: mapped, mst protected (extent) mft record to synchronize
420 * Write the mapped, mst protected (extent) mft record @m with mft record
421 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
422 * bypassing the page cache and the $MFTMirr inode itself.
424 * This function is only for use at umount time when the mft mirror inode has
425 * already been disposed off. We BUG() if we are called while the mft mirror
426 * inode is still attached to the volume.
428 * On success return 0. On error return -errno.
430 * NOTE: This function is not implemented yet as I am not convinced it can
431 * actually be triggered considering the sequence of commits we do in super.c::
432 * ntfs_put_super(). But just in case we provide this place holder as the
433 * alternative would be either to BUG() or to get a NULL pointer dereference
436 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
437 const unsigned long mft_no, MFT_RECORD *m)
439 BUG_ON(vol->mftmirr_ino);
440 ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
441 "implemented yet. %s", ntfs_please_email);
446 * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
447 * @vol: ntfs volume on which the mft record to synchronize resides
448 * @mft_no: mft record number of mft record to synchronize
449 * @m: mapped, mst protected (extent) mft record to synchronize
450 * @sync: if true, wait for i/o completion
452 * Write the mapped, mst protected (extent) mft record @m with mft record
453 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
455 * On success return 0. On error return -errno and set the volume errors flag
456 * in the ntfs volume @vol.
458 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
460 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
461 * schedule i/o via ->writepage or do it via kntfsd or whatever.
463 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
464 MFT_RECORD *m, int sync)
467 unsigned int blocksize = vol->sb->s_blocksize;
468 int max_bhs = vol->mft_record_size / blocksize;
469 struct buffer_head *bhs[max_bhs];
470 struct buffer_head *bh, *head;
473 unsigned int block_start, block_end, m_start, m_end, page_ofs;
474 int i_bhs, nr_bhs, err = 0;
475 unsigned char blocksize_bits = vol->mftmirr_ino->i_blkbits;
477 ntfs_debug("Entering for inode 0x%lx.", mft_no);
479 if (unlikely(!vol->mftmirr_ino)) {
480 /* This could happen during umount... */
481 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
486 /* Get the page containing the mirror copy of the mft record @m. */
487 page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
488 (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
490 ntfs_error(vol->sb, "Failed to map mft mirror page.");
495 BUG_ON(!PageUptodate(page));
496 ClearPageUptodate(page);
497 /* Offset of the mft mirror record inside the page. */
498 page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
499 /* The address in the page of the mirror copy of the mft record @m. */
500 kmirr = page_address(page) + page_ofs;
501 /* Copy the mst protected mft record to the mirror. */
502 memcpy(kmirr, m, vol->mft_record_size);
503 /* Create uptodate buffers if not present. */
504 if (unlikely(!page_has_buffers(page))) {
505 struct buffer_head *tail;
507 bh = head = alloc_page_buffers(page, blocksize, 1);
509 set_buffer_uptodate(bh);
511 bh = bh->b_this_page;
513 tail->b_this_page = head;
514 attach_page_buffers(page, head);
516 bh = head = page_buffers(page);
521 m_start = kmirr - (u8*)page_address(page);
522 m_end = m_start + vol->mft_record_size;
524 block_end = block_start + blocksize;
525 /* If the buffer is outside the mft record, skip it. */
526 if (block_end <= m_start)
528 if (unlikely(block_start >= m_end))
530 /* Need to map the buffer if it is not mapped already. */
531 if (unlikely(!buffer_mapped(bh))) {
534 unsigned int vcn_ofs;
536 bh->b_bdev = vol->sb->s_bdev;
537 /* Obtain the vcn and offset of the current block. */
538 vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
539 (block_start - m_start);
540 vcn_ofs = vcn & vol->cluster_size_mask;
541 vcn >>= vol->cluster_size_bits;
543 down_read(&NTFS_I(vol->mftmirr_ino)->
545 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
547 * $MFTMirr always has the whole of its runlist
552 /* Seek to element containing target vcn. */
553 while (rl->length && rl[1].vcn <= vcn)
555 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
556 /* For $MFTMirr, only lcn >= 0 is a successful remap. */
557 if (likely(lcn >= 0)) {
558 /* Setup buffer head to correct block. */
559 bh->b_blocknr = ((lcn <<
560 vol->cluster_size_bits) +
561 vcn_ofs) >> blocksize_bits;
562 set_buffer_mapped(bh);
565 ntfs_error(vol->sb, "Cannot write mft mirror "
566 "record 0x%lx because its "
567 "location on disk could not "
568 "be determined (error code "
574 BUG_ON(!buffer_uptodate(bh));
575 BUG_ON(!nr_bhs && (m_start != block_start));
576 BUG_ON(nr_bhs >= max_bhs);
578 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
579 } while (block_start = block_end, (bh = bh->b_this_page) != head);
581 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
583 /* Lock buffers and start synchronous write i/o on them. */
584 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
585 struct buffer_head *tbh = bhs[i_bhs];
587 if (unlikely(test_set_buffer_locked(tbh)))
589 BUG_ON(!buffer_uptodate(tbh));
590 clear_buffer_dirty(tbh);
592 tbh->b_end_io = end_buffer_write_sync;
593 submit_bh(WRITE, tbh);
595 /* Wait on i/o completion of buffers. */
596 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
597 struct buffer_head *tbh = bhs[i_bhs];
600 if (unlikely(!buffer_uptodate(tbh))) {
603 * Set the buffer uptodate so the page and
604 * buffer states do not become out of sync.
606 set_buffer_uptodate(tbh);
609 } else /* if (unlikely(err)) */ {
610 /* Clean the buffers. */
611 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
612 clear_buffer_dirty(bhs[i_bhs]);
614 /* Current state: all buffers are clean, unlocked, and uptodate. */
615 /* Remove the mst protection fixups again. */
616 post_write_mst_fixup((NTFS_RECORD*)kmirr);
617 flush_dcache_page(page);
618 SetPageUptodate(page);
620 ntfs_unmap_page(page);
624 ntfs_error(vol->sb, "I/O error while writing mft mirror "
625 "record 0x%lx!", mft_no);
627 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
628 "code %i). Volume will be left marked dirty "
629 "on umount. Run ntfsfix on the partition "
630 "after umounting to correct this.", -err);
637 * write_mft_record_nolock - write out a mapped (extent) mft record
638 * @ni: ntfs inode describing the mapped (extent) mft record
639 * @m: mapped (extent) mft record to write
640 * @sync: if true, wait for i/o completion
642 * Write the mapped (extent) mft record @m described by the (regular or extent)
643 * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
644 * the mft mirror, that is also updated.
646 * We only write the mft record if the ntfs inode @ni is dirty and the first
647 * buffer belonging to its mft record is dirty, too. We ignore the dirty state
648 * of subsequent buffers because we could have raced with
649 * fs/ntfs/aops.c::mark_ntfs_record_dirty().
651 * On success, clean the mft record and return 0. On error, leave the mft
652 * record dirty and return -errno. The caller should call make_bad_inode() on
653 * the base inode to ensure no more access happens to this inode. We do not do
654 * it here as the caller may want to finish writing other extent mft records
655 * first to minimize on-disk metadata inconsistencies.
657 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
658 * However, if the mft record has a counterpart in the mft mirror and @sync is
659 * true, we write the mft record, wait for i/o completion, and only then write
660 * the mft mirror copy. This ensures that if the system crashes either the mft
661 * or the mft mirror will contain a self-consistent mft record @m. If @sync is
662 * false on the other hand, we start i/o on both and then wait for completion
663 * on them. This provides a speedup but no longer guarantees that you will end
664 * up with a self-consistent mft record in the case of a crash but if you asked
665 * for asynchronous writing you probably do not care about that anyway.
667 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
668 * schedule i/o via ->writepage or do it via kntfsd or whatever.
670 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
672 ntfs_volume *vol = ni->vol;
673 struct page *page = ni->page;
674 unsigned char blocksize_bits = vol->mft_ino->i_blkbits;
675 unsigned int blocksize = 1 << blocksize_bits;
676 int max_bhs = vol->mft_record_size / blocksize;
677 struct buffer_head *bhs[max_bhs];
678 struct buffer_head *bh, *head;
680 unsigned int block_start, block_end, m_start, m_end;
681 int i_bhs, nr_bhs, err = 0;
683 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
684 BUG_ON(NInoAttr(ni));
686 BUG_ON(!PageLocked(page));
688 * If the ntfs_inode is clean no need to do anything. If it is dirty,
689 * mark it as clean now so that it can be redirtied later on if needed.
690 * There is no danger of races since the caller is holding the locks
691 * for the mft record @m and the page it is in.
693 if (!NInoTestClearDirty(ni))
695 bh = head = page_buffers(page);
700 m_start = ni->page_ofs;
701 m_end = m_start + vol->mft_record_size;
703 block_end = block_start + blocksize;
704 /* If the buffer is outside the mft record, skip it. */
705 if (block_end <= m_start)
707 if (unlikely(block_start >= m_end))
710 * If this block is not the first one in the record, we ignore
711 * the buffer's dirty state because we could have raced with a
712 * parallel mark_ntfs_record_dirty().
714 if (block_start == m_start) {
715 /* This block is the first one in the record. */
716 if (!buffer_dirty(bh)) {
718 /* Clean records are not written out. */
722 /* Need to map the buffer if it is not mapped already. */
723 if (unlikely(!buffer_mapped(bh))) {
726 unsigned int vcn_ofs;
728 bh->b_bdev = vol->sb->s_bdev;
729 /* Obtain the vcn and offset of the current block. */
730 vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
731 (block_start - m_start);
732 vcn_ofs = vcn & vol->cluster_size_mask;
733 vcn >>= vol->cluster_size_bits;
735 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
736 rl = NTFS_I(vol->mft_ino)->runlist.rl;
739 /* Seek to element containing target vcn. */
740 while (rl->length && rl[1].vcn <= vcn)
742 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
743 /* For $MFT, only lcn >= 0 is a successful remap. */
744 if (likely(lcn >= 0)) {
745 /* Setup buffer head to correct block. */
746 bh->b_blocknr = ((lcn <<
747 vol->cluster_size_bits) +
748 vcn_ofs) >> blocksize_bits;
749 set_buffer_mapped(bh);
752 ntfs_error(vol->sb, "Cannot write mft record "
753 "0x%lx because its location "
754 "on disk could not be "
755 "determined (error code %lli).",
756 ni->mft_no, (long long)lcn);
760 BUG_ON(!buffer_uptodate(bh));
761 BUG_ON(!nr_bhs && (m_start != block_start));
762 BUG_ON(nr_bhs >= max_bhs);
764 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
765 } while (block_start = block_end, (bh = bh->b_this_page) != head);
767 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
772 /* Apply the mst protection fixups. */
773 err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
775 ntfs_error(vol->sb, "Failed to apply mst fixups!");
778 flush_dcache_mft_record_page(ni);
779 /* Lock buffers and start synchronous write i/o on them. */
780 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
781 struct buffer_head *tbh = bhs[i_bhs];
783 if (unlikely(test_set_buffer_locked(tbh)))
785 BUG_ON(!buffer_uptodate(tbh));
786 clear_buffer_dirty(tbh);
788 tbh->b_end_io = end_buffer_write_sync;
789 submit_bh(WRITE, tbh);
791 /* Synchronize the mft mirror now if not @sync. */
792 if (!sync && ni->mft_no < vol->mftmirr_size)
793 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
794 /* Wait on i/o completion of buffers. */
795 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
796 struct buffer_head *tbh = bhs[i_bhs];
799 if (unlikely(!buffer_uptodate(tbh))) {
802 * Set the buffer uptodate so the page and buffer
803 * states do not become out of sync.
805 if (PageUptodate(page))
806 set_buffer_uptodate(tbh);
809 /* If @sync, now synchronize the mft mirror. */
810 if (sync && ni->mft_no < vol->mftmirr_size)
811 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
812 /* Remove the mst protection fixups again. */
813 post_write_mst_fixup((NTFS_RECORD*)m);
814 flush_dcache_mft_record_page(ni);
816 /* I/O error during writing. This is really bad! */
817 ntfs_error(vol->sb, "I/O error while writing mft record "
818 "0x%lx! Marking base inode as bad. You "
819 "should unmount the volume and run chkdsk.",
827 /* Clean the buffers. */
828 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
829 clear_buffer_dirty(bhs[i_bhs]);
832 * Current state: all buffers are clean, unlocked, and uptodate.
833 * The caller should mark the base inode as bad so that no more i/o
834 * happens. ->clear_inode() will still be invoked so all extent inodes
835 * and other allocated memory will be freed.
837 if (err == -ENOMEM) {
838 ntfs_error(vol->sb, "Not enough memory to write mft record. "
839 "Redirtying so the write is retried later.");
840 mark_mft_record_dirty(ni);
848 * ntfs_may_write_mft_record - check if an mft record may be written out
849 * @vol: [IN] ntfs volume on which the mft record to check resides
850 * @mft_no: [IN] mft record number of the mft record to check
851 * @m: [IN] mapped mft record to check
852 * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
854 * Check if the mapped (base or extent) mft record @m with mft record number
855 * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
856 * and possible the ntfs inode of the mft record is locked and the base vfs
857 * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
858 * caller is responsible for unlocking the ntfs inode and unpinning the base
861 * Return TRUE if the mft record may be written out and FALSE if not.
863 * The caller has locked the page and cleared the uptodate flag on it which
864 * means that we can safely write out any dirty mft records that do not have
865 * their inodes in icache as determined by ilookup5() as anyone
866 * opening/creating such an inode would block when attempting to map the mft
867 * record in read_cache_page() until we are finished with the write out.
869 * Here is a description of the tests we perform:
871 * If the inode is found in icache we know the mft record must be a base mft
872 * record. If it is dirty, we do not write it and return FALSE as the vfs
873 * inode write paths will result in the access times being updated which would
874 * cause the base mft record to be redirtied and written out again. (We know
875 * the access time update will modify the base mft record because Windows
876 * chkdsk complains if the standard information attribute is not in the base
879 * If the inode is in icache and not dirty, we attempt to lock the mft record
880 * and if we find the lock was already taken, it is not safe to write the mft
881 * record and we return FALSE.
883 * If we manage to obtain the lock we have exclusive access to the mft record,
884 * which also allows us safe writeout of the mft record. We then set
885 * @locked_ni to the locked ntfs inode and return TRUE.
887 * Note we cannot just lock the mft record and sleep while waiting for the lock
888 * because this would deadlock due to lock reversal (normally the mft record is
889 * locked before the page is locked but we already have the page locked here
890 * when we try to lock the mft record).
892 * If the inode is not in icache we need to perform further checks.
894 * If the mft record is not a FILE record or it is a base mft record, we can
895 * safely write it and return TRUE.
897 * We now know the mft record is an extent mft record. We check if the inode
898 * corresponding to its base mft record is in icache and obtain a reference to
899 * it if it is. If it is not, we can safely write it and return TRUE.
901 * We now have the base inode for the extent mft record. We check if it has an
902 * ntfs inode for the extent mft record attached and if not it is safe to write
903 * the extent mft record and we return TRUE.
905 * The ntfs inode for the extent mft record is attached to the base inode so we
906 * attempt to lock the extent mft record and if we find the lock was already
907 * taken, it is not safe to write the extent mft record and we return FALSE.
909 * If we manage to obtain the lock we have exclusive access to the extent mft
910 * record, which also allows us safe writeout of the extent mft record. We
911 * set the ntfs inode of the extent mft record clean and then set @locked_ni to
912 * the now locked ntfs inode and return TRUE.
914 * Note, the reason for actually writing dirty mft records here and not just
915 * relying on the vfs inode dirty code paths is that we can have mft records
916 * modified without them ever having actual inodes in memory. Also we can have
917 * dirty mft records with clean ntfs inodes in memory. None of the described
918 * cases would result in the dirty mft records being written out if we only
919 * relied on the vfs inode dirty code paths. And these cases can really occur
920 * during allocation of new mft records and in particular when the
921 * initialized_size of the $MFT/$DATA attribute is extended and the new space
922 * is initialized using ntfs_mft_record_format(). The clean inode can then
923 * appear if the mft record is reused for a new inode before it got written
926 BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
927 const MFT_RECORD *m, ntfs_inode **locked_ni)
929 struct super_block *sb = vol->sb;
930 struct inode *mft_vi = vol->mft_ino;
932 ntfs_inode *ni, *eni, **extent_nis;
936 ntfs_debug("Entering for inode 0x%lx.", mft_no);
938 * Normally we do not return a locked inode so set @locked_ni to NULL.
943 * Check if the inode corresponding to this mft record is in the VFS
944 * inode cache and obtain a reference to it if it is.
946 ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
952 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
953 * we get here for it rather often.
956 /* Balance the below iput(). */
958 BUG_ON(vi != mft_vi);
961 * Have to use ilookup5_nowait() since ilookup5() waits for the
962 * inode lock which causes ntfs to deadlock when a concurrent
963 * inode write via the inode dirty code paths and the page
964 * dirty code path of the inode dirty code path when writing
967 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
970 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
971 /* The inode is in icache. */
973 /* Take a reference to the ntfs inode. */
974 atomic_inc(&ni->count);
975 /* If the inode is dirty, do not write this record. */
977 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
979 atomic_dec(&ni->count);
983 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
984 /* The inode is not dirty, try to take the mft record lock. */
985 if (unlikely(down_trylock(&ni->mrec_lock))) {
986 ntfs_debug("Mft record 0x%lx is already locked, do "
987 "not write it.", mft_no);
988 atomic_dec(&ni->count);
992 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
995 * The write has to occur while we hold the mft record lock so
996 * return the locked ntfs inode.
1001 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1002 /* The inode is not in icache. */
1003 /* Write the record if it is not a mft record (type "FILE"). */
1004 if (!ntfs_is_mft_record(m->magic)) {
1005 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1009 /* Write the mft record if it is a base inode. */
1010 if (!m->base_mft_record) {
1011 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1016 * This is an extent mft record. Check if the inode corresponding to
1017 * its base mft record is in icache and obtain a reference to it if it
1020 na.mft_no = MREF_LE(m->base_mft_record);
1021 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1022 "inode 0x%lx in icache.", mft_no, na.mft_no);
1024 /* Balance the below iput(). */
1026 BUG_ON(vi != mft_vi);
1028 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1032 * The base inode is not in icache, write this extent mft
1035 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1036 "extent record.", na.mft_no);
1039 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1041 * The base inode is in icache. Check if it has the extent inode
1042 * corresponding to this extent mft record attached.
1045 down(&ni->extent_lock);
1046 if (ni->nr_extents <= 0) {
1048 * The base inode has no attached extent inodes, write this
1049 * extent mft record.
1051 up(&ni->extent_lock);
1053 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1054 "write the extent record.", na.mft_no);
1057 /* Iterate over the attached extent inodes. */
1058 extent_nis = ni->ext.extent_ntfs_inos;
1059 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1060 if (mft_no == extent_nis[i]->mft_no) {
1062 * Found the extent inode corresponding to this extent
1065 eni = extent_nis[i];
1070 * If the extent inode was not attached to the base inode, write this
1071 * extent mft record.
1074 up(&ni->extent_lock);
1076 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1077 "inode 0x%lx, write the extent record.",
1081 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1083 /* Take a reference to the extent ntfs inode. */
1084 atomic_inc(&eni->count);
1085 up(&ni->extent_lock);
1087 * Found the extent inode coresponding to this extent mft record.
1088 * Try to take the mft record lock.
1090 if (unlikely(down_trylock(&eni->mrec_lock))) {
1091 atomic_dec(&eni->count);
1093 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1094 "not write it.", mft_no);
1097 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1099 if (NInoTestClearDirty(eni))
1100 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1103 * The write has to occur while we hold the mft record lock so return
1104 * the locked extent ntfs inode.
1110 static const char *es = " Leaving inconsistent metadata. Unmount and run "
1114 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1115 * @vol: volume on which to search for a free mft record
1116 * @base_ni: open base inode if allocating an extent mft record or NULL
1118 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1121 * If @base_ni is NULL start the search at the default allocator position.
1123 * If @base_ni is not NULL start the search at the mft record after the base
1124 * mft record @base_ni.
1126 * Return the free mft record on success and -errno on error. An error code of
1127 * -ENOSPC means that there are no free mft records in the currently
1128 * initialized mft bitmap.
1130 * Locking: Caller must hold vol->mftbmp_lock for writing.
1132 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1133 ntfs_inode *base_ni)
1135 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1136 unsigned long flags;
1137 struct address_space *mftbmp_mapping;
1140 unsigned int page_ofs, size;
1143 ntfs_debug("Searching for free mft record in the currently "
1144 "initialized mft bitmap.");
1145 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1147 * Set the end of the pass making sure we do not overflow the mft
1150 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1151 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1152 vol->mft_record_size_bits;
1153 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1154 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1155 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1156 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1161 data_pos = vol->mft_data_pos;
1163 data_pos = base_ni->mft_no + 1;
1166 if (data_pos >= pass_end) {
1169 /* This happens on a freshly formatted volume. */
1170 if (data_pos >= pass_end)
1173 pass_start = data_pos;
1174 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1175 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1176 (long long)pass_start, (long long)pass_end,
1177 (long long)data_pos);
1178 /* Loop until a free mft record is found. */
1179 for (; pass <= 2;) {
1180 /* Cap size to pass_end. */
1181 ofs = data_pos >> 3;
1182 page_ofs = ofs & ~PAGE_CACHE_MASK;
1183 size = PAGE_CACHE_SIZE - page_ofs;
1184 ll = ((pass_end + 7) >> 3) - ofs;
1189 * If we are still within the active pass, search the next page
1193 page = ntfs_map_page(mftbmp_mapping,
1194 ofs >> PAGE_CACHE_SHIFT);
1195 if (unlikely(IS_ERR(page))) {
1196 ntfs_error(vol->sb, "Failed to read mft "
1197 "bitmap, aborting.");
1198 return PTR_ERR(page);
1200 buf = (u8*)page_address(page) + page_ofs;
1203 ntfs_debug("Before inner for loop: size 0x%x, "
1204 "data_pos 0x%llx, bit 0x%llx", size,
1205 (long long)data_pos, (long long)bit);
1206 for (; bit < size && data_pos + bit < pass_end;
1207 bit &= ~7ull, bit += 8) {
1208 byte = buf + (bit >> 3);
1211 b = ffz((unsigned long)*byte);
1212 if (b < 8 && b >= (bit & 7)) {
1213 ll = data_pos + (bit & ~7ull) + b;
1214 if (unlikely(ll > (1ll << 32))) {
1215 ntfs_unmap_page(page);
1219 flush_dcache_page(page);
1220 set_page_dirty(page);
1221 ntfs_unmap_page(page);
1222 ntfs_debug("Done. (Found and "
1223 "allocated mft record "
1229 ntfs_debug("After inner for loop: size 0x%x, "
1230 "data_pos 0x%llx, bit 0x%llx", size,
1231 (long long)data_pos, (long long)bit);
1233 ntfs_unmap_page(page);
1235 * If the end of the pass has not been reached yet,
1236 * continue searching the mft bitmap for a zero bit.
1238 if (data_pos < pass_end)
1241 /* Do the next pass. */
1244 * Starting the second pass, in which we scan the first
1245 * part of the zone which we omitted earlier.
1247 pass_end = pass_start;
1248 data_pos = pass_start = 24;
1249 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1250 "0x%llx.", pass, (long long)pass_start,
1251 (long long)pass_end);
1252 if (data_pos >= pass_end)
1256 /* No free mft records in currently initialized mft bitmap. */
1257 ntfs_debug("Done. (No free mft records left in currently initialized "
1263 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1264 * @vol: volume on which to extend the mft bitmap attribute
1266 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1268 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1271 * Return 0 on success and -errno on error.
1273 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1274 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1275 * writing and releases it before returning.
1276 * - This function takes vol->lcnbmp_lock for writing and releases it
1279 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1283 unsigned long flags;
1285 ntfs_inode *mft_ni, *mftbmp_ni;
1286 runlist_element *rl, *rl2 = NULL;
1287 ntfs_attr_search_ctx *ctx = NULL;
1289 ATTR_RECORD *a = NULL;
1297 } status = { 0, 0, 0 };
1299 ntfs_debug("Extending mft bitmap allocation.");
1300 mft_ni = NTFS_I(vol->mft_ino);
1301 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1303 * Determine the last lcn of the mft bitmap. The allocated size of the
1304 * mft bitmap cannot be zero so we are ok to do this.
1306 down_write(&mftbmp_ni->runlist.lock);
1307 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1308 ll = mftbmp_ni->allocated_size;
1309 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1310 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1311 (ll - 1) >> vol->cluster_size_bits, TRUE);
1312 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1313 up_write(&mftbmp_ni->runlist.lock);
1314 ntfs_error(vol->sb, "Failed to determine last allocated "
1315 "cluster of mft bitmap attribute.");
1322 lcn = rl->lcn + rl->length;
1323 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1326 * Attempt to get the cluster following the last allocated cluster by
1327 * hand as it may be in the MFT zone so the allocator would not give it
1331 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1332 ll >> PAGE_CACHE_SHIFT);
1334 up_write(&mftbmp_ni->runlist.lock);
1335 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1336 return PTR_ERR(page);
1338 b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1339 tb = 1 << (lcn & 7ull);
1340 down_write(&vol->lcnbmp_lock);
1341 if (*b != 0xff && !(*b & tb)) {
1342 /* Next cluster is free, allocate it. */
1344 flush_dcache_page(page);
1345 set_page_dirty(page);
1346 up_write(&vol->lcnbmp_lock);
1347 ntfs_unmap_page(page);
1348 /* Update the mft bitmap runlist. */
1351 status.added_cluster = 1;
1352 ntfs_debug("Appending one cluster to mft bitmap.");
1354 up_write(&vol->lcnbmp_lock);
1355 ntfs_unmap_page(page);
1356 /* Allocate a cluster from the DATA_ZONE. */
1357 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE);
1359 up_write(&mftbmp_ni->runlist.lock);
1360 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1362 return PTR_ERR(rl2);
1364 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1366 up_write(&mftbmp_ni->runlist.lock);
1367 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1369 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1370 ntfs_error(vol->sb, "Failed to dealocate "
1371 "allocated cluster.%s", es);
1377 mftbmp_ni->runlist.rl = rl;
1378 status.added_run = 1;
1379 ntfs_debug("Adding one run to mft bitmap.");
1380 /* Find the last run in the new runlist. */
1381 for (; rl[1].length; rl++)
1385 * Update the attribute record as well. Note: @rl is the last
1386 * (non-terminator) runlist element of mft bitmap.
1388 mrec = map_mft_record(mft_ni);
1390 ntfs_error(vol->sb, "Failed to map mft record.");
1391 ret = PTR_ERR(mrec);
1394 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1395 if (unlikely(!ctx)) {
1396 ntfs_error(vol->sb, "Failed to get search context.");
1400 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1401 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1403 if (unlikely(ret)) {
1404 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1405 "mft bitmap attribute.");
1411 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1412 /* Search back for the previous last allocated cluster of mft bitmap. */
1413 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1417 BUG_ON(ll < rl2->vcn);
1418 BUG_ON(ll >= rl2->vcn + rl2->length);
1419 /* Get the size for the new mapping pairs array for this extent. */
1420 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1421 if (unlikely(mp_size <= 0)) {
1422 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1423 "mft bitmap attribute extent.");
1429 /* Expand the attribute record if necessary. */
1430 old_alen = le32_to_cpu(a->length);
1431 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1432 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1433 if (unlikely(ret)) {
1434 if (ret != -ENOSPC) {
1435 ntfs_error(vol->sb, "Failed to resize attribute "
1436 "record for mft bitmap attribute.");
1439 // TODO: Deal with this by moving this extent to a new mft
1440 // record or by starting a new extent in a new mft record or by
1441 // moving other attributes out of this mft record.
1442 // Note: It will need to be a special mft record and if none of
1443 // those are available it gets rather complicated...
1444 ntfs_error(vol->sb, "Not enough space in this mft record to "
1445 "accomodate extended mft bitmap attribute "
1446 "extent. Cannot handle this yet.");
1450 status.mp_rebuilt = 1;
1451 /* Generate the mapping pairs array directly into the attr record. */
1452 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1453 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1454 mp_size, rl2, ll, -1, NULL);
1455 if (unlikely(ret)) {
1456 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1457 "mft bitmap attribute.");
1460 /* Update the highest_vcn. */
1461 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1463 * We now have extended the mft bitmap allocated_size by one cluster.
1464 * Reflect this in the ntfs_inode structure and the attribute record.
1466 if (a->data.non_resident.lowest_vcn) {
1468 * We are not in the first attribute extent, switch to it, but
1469 * first ensure the changes will make it to disk later.
1471 flush_dcache_mft_record_page(ctx->ntfs_ino);
1472 mark_mft_record_dirty(ctx->ntfs_ino);
1473 ntfs_attr_reinit_search_ctx(ctx);
1474 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1475 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1477 if (unlikely(ret)) {
1478 ntfs_error(vol->sb, "Failed to find first attribute "
1479 "extent of mft bitmap attribute.");
1480 goto restore_undo_alloc;
1484 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1485 mftbmp_ni->allocated_size += vol->cluster_size;
1486 a->data.non_resident.allocated_size =
1487 cpu_to_sle64(mftbmp_ni->allocated_size);
1488 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1489 /* Ensure the changes make it to disk. */
1490 flush_dcache_mft_record_page(ctx->ntfs_ino);
1491 mark_mft_record_dirty(ctx->ntfs_ino);
1492 ntfs_attr_put_search_ctx(ctx);
1493 unmap_mft_record(mft_ni);
1494 up_write(&mftbmp_ni->runlist.lock);
1495 ntfs_debug("Done.");
1498 ntfs_attr_reinit_search_ctx(ctx);
1499 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1500 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1502 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1503 "mft bitmap attribute.%s", es);
1504 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1505 mftbmp_ni->allocated_size += vol->cluster_size;
1506 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1507 ntfs_attr_put_search_ctx(ctx);
1508 unmap_mft_record(mft_ni);
1509 up_write(&mftbmp_ni->runlist.lock);
1511 * The only thing that is now wrong is ->allocated_size of the
1512 * base attribute extent which chkdsk should be able to fix.
1518 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1520 if (status.added_cluster) {
1521 /* Truncate the last run in the runlist by one cluster. */
1524 } else if (status.added_run) {
1526 /* Remove the last run from the runlist. */
1527 rl->lcn = rl[1].lcn;
1530 /* Deallocate the cluster. */
1531 down_write(&vol->lcnbmp_lock);
1532 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1533 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1536 up_write(&vol->lcnbmp_lock);
1537 if (status.mp_rebuilt) {
1538 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1539 a->data.non_resident.mapping_pairs_offset),
1540 old_alen - le16_to_cpu(
1541 a->data.non_resident.mapping_pairs_offset),
1542 rl2, ll, -1, NULL)) {
1543 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1547 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1548 ntfs_error(vol->sb, "Failed to restore attribute "
1552 flush_dcache_mft_record_page(ctx->ntfs_ino);
1553 mark_mft_record_dirty(ctx->ntfs_ino);
1556 ntfs_attr_put_search_ctx(ctx);
1558 unmap_mft_record(mft_ni);
1559 up_write(&mftbmp_ni->runlist.lock);
1564 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1565 * @vol: volume on which to extend the mft bitmap attribute
1567 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1568 * volume @vol by 8 bytes.
1570 * Note: Only changes initialized_size and data_size, i.e. requires that
1571 * allocated_size is big enough to fit the new initialized_size.
1573 * Return 0 on success and -error on error.
1575 * Locking: Caller must hold vol->mftbmp_lock for writing.
1577 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1579 s64 old_data_size, old_initialized_size;
1580 unsigned long flags;
1581 struct inode *mftbmp_vi;
1582 ntfs_inode *mft_ni, *mftbmp_ni;
1583 ntfs_attr_search_ctx *ctx;
1588 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1589 mft_ni = NTFS_I(vol->mft_ino);
1590 mftbmp_vi = vol->mftbmp_ino;
1591 mftbmp_ni = NTFS_I(mftbmp_vi);
1592 /* Get the attribute record. */
1593 mrec = map_mft_record(mft_ni);
1595 ntfs_error(vol->sb, "Failed to map mft record.");
1596 return PTR_ERR(mrec);
1598 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1599 if (unlikely(!ctx)) {
1600 ntfs_error(vol->sb, "Failed to get search context.");
1604 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1605 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1606 if (unlikely(ret)) {
1607 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1608 "mft bitmap attribute.");
1614 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1615 old_data_size = i_size_read(mftbmp_vi);
1616 old_initialized_size = mftbmp_ni->initialized_size;
1618 * We can simply update the initialized_size before filling the space
1619 * with zeroes because the caller is holding the mft bitmap lock for
1620 * writing which ensures that no one else is trying to access the data.
1622 mftbmp_ni->initialized_size += 8;
1623 a->data.non_resident.initialized_size =
1624 cpu_to_sle64(mftbmp_ni->initialized_size);
1625 if (mftbmp_ni->initialized_size > old_data_size) {
1626 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1627 a->data.non_resident.data_size =
1628 cpu_to_sle64(mftbmp_ni->initialized_size);
1630 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1631 /* Ensure the changes make it to disk. */
1632 flush_dcache_mft_record_page(ctx->ntfs_ino);
1633 mark_mft_record_dirty(ctx->ntfs_ino);
1634 ntfs_attr_put_search_ctx(ctx);
1635 unmap_mft_record(mft_ni);
1636 /* Initialize the mft bitmap attribute value with zeroes. */
1637 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1639 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1643 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1644 /* Try to recover from the error. */
1645 mrec = map_mft_record(mft_ni);
1647 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1651 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1652 if (unlikely(!ctx)) {
1653 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1657 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1658 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1659 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1660 "mft bitmap attribute.%s", es);
1663 ntfs_attr_put_search_ctx(ctx);
1665 unmap_mft_record(mft_ni);
1669 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1670 mftbmp_ni->initialized_size = old_initialized_size;
1671 a->data.non_resident.initialized_size =
1672 cpu_to_sle64(old_initialized_size);
1673 if (i_size_read(mftbmp_vi) != old_data_size) {
1674 i_size_write(mftbmp_vi, old_data_size);
1675 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1677 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1678 flush_dcache_mft_record_page(ctx->ntfs_ino);
1679 mark_mft_record_dirty(ctx->ntfs_ino);
1680 ntfs_attr_put_search_ctx(ctx);
1681 unmap_mft_record(mft_ni);
1683 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1684 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1685 "data_size 0x%llx, initialized_size 0x%llx.",
1686 (long long)mftbmp_ni->allocated_size,
1687 (long long)i_size_read(mftbmp_vi),
1688 (long long)mftbmp_ni->initialized_size);
1689 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1696 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1697 * @vol: volume on which to extend the mft data attribute
1699 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1700 * worth of clusters or if not enough space for this by one mft record worth
1703 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1706 * Return 0 on success and -errno on error.
1708 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1709 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1710 * writing and releases it before returning.
1711 * - This function calls functions which take vol->lcnbmp_lock for
1712 * writing and release it before returning.
1714 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1719 unsigned long flags;
1721 runlist_element *rl, *rl2;
1722 ntfs_attr_search_ctx *ctx = NULL;
1724 ATTR_RECORD *a = NULL;
1727 BOOL mp_rebuilt = FALSE;
1729 ntfs_debug("Extending mft data allocation.");
1730 mft_ni = NTFS_I(vol->mft_ino);
1732 * Determine the preferred allocation location, i.e. the last lcn of
1733 * the mft data attribute. The allocated size of the mft data
1734 * attribute cannot be zero so we are ok to do this.
1736 down_write(&mft_ni->runlist.lock);
1737 read_lock_irqsave(&mft_ni->size_lock, flags);
1738 ll = mft_ni->allocated_size;
1739 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1740 rl = ntfs_attr_find_vcn_nolock(mft_ni,
1741 (ll - 1) >> vol->cluster_size_bits, TRUE);
1742 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1743 up_write(&mft_ni->runlist.lock);
1744 ntfs_error(vol->sb, "Failed to determine last allocated "
1745 "cluster of mft data attribute.");
1752 lcn = rl->lcn + rl->length;
1753 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1754 /* Minimum allocation is one mft record worth of clusters. */
1755 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1758 /* Want to allocate 16 mft records worth of clusters. */
1759 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1762 /* Ensure we do not go above 2^32-1 mft records. */
1763 read_lock_irqsave(&mft_ni->size_lock, flags);
1764 ll = mft_ni->allocated_size;
1765 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1766 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1767 vol->mft_record_size_bits >= (1ll << 32))) {
1769 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1770 vol->mft_record_size_bits >= (1ll << 32))) {
1771 ntfs_warning(vol->sb, "Cannot allocate mft record "
1772 "because the maximum number of inodes "
1773 "(2^32) has already been reached.");
1774 up_write(&mft_ni->runlist.lock);
1778 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1779 nr > min_nr ? "default" : "minimal", (long long)nr);
1780 old_last_vcn = rl[1].vcn;
1782 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1783 if (likely(!IS_ERR(rl2)))
1785 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1786 ntfs_error(vol->sb, "Failed to allocate the minimal "
1787 "number of clusters (%lli) for the "
1788 "mft data attribute.", (long long)nr);
1789 up_write(&mft_ni->runlist.lock);
1790 return PTR_ERR(rl2);
1793 * There is not enough space to do the allocation, but there
1794 * might be enough space to do a minimal allocation so try that
1798 ntfs_debug("Retrying mft data allocation with minimal cluster "
1799 "count %lli.", (long long)nr);
1801 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1803 up_write(&mft_ni->runlist.lock);
1804 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1806 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1807 ntfs_error(vol->sb, "Failed to dealocate clusters "
1808 "from the mft data attribute.%s", es);
1814 mft_ni->runlist.rl = rl;
1815 ntfs_debug("Allocated %lli clusters.", (long long)nr);
1816 /* Find the last run in the new runlist. */
1817 for (; rl[1].length; rl++)
1819 /* Update the attribute record as well. */
1820 mrec = map_mft_record(mft_ni);
1822 ntfs_error(vol->sb, "Failed to map mft record.");
1823 ret = PTR_ERR(mrec);
1826 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1827 if (unlikely(!ctx)) {
1828 ntfs_error(vol->sb, "Failed to get search context.");
1832 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1833 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1834 if (unlikely(ret)) {
1835 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1836 "mft data attribute.");
1842 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1843 /* Search back for the previous last allocated cluster of mft bitmap. */
1844 for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1848 BUG_ON(ll < rl2->vcn);
1849 BUG_ON(ll >= rl2->vcn + rl2->length);
1850 /* Get the size for the new mapping pairs array for this extent. */
1851 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1852 if (unlikely(mp_size <= 0)) {
1853 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1854 "mft data attribute extent.");
1860 /* Expand the attribute record if necessary. */
1861 old_alen = le32_to_cpu(a->length);
1862 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1863 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1864 if (unlikely(ret)) {
1865 if (ret != -ENOSPC) {
1866 ntfs_error(vol->sb, "Failed to resize attribute "
1867 "record for mft data attribute.");
1870 // TODO: Deal with this by moving this extent to a new mft
1871 // record or by starting a new extent in a new mft record or by
1872 // moving other attributes out of this mft record.
1873 // Note: Use the special reserved mft records and ensure that
1874 // this extent is not required to find the mft record in
1875 // question. If no free special records left we would need to
1876 // move an existing record away, insert ours in its place, and
1877 // then place the moved record into the newly allocated space
1878 // and we would then need to update all references to this mft
1879 // record appropriately. This is rather complicated...
1880 ntfs_error(vol->sb, "Not enough space in this mft record to "
1881 "accomodate extended mft data attribute "
1882 "extent. Cannot handle this yet.");
1887 /* Generate the mapping pairs array directly into the attr record. */
1888 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1889 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1890 mp_size, rl2, ll, -1, NULL);
1891 if (unlikely(ret)) {
1892 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1893 "mft data attribute.");
1896 /* Update the highest_vcn. */
1897 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1899 * We now have extended the mft data allocated_size by nr clusters.
1900 * Reflect this in the ntfs_inode structure and the attribute record.
1901 * @rl is the last (non-terminator) runlist element of mft data
1904 if (a->data.non_resident.lowest_vcn) {
1906 * We are not in the first attribute extent, switch to it, but
1907 * first ensure the changes will make it to disk later.
1909 flush_dcache_mft_record_page(ctx->ntfs_ino);
1910 mark_mft_record_dirty(ctx->ntfs_ino);
1911 ntfs_attr_reinit_search_ctx(ctx);
1912 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1913 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1915 if (unlikely(ret)) {
1916 ntfs_error(vol->sb, "Failed to find first attribute "
1917 "extent of mft data attribute.");
1918 goto restore_undo_alloc;
1922 write_lock_irqsave(&mft_ni->size_lock, flags);
1923 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1924 a->data.non_resident.allocated_size =
1925 cpu_to_sle64(mft_ni->allocated_size);
1926 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1927 /* Ensure the changes make it to disk. */
1928 flush_dcache_mft_record_page(ctx->ntfs_ino);
1929 mark_mft_record_dirty(ctx->ntfs_ino);
1930 ntfs_attr_put_search_ctx(ctx);
1931 unmap_mft_record(mft_ni);
1932 up_write(&mft_ni->runlist.lock);
1933 ntfs_debug("Done.");
1936 ntfs_attr_reinit_search_ctx(ctx);
1937 if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1938 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1939 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1940 "mft data attribute.%s", es);
1941 write_lock_irqsave(&mft_ni->size_lock, flags);
1942 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1943 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1944 ntfs_attr_put_search_ctx(ctx);
1945 unmap_mft_record(mft_ni);
1946 up_write(&mft_ni->runlist.lock);
1948 * The only thing that is now wrong is ->allocated_size of the
1949 * base attribute extent which chkdsk should be able to fix.
1955 a->data.non_resident.highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1957 if (ntfs_cluster_free(mft_ni, old_last_vcn, -1) < 0) {
1958 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1959 "attribute.%s", es);
1962 if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1963 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1968 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1969 a->data.non_resident.mapping_pairs_offset),
1970 old_alen - le16_to_cpu(
1971 a->data.non_resident.mapping_pairs_offset),
1972 rl2, ll, -1, NULL)) {
1973 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1977 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1978 ntfs_error(vol->sb, "Failed to restore attribute "
1982 flush_dcache_mft_record_page(ctx->ntfs_ino);
1983 mark_mft_record_dirty(ctx->ntfs_ino);
1986 ntfs_attr_put_search_ctx(ctx);
1988 unmap_mft_record(mft_ni);
1989 up_write(&mft_ni->runlist.lock);
1994 * ntfs_mft_record_layout - layout an mft record into a memory buffer
1995 * @vol: volume to which the mft record will belong
1996 * @mft_no: mft reference specifying the mft record number
1997 * @m: destination buffer of size >= @vol->mft_record_size bytes
1999 * Layout an empty, unused mft record with the mft record number @mft_no into
2000 * the buffer @m. The volume @vol is needed because the mft record structure
2001 * was modified in NTFS 3.1 so we need to know which volume version this mft
2002 * record will be used on.
2004 * Return 0 on success and -errno on error.
2006 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2011 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2012 if (mft_no >= (1ll << 32)) {
2013 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2014 "maximum of 2^32.", (long long)mft_no);
2017 /* Start by clearing the whole mft record to gives us a clean slate. */
2018 memset(m, 0, vol->mft_record_size);
2019 /* Aligned to 2-byte boundary. */
2020 if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2021 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2023 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2025 * Set the NTFS 3.1+ specific fields while we know that the
2026 * volume version is 3.1+.
2029 m->mft_record_number = cpu_to_le32((u32)mft_no);
2031 m->magic = magic_FILE;
2032 if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2033 m->usa_count = cpu_to_le16(vol->mft_record_size /
2034 NTFS_BLOCK_SIZE + 1);
2036 m->usa_count = cpu_to_le16(1);
2037 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2038 "size. Setting usa_count to 1. If chkdsk "
2039 "reports this as corruption, please email "
2040 "linux-ntfs-dev@lists.sourceforge.net stating "
2041 "that you saw this message and that the "
2042 "modified filesystem created was corrupt. "
2045 /* Set the update sequence number to 1. */
2046 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2048 m->sequence_number = cpu_to_le16(1);
2051 * Place the attributes straight after the update sequence array,
2052 * aligned to 8-byte boundary.
2054 m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2055 (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2058 * Using attrs_offset plus eight bytes (for the termination attribute).
2059 * attrs_offset is already aligned to 8-byte boundary, so no need to
2062 m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2063 m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2064 m->base_mft_record = 0;
2065 m->next_attr_instance = 0;
2066 /* Add the termination attribute. */
2067 a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2070 ntfs_debug("Done.");
2075 * ntfs_mft_record_format - format an mft record on an ntfs volume
2076 * @vol: volume on which to format the mft record
2077 * @mft_no: mft record number to format
2079 * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2080 * mft record into the appropriate place of the mft data attribute. This is
2081 * used when extending the mft data attribute.
2083 * Return 0 on success and -errno on error.
2085 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2088 struct inode *mft_vi = vol->mft_ino;
2091 pgoff_t index, end_index;
2095 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2097 * The index into the page cache and the offset within the page cache
2098 * page of the wanted mft record.
2100 index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2101 ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2102 /* The maximum valid index into the page cache for $MFT's data. */
2103 i_size = i_size_read(mft_vi);
2104 end_index = i_size >> PAGE_CACHE_SHIFT;
2105 if (unlikely(index >= end_index)) {
2106 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2107 (i_size & ~PAGE_CACHE_MASK))) {
2108 ntfs_error(vol->sb, "Tried to format non-existing mft "
2109 "record 0x%llx.", (long long)mft_no);
2113 /* Read, map, and pin the page containing the mft record. */
2114 page = ntfs_map_page(mft_vi->i_mapping, index);
2115 if (unlikely(IS_ERR(page))) {
2116 ntfs_error(vol->sb, "Failed to map page containing mft record "
2117 "to format 0x%llx.", (long long)mft_no);
2118 return PTR_ERR(page);
2121 BUG_ON(!PageUptodate(page));
2122 ClearPageUptodate(page);
2123 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2124 err = ntfs_mft_record_layout(vol, mft_no, m);
2125 if (unlikely(err)) {
2126 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2128 SetPageUptodate(page);
2130 ntfs_unmap_page(page);
2133 flush_dcache_page(page);
2134 SetPageUptodate(page);
2137 * Make sure the mft record is written out to disk. We could use
2138 * ilookup5() to check if an inode is in icache and so on but this is
2139 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2141 mark_ntfs_record_dirty(page, ofs);
2142 ntfs_unmap_page(page);
2143 ntfs_debug("Done.");
2148 * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2149 * @vol: [IN] volume on which to allocate the mft record
2150 * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
2151 * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
2152 * @mrec: [OUT] on successful return this is the mapped mft record
2154 * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2156 * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2157 * direvctory inode, and allocate it at the default allocator position. In
2158 * this case @mode is the file mode as given to us by the caller. We in
2159 * particular use @mode to distinguish whether a file or a directory is being
2160 * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2162 * If @base_ni is not NULL make the allocated mft record an extent record,
2163 * allocate it starting at the mft record after the base mft record and attach
2164 * the allocated and opened ntfs inode to the base inode @base_ni. In this
2165 * case @mode must be 0 as it is meaningless for extent inodes.
2167 * You need to check the return value with IS_ERR(). If false, the function
2168 * was successful and the return value is the now opened ntfs inode of the
2169 * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
2170 * and locked mft record. If IS_ERR() is true, the function failed and the
2171 * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
2174 * Allocation strategy:
2176 * To find a free mft record, we scan the mft bitmap for a zero bit. To
2177 * optimize this we start scanning at the place specified by @base_ni or if
2178 * @base_ni is NULL we start where we last stopped and we perform wrap around
2179 * when we reach the end. Note, we do not try to allocate mft records below
2180 * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2181 * to 24 are special in that they are used for storing extension mft records
2182 * for the $DATA attribute of $MFT. This is required to avoid the possibility
2183 * of creating a runlist with a circular dependency which once written to disk
2184 * can never be read in again. Windows will only use records 16 to 24 for
2185 * normal files if the volume is completely out of space. We never use them
2186 * which means that when the volume is really out of space we cannot create any
2187 * more files while Windows can still create up to 8 small files. We can start
2188 * doing this at some later time, it does not matter much for now.
2190 * When scanning the mft bitmap, we only search up to the last allocated mft
2191 * record. If there are no free records left in the range 24 to number of
2192 * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2193 * create free mft records. We extend the allocated size of $MFT/$DATA by 16
2194 * records at a time or one cluster, if cluster size is above 16kiB. If there
2195 * is not sufficient space to do this, we try to extend by a single mft record
2196 * or one cluster, if cluster size is above the mft record size.
2198 * No matter how many mft records we allocate, we initialize only the first
2199 * allocated mft record, incrementing mft data size and initialized size
2200 * accordingly, open an ntfs_inode for it and return it to the caller, unless
2201 * there are less than 24 mft records, in which case we allocate and initialize
2202 * mft records until we reach record 24 which we consider as the first free mft
2203 * record for use by normal files.
2205 * If during any stage we overflow the initialized data in the mft bitmap, we
2206 * extend the initialized size (and data size) by 8 bytes, allocating another
2207 * cluster if required. The bitmap data size has to be at least equal to the
2208 * number of mft records in the mft, but it can be bigger, in which case the
2209 * superflous bits are padded with zeroes.
2211 * Thus, when we return successfully (IS_ERR() is false), we will have:
2212 * - initialized / extended the mft bitmap if necessary,
2213 * - initialized / extended the mft data if necessary,
2214 * - set the bit corresponding to the mft record being allocated in the
2216 * - opened an ntfs_inode for the allocated mft record, and we will have
2217 * - returned the ntfs_inode as well as the allocated mapped, pinned, and
2218 * locked mft record.
2220 * On error, the volume will be left in a consistent state and no record will
2221 * be allocated. If rolling back a partial operation fails, we may leave some
2222 * inconsistent metadata in which case we set NVolErrors() so the volume is
2223 * left dirty when unmounted.
2225 * Note, this function cannot make use of most of the normal functions, like
2226 * for example for attribute resizing, etc, because when the run list overflows
2227 * the base mft record and an attribute list is used, it is very important that
2228 * the extension mft records used to store the $DATA attribute of $MFT can be
2229 * reached without having to read the information contained inside them, as
2230 * this would make it impossible to find them in the first place after the
2231 * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
2232 * rule because the bitmap is not essential for finding the mft records, but on
2233 * the other hand, handling the bitmap in this special way would make life
2234 * easier because otherwise there might be circular invocations of functions
2235 * when reading the bitmap.
2237 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2238 ntfs_inode *base_ni, MFT_RECORD **mrec)
2240 s64 ll, bit, old_data_initialized, old_data_size;
2241 unsigned long flags;
2244 ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2245 ntfs_attr_search_ctx *ctx;
2252 BOOL record_formatted = FALSE;
2255 ntfs_debug("Entering (allocating an extent mft record for "
2256 "base mft record 0x%llx).",
2257 (long long)base_ni->mft_no);
2258 /* @mode and @base_ni are mutually exclusive. */
2261 ntfs_debug("Entering (allocating a base mft record).");
2263 /* @mode and @base_ni are mutually exclusive. */
2265 /* We only support creation of normal files and directories. */
2266 if (!S_ISREG(mode) && !S_ISDIR(mode))
2267 return ERR_PTR(-EOPNOTSUPP);
2270 mft_ni = NTFS_I(vol->mft_ino);
2271 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2272 down_write(&vol->mftbmp_lock);
2273 bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2275 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2277 goto have_alloc_rec;
2279 if (bit != -ENOSPC) {
2280 up_write(&vol->mftbmp_lock);
2281 return ERR_PTR(bit);
2284 * No free mft records left. If the mft bitmap already covers more
2285 * than the currently used mft records, the next records are all free,
2286 * so we can simply allocate the first unused mft record.
2287 * Note: We also have to make sure that the mft bitmap at least covers
2288 * the first 24 mft records as they are special and whilst they may not
2289 * be in use, we do not allocate from them.
2291 read_lock_irqsave(&mft_ni->size_lock, flags);
2292 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2293 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2294 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2295 old_data_initialized = mftbmp_ni->initialized_size;
2296 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2297 if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2301 if (unlikely(bit >= (1ll << 32)))
2303 ntfs_debug("Found free record (#2), bit 0x%llx.",
2305 goto found_free_rec;
2308 * The mft bitmap needs to be expanded until it covers the first unused
2309 * mft record that we can allocate.
2310 * Note: The smallest mft record we allocate is mft record 24.
2312 bit = old_data_initialized << 3;
2313 if (unlikely(bit >= (1ll << 32)))
2315 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2316 old_data_size = mftbmp_ni->allocated_size;
2317 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2318 "data_size 0x%llx, initialized_size 0x%llx.",
2319 (long long)old_data_size,
2320 (long long)i_size_read(vol->mftbmp_ino),
2321 (long long)old_data_initialized);
2322 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2323 if (old_data_initialized + 8 > old_data_size) {
2324 /* Need to extend bitmap by one more cluster. */
2325 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2326 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2327 if (unlikely(err)) {
2328 up_write(&vol->mftbmp_lock);
2332 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2333 ntfs_debug("Status of mftbmp after allocation extension: "
2334 "allocated_size 0x%llx, data_size 0x%llx, "
2335 "initialized_size 0x%llx.",
2336 (long long)mftbmp_ni->allocated_size,
2337 (long long)i_size_read(vol->mftbmp_ino),
2338 (long long)mftbmp_ni->initialized_size);
2339 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2343 * We now have sufficient allocated space, extend the initialized_size
2344 * as well as the data_size if necessary and fill the new space with
2347 err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2348 if (unlikely(err)) {
2349 up_write(&vol->mftbmp_lock);
2353 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2354 ntfs_debug("Status of mftbmp after initialized extention: "
2355 "allocated_size 0x%llx, data_size 0x%llx, "
2356 "initialized_size 0x%llx.",
2357 (long long)mftbmp_ni->allocated_size,
2358 (long long)i_size_read(vol->mftbmp_ino),
2359 (long long)mftbmp_ni->initialized_size);
2360 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2362 ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2364 /* @bit is the found free mft record, allocate it in the mft bitmap. */
2365 ntfs_debug("At found_free_rec.");
2366 err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2367 if (unlikely(err)) {
2368 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2369 up_write(&vol->mftbmp_lock);
2372 ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2375 * The mft bitmap is now uptodate. Deal with mft data attribute now.
2376 * Note, we keep hold of the mft bitmap lock for writing until all
2377 * modifications to the mft data attribute are complete, too, as they
2378 * will impact decisions for mft bitmap and mft record allocation done
2379 * by a parallel allocation and if the lock is not maintained a
2380 * parallel allocation could allocate the same mft record as this one.
2382 ll = (bit + 1) << vol->mft_record_size_bits;
2383 read_lock_irqsave(&mft_ni->size_lock, flags);
2384 old_data_initialized = mft_ni->initialized_size;
2385 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2386 if (ll <= old_data_initialized) {
2387 ntfs_debug("Allocated mft record already initialized.");
2388 goto mft_rec_already_initialized;
2390 ntfs_debug("Initializing allocated mft record.");
2392 * The mft record is outside the initialized data. Extend the mft data
2393 * attribute until it covers the allocated record. The loop is only
2394 * actually traversed more than once when a freshly formatted volume is
2395 * first written to so it optimizes away nicely in the common case.
2397 read_lock_irqsave(&mft_ni->size_lock, flags);
2398 ntfs_debug("Status of mft data before extension: "
2399 "allocated_size 0x%llx, data_size 0x%llx, "
2400 "initialized_size 0x%llx.",
2401 (long long)mft_ni->allocated_size,
2402 (long long)i_size_read(vol->mft_ino),
2403 (long long)mft_ni->initialized_size);
2404 while (ll > mft_ni->allocated_size) {
2405 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2406 err = ntfs_mft_data_extend_allocation_nolock(vol);
2407 if (unlikely(err)) {
2408 ntfs_error(vol->sb, "Failed to extend mft data "
2410 goto undo_mftbmp_alloc_nolock;
2412 read_lock_irqsave(&mft_ni->size_lock, flags);
2413 ntfs_debug("Status of mft data after allocation extension: "
2414 "allocated_size 0x%llx, data_size 0x%llx, "
2415 "initialized_size 0x%llx.",
2416 (long long)mft_ni->allocated_size,
2417 (long long)i_size_read(vol->mft_ino),
2418 (long long)mft_ni->initialized_size);
2420 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2422 * Extend mft data initialized size (and data size of course) to reach
2423 * the allocated mft record, formatting the mft records allong the way.
2424 * Note: We only modify the ntfs_inode structure as that is all that is
2425 * needed by ntfs_mft_record_format(). We will update the attribute
2426 * record itself in one fell swoop later on.
2428 write_lock_irqsave(&mft_ni->size_lock, flags);
2429 old_data_initialized = mft_ni->initialized_size;
2430 old_data_size = vol->mft_ino->i_size;
2431 while (ll > mft_ni->initialized_size) {
2432 s64 new_initialized_size, mft_no;
2434 new_initialized_size = mft_ni->initialized_size +
2435 vol->mft_record_size;
2436 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2437 if (new_initialized_size > i_size_read(vol->mft_ino))
2438 i_size_write(vol->mft_ino, new_initialized_size);
2439 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2440 ntfs_debug("Initializing mft record 0x%llx.",
2442 err = ntfs_mft_record_format(vol, mft_no);
2443 if (unlikely(err)) {
2444 ntfs_error(vol->sb, "Failed to format mft record.");
2445 goto undo_data_init;
2447 write_lock_irqsave(&mft_ni->size_lock, flags);
2448 mft_ni->initialized_size = new_initialized_size;
2450 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2451 record_formatted = TRUE;
2452 /* Update the mft data attribute record to reflect the new sizes. */
2453 m = map_mft_record(mft_ni);
2455 ntfs_error(vol->sb, "Failed to map mft record.");
2457 goto undo_data_init;
2459 ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2460 if (unlikely(!ctx)) {
2461 ntfs_error(vol->sb, "Failed to get search context.");
2463 unmap_mft_record(mft_ni);
2464 goto undo_data_init;
2466 err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2467 CASE_SENSITIVE, 0, NULL, 0, ctx);
2468 if (unlikely(err)) {
2469 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2470 "mft data attribute.");
2471 ntfs_attr_put_search_ctx(ctx);
2472 unmap_mft_record(mft_ni);
2473 goto undo_data_init;
2476 read_lock_irqsave(&mft_ni->size_lock, flags);
2477 a->data.non_resident.initialized_size =
2478 cpu_to_sle64(mft_ni->initialized_size);
2479 a->data.non_resident.data_size =
2480 cpu_to_sle64(i_size_read(vol->mft_ino));
2481 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2482 /* Ensure the changes make it to disk. */
2483 flush_dcache_mft_record_page(ctx->ntfs_ino);
2484 mark_mft_record_dirty(ctx->ntfs_ino);
2485 ntfs_attr_put_search_ctx(ctx);
2486 unmap_mft_record(mft_ni);
2487 read_lock_irqsave(&mft_ni->size_lock, flags);
2488 ntfs_debug("Status of mft data after mft record initialization: "
2489 "allocated_size 0x%llx, data_size 0x%llx, "
2490 "initialized_size 0x%llx.",
2491 (long long)mft_ni->allocated_size,
2492 (long long)i_size_read(vol->mft_ino),
2493 (long long)mft_ni->initialized_size);
2494 BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2495 BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2496 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2497 mft_rec_already_initialized:
2499 * We can finally drop the mft bitmap lock as the mft data attribute
2500 * has been fully updated. The only disparity left is that the
2501 * allocated mft record still needs to be marked as in use to match the
2502 * set bit in the mft bitmap but this is actually not a problem since
2503 * this mft record is not referenced from anywhere yet and the fact
2504 * that it is allocated in the mft bitmap means that no-one will try to
2505 * allocate it either.
2507 up_write(&vol->mftbmp_lock);
2509 * We now have allocated and initialized the mft record. Calculate the
2510 * index of and the offset within the page cache page the record is in.
2512 index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2513 ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2514 /* Read, map, and pin the page containing the mft record. */
2515 page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2516 if (unlikely(IS_ERR(page))) {
2517 ntfs_error(vol->sb, "Failed to map page containing allocated "
2518 "mft record 0x%llx.", (long long)bit);
2519 err = PTR_ERR(page);
2520 goto undo_mftbmp_alloc;
2523 BUG_ON(!PageUptodate(page));
2524 ClearPageUptodate(page);
2525 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2526 /* If we just formatted the mft record no need to do it again. */
2527 if (!record_formatted) {
2528 /* Sanity check that the mft record is really not in use. */
2529 if (ntfs_is_file_record(m->magic) &&
2530 (m->flags & MFT_RECORD_IN_USE)) {
2531 ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2532 "free in mft bitmap but is marked "
2533 "used itself. Corrupt filesystem. "
2534 "Unmount and run chkdsk.",
2537 SetPageUptodate(page);
2539 ntfs_unmap_page(page);
2541 goto undo_mftbmp_alloc;
2544 * We need to (re-)format the mft record, preserving the
2545 * sequence number if it is not zero as well as the update
2546 * sequence number if it is not zero or -1 (0xffff). This
2547 * means we do not need to care whether or not something went
2548 * wrong with the previous mft record.
2550 seq_no = m->sequence_number;
2551 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2552 err = ntfs_mft_record_layout(vol, bit, m);
2553 if (unlikely(err)) {
2554 ntfs_error(vol->sb, "Failed to layout allocated mft "
2555 "record 0x%llx.", (long long)bit);
2556 SetPageUptodate(page);
2558 ntfs_unmap_page(page);
2559 goto undo_mftbmp_alloc;
2562 m->sequence_number = seq_no;
2563 if (usn && le16_to_cpu(usn) != 0xffff)
2564 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2566 /* Set the mft record itself in use. */
2567 m->flags |= MFT_RECORD_IN_USE;
2569 m->flags |= MFT_RECORD_IS_DIRECTORY;
2570 flush_dcache_page(page);
2571 SetPageUptodate(page);
2574 * Setup the base mft record in the extent mft record. This
2575 * completes initialization of the allocated extent mft record
2576 * and we can simply use it with map_extent_mft_record().
2578 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2581 * Allocate an extent inode structure for the new mft record,
2582 * attach it to the base inode @base_ni and map, pin, and lock
2583 * its, i.e. the allocated, mft record.
2585 m = map_extent_mft_record(base_ni, bit, &ni);
2587 ntfs_error(vol->sb, "Failed to map allocated extent "
2588 "mft record 0x%llx.", (long long)bit);
2590 /* Set the mft record itself not in use. */
2591 m->flags &= cpu_to_le16(
2592 ~le16_to_cpu(MFT_RECORD_IN_USE));
2593 flush_dcache_page(page);
2594 /* Make sure the mft record is written out to disk. */
2595 mark_ntfs_record_dirty(page, ofs);
2597 ntfs_unmap_page(page);
2598 goto undo_mftbmp_alloc;
2601 * Make sure the allocated mft record is written out to disk.
2602 * No need to set the inode dirty because the caller is going
2603 * to do that anyway after finishing with the new extent mft
2604 * record (e.g. at a minimum a new attribute will be added to
2607 mark_ntfs_record_dirty(page, ofs);
2610 * Need to unmap the page since map_extent_mft_record() mapped
2611 * it as well so we have it mapped twice at the moment.
2613 ntfs_unmap_page(page);
2616 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2617 * is set to 1 but the mft record->link_count is 0. The caller
2618 * needs to bear this in mind.
2620 vi = new_inode(vol->sb);
2621 if (unlikely(!vi)) {
2623 /* Set the mft record itself not in use. */
2624 m->flags &= cpu_to_le16(
2625 ~le16_to_cpu(MFT_RECORD_IN_USE));
2626 flush_dcache_page(page);
2627 /* Make sure the mft record is written out to disk. */
2628 mark_ntfs_record_dirty(page, ofs);
2630 ntfs_unmap_page(page);
2631 goto undo_mftbmp_alloc;
2635 * This is the optimal IO size (for stat), not the fs block
2638 vi->i_blksize = PAGE_CACHE_SIZE;
2640 * This is for checking whether an inode has changed w.r.t. a
2641 * file so that the file can be updated if necessary (compare
2646 /* The owner and group come from the ntfs volume. */
2647 vi->i_uid = vol->uid;
2648 vi->i_gid = vol->gid;
2650 /* Initialize the ntfs specific part of @vi. */
2651 ntfs_init_big_inode(vi);
2654 * Set the appropriate mode, attribute type, and name. For
2655 * directories, also setup the index values to the defaults.
2657 if (S_ISDIR(mode)) {
2658 vi->i_mode = S_IFDIR | S_IRWXUGO;
2659 vi->i_mode &= ~vol->dmask;
2661 NInoSetMstProtected(ni);
2662 ni->type = AT_INDEX_ALLOCATION;
2666 ni->itype.index.block_size = 4096;
2667 ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2668 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2669 if (vol->cluster_size <= ni->itype.index.block_size) {
2670 ni->itype.index.vcn_size = vol->cluster_size;
2671 ni->itype.index.vcn_size_bits =
2672 vol->cluster_size_bits;
2674 ni->itype.index.vcn_size = vol->sector_size;
2675 ni->itype.index.vcn_size_bits =
2676 vol->sector_size_bits;
2679 vi->i_mode = S_IFREG | S_IRWXUGO;
2680 vi->i_mode &= ~vol->fmask;
2687 vi->i_mode &= ~S_IWUGO;
2689 /* Set the inode times to the current time. */
2690 vi->i_atime = vi->i_mtime = vi->i_ctime =
2691 current_fs_time(vi->i_sb);
2693 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2694 * the call to ntfs_init_big_inode() below.
2699 /* Set the sequence number. */
2700 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2702 * Manually map, pin, and lock the mft record as we already
2703 * have its page mapped and it is very easy to do.
2705 atomic_inc(&ni->count);
2706 down(&ni->mrec_lock);
2710 * Make sure the allocated mft record is written out to disk.
2711 * NOTE: We do not set the ntfs inode dirty because this would
2712 * fail in ntfs_write_inode() because the inode does not have a
2713 * standard information attribute yet. Also, there is no need
2714 * to set the inode dirty because the caller is going to do
2715 * that anyway after finishing with the new mft record (e.g. at
2716 * a minimum some new attributes will be added to the mft
2719 mark_ntfs_record_dirty(page, ofs);
2722 /* Add the inode to the inode hash for the superblock. */
2723 insert_inode_hash(vi);
2725 /* Update the default mft allocation position. */
2726 vol->mft_data_pos = bit + 1;
2729 * Return the opened, allocated inode of the allocated mft record as
2730 * well as the mapped, pinned, and locked mft record.
2732 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2733 base_ni ? "extent " : "", (long long)bit);
2737 write_lock_irqsave(&mft_ni->size_lock, flags);
2738 mft_ni->initialized_size = old_data_initialized;
2739 i_size_write(vol->mft_ino, old_data_size);
2740 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2741 goto undo_mftbmp_alloc_nolock;
2743 down_write(&vol->mftbmp_lock);
2744 undo_mftbmp_alloc_nolock:
2745 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2746 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2749 up_write(&vol->mftbmp_lock);
2751 return ERR_PTR(err);
2753 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2754 "number of inodes (2^32) has already been reached.");
2755 up_write(&vol->mftbmp_lock);
2756 return ERR_PTR(-ENOSPC);
2760 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2761 * @ni: ntfs inode of the mapped extent mft record to free
2762 * @m: mapped extent mft record of the ntfs inode @ni
2764 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2766 * Note that this function unmaps the mft record and closes and destroys @ni
2767 * internally and hence you cannot use either @ni nor @m any more after this
2768 * function returns success.
2770 * On success return 0 and on error return -errno. @ni and @m are still valid
2771 * in this case and have not been freed.
2773 * For some errors an error message is displayed and the success code 0 is
2774 * returned and the volume is then left dirty on umount. This makes sense in
2775 * case we could not rollback the changes that were already done since the
2776 * caller no longer wants to reference this mft record so it does not matter to
2777 * the caller if something is wrong with it as long as it is properly detached
2778 * from the base inode.
2780 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2782 unsigned long mft_no = ni->mft_no;
2783 ntfs_volume *vol = ni->vol;
2784 ntfs_inode *base_ni;
2785 ntfs_inode **extent_nis;
2790 BUG_ON(NInoAttr(ni));
2791 BUG_ON(ni->nr_extents != -1);
2793 down(&ni->extent_lock);
2794 base_ni = ni->ext.base_ntfs_ino;
2795 up(&ni->extent_lock);
2797 BUG_ON(base_ni->nr_extents <= 0);
2799 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2800 mft_no, base_ni->mft_no);
2802 down(&base_ni->extent_lock);
2804 /* Make sure we are holding the only reference to the extent inode. */
2805 if (atomic_read(&ni->count) > 2) {
2806 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2807 "not freeing.", base_ni->mft_no);
2808 up(&base_ni->extent_lock);
2812 /* Dissociate the ntfs inode from the base inode. */
2813 extent_nis = base_ni->ext.extent_ntfs_inos;
2815 for (i = 0; i < base_ni->nr_extents; i++) {
2816 if (ni != extent_nis[i])
2819 base_ni->nr_extents--;
2820 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2821 sizeof(ntfs_inode*));
2826 up(&base_ni->extent_lock);
2828 if (unlikely(err)) {
2829 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2830 "its base inode 0x%lx.", mft_no,
2836 * The extent inode is no longer attached to the base inode so no one
2837 * can get a reference to it any more.
2840 /* Mark the mft record as not in use. */
2841 m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2843 /* Increment the sequence number, skipping zero, if it is not zero. */
2844 old_seq_no = m->sequence_number;
2845 seq_no = le16_to_cpu(old_seq_no);
2846 if (seq_no == 0xffff)
2850 m->sequence_number = cpu_to_le16(seq_no);
2853 * Set the ntfs inode dirty and write it out. We do not need to worry
2854 * about the base inode here since whatever caused the extent mft
2855 * record to be freed is guaranteed to do it already.
2858 err = write_mft_record(ni, m, 0);
2859 if (unlikely(err)) {
2860 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2861 "freeing.", mft_no);
2865 /* Unmap and throw away the now freed extent inode. */
2866 unmap_extent_mft_record(ni);
2867 ntfs_clear_extent_inode(ni);
2869 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2870 down_write(&vol->mftbmp_lock);
2871 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2872 up_write(&vol->mftbmp_lock);
2873 if (unlikely(err)) {
2875 * The extent inode is gone but we failed to deallocate it in
2876 * the mft bitmap. Just emit a warning and leave the volume
2879 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2884 /* Rollback what we did... */
2885 down(&base_ni->extent_lock);
2886 extent_nis = base_ni->ext.extent_ntfs_inos;
2887 if (!(base_ni->nr_extents & 3)) {
2888 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2890 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2891 if (unlikely(!extent_nis)) {
2892 ntfs_error(vol->sb, "Failed to allocate internal "
2893 "buffer during rollback.%s", es);
2894 up(&base_ni->extent_lock);
2896 goto rollback_error;
2898 if (base_ni->nr_extents) {
2899 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2900 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2901 new_size - 4 * sizeof(ntfs_inode*));
2902 kfree(base_ni->ext.extent_ntfs_inos);
2904 base_ni->ext.extent_ntfs_inos = extent_nis;
2906 m->flags |= MFT_RECORD_IN_USE;
2907 m->sequence_number = old_seq_no;
2908 extent_nis[base_ni->nr_extents++] = ni;
2909 up(&base_ni->extent_lock);
2910 mark_mft_record_dirty(ni);
2913 #endif /* NTFS_RW */