2 * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
4 * Copyright (c) 2001-2006 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, end_index;
57 * The index into the page cache and the offset within the page cache
58 * page of the wanted mft record. FIXME: We need to check for
59 * overflowing the unsigned long, but I don't think we would ever get
60 * here if the volume was that big...
62 index = (u64)ni->mft_no << vol->mft_record_size_bits >>
64 ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
66 i_size = i_size_read(mft_vi);
67 /* The maximum valid index into the page cache for $MFT's data. */
68 end_index = i_size >> PAGE_CACHE_SHIFT;
70 /* If the wanted index is out of bounds the mft record doesn't exist. */
71 if (unlikely(index >= end_index)) {
72 if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
73 vol->mft_record_size) {
74 page = ERR_PTR(-ENOENT);
75 ntfs_error(vol->sb, "Attemt to read mft record 0x%lx, "
76 "which is beyond the end of the mft. "
77 "This is probably a bug in the ntfs "
78 "driver.", ni->mft_no);
82 /* Read, map, and pin the page. */
83 page = ntfs_map_page(mft_vi->i_mapping, index);
84 if (likely(!IS_ERR(page))) {
85 /* Catch multi sector transfer fixup errors. */
86 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
90 return page_address(page) + ofs;
92 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
93 "Run chkdsk.", ni->mft_no);
94 ntfs_unmap_page(page);
105 * map_mft_record - map, pin and lock an mft record
106 * @ni: ntfs inode whose MFT record to map
108 * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
109 * for the semaphore if it was already locked by someone else.
111 * The page of the record is mapped using map_mft_record_page() before being
112 * returned to the caller.
114 * This in turn uses ntfs_map_page() to get the page containing the wanted mft
115 * record (it in turn calls read_cache_page() which reads it in from disk if
116 * necessary, increments the use count on the page so that it cannot disappear
117 * under us and returns a reference to the page cache page).
119 * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
120 * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
121 * and the post-read mst fixups on each mft record in the page have been
122 * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
123 * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
124 * ntfs_map_page() waits for PG_locked to become clear and checks if
125 * PG_uptodate is set and returns an error code if not. This provides
126 * sufficient protection against races when reading/using the page.
128 * However there is the write mapping to think about. Doing the above described
129 * checking here will be fine, because when initiating the write we will set
130 * PG_locked and clear PG_uptodate making sure nobody is touching the page
131 * contents. Doing the locking this way means that the commit to disk code in
132 * the page cache code paths is automatically sufficiently locked with us as
133 * we will not touch a page that has been locked or is not uptodate. The only
134 * locking problem then is them locking the page while we are accessing it.
136 * So that code will end up having to own the mrec_lock of all mft
137 * records/inodes present in the page before I/O can proceed. In that case we
138 * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
139 * accessing anything without owning the mrec_lock semaphore. But we do need
140 * to use them because of the read_cache_page() invocation and the code becomes
141 * so much simpler this way that it is well worth it.
143 * The mft record is now ours and we return a pointer to it. You need to check
144 * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
147 * NOTE: Caller is responsible for setting the mft record dirty before calling
148 * unmap_mft_record(). This is obviously only necessary if the caller really
149 * modified the mft record...
150 * Q: Do we want to recycle one of the VFS inode state bits instead?
151 * A: No, the inode ones mean we want to change the mft record, not we want to
154 MFT_RECORD *map_mft_record(ntfs_inode *ni)
158 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
160 /* Make sure the ntfs inode doesn't go away. */
161 atomic_inc(&ni->count);
163 /* Serialize access to this mft record. */
164 down(&ni->mrec_lock);
166 m = map_mft_record_page(ni);
167 if (likely(!IS_ERR(m)))
171 atomic_dec(&ni->count);
172 ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
177 * unmap_mft_record_page - unmap the page in which a specific mft record resides
178 * @ni: ntfs inode whose mft record page to unmap
180 * This unmaps the page in which the mft record of the ntfs inode @ni is
181 * situated and returns. This is a NOOP if highmem is not configured.
183 * The unmap happens via ntfs_unmap_page() which in turn decrements the use
184 * count on the page thus releasing it from the pinned state.
186 * We do not actually unmap the page from memory of course, as that will be
187 * done by the page cache code itself when memory pressure increases or
190 static inline void unmap_mft_record_page(ntfs_inode *ni)
194 // TODO: If dirty, blah...
195 ntfs_unmap_page(ni->page);
202 * unmap_mft_record - release a mapped mft record
203 * @ni: ntfs inode whose MFT record to unmap
205 * We release the page mapping and the mrec_lock mutex which unmaps the mft
206 * record and releases it for others to get hold of. We also release the ntfs
207 * inode by decrementing the ntfs inode reference count.
209 * NOTE: If caller has modified the mft record, it is imperative to set the mft
210 * record dirty BEFORE calling unmap_mft_record().
212 void unmap_mft_record(ntfs_inode *ni)
214 struct page *page = ni->page;
218 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
220 unmap_mft_record_page(ni);
222 atomic_dec(&ni->count);
224 * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
225 * ntfs_clear_extent_inode() in the extent inode case, and to the
226 * caller in the non-extent, yet pure ntfs inode case, to do the actual
227 * tear down of all structures and freeing of all allocated memory.
233 * map_extent_mft_record - load an extent inode and attach it to its base
234 * @base_ni: base ntfs inode
235 * @mref: mft reference of the extent inode to load
236 * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
238 * Load the extent mft record @mref and attach it to its base inode @base_ni.
239 * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
240 * PTR_ERR(result) gives the negative error code.
242 * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
243 * structure of the mapped extent inode.
245 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
246 ntfs_inode **ntfs_ino)
249 ntfs_inode *ni = NULL;
250 ntfs_inode **extent_nis = NULL;
252 unsigned long mft_no = MREF(mref);
253 u16 seq_no = MSEQNO(mref);
254 BOOL destroy_ni = FALSE;
256 ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
257 mft_no, base_ni->mft_no);
258 /* Make sure the base ntfs inode doesn't go away. */
259 atomic_inc(&base_ni->count);
261 * Check if this extent inode has already been added to the base inode,
262 * in which case just return it. If not found, add it to the base
263 * inode before returning it.
265 down(&base_ni->extent_lock);
266 if (base_ni->nr_extents > 0) {
267 extent_nis = base_ni->ext.extent_ntfs_inos;
268 for (i = 0; i < base_ni->nr_extents; i++) {
269 if (mft_no != extent_nis[i]->mft_no)
272 /* Make sure the ntfs inode doesn't go away. */
273 atomic_inc(&ni->count);
277 if (likely(ni != NULL)) {
278 up(&base_ni->extent_lock);
279 atomic_dec(&base_ni->count);
280 /* We found the record; just have to map and return it. */
281 m = map_mft_record(ni);
282 /* map_mft_record() has incremented this on success. */
283 atomic_dec(&ni->count);
284 if (likely(!IS_ERR(m))) {
285 /* Verify the sequence number. */
286 if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
287 ntfs_debug("Done 1.");
291 unmap_mft_record(ni);
292 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
293 "reference! Corrupt filesystem. "
295 return ERR_PTR(-EIO);
298 ntfs_error(base_ni->vol->sb, "Failed to map extent "
299 "mft record, error code %ld.", -PTR_ERR(m));
302 /* Record wasn't there. Get a new ntfs inode and initialize it. */
303 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
305 up(&base_ni->extent_lock);
306 atomic_dec(&base_ni->count);
307 return ERR_PTR(-ENOMEM);
309 ni->vol = base_ni->vol;
312 ni->ext.base_ntfs_ino = base_ni;
313 /* Now map the record. */
314 m = map_mft_record(ni);
316 up(&base_ni->extent_lock);
317 atomic_dec(&base_ni->count);
318 ntfs_clear_extent_inode(ni);
321 /* Verify the sequence number if it is present. */
322 if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
323 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
324 "reference! Corrupt filesystem. Run chkdsk.");
329 /* Attach extent inode to base inode, reallocating memory if needed. */
330 if (!(base_ni->nr_extents & 3)) {
332 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
334 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
335 if (unlikely(!tmp)) {
336 ntfs_error(base_ni->vol->sb, "Failed to allocate "
339 m = ERR_PTR(-ENOMEM);
342 if (base_ni->nr_extents) {
343 BUG_ON(!base_ni->ext.extent_ntfs_inos);
344 memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
345 4 * sizeof(ntfs_inode *));
346 kfree(base_ni->ext.extent_ntfs_inos);
348 base_ni->ext.extent_ntfs_inos = tmp;
350 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
351 up(&base_ni->extent_lock);
352 atomic_dec(&base_ni->count);
353 ntfs_debug("Done 2.");
357 unmap_mft_record(ni);
358 up(&base_ni->extent_lock);
359 atomic_dec(&base_ni->count);
361 * If the extent inode was not attached to the base inode we need to
362 * release it or we will leak memory.
365 ntfs_clear_extent_inode(ni);
372 * __mark_mft_record_dirty - set the mft record and the page containing it dirty
373 * @ni: ntfs inode describing the mapped mft record
375 * Internal function. Users should call mark_mft_record_dirty() instead.
377 * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
378 * as well as the page containing the mft record, dirty. Also, mark the base
379 * vfs inode dirty. This ensures that any changes to the mft record are
380 * written out to disk.
382 * NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
383 * on the base vfs inode, because even though file data may have been modified,
384 * it is dirty in the inode meta data rather than the data page cache of the
385 * inode, and thus there are no data pages that need writing out. Therefore, a
386 * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
387 * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
388 * ensure ->write_inode is called from generic_osync_inode() and this needs to
389 * happen or the file data would not necessarily hit the device synchronously,
390 * even though the vfs inode has the O_SYNC flag set. Also, I_DIRTY_DATASYNC
391 * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
392 * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
395 void __mark_mft_record_dirty(ntfs_inode *ni)
399 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
400 BUG_ON(NInoAttr(ni));
401 mark_ntfs_record_dirty(ni->page, ni->page_ofs);
402 /* Determine the base vfs inode and mark it dirty, too. */
403 down(&ni->extent_lock);
404 if (likely(ni->nr_extents >= 0))
407 base_ni = ni->ext.base_ntfs_ino;
408 up(&ni->extent_lock);
409 __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
412 static const char *ntfs_please_email = "Please email "
413 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
414 "this message. Thank you.";
417 * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
418 * @vol: ntfs volume on which the mft record to synchronize resides
419 * @mft_no: mft record number of mft record to synchronize
420 * @m: mapped, mst protected (extent) mft record to synchronize
422 * Write the mapped, mst protected (extent) mft record @m with mft record
423 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
424 * bypassing the page cache and the $MFTMirr inode itself.
426 * This function is only for use at umount time when the mft mirror inode has
427 * already been disposed off. We BUG() if we are called while the mft mirror
428 * inode is still attached to the volume.
430 * On success return 0. On error return -errno.
432 * NOTE: This function is not implemented yet as I am not convinced it can
433 * actually be triggered considering the sequence of commits we do in super.c::
434 * ntfs_put_super(). But just in case we provide this place holder as the
435 * alternative would be either to BUG() or to get a NULL pointer dereference
438 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
439 const unsigned long mft_no, MFT_RECORD *m)
441 BUG_ON(vol->mftmirr_ino);
442 ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
443 "implemented yet. %s", ntfs_please_email);
448 * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
449 * @vol: ntfs volume on which the mft record to synchronize resides
450 * @mft_no: mft record number of mft record to synchronize
451 * @m: mapped, mst protected (extent) mft record to synchronize
452 * @sync: if true, wait for i/o completion
454 * Write the mapped, mst protected (extent) mft record @m with mft record
455 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
457 * On success return 0. On error return -errno and set the volume errors flag
458 * in the ntfs volume @vol.
460 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
462 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
463 * schedule i/o via ->writepage or do it via kntfsd or whatever.
465 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
466 MFT_RECORD *m, int sync)
469 unsigned int blocksize = vol->sb->s_blocksize;
470 int max_bhs = vol->mft_record_size / blocksize;
471 struct buffer_head *bhs[max_bhs];
472 struct buffer_head *bh, *head;
475 unsigned int block_start, block_end, m_start, m_end, page_ofs;
476 int i_bhs, nr_bhs, err = 0;
477 unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
479 ntfs_debug("Entering for inode 0x%lx.", mft_no);
481 if (unlikely(!vol->mftmirr_ino)) {
482 /* This could happen during umount... */
483 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
488 /* Get the page containing the mirror copy of the mft record @m. */
489 page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
490 (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
492 ntfs_error(vol->sb, "Failed to map mft mirror page.");
497 BUG_ON(!PageUptodate(page));
498 ClearPageUptodate(page);
499 /* Offset of the mft mirror record inside the page. */
500 page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
501 /* The address in the page of the mirror copy of the mft record @m. */
502 kmirr = page_address(page) + page_ofs;
503 /* Copy the mst protected mft record to the mirror. */
504 memcpy(kmirr, m, vol->mft_record_size);
505 /* Create uptodate buffers if not present. */
506 if (unlikely(!page_has_buffers(page))) {
507 struct buffer_head *tail;
509 bh = head = alloc_page_buffers(page, blocksize, 1);
511 set_buffer_uptodate(bh);
513 bh = bh->b_this_page;
515 tail->b_this_page = head;
516 attach_page_buffers(page, head);
518 bh = head = page_buffers(page);
523 m_start = kmirr - (u8*)page_address(page);
524 m_end = m_start + vol->mft_record_size;
526 block_end = block_start + blocksize;
527 /* If the buffer is outside the mft record, skip it. */
528 if (block_end <= m_start)
530 if (unlikely(block_start >= m_end))
532 /* Need to map the buffer if it is not mapped already. */
533 if (unlikely(!buffer_mapped(bh))) {
536 unsigned int vcn_ofs;
538 bh->b_bdev = vol->sb->s_bdev;
539 /* Obtain the vcn and offset of the current block. */
540 vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
541 (block_start - m_start);
542 vcn_ofs = vcn & vol->cluster_size_mask;
543 vcn >>= vol->cluster_size_bits;
545 down_read(&NTFS_I(vol->mftmirr_ino)->
547 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
549 * $MFTMirr always has the whole of its runlist
554 /* Seek to element containing target vcn. */
555 while (rl->length && rl[1].vcn <= vcn)
557 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
558 /* For $MFTMirr, only lcn >= 0 is a successful remap. */
559 if (likely(lcn >= 0)) {
560 /* Setup buffer head to correct block. */
561 bh->b_blocknr = ((lcn <<
562 vol->cluster_size_bits) +
563 vcn_ofs) >> blocksize_bits;
564 set_buffer_mapped(bh);
567 ntfs_error(vol->sb, "Cannot write mft mirror "
568 "record 0x%lx because its "
569 "location on disk could not "
570 "be determined (error code "
576 BUG_ON(!buffer_uptodate(bh));
577 BUG_ON(!nr_bhs && (m_start != block_start));
578 BUG_ON(nr_bhs >= max_bhs);
580 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
581 } while (block_start = block_end, (bh = bh->b_this_page) != head);
583 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
585 /* Lock buffers and start synchronous write i/o on them. */
586 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
587 struct buffer_head *tbh = bhs[i_bhs];
589 if (unlikely(test_set_buffer_locked(tbh)))
591 BUG_ON(!buffer_uptodate(tbh));
592 clear_buffer_dirty(tbh);
594 tbh->b_end_io = end_buffer_write_sync;
595 submit_bh(WRITE, tbh);
597 /* Wait on i/o completion of buffers. */
598 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
599 struct buffer_head *tbh = bhs[i_bhs];
602 if (unlikely(!buffer_uptodate(tbh))) {
605 * Set the buffer uptodate so the page and
606 * buffer states do not become out of sync.
608 set_buffer_uptodate(tbh);
611 } else /* if (unlikely(err)) */ {
612 /* Clean the buffers. */
613 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
614 clear_buffer_dirty(bhs[i_bhs]);
616 /* Current state: all buffers are clean, unlocked, and uptodate. */
617 /* Remove the mst protection fixups again. */
618 post_write_mst_fixup((NTFS_RECORD*)kmirr);
619 flush_dcache_page(page);
620 SetPageUptodate(page);
622 ntfs_unmap_page(page);
626 ntfs_error(vol->sb, "I/O error while writing mft mirror "
627 "record 0x%lx!", mft_no);
629 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
630 "code %i). Volume will be left marked dirty "
631 "on umount. Run ntfsfix on the partition "
632 "after umounting to correct this.", -err);
639 * write_mft_record_nolock - write out a mapped (extent) mft record
640 * @ni: ntfs inode describing the mapped (extent) mft record
641 * @m: mapped (extent) mft record to write
642 * @sync: if true, wait for i/o completion
644 * Write the mapped (extent) mft record @m described by the (regular or extent)
645 * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
646 * the mft mirror, that is also updated.
648 * We only write the mft record if the ntfs inode @ni is dirty and the first
649 * buffer belonging to its mft record is dirty, too. We ignore the dirty state
650 * of subsequent buffers because we could have raced with
651 * fs/ntfs/aops.c::mark_ntfs_record_dirty().
653 * On success, clean the mft record and return 0. On error, leave the mft
654 * record dirty and return -errno. The caller should call make_bad_inode() on
655 * the base inode to ensure no more access happens to this inode. We do not do
656 * it here as the caller may want to finish writing other extent mft records
657 * first to minimize on-disk metadata inconsistencies.
659 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
660 * However, if the mft record has a counterpart in the mft mirror and @sync is
661 * true, we write the mft record, wait for i/o completion, and only then write
662 * the mft mirror copy. This ensures that if the system crashes either the mft
663 * or the mft mirror will contain a self-consistent mft record @m. If @sync is
664 * false on the other hand, we start i/o on both and then wait for completion
665 * on them. This provides a speedup but no longer guarantees that you will end
666 * up with a self-consistent mft record in the case of a crash but if you asked
667 * for asynchronous writing you probably do not care about that anyway.
669 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
670 * schedule i/o via ->writepage or do it via kntfsd or whatever.
672 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
674 ntfs_volume *vol = ni->vol;
675 struct page *page = ni->page;
676 unsigned int blocksize = vol->sb->s_blocksize;
677 unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
678 int max_bhs = vol->mft_record_size / blocksize;
679 struct buffer_head *bhs[max_bhs];
680 struct buffer_head *bh, *head;
682 unsigned int block_start, block_end, m_start, m_end;
683 int i_bhs, nr_bhs, err = 0;
685 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
686 BUG_ON(NInoAttr(ni));
688 BUG_ON(!PageLocked(page));
690 * If the ntfs_inode is clean no need to do anything. If it is dirty,
691 * mark it as clean now so that it can be redirtied later on if needed.
692 * There is no danger of races since the caller is holding the locks
693 * for the mft record @m and the page it is in.
695 if (!NInoTestClearDirty(ni))
697 bh = head = page_buffers(page);
702 m_start = ni->page_ofs;
703 m_end = m_start + vol->mft_record_size;
705 block_end = block_start + blocksize;
706 /* If the buffer is outside the mft record, skip it. */
707 if (block_end <= m_start)
709 if (unlikely(block_start >= m_end))
712 * If this block is not the first one in the record, we ignore
713 * the buffer's dirty state because we could have raced with a
714 * parallel mark_ntfs_record_dirty().
716 if (block_start == m_start) {
717 /* This block is the first one in the record. */
718 if (!buffer_dirty(bh)) {
720 /* Clean records are not written out. */
724 /* Need to map the buffer if it is not mapped already. */
725 if (unlikely(!buffer_mapped(bh))) {
728 unsigned int vcn_ofs;
730 bh->b_bdev = vol->sb->s_bdev;
731 /* Obtain the vcn and offset of the current block. */
732 vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
733 (block_start - m_start);
734 vcn_ofs = vcn & vol->cluster_size_mask;
735 vcn >>= vol->cluster_size_bits;
737 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
738 rl = NTFS_I(vol->mft_ino)->runlist.rl;
741 /* Seek to element containing target vcn. */
742 while (rl->length && rl[1].vcn <= vcn)
744 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
745 /* For $MFT, only lcn >= 0 is a successful remap. */
746 if (likely(lcn >= 0)) {
747 /* Setup buffer head to correct block. */
748 bh->b_blocknr = ((lcn <<
749 vol->cluster_size_bits) +
750 vcn_ofs) >> blocksize_bits;
751 set_buffer_mapped(bh);
754 ntfs_error(vol->sb, "Cannot write mft record "
755 "0x%lx because its location "
756 "on disk could not be "
757 "determined (error code %lli).",
758 ni->mft_no, (long long)lcn);
762 BUG_ON(!buffer_uptodate(bh));
763 BUG_ON(!nr_bhs && (m_start != block_start));
764 BUG_ON(nr_bhs >= max_bhs);
766 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
767 } while (block_start = block_end, (bh = bh->b_this_page) != head);
769 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
774 /* Apply the mst protection fixups. */
775 err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
777 ntfs_error(vol->sb, "Failed to apply mst fixups!");
780 flush_dcache_mft_record_page(ni);
781 /* Lock buffers and start synchronous write i/o on them. */
782 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
783 struct buffer_head *tbh = bhs[i_bhs];
785 if (unlikely(test_set_buffer_locked(tbh)))
787 BUG_ON(!buffer_uptodate(tbh));
788 clear_buffer_dirty(tbh);
790 tbh->b_end_io = end_buffer_write_sync;
791 submit_bh(WRITE, tbh);
793 /* Synchronize the mft mirror now if not @sync. */
794 if (!sync && ni->mft_no < vol->mftmirr_size)
795 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
796 /* Wait on i/o completion of buffers. */
797 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
798 struct buffer_head *tbh = bhs[i_bhs];
801 if (unlikely(!buffer_uptodate(tbh))) {
804 * Set the buffer uptodate so the page and buffer
805 * states do not become out of sync.
807 if (PageUptodate(page))
808 set_buffer_uptodate(tbh);
811 /* If @sync, now synchronize the mft mirror. */
812 if (sync && ni->mft_no < vol->mftmirr_size)
813 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
814 /* Remove the mst protection fixups again. */
815 post_write_mst_fixup((NTFS_RECORD*)m);
816 flush_dcache_mft_record_page(ni);
818 /* I/O error during writing. This is really bad! */
819 ntfs_error(vol->sb, "I/O error while writing mft record "
820 "0x%lx! Marking base inode as bad. You "
821 "should unmount the volume and run chkdsk.",
829 /* Clean the buffers. */
830 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
831 clear_buffer_dirty(bhs[i_bhs]);
834 * Current state: all buffers are clean, unlocked, and uptodate.
835 * The caller should mark the base inode as bad so that no more i/o
836 * happens. ->clear_inode() will still be invoked so all extent inodes
837 * and other allocated memory will be freed.
839 if (err == -ENOMEM) {
840 ntfs_error(vol->sb, "Not enough memory to write mft record. "
841 "Redirtying so the write is retried later.");
842 mark_mft_record_dirty(ni);
850 * ntfs_may_write_mft_record - check if an mft record may be written out
851 * @vol: [IN] ntfs volume on which the mft record to check resides
852 * @mft_no: [IN] mft record number of the mft record to check
853 * @m: [IN] mapped mft record to check
854 * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
856 * Check if the mapped (base or extent) mft record @m with mft record number
857 * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
858 * and possible the ntfs inode of the mft record is locked and the base vfs
859 * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
860 * caller is responsible for unlocking the ntfs inode and unpinning the base
863 * Return TRUE if the mft record may be written out and FALSE if not.
865 * The caller has locked the page and cleared the uptodate flag on it which
866 * means that we can safely write out any dirty mft records that do not have
867 * their inodes in icache as determined by ilookup5() as anyone
868 * opening/creating such an inode would block when attempting to map the mft
869 * record in read_cache_page() until we are finished with the write out.
871 * Here is a description of the tests we perform:
873 * If the inode is found in icache we know the mft record must be a base mft
874 * record. If it is dirty, we do not write it and return FALSE as the vfs
875 * inode write paths will result in the access times being updated which would
876 * cause the base mft record to be redirtied and written out again. (We know
877 * the access time update will modify the base mft record because Windows
878 * chkdsk complains if the standard information attribute is not in the base
881 * If the inode is in icache and not dirty, we attempt to lock the mft record
882 * and if we find the lock was already taken, it is not safe to write the mft
883 * record and we return FALSE.
885 * If we manage to obtain the lock we have exclusive access to the mft record,
886 * which also allows us safe writeout of the mft record. We then set
887 * @locked_ni to the locked ntfs inode and return TRUE.
889 * Note we cannot just lock the mft record and sleep while waiting for the lock
890 * because this would deadlock due to lock reversal (normally the mft record is
891 * locked before the page is locked but we already have the page locked here
892 * when we try to lock the mft record).
894 * If the inode is not in icache we need to perform further checks.
896 * If the mft record is not a FILE record or it is a base mft record, we can
897 * safely write it and return TRUE.
899 * We now know the mft record is an extent mft record. We check if the inode
900 * corresponding to its base mft record is in icache and obtain a reference to
901 * it if it is. If it is not, we can safely write it and return TRUE.
903 * We now have the base inode for the extent mft record. We check if it has an
904 * ntfs inode for the extent mft record attached and if not it is safe to write
905 * the extent mft record and we return TRUE.
907 * The ntfs inode for the extent mft record is attached to the base inode so we
908 * attempt to lock the extent mft record and if we find the lock was already
909 * taken, it is not safe to write the extent mft record and we return FALSE.
911 * If we manage to obtain the lock we have exclusive access to the extent mft
912 * record, which also allows us safe writeout of the extent mft record. We
913 * set the ntfs inode of the extent mft record clean and then set @locked_ni to
914 * the now locked ntfs inode and return TRUE.
916 * Note, the reason for actually writing dirty mft records here and not just
917 * relying on the vfs inode dirty code paths is that we can have mft records
918 * modified without them ever having actual inodes in memory. Also we can have
919 * dirty mft records with clean ntfs inodes in memory. None of the described
920 * cases would result in the dirty mft records being written out if we only
921 * relied on the vfs inode dirty code paths. And these cases can really occur
922 * during allocation of new mft records and in particular when the
923 * initialized_size of the $MFT/$DATA attribute is extended and the new space
924 * is initialized using ntfs_mft_record_format(). The clean inode can then
925 * appear if the mft record is reused for a new inode before it got written
928 BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
929 const MFT_RECORD *m, ntfs_inode **locked_ni)
931 struct super_block *sb = vol->sb;
932 struct inode *mft_vi = vol->mft_ino;
934 ntfs_inode *ni, *eni, **extent_nis;
938 ntfs_debug("Entering for inode 0x%lx.", mft_no);
940 * Normally we do not return a locked inode so set @locked_ni to NULL.
945 * Check if the inode corresponding to this mft record is in the VFS
946 * inode cache and obtain a reference to it if it is.
948 ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
954 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
955 * we get here for it rather often.
958 /* Balance the below iput(). */
960 BUG_ON(vi != mft_vi);
963 * Have to use ilookup5_nowait() since ilookup5() waits for the
964 * inode lock which causes ntfs to deadlock when a concurrent
965 * inode write via the inode dirty code paths and the page
966 * dirty code path of the inode dirty code path when writing
969 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
972 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
973 /* The inode is in icache. */
975 /* Take a reference to the ntfs inode. */
976 atomic_inc(&ni->count);
977 /* If the inode is dirty, do not write this record. */
979 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
981 atomic_dec(&ni->count);
985 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
986 /* The inode is not dirty, try to take the mft record lock. */
987 if (unlikely(down_trylock(&ni->mrec_lock))) {
988 ntfs_debug("Mft record 0x%lx is already locked, do "
989 "not write it.", mft_no);
990 atomic_dec(&ni->count);
994 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
997 * The write has to occur while we hold the mft record lock so
998 * return the locked ntfs inode.
1003 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1004 /* The inode is not in icache. */
1005 /* Write the record if it is not a mft record (type "FILE"). */
1006 if (!ntfs_is_mft_record(m->magic)) {
1007 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1011 /* Write the mft record if it is a base inode. */
1012 if (!m->base_mft_record) {
1013 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1018 * This is an extent mft record. Check if the inode corresponding to
1019 * its base mft record is in icache and obtain a reference to it if it
1022 na.mft_no = MREF_LE(m->base_mft_record);
1023 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1024 "inode 0x%lx in icache.", mft_no, na.mft_no);
1026 /* Balance the below iput(). */
1028 BUG_ON(vi != mft_vi);
1030 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1034 * The base inode is not in icache, write this extent mft
1037 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1038 "extent record.", na.mft_no);
1041 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1043 * The base inode is in icache. Check if it has the extent inode
1044 * corresponding to this extent mft record attached.
1047 down(&ni->extent_lock);
1048 if (ni->nr_extents <= 0) {
1050 * The base inode has no attached extent inodes, write this
1051 * extent mft record.
1053 up(&ni->extent_lock);
1055 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1056 "write the extent record.", na.mft_no);
1059 /* Iterate over the attached extent inodes. */
1060 extent_nis = ni->ext.extent_ntfs_inos;
1061 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1062 if (mft_no == extent_nis[i]->mft_no) {
1064 * Found the extent inode corresponding to this extent
1067 eni = extent_nis[i];
1072 * If the extent inode was not attached to the base inode, write this
1073 * extent mft record.
1076 up(&ni->extent_lock);
1078 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1079 "inode 0x%lx, write the extent record.",
1083 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1085 /* Take a reference to the extent ntfs inode. */
1086 atomic_inc(&eni->count);
1087 up(&ni->extent_lock);
1089 * Found the extent inode coresponding to this extent mft record.
1090 * Try to take the mft record lock.
1092 if (unlikely(down_trylock(&eni->mrec_lock))) {
1093 atomic_dec(&eni->count);
1095 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1096 "not write it.", mft_no);
1099 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1101 if (NInoTestClearDirty(eni))
1102 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1105 * The write has to occur while we hold the mft record lock so return
1106 * the locked extent ntfs inode.
1112 static const char *es = " Leaving inconsistent metadata. Unmount and run "
1116 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1117 * @vol: volume on which to search for a free mft record
1118 * @base_ni: open base inode if allocating an extent mft record or NULL
1120 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1123 * If @base_ni is NULL start the search at the default allocator position.
1125 * If @base_ni is not NULL start the search at the mft record after the base
1126 * mft record @base_ni.
1128 * Return the free mft record on success and -errno on error. An error code of
1129 * -ENOSPC means that there are no free mft records in the currently
1130 * initialized mft bitmap.
1132 * Locking: Caller must hold vol->mftbmp_lock for writing.
1134 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1135 ntfs_inode *base_ni)
1137 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1138 unsigned long flags;
1139 struct address_space *mftbmp_mapping;
1142 unsigned int page_ofs, size;
1145 ntfs_debug("Searching for free mft record in the currently "
1146 "initialized mft bitmap.");
1147 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1149 * Set the end of the pass making sure we do not overflow the mft
1152 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1153 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1154 vol->mft_record_size_bits;
1155 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1156 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1157 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1158 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1163 data_pos = vol->mft_data_pos;
1165 data_pos = base_ni->mft_no + 1;
1168 if (data_pos >= pass_end) {
1171 /* This happens on a freshly formatted volume. */
1172 if (data_pos >= pass_end)
1175 pass_start = data_pos;
1176 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1177 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1178 (long long)pass_start, (long long)pass_end,
1179 (long long)data_pos);
1180 /* Loop until a free mft record is found. */
1181 for (; pass <= 2;) {
1182 /* Cap size to pass_end. */
1183 ofs = data_pos >> 3;
1184 page_ofs = ofs & ~PAGE_CACHE_MASK;
1185 size = PAGE_CACHE_SIZE - page_ofs;
1186 ll = ((pass_end + 7) >> 3) - ofs;
1191 * If we are still within the active pass, search the next page
1195 page = ntfs_map_page(mftbmp_mapping,
1196 ofs >> PAGE_CACHE_SHIFT);
1197 if (unlikely(IS_ERR(page))) {
1198 ntfs_error(vol->sb, "Failed to read mft "
1199 "bitmap, aborting.");
1200 return PTR_ERR(page);
1202 buf = (u8*)page_address(page) + page_ofs;
1205 ntfs_debug("Before inner for loop: size 0x%x, "
1206 "data_pos 0x%llx, bit 0x%llx", size,
1207 (long long)data_pos, (long long)bit);
1208 for (; bit < size && data_pos + bit < pass_end;
1209 bit &= ~7ull, bit += 8) {
1210 byte = buf + (bit >> 3);
1213 b = ffz((unsigned long)*byte);
1214 if (b < 8 && b >= (bit & 7)) {
1215 ll = data_pos + (bit & ~7ull) + b;
1216 if (unlikely(ll > (1ll << 32))) {
1217 ntfs_unmap_page(page);
1221 flush_dcache_page(page);
1222 set_page_dirty(page);
1223 ntfs_unmap_page(page);
1224 ntfs_debug("Done. (Found and "
1225 "allocated mft record "
1231 ntfs_debug("After inner for loop: size 0x%x, "
1232 "data_pos 0x%llx, bit 0x%llx", size,
1233 (long long)data_pos, (long long)bit);
1235 ntfs_unmap_page(page);
1237 * If the end of the pass has not been reached yet,
1238 * continue searching the mft bitmap for a zero bit.
1240 if (data_pos < pass_end)
1243 /* Do the next pass. */
1246 * Starting the second pass, in which we scan the first
1247 * part of the zone which we omitted earlier.
1249 pass_end = pass_start;
1250 data_pos = pass_start = 24;
1251 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1252 "0x%llx.", pass, (long long)pass_start,
1253 (long long)pass_end);
1254 if (data_pos >= pass_end)
1258 /* No free mft records in currently initialized mft bitmap. */
1259 ntfs_debug("Done. (No free mft records left in currently initialized "
1265 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1266 * @vol: volume on which to extend the mft bitmap attribute
1268 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1270 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1273 * Return 0 on success and -errno on error.
1275 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1276 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1277 * writing and releases it before returning.
1278 * - This function takes vol->lcnbmp_lock for writing and releases it
1281 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1285 unsigned long flags;
1287 ntfs_inode *mft_ni, *mftbmp_ni;
1288 runlist_element *rl, *rl2 = NULL;
1289 ntfs_attr_search_ctx *ctx = NULL;
1291 ATTR_RECORD *a = NULL;
1299 } status = { 0, 0, 0 };
1301 ntfs_debug("Extending mft bitmap allocation.");
1302 mft_ni = NTFS_I(vol->mft_ino);
1303 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1305 * Determine the last lcn of the mft bitmap. The allocated size of the
1306 * mft bitmap cannot be zero so we are ok to do this.
1308 down_write(&mftbmp_ni->runlist.lock);
1309 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1310 ll = mftbmp_ni->allocated_size;
1311 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1312 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1313 (ll - 1) >> vol->cluster_size_bits, NULL);
1314 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1315 up_write(&mftbmp_ni->runlist.lock);
1316 ntfs_error(vol->sb, "Failed to determine last allocated "
1317 "cluster of mft bitmap attribute.");
1324 lcn = rl->lcn + rl->length;
1325 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1328 * Attempt to get the cluster following the last allocated cluster by
1329 * hand as it may be in the MFT zone so the allocator would not give it
1333 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1334 ll >> PAGE_CACHE_SHIFT);
1336 up_write(&mftbmp_ni->runlist.lock);
1337 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1338 return PTR_ERR(page);
1340 b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1341 tb = 1 << (lcn & 7ull);
1342 down_write(&vol->lcnbmp_lock);
1343 if (*b != 0xff && !(*b & tb)) {
1344 /* Next cluster is free, allocate it. */
1346 flush_dcache_page(page);
1347 set_page_dirty(page);
1348 up_write(&vol->lcnbmp_lock);
1349 ntfs_unmap_page(page);
1350 /* Update the mft bitmap runlist. */
1353 status.added_cluster = 1;
1354 ntfs_debug("Appending one cluster to mft bitmap.");
1356 up_write(&vol->lcnbmp_lock);
1357 ntfs_unmap_page(page);
1358 /* Allocate a cluster from the DATA_ZONE. */
1359 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
1362 up_write(&mftbmp_ni->runlist.lock);
1363 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1365 return PTR_ERR(rl2);
1367 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1369 up_write(&mftbmp_ni->runlist.lock);
1370 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1372 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1373 ntfs_error(vol->sb, "Failed to dealocate "
1374 "allocated cluster.%s", es);
1380 mftbmp_ni->runlist.rl = rl;
1381 status.added_run = 1;
1382 ntfs_debug("Adding one run to mft bitmap.");
1383 /* Find the last run in the new runlist. */
1384 for (; rl[1].length; rl++)
1388 * Update the attribute record as well. Note: @rl is the last
1389 * (non-terminator) runlist element of mft bitmap.
1391 mrec = map_mft_record(mft_ni);
1393 ntfs_error(vol->sb, "Failed to map mft record.");
1394 ret = PTR_ERR(mrec);
1397 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1398 if (unlikely(!ctx)) {
1399 ntfs_error(vol->sb, "Failed to get search context.");
1403 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1404 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1406 if (unlikely(ret)) {
1407 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1408 "mft bitmap attribute.");
1414 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1415 /* Search back for the previous last allocated cluster of mft bitmap. */
1416 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1420 BUG_ON(ll < rl2->vcn);
1421 BUG_ON(ll >= rl2->vcn + rl2->length);
1422 /* Get the size for the new mapping pairs array for this extent. */
1423 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1424 if (unlikely(mp_size <= 0)) {
1425 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1426 "mft bitmap attribute extent.");
1432 /* Expand the attribute record if necessary. */
1433 old_alen = le32_to_cpu(a->length);
1434 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1435 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1436 if (unlikely(ret)) {
1437 if (ret != -ENOSPC) {
1438 ntfs_error(vol->sb, "Failed to resize attribute "
1439 "record for mft bitmap attribute.");
1442 // TODO: Deal with this by moving this extent to a new mft
1443 // record or by starting a new extent in a new mft record or by
1444 // moving other attributes out of this mft record.
1445 // Note: It will need to be a special mft record and if none of
1446 // those are available it gets rather complicated...
1447 ntfs_error(vol->sb, "Not enough space in this mft record to "
1448 "accomodate extended mft bitmap attribute "
1449 "extent. Cannot handle this yet.");
1453 status.mp_rebuilt = 1;
1454 /* Generate the mapping pairs array directly into the attr record. */
1455 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1456 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1457 mp_size, rl2, ll, -1, NULL);
1458 if (unlikely(ret)) {
1459 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1460 "mft bitmap attribute.");
1463 /* Update the highest_vcn. */
1464 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1466 * We now have extended the mft bitmap allocated_size by one cluster.
1467 * Reflect this in the ntfs_inode structure and the attribute record.
1469 if (a->data.non_resident.lowest_vcn) {
1471 * We are not in the first attribute extent, switch to it, but
1472 * first ensure the changes will make it to disk later.
1474 flush_dcache_mft_record_page(ctx->ntfs_ino);
1475 mark_mft_record_dirty(ctx->ntfs_ino);
1476 ntfs_attr_reinit_search_ctx(ctx);
1477 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1478 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1480 if (unlikely(ret)) {
1481 ntfs_error(vol->sb, "Failed to find first attribute "
1482 "extent of mft bitmap attribute.");
1483 goto restore_undo_alloc;
1487 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1488 mftbmp_ni->allocated_size += vol->cluster_size;
1489 a->data.non_resident.allocated_size =
1490 cpu_to_sle64(mftbmp_ni->allocated_size);
1491 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1492 /* Ensure the changes make it to disk. */
1493 flush_dcache_mft_record_page(ctx->ntfs_ino);
1494 mark_mft_record_dirty(ctx->ntfs_ino);
1495 ntfs_attr_put_search_ctx(ctx);
1496 unmap_mft_record(mft_ni);
1497 up_write(&mftbmp_ni->runlist.lock);
1498 ntfs_debug("Done.");
1501 ntfs_attr_reinit_search_ctx(ctx);
1502 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1503 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1505 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1506 "mft bitmap attribute.%s", es);
1507 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1508 mftbmp_ni->allocated_size += vol->cluster_size;
1509 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1510 ntfs_attr_put_search_ctx(ctx);
1511 unmap_mft_record(mft_ni);
1512 up_write(&mftbmp_ni->runlist.lock);
1514 * The only thing that is now wrong is ->allocated_size of the
1515 * base attribute extent which chkdsk should be able to fix.
1521 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1523 if (status.added_cluster) {
1524 /* Truncate the last run in the runlist by one cluster. */
1527 } else if (status.added_run) {
1529 /* Remove the last run from the runlist. */
1530 rl->lcn = rl[1].lcn;
1533 /* Deallocate the cluster. */
1534 down_write(&vol->lcnbmp_lock);
1535 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1536 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1539 up_write(&vol->lcnbmp_lock);
1540 if (status.mp_rebuilt) {
1541 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1542 a->data.non_resident.mapping_pairs_offset),
1543 old_alen - le16_to_cpu(
1544 a->data.non_resident.mapping_pairs_offset),
1545 rl2, ll, -1, NULL)) {
1546 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1550 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1551 ntfs_error(vol->sb, "Failed to restore attribute "
1555 flush_dcache_mft_record_page(ctx->ntfs_ino);
1556 mark_mft_record_dirty(ctx->ntfs_ino);
1559 ntfs_attr_put_search_ctx(ctx);
1561 unmap_mft_record(mft_ni);
1562 up_write(&mftbmp_ni->runlist.lock);
1567 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1568 * @vol: volume on which to extend the mft bitmap attribute
1570 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1571 * volume @vol by 8 bytes.
1573 * Note: Only changes initialized_size and data_size, i.e. requires that
1574 * allocated_size is big enough to fit the new initialized_size.
1576 * Return 0 on success and -error on error.
1578 * Locking: Caller must hold vol->mftbmp_lock for writing.
1580 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1582 s64 old_data_size, old_initialized_size;
1583 unsigned long flags;
1584 struct inode *mftbmp_vi;
1585 ntfs_inode *mft_ni, *mftbmp_ni;
1586 ntfs_attr_search_ctx *ctx;
1591 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1592 mft_ni = NTFS_I(vol->mft_ino);
1593 mftbmp_vi = vol->mftbmp_ino;
1594 mftbmp_ni = NTFS_I(mftbmp_vi);
1595 /* Get the attribute record. */
1596 mrec = map_mft_record(mft_ni);
1598 ntfs_error(vol->sb, "Failed to map mft record.");
1599 return PTR_ERR(mrec);
1601 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1602 if (unlikely(!ctx)) {
1603 ntfs_error(vol->sb, "Failed to get search context.");
1607 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1608 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1609 if (unlikely(ret)) {
1610 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1611 "mft bitmap attribute.");
1617 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1618 old_data_size = i_size_read(mftbmp_vi);
1619 old_initialized_size = mftbmp_ni->initialized_size;
1621 * We can simply update the initialized_size before filling the space
1622 * with zeroes because the caller is holding the mft bitmap lock for
1623 * writing which ensures that no one else is trying to access the data.
1625 mftbmp_ni->initialized_size += 8;
1626 a->data.non_resident.initialized_size =
1627 cpu_to_sle64(mftbmp_ni->initialized_size);
1628 if (mftbmp_ni->initialized_size > old_data_size) {
1629 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1630 a->data.non_resident.data_size =
1631 cpu_to_sle64(mftbmp_ni->initialized_size);
1633 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1634 /* Ensure the changes make it to disk. */
1635 flush_dcache_mft_record_page(ctx->ntfs_ino);
1636 mark_mft_record_dirty(ctx->ntfs_ino);
1637 ntfs_attr_put_search_ctx(ctx);
1638 unmap_mft_record(mft_ni);
1639 /* Initialize the mft bitmap attribute value with zeroes. */
1640 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1642 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1646 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1647 /* Try to recover from the error. */
1648 mrec = map_mft_record(mft_ni);
1650 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1654 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1655 if (unlikely(!ctx)) {
1656 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1660 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1661 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1662 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1663 "mft bitmap attribute.%s", es);
1666 ntfs_attr_put_search_ctx(ctx);
1668 unmap_mft_record(mft_ni);
1672 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1673 mftbmp_ni->initialized_size = old_initialized_size;
1674 a->data.non_resident.initialized_size =
1675 cpu_to_sle64(old_initialized_size);
1676 if (i_size_read(mftbmp_vi) != old_data_size) {
1677 i_size_write(mftbmp_vi, old_data_size);
1678 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1680 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1681 flush_dcache_mft_record_page(ctx->ntfs_ino);
1682 mark_mft_record_dirty(ctx->ntfs_ino);
1683 ntfs_attr_put_search_ctx(ctx);
1684 unmap_mft_record(mft_ni);
1686 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1687 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1688 "data_size 0x%llx, initialized_size 0x%llx.",
1689 (long long)mftbmp_ni->allocated_size,
1690 (long long)i_size_read(mftbmp_vi),
1691 (long long)mftbmp_ni->initialized_size);
1692 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1699 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1700 * @vol: volume on which to extend the mft data attribute
1702 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1703 * worth of clusters or if not enough space for this by one mft record worth
1706 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1709 * Return 0 on success and -errno on error.
1711 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1712 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1713 * writing and releases it before returning.
1714 * - This function calls functions which take vol->lcnbmp_lock for
1715 * writing and release it before returning.
1717 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1722 unsigned long flags;
1724 runlist_element *rl, *rl2;
1725 ntfs_attr_search_ctx *ctx = NULL;
1727 ATTR_RECORD *a = NULL;
1730 BOOL mp_rebuilt = FALSE;
1732 ntfs_debug("Extending mft data allocation.");
1733 mft_ni = NTFS_I(vol->mft_ino);
1735 * Determine the preferred allocation location, i.e. the last lcn of
1736 * the mft data attribute. The allocated size of the mft data
1737 * attribute cannot be zero so we are ok to do this.
1739 down_write(&mft_ni->runlist.lock);
1740 read_lock_irqsave(&mft_ni->size_lock, flags);
1741 ll = mft_ni->allocated_size;
1742 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1743 rl = ntfs_attr_find_vcn_nolock(mft_ni,
1744 (ll - 1) >> vol->cluster_size_bits, NULL);
1745 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1746 up_write(&mft_ni->runlist.lock);
1747 ntfs_error(vol->sb, "Failed to determine last allocated "
1748 "cluster of mft data attribute.");
1755 lcn = rl->lcn + rl->length;
1756 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1757 /* Minimum allocation is one mft record worth of clusters. */
1758 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1761 /* Want to allocate 16 mft records worth of clusters. */
1762 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1765 /* Ensure we do not go above 2^32-1 mft records. */
1766 read_lock_irqsave(&mft_ni->size_lock, flags);
1767 ll = mft_ni->allocated_size;
1768 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1769 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1770 vol->mft_record_size_bits >= (1ll << 32))) {
1772 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1773 vol->mft_record_size_bits >= (1ll << 32))) {
1774 ntfs_warning(vol->sb, "Cannot allocate mft record "
1775 "because the maximum number of inodes "
1776 "(2^32) has already been reached.");
1777 up_write(&mft_ni->runlist.lock);
1781 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1782 nr > min_nr ? "default" : "minimal", (long long)nr);
1783 old_last_vcn = rl[1].vcn;
1785 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
1787 if (likely(!IS_ERR(rl2)))
1789 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1790 ntfs_error(vol->sb, "Failed to allocate the minimal "
1791 "number of clusters (%lli) for the "
1792 "mft data attribute.", (long long)nr);
1793 up_write(&mft_ni->runlist.lock);
1794 return PTR_ERR(rl2);
1797 * There is not enough space to do the allocation, but there
1798 * might be enough space to do a minimal allocation so try that
1802 ntfs_debug("Retrying mft data allocation with minimal cluster "
1803 "count %lli.", (long long)nr);
1805 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1807 up_write(&mft_ni->runlist.lock);
1808 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1810 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1811 ntfs_error(vol->sb, "Failed to dealocate clusters "
1812 "from the mft data attribute.%s", es);
1818 mft_ni->runlist.rl = rl;
1819 ntfs_debug("Allocated %lli clusters.", (long long)nr);
1820 /* Find the last run in the new runlist. */
1821 for (; rl[1].length; rl++)
1823 /* Update the attribute record as well. */
1824 mrec = map_mft_record(mft_ni);
1826 ntfs_error(vol->sb, "Failed to map mft record.");
1827 ret = PTR_ERR(mrec);
1830 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1831 if (unlikely(!ctx)) {
1832 ntfs_error(vol->sb, "Failed to get search context.");
1836 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1837 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1838 if (unlikely(ret)) {
1839 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1840 "mft data attribute.");
1846 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1847 /* Search back for the previous last allocated cluster of mft bitmap. */
1848 for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1852 BUG_ON(ll < rl2->vcn);
1853 BUG_ON(ll >= rl2->vcn + rl2->length);
1854 /* Get the size for the new mapping pairs array for this extent. */
1855 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1856 if (unlikely(mp_size <= 0)) {
1857 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1858 "mft data attribute extent.");
1864 /* Expand the attribute record if necessary. */
1865 old_alen = le32_to_cpu(a->length);
1866 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1867 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1868 if (unlikely(ret)) {
1869 if (ret != -ENOSPC) {
1870 ntfs_error(vol->sb, "Failed to resize attribute "
1871 "record for mft data attribute.");
1874 // TODO: Deal with this by moving this extent to a new mft
1875 // record or by starting a new extent in a new mft record or by
1876 // moving other attributes out of this mft record.
1877 // Note: Use the special reserved mft records and ensure that
1878 // this extent is not required to find the mft record in
1879 // question. If no free special records left we would need to
1880 // move an existing record away, insert ours in its place, and
1881 // then place the moved record into the newly allocated space
1882 // and we would then need to update all references to this mft
1883 // record appropriately. This is rather complicated...
1884 ntfs_error(vol->sb, "Not enough space in this mft record to "
1885 "accomodate extended mft data attribute "
1886 "extent. Cannot handle this yet.");
1891 /* Generate the mapping pairs array directly into the attr record. */
1892 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1893 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1894 mp_size, rl2, ll, -1, NULL);
1895 if (unlikely(ret)) {
1896 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1897 "mft data attribute.");
1900 /* Update the highest_vcn. */
1901 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1903 * We now have extended the mft data allocated_size by nr clusters.
1904 * Reflect this in the ntfs_inode structure and the attribute record.
1905 * @rl is the last (non-terminator) runlist element of mft data
1908 if (a->data.non_resident.lowest_vcn) {
1910 * We are not in the first attribute extent, switch to it, but
1911 * first ensure the changes will make it to disk later.
1913 flush_dcache_mft_record_page(ctx->ntfs_ino);
1914 mark_mft_record_dirty(ctx->ntfs_ino);
1915 ntfs_attr_reinit_search_ctx(ctx);
1916 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1917 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1919 if (unlikely(ret)) {
1920 ntfs_error(vol->sb, "Failed to find first attribute "
1921 "extent of mft data attribute.");
1922 goto restore_undo_alloc;
1926 write_lock_irqsave(&mft_ni->size_lock, flags);
1927 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1928 a->data.non_resident.allocated_size =
1929 cpu_to_sle64(mft_ni->allocated_size);
1930 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1931 /* Ensure the changes make it to disk. */
1932 flush_dcache_mft_record_page(ctx->ntfs_ino);
1933 mark_mft_record_dirty(ctx->ntfs_ino);
1934 ntfs_attr_put_search_ctx(ctx);
1935 unmap_mft_record(mft_ni);
1936 up_write(&mft_ni->runlist.lock);
1937 ntfs_debug("Done.");
1940 ntfs_attr_reinit_search_ctx(ctx);
1941 if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1942 CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1943 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1944 "mft data attribute.%s", es);
1945 write_lock_irqsave(&mft_ni->size_lock, flags);
1946 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1947 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1948 ntfs_attr_put_search_ctx(ctx);
1949 unmap_mft_record(mft_ni);
1950 up_write(&mft_ni->runlist.lock);
1952 * The only thing that is now wrong is ->allocated_size of the
1953 * base attribute extent which chkdsk should be able to fix.
1958 ctx->attr->data.non_resident.highest_vcn =
1959 cpu_to_sle64(old_last_vcn - 1);
1961 if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
1962 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1963 "attribute.%s", es);
1967 if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1968 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1972 if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
1973 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1974 a->data.non_resident.mapping_pairs_offset),
1975 old_alen - le16_to_cpu(
1976 a->data.non_resident.mapping_pairs_offset),
1977 rl2, ll, -1, NULL)) {
1978 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1982 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1983 ntfs_error(vol->sb, "Failed to restore attribute "
1987 flush_dcache_mft_record_page(ctx->ntfs_ino);
1988 mark_mft_record_dirty(ctx->ntfs_ino);
1989 } else if (IS_ERR(ctx->mrec)) {
1990 ntfs_error(vol->sb, "Failed to restore attribute search "
1995 ntfs_attr_put_search_ctx(ctx);
1997 unmap_mft_record(mft_ni);
1998 up_write(&mft_ni->runlist.lock);
2003 * ntfs_mft_record_layout - layout an mft record into a memory buffer
2004 * @vol: volume to which the mft record will belong
2005 * @mft_no: mft reference specifying the mft record number
2006 * @m: destination buffer of size >= @vol->mft_record_size bytes
2008 * Layout an empty, unused mft record with the mft record number @mft_no into
2009 * the buffer @m. The volume @vol is needed because the mft record structure
2010 * was modified in NTFS 3.1 so we need to know which volume version this mft
2011 * record will be used on.
2013 * Return 0 on success and -errno on error.
2015 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2020 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2021 if (mft_no >= (1ll << 32)) {
2022 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2023 "maximum of 2^32.", (long long)mft_no);
2026 /* Start by clearing the whole mft record to gives us a clean slate. */
2027 memset(m, 0, vol->mft_record_size);
2028 /* Aligned to 2-byte boundary. */
2029 if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2030 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2032 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2034 * Set the NTFS 3.1+ specific fields while we know that the
2035 * volume version is 3.1+.
2038 m->mft_record_number = cpu_to_le32((u32)mft_no);
2040 m->magic = magic_FILE;
2041 if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2042 m->usa_count = cpu_to_le16(vol->mft_record_size /
2043 NTFS_BLOCK_SIZE + 1);
2045 m->usa_count = cpu_to_le16(1);
2046 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2047 "size. Setting usa_count to 1. If chkdsk "
2048 "reports this as corruption, please email "
2049 "linux-ntfs-dev@lists.sourceforge.net stating "
2050 "that you saw this message and that the "
2051 "modified filesystem created was corrupt. "
2054 /* Set the update sequence number to 1. */
2055 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2057 m->sequence_number = cpu_to_le16(1);
2060 * Place the attributes straight after the update sequence array,
2061 * aligned to 8-byte boundary.
2063 m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2064 (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2067 * Using attrs_offset plus eight bytes (for the termination attribute).
2068 * attrs_offset is already aligned to 8-byte boundary, so no need to
2071 m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2072 m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2073 m->base_mft_record = 0;
2074 m->next_attr_instance = 0;
2075 /* Add the termination attribute. */
2076 a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2079 ntfs_debug("Done.");
2084 * ntfs_mft_record_format - format an mft record on an ntfs volume
2085 * @vol: volume on which to format the mft record
2086 * @mft_no: mft record number to format
2088 * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2089 * mft record into the appropriate place of the mft data attribute. This is
2090 * used when extending the mft data attribute.
2092 * Return 0 on success and -errno on error.
2094 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2097 struct inode *mft_vi = vol->mft_ino;
2100 pgoff_t index, end_index;
2104 ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2106 * The index into the page cache and the offset within the page cache
2107 * page of the wanted mft record.
2109 index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2110 ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2111 /* The maximum valid index into the page cache for $MFT's data. */
2112 i_size = i_size_read(mft_vi);
2113 end_index = i_size >> PAGE_CACHE_SHIFT;
2114 if (unlikely(index >= end_index)) {
2115 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2116 (i_size & ~PAGE_CACHE_MASK))) {
2117 ntfs_error(vol->sb, "Tried to format non-existing mft "
2118 "record 0x%llx.", (long long)mft_no);
2122 /* Read, map, and pin the page containing the mft record. */
2123 page = ntfs_map_page(mft_vi->i_mapping, index);
2124 if (unlikely(IS_ERR(page))) {
2125 ntfs_error(vol->sb, "Failed to map page containing mft record "
2126 "to format 0x%llx.", (long long)mft_no);
2127 return PTR_ERR(page);
2130 BUG_ON(!PageUptodate(page));
2131 ClearPageUptodate(page);
2132 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2133 err = ntfs_mft_record_layout(vol, mft_no, m);
2134 if (unlikely(err)) {
2135 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2137 SetPageUptodate(page);
2139 ntfs_unmap_page(page);
2142 flush_dcache_page(page);
2143 SetPageUptodate(page);
2146 * Make sure the mft record is written out to disk. We could use
2147 * ilookup5() to check if an inode is in icache and so on but this is
2148 * unnecessary as ntfs_writepage() will write the dirty record anyway.
2150 mark_ntfs_record_dirty(page, ofs);
2151 ntfs_unmap_page(page);
2152 ntfs_debug("Done.");
2157 * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2158 * @vol: [IN] volume on which to allocate the mft record
2159 * @mode: [IN] mode if want a file or directory, i.e. base inode or 0
2160 * @base_ni: [IN] open base inode if allocating an extent mft record or NULL
2161 * @mrec: [OUT] on successful return this is the mapped mft record
2163 * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2165 * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2166 * direvctory inode, and allocate it at the default allocator position. In
2167 * this case @mode is the file mode as given to us by the caller. We in
2168 * particular use @mode to distinguish whether a file or a directory is being
2169 * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2171 * If @base_ni is not NULL make the allocated mft record an extent record,
2172 * allocate it starting at the mft record after the base mft record and attach
2173 * the allocated and opened ntfs inode to the base inode @base_ni. In this
2174 * case @mode must be 0 as it is meaningless for extent inodes.
2176 * You need to check the return value with IS_ERR(). If false, the function
2177 * was successful and the return value is the now opened ntfs inode of the
2178 * allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
2179 * and locked mft record. If IS_ERR() is true, the function failed and the
2180 * error code is obtained from PTR_ERR(return value). *@mrec is undefined in
2183 * Allocation strategy:
2185 * To find a free mft record, we scan the mft bitmap for a zero bit. To
2186 * optimize this we start scanning at the place specified by @base_ni or if
2187 * @base_ni is NULL we start where we last stopped and we perform wrap around
2188 * when we reach the end. Note, we do not try to allocate mft records below
2189 * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2190 * to 24 are special in that they are used for storing extension mft records
2191 * for the $DATA attribute of $MFT. This is required to avoid the possibility
2192 * of creating a runlist with a circular dependency which once written to disk
2193 * can never be read in again. Windows will only use records 16 to 24 for
2194 * normal files if the volume is completely out of space. We never use them
2195 * which means that when the volume is really out of space we cannot create any
2196 * more files while Windows can still create up to 8 small files. We can start
2197 * doing this at some later time, it does not matter much for now.
2199 * When scanning the mft bitmap, we only search up to the last allocated mft
2200 * record. If there are no free records left in the range 24 to number of
2201 * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2202 * create free mft records. We extend the allocated size of $MFT/$DATA by 16
2203 * records at a time or one cluster, if cluster size is above 16kiB. If there
2204 * is not sufficient space to do this, we try to extend by a single mft record
2205 * or one cluster, if cluster size is above the mft record size.
2207 * No matter how many mft records we allocate, we initialize only the first
2208 * allocated mft record, incrementing mft data size and initialized size
2209 * accordingly, open an ntfs_inode for it and return it to the caller, unless
2210 * there are less than 24 mft records, in which case we allocate and initialize
2211 * mft records until we reach record 24 which we consider as the first free mft
2212 * record for use by normal files.
2214 * If during any stage we overflow the initialized data in the mft bitmap, we
2215 * extend the initialized size (and data size) by 8 bytes, allocating another
2216 * cluster if required. The bitmap data size has to be at least equal to the
2217 * number of mft records in the mft, but it can be bigger, in which case the
2218 * superflous bits are padded with zeroes.
2220 * Thus, when we return successfully (IS_ERR() is false), we will have:
2221 * - initialized / extended the mft bitmap if necessary,
2222 * - initialized / extended the mft data if necessary,
2223 * - set the bit corresponding to the mft record being allocated in the
2225 * - opened an ntfs_inode for the allocated mft record, and we will have
2226 * - returned the ntfs_inode as well as the allocated mapped, pinned, and
2227 * locked mft record.
2229 * On error, the volume will be left in a consistent state and no record will
2230 * be allocated. If rolling back a partial operation fails, we may leave some
2231 * inconsistent metadata in which case we set NVolErrors() so the volume is
2232 * left dirty when unmounted.
2234 * Note, this function cannot make use of most of the normal functions, like
2235 * for example for attribute resizing, etc, because when the run list overflows
2236 * the base mft record and an attribute list is used, it is very important that
2237 * the extension mft records used to store the $DATA attribute of $MFT can be
2238 * reached without having to read the information contained inside them, as
2239 * this would make it impossible to find them in the first place after the
2240 * volume is unmounted. $MFT/$BITMAP probably does not need to follow this
2241 * rule because the bitmap is not essential for finding the mft records, but on
2242 * the other hand, handling the bitmap in this special way would make life
2243 * easier because otherwise there might be circular invocations of functions
2244 * when reading the bitmap.
2246 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2247 ntfs_inode *base_ni, MFT_RECORD **mrec)
2249 s64 ll, bit, old_data_initialized, old_data_size;
2250 unsigned long flags;
2253 ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2254 ntfs_attr_search_ctx *ctx;
2261 BOOL record_formatted = FALSE;
2264 ntfs_debug("Entering (allocating an extent mft record for "
2265 "base mft record 0x%llx).",
2266 (long long)base_ni->mft_no);
2267 /* @mode and @base_ni are mutually exclusive. */
2270 ntfs_debug("Entering (allocating a base mft record).");
2272 /* @mode and @base_ni are mutually exclusive. */
2274 /* We only support creation of normal files and directories. */
2275 if (!S_ISREG(mode) && !S_ISDIR(mode))
2276 return ERR_PTR(-EOPNOTSUPP);
2279 mft_ni = NTFS_I(vol->mft_ino);
2280 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2281 down_write(&vol->mftbmp_lock);
2282 bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2284 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2286 goto have_alloc_rec;
2288 if (bit != -ENOSPC) {
2289 up_write(&vol->mftbmp_lock);
2290 return ERR_PTR(bit);
2293 * No free mft records left. If the mft bitmap already covers more
2294 * than the currently used mft records, the next records are all free,
2295 * so we can simply allocate the first unused mft record.
2296 * Note: We also have to make sure that the mft bitmap at least covers
2297 * the first 24 mft records as they are special and whilst they may not
2298 * be in use, we do not allocate from them.
2300 read_lock_irqsave(&mft_ni->size_lock, flags);
2301 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2302 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2303 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2304 old_data_initialized = mftbmp_ni->initialized_size;
2305 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2306 if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2310 if (unlikely(bit >= (1ll << 32)))
2312 ntfs_debug("Found free record (#2), bit 0x%llx.",
2314 goto found_free_rec;
2317 * The mft bitmap needs to be expanded until it covers the first unused
2318 * mft record that we can allocate.
2319 * Note: The smallest mft record we allocate is mft record 24.
2321 bit = old_data_initialized << 3;
2322 if (unlikely(bit >= (1ll << 32)))
2324 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2325 old_data_size = mftbmp_ni->allocated_size;
2326 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2327 "data_size 0x%llx, initialized_size 0x%llx.",
2328 (long long)old_data_size,
2329 (long long)i_size_read(vol->mftbmp_ino),
2330 (long long)old_data_initialized);
2331 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2332 if (old_data_initialized + 8 > old_data_size) {
2333 /* Need to extend bitmap by one more cluster. */
2334 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2335 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2336 if (unlikely(err)) {
2337 up_write(&vol->mftbmp_lock);
2341 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2342 ntfs_debug("Status of mftbmp after allocation extension: "
2343 "allocated_size 0x%llx, data_size 0x%llx, "
2344 "initialized_size 0x%llx.",
2345 (long long)mftbmp_ni->allocated_size,
2346 (long long)i_size_read(vol->mftbmp_ino),
2347 (long long)mftbmp_ni->initialized_size);
2348 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2352 * We now have sufficient allocated space, extend the initialized_size
2353 * as well as the data_size if necessary and fill the new space with
2356 err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2357 if (unlikely(err)) {
2358 up_write(&vol->mftbmp_lock);
2362 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2363 ntfs_debug("Status of mftbmp after initialized extention: "
2364 "allocated_size 0x%llx, data_size 0x%llx, "
2365 "initialized_size 0x%llx.",
2366 (long long)mftbmp_ni->allocated_size,
2367 (long long)i_size_read(vol->mftbmp_ino),
2368 (long long)mftbmp_ni->initialized_size);
2369 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2371 ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2373 /* @bit is the found free mft record, allocate it in the mft bitmap. */
2374 ntfs_debug("At found_free_rec.");
2375 err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2376 if (unlikely(err)) {
2377 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2378 up_write(&vol->mftbmp_lock);
2381 ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2384 * The mft bitmap is now uptodate. Deal with mft data attribute now.
2385 * Note, we keep hold of the mft bitmap lock for writing until all
2386 * modifications to the mft data attribute are complete, too, as they
2387 * will impact decisions for mft bitmap and mft record allocation done
2388 * by a parallel allocation and if the lock is not maintained a
2389 * parallel allocation could allocate the same mft record as this one.
2391 ll = (bit + 1) << vol->mft_record_size_bits;
2392 read_lock_irqsave(&mft_ni->size_lock, flags);
2393 old_data_initialized = mft_ni->initialized_size;
2394 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2395 if (ll <= old_data_initialized) {
2396 ntfs_debug("Allocated mft record already initialized.");
2397 goto mft_rec_already_initialized;
2399 ntfs_debug("Initializing allocated mft record.");
2401 * The mft record is outside the initialized data. Extend the mft data
2402 * attribute until it covers the allocated record. The loop is only
2403 * actually traversed more than once when a freshly formatted volume is
2404 * first written to so it optimizes away nicely in the common case.
2406 read_lock_irqsave(&mft_ni->size_lock, flags);
2407 ntfs_debug("Status of mft data before extension: "
2408 "allocated_size 0x%llx, data_size 0x%llx, "
2409 "initialized_size 0x%llx.",
2410 (long long)mft_ni->allocated_size,
2411 (long long)i_size_read(vol->mft_ino),
2412 (long long)mft_ni->initialized_size);
2413 while (ll > mft_ni->allocated_size) {
2414 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2415 err = ntfs_mft_data_extend_allocation_nolock(vol);
2416 if (unlikely(err)) {
2417 ntfs_error(vol->sb, "Failed to extend mft data "
2419 goto undo_mftbmp_alloc_nolock;
2421 read_lock_irqsave(&mft_ni->size_lock, flags);
2422 ntfs_debug("Status of mft data after allocation extension: "
2423 "allocated_size 0x%llx, data_size 0x%llx, "
2424 "initialized_size 0x%llx.",
2425 (long long)mft_ni->allocated_size,
2426 (long long)i_size_read(vol->mft_ino),
2427 (long long)mft_ni->initialized_size);
2429 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2431 * Extend mft data initialized size (and data size of course) to reach
2432 * the allocated mft record, formatting the mft records allong the way.
2433 * Note: We only modify the ntfs_inode structure as that is all that is
2434 * needed by ntfs_mft_record_format(). We will update the attribute
2435 * record itself in one fell swoop later on.
2437 write_lock_irqsave(&mft_ni->size_lock, flags);
2438 old_data_initialized = mft_ni->initialized_size;
2439 old_data_size = vol->mft_ino->i_size;
2440 while (ll > mft_ni->initialized_size) {
2441 s64 new_initialized_size, mft_no;
2443 new_initialized_size = mft_ni->initialized_size +
2444 vol->mft_record_size;
2445 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2446 if (new_initialized_size > i_size_read(vol->mft_ino))
2447 i_size_write(vol->mft_ino, new_initialized_size);
2448 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2449 ntfs_debug("Initializing mft record 0x%llx.",
2451 err = ntfs_mft_record_format(vol, mft_no);
2452 if (unlikely(err)) {
2453 ntfs_error(vol->sb, "Failed to format mft record.");
2454 goto undo_data_init;
2456 write_lock_irqsave(&mft_ni->size_lock, flags);
2457 mft_ni->initialized_size = new_initialized_size;
2459 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2460 record_formatted = TRUE;
2461 /* Update the mft data attribute record to reflect the new sizes. */
2462 m = map_mft_record(mft_ni);
2464 ntfs_error(vol->sb, "Failed to map mft record.");
2466 goto undo_data_init;
2468 ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2469 if (unlikely(!ctx)) {
2470 ntfs_error(vol->sb, "Failed to get search context.");
2472 unmap_mft_record(mft_ni);
2473 goto undo_data_init;
2475 err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2476 CASE_SENSITIVE, 0, NULL, 0, ctx);
2477 if (unlikely(err)) {
2478 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2479 "mft data attribute.");
2480 ntfs_attr_put_search_ctx(ctx);
2481 unmap_mft_record(mft_ni);
2482 goto undo_data_init;
2485 read_lock_irqsave(&mft_ni->size_lock, flags);
2486 a->data.non_resident.initialized_size =
2487 cpu_to_sle64(mft_ni->initialized_size);
2488 a->data.non_resident.data_size =
2489 cpu_to_sle64(i_size_read(vol->mft_ino));
2490 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2491 /* Ensure the changes make it to disk. */
2492 flush_dcache_mft_record_page(ctx->ntfs_ino);
2493 mark_mft_record_dirty(ctx->ntfs_ino);
2494 ntfs_attr_put_search_ctx(ctx);
2495 unmap_mft_record(mft_ni);
2496 read_lock_irqsave(&mft_ni->size_lock, flags);
2497 ntfs_debug("Status of mft data after mft record initialization: "
2498 "allocated_size 0x%llx, data_size 0x%llx, "
2499 "initialized_size 0x%llx.",
2500 (long long)mft_ni->allocated_size,
2501 (long long)i_size_read(vol->mft_ino),
2502 (long long)mft_ni->initialized_size);
2503 BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2504 BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2505 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2506 mft_rec_already_initialized:
2508 * We can finally drop the mft bitmap lock as the mft data attribute
2509 * has been fully updated. The only disparity left is that the
2510 * allocated mft record still needs to be marked as in use to match the
2511 * set bit in the mft bitmap but this is actually not a problem since
2512 * this mft record is not referenced from anywhere yet and the fact
2513 * that it is allocated in the mft bitmap means that no-one will try to
2514 * allocate it either.
2516 up_write(&vol->mftbmp_lock);
2518 * We now have allocated and initialized the mft record. Calculate the
2519 * index of and the offset within the page cache page the record is in.
2521 index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2522 ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2523 /* Read, map, and pin the page containing the mft record. */
2524 page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2525 if (unlikely(IS_ERR(page))) {
2526 ntfs_error(vol->sb, "Failed to map page containing allocated "
2527 "mft record 0x%llx.", (long long)bit);
2528 err = PTR_ERR(page);
2529 goto undo_mftbmp_alloc;
2532 BUG_ON(!PageUptodate(page));
2533 ClearPageUptodate(page);
2534 m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2535 /* If we just formatted the mft record no need to do it again. */
2536 if (!record_formatted) {
2537 /* Sanity check that the mft record is really not in use. */
2538 if (ntfs_is_file_record(m->magic) &&
2539 (m->flags & MFT_RECORD_IN_USE)) {
2540 ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2541 "free in mft bitmap but is marked "
2542 "used itself. Corrupt filesystem. "
2543 "Unmount and run chkdsk.",
2546 SetPageUptodate(page);
2548 ntfs_unmap_page(page);
2550 goto undo_mftbmp_alloc;
2553 * We need to (re-)format the mft record, preserving the
2554 * sequence number if it is not zero as well as the update
2555 * sequence number if it is not zero or -1 (0xffff). This
2556 * means we do not need to care whether or not something went
2557 * wrong with the previous mft record.
2559 seq_no = m->sequence_number;
2560 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2561 err = ntfs_mft_record_layout(vol, bit, m);
2562 if (unlikely(err)) {
2563 ntfs_error(vol->sb, "Failed to layout allocated mft "
2564 "record 0x%llx.", (long long)bit);
2565 SetPageUptodate(page);
2567 ntfs_unmap_page(page);
2568 goto undo_mftbmp_alloc;
2571 m->sequence_number = seq_no;
2572 if (usn && le16_to_cpu(usn) != 0xffff)
2573 *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2575 /* Set the mft record itself in use. */
2576 m->flags |= MFT_RECORD_IN_USE;
2578 m->flags |= MFT_RECORD_IS_DIRECTORY;
2579 flush_dcache_page(page);
2580 SetPageUptodate(page);
2583 * Setup the base mft record in the extent mft record. This
2584 * completes initialization of the allocated extent mft record
2585 * and we can simply use it with map_extent_mft_record().
2587 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2590 * Allocate an extent inode structure for the new mft record,
2591 * attach it to the base inode @base_ni and map, pin, and lock
2592 * its, i.e. the allocated, mft record.
2594 m = map_extent_mft_record(base_ni, bit, &ni);
2596 ntfs_error(vol->sb, "Failed to map allocated extent "
2597 "mft record 0x%llx.", (long long)bit);
2599 /* Set the mft record itself not in use. */
2600 m->flags &= cpu_to_le16(
2601 ~le16_to_cpu(MFT_RECORD_IN_USE));
2602 flush_dcache_page(page);
2603 /* Make sure the mft record is written out to disk. */
2604 mark_ntfs_record_dirty(page, ofs);
2606 ntfs_unmap_page(page);
2607 goto undo_mftbmp_alloc;
2610 * Make sure the allocated mft record is written out to disk.
2611 * No need to set the inode dirty because the caller is going
2612 * to do that anyway after finishing with the new extent mft
2613 * record (e.g. at a minimum a new attribute will be added to
2616 mark_ntfs_record_dirty(page, ofs);
2619 * Need to unmap the page since map_extent_mft_record() mapped
2620 * it as well so we have it mapped twice at the moment.
2622 ntfs_unmap_page(page);
2625 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2626 * is set to 1 but the mft record->link_count is 0. The caller
2627 * needs to bear this in mind.
2629 vi = new_inode(vol->sb);
2630 if (unlikely(!vi)) {
2632 /* Set the mft record itself not in use. */
2633 m->flags &= cpu_to_le16(
2634 ~le16_to_cpu(MFT_RECORD_IN_USE));
2635 flush_dcache_page(page);
2636 /* Make sure the mft record is written out to disk. */
2637 mark_ntfs_record_dirty(page, ofs);
2639 ntfs_unmap_page(page);
2640 goto undo_mftbmp_alloc;
2644 * This is the optimal IO size (for stat), not the fs block
2647 vi->i_blksize = PAGE_CACHE_SIZE;
2649 * This is for checking whether an inode has changed w.r.t. a
2650 * file so that the file can be updated if necessary (compare
2655 /* The owner and group come from the ntfs volume. */
2656 vi->i_uid = vol->uid;
2657 vi->i_gid = vol->gid;
2659 /* Initialize the ntfs specific part of @vi. */
2660 ntfs_init_big_inode(vi);
2663 * Set the appropriate mode, attribute type, and name. For
2664 * directories, also setup the index values to the defaults.
2666 if (S_ISDIR(mode)) {
2667 vi->i_mode = S_IFDIR | S_IRWXUGO;
2668 vi->i_mode &= ~vol->dmask;
2670 NInoSetMstProtected(ni);
2671 ni->type = AT_INDEX_ALLOCATION;
2675 ni->itype.index.block_size = 4096;
2676 ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2677 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2678 if (vol->cluster_size <= ni->itype.index.block_size) {
2679 ni->itype.index.vcn_size = vol->cluster_size;
2680 ni->itype.index.vcn_size_bits =
2681 vol->cluster_size_bits;
2683 ni->itype.index.vcn_size = vol->sector_size;
2684 ni->itype.index.vcn_size_bits =
2685 vol->sector_size_bits;
2688 vi->i_mode = S_IFREG | S_IRWXUGO;
2689 vi->i_mode &= ~vol->fmask;
2696 vi->i_mode &= ~S_IWUGO;
2698 /* Set the inode times to the current time. */
2699 vi->i_atime = vi->i_mtime = vi->i_ctime =
2700 current_fs_time(vi->i_sb);
2702 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2703 * the call to ntfs_init_big_inode() below.
2708 /* Set the sequence number. */
2709 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2711 * Manually map, pin, and lock the mft record as we already
2712 * have its page mapped and it is very easy to do.
2714 atomic_inc(&ni->count);
2715 down(&ni->mrec_lock);
2719 * Make sure the allocated mft record is written out to disk.
2720 * NOTE: We do not set the ntfs inode dirty because this would
2721 * fail in ntfs_write_inode() because the inode does not have a
2722 * standard information attribute yet. Also, there is no need
2723 * to set the inode dirty because the caller is going to do
2724 * that anyway after finishing with the new mft record (e.g. at
2725 * a minimum some new attributes will be added to the mft
2728 mark_ntfs_record_dirty(page, ofs);
2731 /* Add the inode to the inode hash for the superblock. */
2732 insert_inode_hash(vi);
2734 /* Update the default mft allocation position. */
2735 vol->mft_data_pos = bit + 1;
2738 * Return the opened, allocated inode of the allocated mft record as
2739 * well as the mapped, pinned, and locked mft record.
2741 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2742 base_ni ? "extent " : "", (long long)bit);
2746 write_lock_irqsave(&mft_ni->size_lock, flags);
2747 mft_ni->initialized_size = old_data_initialized;
2748 i_size_write(vol->mft_ino, old_data_size);
2749 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2750 goto undo_mftbmp_alloc_nolock;
2752 down_write(&vol->mftbmp_lock);
2753 undo_mftbmp_alloc_nolock:
2754 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2755 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2758 up_write(&vol->mftbmp_lock);
2760 return ERR_PTR(err);
2762 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2763 "number of inodes (2^32) has already been reached.");
2764 up_write(&vol->mftbmp_lock);
2765 return ERR_PTR(-ENOSPC);
2769 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2770 * @ni: ntfs inode of the mapped extent mft record to free
2771 * @m: mapped extent mft record of the ntfs inode @ni
2773 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2775 * Note that this function unmaps the mft record and closes and destroys @ni
2776 * internally and hence you cannot use either @ni nor @m any more after this
2777 * function returns success.
2779 * On success return 0 and on error return -errno. @ni and @m are still valid
2780 * in this case and have not been freed.
2782 * For some errors an error message is displayed and the success code 0 is
2783 * returned and the volume is then left dirty on umount. This makes sense in
2784 * case we could not rollback the changes that were already done since the
2785 * caller no longer wants to reference this mft record so it does not matter to
2786 * the caller if something is wrong with it as long as it is properly detached
2787 * from the base inode.
2789 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2791 unsigned long mft_no = ni->mft_no;
2792 ntfs_volume *vol = ni->vol;
2793 ntfs_inode *base_ni;
2794 ntfs_inode **extent_nis;
2799 BUG_ON(NInoAttr(ni));
2800 BUG_ON(ni->nr_extents != -1);
2802 down(&ni->extent_lock);
2803 base_ni = ni->ext.base_ntfs_ino;
2804 up(&ni->extent_lock);
2806 BUG_ON(base_ni->nr_extents <= 0);
2808 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2809 mft_no, base_ni->mft_no);
2811 down(&base_ni->extent_lock);
2813 /* Make sure we are holding the only reference to the extent inode. */
2814 if (atomic_read(&ni->count) > 2) {
2815 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2816 "not freeing.", base_ni->mft_no);
2817 up(&base_ni->extent_lock);
2821 /* Dissociate the ntfs inode from the base inode. */
2822 extent_nis = base_ni->ext.extent_ntfs_inos;
2824 for (i = 0; i < base_ni->nr_extents; i++) {
2825 if (ni != extent_nis[i])
2828 base_ni->nr_extents--;
2829 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2830 sizeof(ntfs_inode*));
2835 up(&base_ni->extent_lock);
2837 if (unlikely(err)) {
2838 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2839 "its base inode 0x%lx.", mft_no,
2845 * The extent inode is no longer attached to the base inode so no one
2846 * can get a reference to it any more.
2849 /* Mark the mft record as not in use. */
2850 m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2852 /* Increment the sequence number, skipping zero, if it is not zero. */
2853 old_seq_no = m->sequence_number;
2854 seq_no = le16_to_cpu(old_seq_no);
2855 if (seq_no == 0xffff)
2859 m->sequence_number = cpu_to_le16(seq_no);
2862 * Set the ntfs inode dirty and write it out. We do not need to worry
2863 * about the base inode here since whatever caused the extent mft
2864 * record to be freed is guaranteed to do it already.
2867 err = write_mft_record(ni, m, 0);
2868 if (unlikely(err)) {
2869 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2870 "freeing.", mft_no);
2874 /* Unmap and throw away the now freed extent inode. */
2875 unmap_extent_mft_record(ni);
2876 ntfs_clear_extent_inode(ni);
2878 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2879 down_write(&vol->mftbmp_lock);
2880 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2881 up_write(&vol->mftbmp_lock);
2882 if (unlikely(err)) {
2884 * The extent inode is gone but we failed to deallocate it in
2885 * the mft bitmap. Just emit a warning and leave the volume
2888 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2893 /* Rollback what we did... */
2894 down(&base_ni->extent_lock);
2895 extent_nis = base_ni->ext.extent_ntfs_inos;
2896 if (!(base_ni->nr_extents & 3)) {
2897 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2899 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2900 if (unlikely(!extent_nis)) {
2901 ntfs_error(vol->sb, "Failed to allocate internal "
2902 "buffer during rollback.%s", es);
2903 up(&base_ni->extent_lock);
2905 goto rollback_error;
2907 if (base_ni->nr_extents) {
2908 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2909 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2910 new_size - 4 * sizeof(ntfs_inode*));
2911 kfree(base_ni->ext.extent_ntfs_inos);
2913 base_ni->ext.extent_ntfs_inos = extent_nis;
2915 m->flags |= MFT_RECORD_IN_USE;
2916 m->sequence_number = old_seq_no;
2917 extent_nis[base_ni->nr_extents++] = ni;
2918 up(&base_ni->extent_lock);
2919 mark_mft_record_dirty(ni);
2922 #endif /* NTFS_RW */