]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - fs/ntfs/mft.c
NTFS: Remove all the make_bad_inode() calls. This should only be called
[linux-2.6.git] / fs / ntfs / mft.c
1 /**
2  * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2001-2006 Anton Altaparmakov
5  * Copyright (c) 2002 Richard Russon
6  *
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.
11  *
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.
16  *
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
21  */
22
23 #include <linux/buffer_head.h>
24 #include <linux/swap.h>
25
26 #include "attrib.h"
27 #include "aops.h"
28 #include "bitmap.h"
29 #include "debug.h"
30 #include "dir.h"
31 #include "lcnalloc.h"
32 #include "malloc.h"
33 #include "mft.h"
34 #include "ntfs.h"
35
36 /**
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
39  *
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.
42  *
43  * Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
44  * contains the negative error code returned.
45  */
46 static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
47 {
48         loff_t i_size;
49         ntfs_volume *vol = ni->vol;
50         struct inode *mft_vi = vol->mft_ino;
51         struct page *page;
52         unsigned long index, end_index;
53         unsigned ofs;
54
55         BUG_ON(ni->page);
56         /*
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...
61          */
62         index = (u64)ni->mft_no << vol->mft_record_size_bits >>
63                         PAGE_CACHE_SHIFT;
64         ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
65
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;
69
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);
79                         goto err_out;
80                 }
81         }
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) +
87                                 ofs)))) {
88                         ni->page = page;
89                         ni->page_ofs = ofs;
90                         return page_address(page) + ofs;
91                 }
92                 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt.  "
93                                 "Run chkdsk.", ni->mft_no);
94                 ntfs_unmap_page(page);
95                 page = ERR_PTR(-EIO);
96                 NVolSetErrors(vol);
97         }
98 err_out:
99         ni->page = NULL;
100         ni->page_ofs = 0;
101         return (void*)page;
102 }
103
104 /**
105  * map_mft_record - map, pin and lock an mft record
106  * @ni:         ntfs inode whose MFT record to map
107  *
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.
110  *
111  * The page of the record is mapped using map_mft_record_page() before being
112  * returned to the caller.
113  *
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).
118  *
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.
127  *
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.
135  *
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.
142  *
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
145  * the error code.
146  *
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
152  * write it out.
153  */
154 MFT_RECORD *map_mft_record(ntfs_inode *ni)
155 {
156         MFT_RECORD *m;
157
158         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
159
160         /* Make sure the ntfs inode doesn't go away. */
161         atomic_inc(&ni->count);
162
163         /* Serialize access to this mft record. */
164         down(&ni->mrec_lock);
165
166         m = map_mft_record_page(ni);
167         if (likely(!IS_ERR(m)))
168                 return m;
169
170         up(&ni->mrec_lock);
171         atomic_dec(&ni->count);
172         ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
173         return m;
174 }
175
176 /**
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
179  *
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.
182  *
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.
185  *
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
188  * whatever.
189  */
190 static inline void unmap_mft_record_page(ntfs_inode *ni)
191 {
192         BUG_ON(!ni->page);
193
194         // TODO: If dirty, blah...
195         ntfs_unmap_page(ni->page);
196         ni->page = NULL;
197         ni->page_ofs = 0;
198         return;
199 }
200
201 /**
202  * unmap_mft_record - release a mapped mft record
203  * @ni:         ntfs inode whose MFT record to unmap
204  *
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.
208  *
209  * NOTE: If caller has modified the mft record, it is imperative to set the mft
210  * record dirty BEFORE calling unmap_mft_record().
211  */
212 void unmap_mft_record(ntfs_inode *ni)
213 {
214         struct page *page = ni->page;
215
216         BUG_ON(!page);
217
218         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
219
220         unmap_mft_record_page(ni);
221         up(&ni->mrec_lock);
222         atomic_dec(&ni->count);
223         /*
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.
228          */
229         return;
230 }
231
232 /**
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
237  *
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.
241  *
242  * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
243  * structure of the mapped extent inode.
244  */
245 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
246                 ntfs_inode **ntfs_ino)
247 {
248         MFT_RECORD *m;
249         ntfs_inode *ni = NULL;
250         ntfs_inode **extent_nis = NULL;
251         int i;
252         unsigned long mft_no = MREF(mref);
253         u16 seq_no = MSEQNO(mref);
254         BOOL destroy_ni = FALSE;
255
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);
260         /*
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.
264          */
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)
270                                 continue;
271                         ni = extent_nis[i];
272                         /* Make sure the ntfs inode doesn't go away. */
273                         atomic_inc(&ni->count);
274                         break;
275                 }
276         }
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.");
288                                 *ntfs_ino = ni;
289                                 return m;
290                         }
291                         unmap_mft_record(ni);
292                         ntfs_error(base_ni->vol->sb, "Found stale extent mft "
293                                         "reference! Corrupt filesystem. "
294                                         "Run chkdsk.");
295                         return ERR_PTR(-EIO);
296                 }
297 map_err_out:
298                 ntfs_error(base_ni->vol->sb, "Failed to map extent "
299                                 "mft record, error code %ld.", -PTR_ERR(m));
300                 return m;
301         }
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);
304         if (unlikely(!ni)) {
305                 up(&base_ni->extent_lock);
306                 atomic_dec(&base_ni->count);
307                 return ERR_PTR(-ENOMEM);
308         }
309         ni->vol = base_ni->vol;
310         ni->seq_no = seq_no;
311         ni->nr_extents = -1;
312         ni->ext.base_ntfs_ino = base_ni;
313         /* Now map the record. */
314         m = map_mft_record(ni);
315         if (IS_ERR(m)) {
316                 up(&base_ni->extent_lock);
317                 atomic_dec(&base_ni->count);
318                 ntfs_clear_extent_inode(ni);
319                 goto map_err_out;
320         }
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.");
325                 destroy_ni = TRUE;
326                 m = ERR_PTR(-EIO);
327                 goto unm_err_out;
328         }
329         /* Attach extent inode to base inode, reallocating memory if needed. */
330         if (!(base_ni->nr_extents & 3)) {
331                 ntfs_inode **tmp;
332                 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
333
334                 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
335                 if (unlikely(!tmp)) {
336                         ntfs_error(base_ni->vol->sb, "Failed to allocate "
337                                         "internal buffer.");
338                         destroy_ni = TRUE;
339                         m = ERR_PTR(-ENOMEM);
340                         goto unm_err_out;
341                 }
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);
347                 }
348                 base_ni->ext.extent_ntfs_inos = tmp;
349         }
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.");
354         *ntfs_ino = ni;
355         return m;
356 unm_err_out:
357         unmap_mft_record(ni);
358         up(&base_ni->extent_lock);
359         atomic_dec(&base_ni->count);
360         /*
361          * If the extent inode was not attached to the base inode we need to
362          * release it or we will leak memory.
363          */
364         if (destroy_ni)
365                 ntfs_clear_extent_inode(ni);
366         return m;
367 }
368
369 #ifdef NTFS_RW
370
371 /**
372  * __mark_mft_record_dirty - set the mft record and the page containing it dirty
373  * @ni:         ntfs inode describing the mapped mft record
374  *
375  * Internal function.  Users should call mark_mft_record_dirty() instead.
376  *
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.
381  *
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
393  * would suggest.
394  */
395 void __mark_mft_record_dirty(ntfs_inode *ni)
396 {
397         ntfs_inode *base_ni;
398
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))
405                 base_ni = ni;
406         else
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);
410 }
411
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.";
415
416 /**
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
421  *
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.
425  *
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.
429  *
430  * On success return 0.  On error return -errno.
431  *
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
436  * and Oops.
437  */
438 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
439                 const unsigned long mft_no, MFT_RECORD *m)
440 {
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);
444         return -EOPNOTSUPP;
445 }
446
447 /**
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
453  *
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.
456  *
457  * On success return 0.  On error return -errno and set the volume errors flag
458  * in the ntfs volume @vol.
459  *
460  * NOTE:  We always perform synchronous i/o and ignore the @sync parameter.
461  *
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.
464  */
465 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
466                 MFT_RECORD *m, int sync)
467 {
468         struct page *page;
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;
473         u8 *kmirr;
474         runlist_element *rl;
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;
478
479         ntfs_debug("Entering for inode 0x%lx.", mft_no);
480         BUG_ON(!max_bhs);
481         if (unlikely(!vol->mftmirr_ino)) {
482                 /* This could happen during umount... */
483                 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
484                 if (likely(!err))
485                         return err;
486                 goto err_out;
487         }
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));
491         if (IS_ERR(page)) {
492                 ntfs_error(vol->sb, "Failed to map mft mirror page.");
493                 err = PTR_ERR(page);
494                 goto err_out;
495         }
496         lock_page(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;
508
509                 bh = head = alloc_page_buffers(page, blocksize, 1);
510                 do {
511                         set_buffer_uptodate(bh);
512                         tail = bh;
513                         bh = bh->b_this_page;
514                 } while (bh);
515                 tail->b_this_page = head;
516                 attach_page_buffers(page, head);
517         }
518         bh = head = page_buffers(page);
519         BUG_ON(!bh);
520         rl = NULL;
521         nr_bhs = 0;
522         block_start = 0;
523         m_start = kmirr - (u8*)page_address(page);
524         m_end = m_start + vol->mft_record_size;
525         do {
526                 block_end = block_start + blocksize;
527                 /* If the buffer is outside the mft record, skip it. */
528                 if (block_end <= m_start)
529                         continue;
530                 if (unlikely(block_start >= m_end))
531                         break;
532                 /* Need to map the buffer if it is not mapped already. */
533                 if (unlikely(!buffer_mapped(bh))) {
534                         VCN vcn;
535                         LCN lcn;
536                         unsigned int vcn_ofs;
537
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;
544                         if (!rl) {
545                                 down_read(&NTFS_I(vol->mftmirr_ino)->
546                                                 runlist.lock);
547                                 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
548                                 /*
549                                  * $MFTMirr always has the whole of its runlist
550                                  * in memory.
551                                  */
552                                 BUG_ON(!rl);
553                         }
554                         /* Seek to element containing target vcn. */
555                         while (rl->length && rl[1].vcn <= vcn)
556                                 rl++;
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);
565                         } else {
566                                 bh->b_blocknr = -1;
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 "
571                                                 "%lli).", mft_no,
572                                                 (long long)lcn);
573                                 err = -EIO;
574                         }
575                 }
576                 BUG_ON(!buffer_uptodate(bh));
577                 BUG_ON(!nr_bhs && (m_start != block_start));
578                 BUG_ON(nr_bhs >= max_bhs);
579                 bhs[nr_bhs++] = bh;
580                 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
581         } while (block_start = block_end, (bh = bh->b_this_page) != head);
582         if (unlikely(rl))
583                 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
584         if (likely(!err)) {
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];
588
589                         if (unlikely(test_set_buffer_locked(tbh)))
590                                 BUG();
591                         BUG_ON(!buffer_uptodate(tbh));
592                         clear_buffer_dirty(tbh);
593                         get_bh(tbh);
594                         tbh->b_end_io = end_buffer_write_sync;
595                         submit_bh(WRITE, tbh);
596                 }
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];
600
601                         wait_on_buffer(tbh);
602                         if (unlikely(!buffer_uptodate(tbh))) {
603                                 err = -EIO;
604                                 /*
605                                  * Set the buffer uptodate so the page and
606                                  * buffer states do not become out of sync.
607                                  */
608                                 set_buffer_uptodate(tbh);
609                         }
610                 }
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]);
615         }
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);
621         unlock_page(page);
622         ntfs_unmap_page(page);
623         if (likely(!err)) {
624                 ntfs_debug("Done.");
625         } else {
626                 ntfs_error(vol->sb, "I/O error while writing mft mirror "
627                                 "record 0x%lx!", mft_no);
628 err_out:
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);
633                 NVolSetErrors(vol);
634         }
635         return err;
636 }
637
638 /**
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
643  *
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.
647  *
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().
652  *
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.
658  *
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.
668  *
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.
671  */
672 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
673 {
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;
681         runlist_element *rl;
682         unsigned int block_start, block_end, m_start, m_end;
683         int i_bhs, nr_bhs, err = 0;
684
685         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
686         BUG_ON(NInoAttr(ni));
687         BUG_ON(!max_bhs);
688         BUG_ON(!PageLocked(page));
689         /*
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.
694          */
695         if (!NInoTestClearDirty(ni))
696                 goto done;
697         bh = head = page_buffers(page);
698         BUG_ON(!bh);
699         rl = NULL;
700         nr_bhs = 0;
701         block_start = 0;
702         m_start = ni->page_ofs;
703         m_end = m_start + vol->mft_record_size;
704         do {
705                 block_end = block_start + blocksize;
706                 /* If the buffer is outside the mft record, skip it. */
707                 if (block_end <= m_start)
708                         continue;
709                 if (unlikely(block_start >= m_end))
710                         break;
711                 /*
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().
715                  */
716                 if (block_start == m_start) {
717                         /* This block is the first one in the record. */
718                         if (!buffer_dirty(bh)) {
719                                 BUG_ON(nr_bhs);
720                                 /* Clean records are not written out. */
721                                 break;
722                         }
723                 }
724                 /* Need to map the buffer if it is not mapped already. */
725                 if (unlikely(!buffer_mapped(bh))) {
726                         VCN vcn;
727                         LCN lcn;
728                         unsigned int vcn_ofs;
729
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;
736                         if (!rl) {
737                                 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
738                                 rl = NTFS_I(vol->mft_ino)->runlist.rl;
739                                 BUG_ON(!rl);
740                         }
741                         /* Seek to element containing target vcn. */
742                         while (rl->length && rl[1].vcn <= vcn)
743                                 rl++;
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);
752                         } else {
753                                 bh->b_blocknr = -1;
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);
759                                 err = -EIO;
760                         }
761                 }
762                 BUG_ON(!buffer_uptodate(bh));
763                 BUG_ON(!nr_bhs && (m_start != block_start));
764                 BUG_ON(nr_bhs >= max_bhs);
765                 bhs[nr_bhs++] = bh;
766                 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
767         } while (block_start = block_end, (bh = bh->b_this_page) != head);
768         if (unlikely(rl))
769                 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
770         if (!nr_bhs)
771                 goto done;
772         if (unlikely(err))
773                 goto cleanup_out;
774         /* Apply the mst protection fixups. */
775         err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
776         if (err) {
777                 ntfs_error(vol->sb, "Failed to apply mst fixups!");
778                 goto cleanup_out;
779         }
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];
784
785                 if (unlikely(test_set_buffer_locked(tbh)))
786                         BUG();
787                 BUG_ON(!buffer_uptodate(tbh));
788                 clear_buffer_dirty(tbh);
789                 get_bh(tbh);
790                 tbh->b_end_io = end_buffer_write_sync;
791                 submit_bh(WRITE, tbh);
792         }
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];
799
800                 wait_on_buffer(tbh);
801                 if (unlikely(!buffer_uptodate(tbh))) {
802                         err = -EIO;
803                         /*
804                          * Set the buffer uptodate so the page and buffer
805                          * states do not become out of sync.
806                          */
807                         if (PageUptodate(page))
808                                 set_buffer_uptodate(tbh);
809                 }
810         }
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);
817         if (unlikely(err)) {
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.",
822                                 ni->mft_no);
823                 goto err_out;
824         }
825 done:
826         ntfs_debug("Done.");
827         return 0;
828 cleanup_out:
829         /* Clean the buffers. */
830         for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
831                 clear_buffer_dirty(bhs[i_bhs]);
832 err_out:
833         /*
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.
838          */
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);
843                 err = 0;
844         } else
845                 NVolSetErrors(vol);
846         return err;
847 }
848
849 /**
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
855  *
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
861  * vfs inode.
862  *
863  * Return TRUE if the mft record may be written out and FALSE if not.
864  *
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.
870  *
871  * Here is a description of the tests we perform:
872  *
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
879  * mft record.)
880  *
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.
884  *
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.
888  *
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).
893  *
894  * If the inode is not in icache we need to perform further checks.
895  *
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.
898  *
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.
902  *
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.
906  *
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.
910  *
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.
915  *
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
926  * out.
927  */
928 BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
929                 const MFT_RECORD *m, ntfs_inode **locked_ni)
930 {
931         struct super_block *sb = vol->sb;
932         struct inode *mft_vi = vol->mft_ino;
933         struct inode *vi;
934         ntfs_inode *ni, *eni, **extent_nis;
935         int i;
936         ntfs_attr na;
937
938         ntfs_debug("Entering for inode 0x%lx.", mft_no);
939         /*
940          * Normally we do not return a locked inode so set @locked_ni to NULL.
941          */
942         BUG_ON(!locked_ni);
943         *locked_ni = NULL;
944         /*
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.
947          */
948         ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
949         na.mft_no = mft_no;
950         na.name = NULL;
951         na.name_len = 0;
952         na.type = AT_UNUSED;
953         /*
954          * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
955          * we get here for it rather often.
956          */
957         if (!mft_no) {
958                 /* Balance the below iput(). */
959                 vi = igrab(mft_vi);
960                 BUG_ON(vi != mft_vi);
961         } else {
962                 /*
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
967                  * $MFT occurs.
968                  */
969                 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
970         }
971         if (vi) {
972                 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
973                 /* The inode is in icache. */
974                 ni = NTFS_I(vi);
975                 /* Take a reference to the ntfs inode. */
976                 atomic_inc(&ni->count);
977                 /* If the inode is dirty, do not write this record. */
978                 if (NInoDirty(ni)) {
979                         ntfs_debug("Inode 0x%lx is dirty, do not write it.",
980                                         mft_no);
981                         atomic_dec(&ni->count);
982                         iput(vi);
983                         return FALSE;
984                 }
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);
991                         iput(vi);
992                         return FALSE;
993                 }
994                 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
995                                 mft_no);
996                 /*
997                  * The write has to occur while we hold the mft record lock so
998                  * return the locked ntfs inode.
999                  */
1000                 *locked_ni = ni;
1001                 return TRUE;
1002         }
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.",
1008                                 mft_no);
1009                 return TRUE;
1010         }
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.",
1014                                 mft_no);
1015                 return TRUE;
1016         }
1017         /*
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
1020          * is.
1021          */
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);
1025         if (!na.mft_no) {
1026                 /* Balance the below iput(). */
1027                 vi = igrab(mft_vi);
1028                 BUG_ON(vi != mft_vi);
1029         } else
1030                 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1031                                 &na);
1032         if (!vi) {
1033                 /*
1034                  * The base inode is not in icache, write this extent mft
1035                  * record.
1036                  */
1037                 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1038                                 "extent record.", na.mft_no);
1039                 return TRUE;
1040         }
1041         ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1042         /*
1043          * The base inode is in icache.  Check if it has the extent inode
1044          * corresponding to this extent mft record attached.
1045          */
1046         ni = NTFS_I(vi);
1047         down(&ni->extent_lock);
1048         if (ni->nr_extents <= 0) {
1049                 /*
1050                  * The base inode has no attached extent inodes, write this
1051                  * extent mft record.
1052                  */
1053                 up(&ni->extent_lock);
1054                 iput(vi);
1055                 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1056                                 "write the extent record.", na.mft_no);
1057                 return TRUE;
1058         }
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) {
1063                         /*
1064                          * Found the extent inode corresponding to this extent
1065                          * mft record.
1066                          */
1067                         eni = extent_nis[i];
1068                         break;
1069                 }
1070         }
1071         /*
1072          * If the extent inode was not attached to the base inode, write this
1073          * extent mft record.
1074          */
1075         if (!eni) {
1076                 up(&ni->extent_lock);
1077                 iput(vi);
1078                 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1079                                 "inode 0x%lx, write the extent record.",
1080                                 mft_no, na.mft_no);
1081                 return TRUE;
1082         }
1083         ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1084                         mft_no, na.mft_no);
1085         /* Take a reference to the extent ntfs inode. */
1086         atomic_inc(&eni->count);
1087         up(&ni->extent_lock);
1088         /*
1089          * Found the extent inode coresponding to this extent mft record.
1090          * Try to take the mft record lock.
1091          */
1092         if (unlikely(down_trylock(&eni->mrec_lock))) {
1093                 atomic_dec(&eni->count);
1094                 iput(vi);
1095                 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1096                                 "not write it.", mft_no);
1097                 return FALSE;
1098         }
1099         ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1100                         mft_no);
1101         if (NInoTestClearDirty(eni))
1102                 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1103                                 mft_no);
1104         /*
1105          * The write has to occur while we hold the mft record lock so return
1106          * the locked extent ntfs inode.
1107          */
1108         *locked_ni = eni;
1109         return TRUE;
1110 }
1111
1112 static const char *es = "  Leaving inconsistent metadata.  Unmount and run "
1113                 "chkdsk.";
1114
1115 /**
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
1119  *
1120  * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1121  * @vol.
1122  *
1123  * If @base_ni is NULL start the search at the default allocator position.
1124  *
1125  * If @base_ni is not NULL start the search at the mft record after the base
1126  * mft record @base_ni.
1127  *
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.
1131  *
1132  * Locking: Caller must hold vol->mftbmp_lock for writing.
1133  */
1134 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1135                 ntfs_inode *base_ni)
1136 {
1137         s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1138         unsigned long flags;
1139         struct address_space *mftbmp_mapping;
1140         u8 *buf, *byte;
1141         struct page *page;
1142         unsigned int page_ofs, size;
1143         u8 pass, b;
1144
1145         ntfs_debug("Searching for free mft record in the currently "
1146                         "initialized mft bitmap.");
1147         mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1148         /*
1149          * Set the end of the pass making sure we do not overflow the mft
1150          * bitmap.
1151          */
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);
1159         if (pass_end > ll)
1160                 pass_end = ll;
1161         pass = 1;
1162         if (!base_ni)
1163                 data_pos = vol->mft_data_pos;
1164         else
1165                 data_pos = base_ni->mft_no + 1;
1166         if (data_pos < 24)
1167                 data_pos = 24;
1168         if (data_pos >= pass_end) {
1169                 data_pos = 24;
1170                 pass = 2;
1171                 /* This happens on a freshly formatted volume. */
1172                 if (data_pos >= pass_end)
1173                         return -ENOSPC;
1174         }
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;
1187                 if (size > ll)
1188                         size = ll;
1189                 size <<= 3;
1190                 /*
1191                  * If we are still within the active pass, search the next page
1192                  * for a zero bit.
1193                  */
1194                 if (size) {
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);
1201                         }
1202                         buf = (u8*)page_address(page) + page_ofs;
1203                         bit = data_pos & 7;
1204                         data_pos &= ~7ull;
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);
1211                                 if (*byte == 0xff)
1212                                         continue;
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);
1218                                                 return -ENOSPC;
1219                                         }
1220                                         *byte |= 1 << b;
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 "
1226                                                         "0x%llx.)",
1227                                                         (long long)ll);
1228                                         return ll;
1229                                 }
1230                         }
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);
1234                         data_pos += size;
1235                         ntfs_unmap_page(page);
1236                         /*
1237                          * If the end of the pass has not been reached yet,
1238                          * continue searching the mft bitmap for a zero bit.
1239                          */
1240                         if (data_pos < pass_end)
1241                                 continue;
1242                 }
1243                 /* Do the next pass. */
1244                 if (++pass == 2) {
1245                         /*
1246                          * Starting the second pass, in which we scan the first
1247                          * part of the zone which we omitted earlier.
1248                          */
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)
1255                                 break;
1256                 }
1257         }
1258         /* No free mft records in currently initialized mft bitmap. */
1259         ntfs_debug("Done.  (No free mft records left in currently initialized "
1260                         "mft bitmap.)");
1261         return -ENOSPC;
1262 }
1263
1264 /**
1265  * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1266  * @vol:        volume on which to extend the mft bitmap attribute
1267  *
1268  * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1269  *
1270  * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1271  * data_size.
1272  *
1273  * Return 0 on success and -errno on error.
1274  *
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
1279  *            before returning.
1280  */
1281 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1282 {
1283         LCN lcn;
1284         s64 ll;
1285         unsigned long flags;
1286         struct page *page;
1287         ntfs_inode *mft_ni, *mftbmp_ni;
1288         runlist_element *rl, *rl2 = NULL;
1289         ntfs_attr_search_ctx *ctx = NULL;
1290         MFT_RECORD *mrec;
1291         ATTR_RECORD *a = NULL;
1292         int ret, mp_size;
1293         u32 old_alen = 0;
1294         u8 *b, tb;
1295         struct {
1296                 u8 added_cluster:1;
1297                 u8 added_run:1;
1298                 u8 mp_rebuilt:1;
1299         } status = { 0, 0, 0 };
1300
1301         ntfs_debug("Extending mft bitmap allocation.");
1302         mft_ni = NTFS_I(vol->mft_ino);
1303         mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1304         /*
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.
1307          */
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.");
1318                 if (!IS_ERR(rl))
1319                         ret = -EIO;
1320                 else
1321                         ret = PTR_ERR(rl);
1322                 return ret;
1323         }
1324         lcn = rl->lcn + rl->length;
1325         ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1326                         (long long)lcn);
1327         /*
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
1330          * to us.
1331          */
1332         ll = lcn >> 3;
1333         page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1334                         ll >> PAGE_CACHE_SHIFT);
1335         if (IS_ERR(page)) {
1336                 up_write(&mftbmp_ni->runlist.lock);
1337                 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1338                 return PTR_ERR(page);
1339         }
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. */
1345                 *b |= tb;
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. */
1351                 rl->length++;
1352                 rl[1].vcn++;
1353                 status.added_cluster = 1;
1354                 ntfs_debug("Appending one cluster to mft bitmap.");
1355         } else {
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,
1360                                 TRUE);
1361                 if (IS_ERR(rl2)) {
1362                         up_write(&mftbmp_ni->runlist.lock);
1363                         ntfs_error(vol->sb, "Failed to allocate a cluster for "
1364                                         "the mft bitmap.");
1365                         return PTR_ERR(rl2);
1366                 }
1367                 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1368                 if (IS_ERR(rl)) {
1369                         up_write(&mftbmp_ni->runlist.lock);
1370                         ntfs_error(vol->sb, "Failed to merge runlists for mft "
1371                                         "bitmap.");
1372                         if (ntfs_cluster_free_from_rl(vol, rl2)) {
1373                                 ntfs_error(vol->sb, "Failed to dealocate "
1374                                                 "allocated cluster.%s", es);
1375                                 NVolSetErrors(vol);
1376                         }
1377                         ntfs_free(rl2);
1378                         return PTR_ERR(rl);
1379                 }
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++)
1385                         ;
1386         }
1387         /*
1388          * Update the attribute record as well.  Note: @rl is the last
1389          * (non-terminator) runlist element of mft bitmap.
1390          */
1391         mrec = map_mft_record(mft_ni);
1392         if (IS_ERR(mrec)) {
1393                 ntfs_error(vol->sb, "Failed to map mft record.");
1394                 ret = PTR_ERR(mrec);
1395                 goto undo_alloc;
1396         }
1397         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1398         if (unlikely(!ctx)) {
1399                 ntfs_error(vol->sb, "Failed to get search context.");
1400                 ret = -ENOMEM;
1401                 goto undo_alloc;
1402         }
1403         ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1404                         mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1405                         0, ctx);
1406         if (unlikely(ret)) {
1407                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1408                                 "mft bitmap attribute.");
1409                 if (ret == -ENOENT)
1410                         ret = -EIO;
1411                 goto undo_alloc;
1412         }
1413         a = ctx->attr;
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--) {
1417                 if (ll >= rl2->vcn)
1418                         break;
1419         }
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.");
1427                 ret = mp_size;
1428                 if (!ret)
1429                         ret = -EIO;
1430                 goto undo_alloc;
1431         }
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.");
1440                         goto undo_alloc;
1441                 }
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.");
1450                 ret = -EOPNOTSUPP;
1451                 goto undo_alloc;
1452         }
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.");
1461                 goto undo_alloc;
1462         }
1463         /* Update the highest_vcn. */
1464         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1465         /*
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.
1468          */
1469         if (a->data.non_resident.lowest_vcn) {
1470                 /*
1471                  * We are not in the first attribute extent, switch to it, but
1472                  * first ensure the changes will make it to disk later.
1473                  */
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,
1479                                 0, ctx);
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;
1484                 }
1485                 a = ctx->attr;
1486         }
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.");
1499         return 0;
1500 restore_undo_alloc:
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,
1504                         0, ctx)) {
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);
1513                 /*
1514                  * The only thing that is now wrong is ->allocated_size of the
1515                  * base attribute extent which chkdsk should be able to fix.
1516                  */
1517                 NVolSetErrors(vol);
1518                 return ret;
1519         }
1520         a = ctx->attr;
1521         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1522 undo_alloc:
1523         if (status.added_cluster) {
1524                 /* Truncate the last run in the runlist by one cluster. */
1525                 rl->length--;
1526                 rl[1].vcn--;
1527         } else if (status.added_run) {
1528                 lcn = rl->lcn;
1529                 /* Remove the last run from the runlist. */
1530                 rl->lcn = rl[1].lcn;
1531                 rl->length = 0;
1532         }
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);
1537                 NVolSetErrors(vol);
1538         }
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 "
1547                                         "array.%s", es);
1548                         NVolSetErrors(vol);
1549                 }
1550                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1551                         ntfs_error(vol->sb, "Failed to restore attribute "
1552                                         "record.%s", es);
1553                         NVolSetErrors(vol);
1554                 }
1555                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1556                 mark_mft_record_dirty(ctx->ntfs_ino);
1557         }
1558         if (ctx)
1559                 ntfs_attr_put_search_ctx(ctx);
1560         if (!IS_ERR(mrec))
1561                 unmap_mft_record(mft_ni);
1562         up_write(&mftbmp_ni->runlist.lock);
1563         return ret;
1564 }
1565
1566 /**
1567  * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1568  * @vol:        volume on which to extend the mft bitmap attribute
1569  *
1570  * Extend the initialized portion of the mft bitmap attribute on the ntfs
1571  * volume @vol by 8 bytes.
1572  *
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.
1575  *
1576  * Return 0 on success and -error on error.
1577  *
1578  * Locking: Caller must hold vol->mftbmp_lock for writing.
1579  */
1580 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1581 {
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;
1587         MFT_RECORD *mrec;
1588         ATTR_RECORD *a;
1589         int ret;
1590
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);
1597         if (IS_ERR(mrec)) {
1598                 ntfs_error(vol->sb, "Failed to map mft record.");
1599                 return PTR_ERR(mrec);
1600         }
1601         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1602         if (unlikely(!ctx)) {
1603                 ntfs_error(vol->sb, "Failed to get search context.");
1604                 ret = -ENOMEM;
1605                 goto unm_err_out;
1606         }
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.");
1612                 if (ret == -ENOENT)
1613                         ret = -EIO;
1614                 goto put_err_out;
1615         }
1616         a = ctx->attr;
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;
1620         /*
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.
1624          */
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);
1632         }
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);
1641         if (likely(!ret)) {
1642                 ntfs_debug("Done.  (Wrote eight initialized bytes to mft "
1643                                 "bitmap.");
1644                 return 0;
1645         }
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);
1649         if (IS_ERR(mrec)) {
1650                 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1651                 NVolSetErrors(vol);
1652                 return ret;
1653         }
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);
1657                 NVolSetErrors(vol);
1658                 goto unm_err_out;
1659         }
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);
1664                 NVolSetErrors(vol);
1665 put_err_out:
1666                 ntfs_attr_put_search_ctx(ctx);
1667 unm_err_out:
1668                 unmap_mft_record(mft_ni);
1669                 goto err_out;
1670         }
1671         a = ctx->attr;
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);
1679         }
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);
1685 #ifdef DEBUG
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);
1693 #endif /* DEBUG */
1694 err_out:
1695         return ret;
1696 }
1697
1698 /**
1699  * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1700  * @vol:        volume on which to extend the mft data attribute
1701  *
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
1704  * of clusters.
1705  *
1706  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
1707  * data_size.
1708  *
1709  * Return 0 on success and -errno on error.
1710  *
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.
1716  */
1717 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1718 {
1719         LCN lcn;
1720         VCN old_last_vcn;
1721         s64 min_nr, nr, ll;
1722         unsigned long flags;
1723         ntfs_inode *mft_ni;
1724         runlist_element *rl, *rl2;
1725         ntfs_attr_search_ctx *ctx = NULL;
1726         MFT_RECORD *mrec;
1727         ATTR_RECORD *a = NULL;
1728         int ret, mp_size;
1729         u32 old_alen = 0;
1730         BOOL mp_rebuilt = FALSE;
1731
1732         ntfs_debug("Extending mft data allocation.");
1733         mft_ni = NTFS_I(vol->mft_ino);
1734         /*
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.
1738          */
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.");
1749                 if (!IS_ERR(rl))
1750                         ret = -EIO;
1751                 else
1752                         ret = PTR_ERR(rl);
1753                 return ret;
1754         }
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;
1759         if (!min_nr)
1760                 min_nr = 1;
1761         /* Want to allocate 16 mft records worth of clusters. */
1762         nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1763         if (!nr)
1764                 nr = min_nr;
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))) {
1771                 nr = min_nr;
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);
1778                         return -ENOSPC;
1779                 }
1780         }
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;
1784         do {
1785                 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
1786                                 TRUE);
1787                 if (likely(!IS_ERR(rl2)))
1788                         break;
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);
1795                 }
1796                 /*
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
1799                  * before failing.
1800                  */
1801                 nr = min_nr;
1802                 ntfs_debug("Retrying mft data allocation with minimal cluster "
1803                                 "count %lli.", (long long)nr);
1804         } while (1);
1805         rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1806         if (IS_ERR(rl)) {
1807                 up_write(&mft_ni->runlist.lock);
1808                 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1809                                 "attribute.");
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);
1813                         NVolSetErrors(vol);
1814                 }
1815                 ntfs_free(rl2);
1816                 return PTR_ERR(rl);
1817         }
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++)
1822                 ;
1823         /* Update the attribute record as well. */
1824         mrec = map_mft_record(mft_ni);
1825         if (IS_ERR(mrec)) {
1826                 ntfs_error(vol->sb, "Failed to map mft record.");
1827                 ret = PTR_ERR(mrec);
1828                 goto undo_alloc;
1829         }
1830         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1831         if (unlikely(!ctx)) {
1832                 ntfs_error(vol->sb, "Failed to get search context.");
1833                 ret = -ENOMEM;
1834                 goto undo_alloc;
1835         }
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.");
1841                 if (ret == -ENOENT)
1842                         ret = -EIO;
1843                 goto undo_alloc;
1844         }
1845         a = ctx->attr;
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--) {
1849                 if (ll >= rl2->vcn)
1850                         break;
1851         }
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.");
1859                 ret = mp_size;
1860                 if (!ret)
1861                         ret = -EIO;
1862                 goto undo_alloc;
1863         }
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.");
1872                         goto undo_alloc;
1873                 }
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.");
1887                 ret = -EOPNOTSUPP;
1888                 goto undo_alloc;
1889         }
1890         mp_rebuilt = TRUE;
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.");
1898                 goto undo_alloc;
1899         }
1900         /* Update the highest_vcn. */
1901         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1902         /*
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
1906          * attribute.
1907          */
1908         if (a->data.non_resident.lowest_vcn) {
1909                 /*
1910                  * We are not in the first attribute extent, switch to it, but
1911                  * first ensure the changes will make it to disk later.
1912                  */
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,
1918                                 ctx);
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;
1923                 }
1924                 a = ctx->attr;
1925         }
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.");
1938         return 0;
1939 restore_undo_alloc:
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);
1951                 /*
1952                  * The only thing that is now wrong is ->allocated_size of the
1953                  * base attribute extent which chkdsk should be able to fix.
1954                  */
1955                 NVolSetErrors(vol);
1956                 return ret;
1957         }
1958         ctx->attr->data.non_resident.highest_vcn =
1959                         cpu_to_sle64(old_last_vcn - 1);
1960 undo_alloc:
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);
1964                 NVolSetErrors(vol);
1965         }
1966         a = ctx->attr;
1967         if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1968                 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1969                                 "runlist.%s", es);
1970                 NVolSetErrors(vol);
1971         }
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 "
1979                                         "array.%s", es);
1980                         NVolSetErrors(vol);
1981                 }
1982                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1983                         ntfs_error(vol->sb, "Failed to restore attribute "
1984                                         "record.%s", es);
1985                         NVolSetErrors(vol);
1986                 }
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 "
1991                                 "context.%s", es);
1992                 NVolSetErrors(vol);
1993         }
1994         if (ctx)
1995                 ntfs_attr_put_search_ctx(ctx);
1996         if (!IS_ERR(mrec))
1997                 unmap_mft_record(mft_ni);
1998         up_write(&mft_ni->runlist.lock);
1999         return ret;
2000 }
2001
2002 /**
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
2007  *
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.
2012  *
2013  * Return 0 on success and -errno on error.
2014  */
2015 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2016                 MFT_RECORD *m)
2017 {
2018         ATTR_RECORD *a;
2019
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);
2024                 return -ERANGE;
2025         }
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);
2031         else {
2032                 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2033                 /*
2034                  * Set the NTFS 3.1+ specific fields while we know that the
2035                  * volume version is 3.1+.
2036                  */
2037                 m->reserved = 0;
2038                 m->mft_record_number = cpu_to_le32((u32)mft_no);
2039         }
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);
2044         else {
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.  "
2052                                 "Thank you.");
2053         }
2054         /* Set the update sequence number to 1. */
2055         *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2056         m->lsn = 0;
2057         m->sequence_number = cpu_to_le16(1);
2058         m->link_count = 0;
2059         /*
2060          * Place the attributes straight after the update sequence array,
2061          * aligned to 8-byte boundary.
2062          */
2063         m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2064                         (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2065         m->flags = 0;
2066         /*
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
2069          * align again.
2070          */
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));
2077         a->type = AT_END;
2078         a->length = 0;
2079         ntfs_debug("Done.");
2080         return 0;
2081 }
2082
2083 /**
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
2087  *
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.
2091  *
2092  * Return 0 on success and -errno on error.
2093  */
2094 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2095 {
2096         loff_t i_size;
2097         struct inode *mft_vi = vol->mft_ino;
2098         struct page *page;
2099         MFT_RECORD *m;
2100         pgoff_t index, end_index;
2101         unsigned int ofs;
2102         int err;
2103
2104         ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2105         /*
2106          * The index into the page cache and the offset within the page cache
2107          * page of the wanted mft record.
2108          */
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);
2119                         return -ENOENT;
2120                 }
2121         }
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);
2128         }
2129         lock_page(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.",
2136                                 (long long)mft_no);
2137                 SetPageUptodate(page);
2138                 unlock_page(page);
2139                 ntfs_unmap_page(page);
2140                 return err;
2141         }
2142         flush_dcache_page(page);
2143         SetPageUptodate(page);
2144         unlock_page(page);
2145         /*
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.
2149          */
2150         mark_ntfs_record_dirty(page, ofs);
2151         ntfs_unmap_page(page);
2152         ntfs_debug("Done.");
2153         return 0;
2154 }
2155
2156 /**
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
2162  *
2163  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2164  *
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).
2170  *
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.
2175  *
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
2181  * this case.
2182  *
2183  * Allocation strategy:
2184  *
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.
2198  *
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.
2206  *
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.
2213  *
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.
2219  *
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
2224  *        mft bitmap,
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.
2228  *
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.
2233  *
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.
2245  */
2246 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2247                 ntfs_inode *base_ni, MFT_RECORD **mrec)
2248 {
2249         s64 ll, bit, old_data_initialized, old_data_size;
2250         unsigned long flags;
2251         struct inode *vi;
2252         struct page *page;
2253         ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2254         ntfs_attr_search_ctx *ctx;
2255         MFT_RECORD *m;
2256         ATTR_RECORD *a;
2257         pgoff_t index;
2258         unsigned int ofs;
2259         int err;
2260         le16 seq_no, usn;
2261         BOOL record_formatted = FALSE;
2262
2263         if (base_ni) {
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. */
2268                 BUG_ON(mode);
2269         } else
2270                 ntfs_debug("Entering (allocating a base mft record).");
2271         if (mode) {
2272                 /* @mode and @base_ni are mutually exclusive. */
2273                 BUG_ON(base_ni);
2274                 /* We only support creation of normal files and directories. */
2275                 if (!S_ISREG(mode) && !S_ISDIR(mode))
2276                         return ERR_PTR(-EOPNOTSUPP);
2277         }
2278         BUG_ON(!mrec);
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);
2283         if (bit >= 0) {
2284                 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2285                                 (long long)bit);
2286                 goto have_alloc_rec;
2287         }
2288         if (bit != -ENOSPC) {
2289                 up_write(&vol->mftbmp_lock);
2290                 return ERR_PTR(bit);
2291         }
2292         /*
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.
2299          */
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) {
2307                 bit = ll;
2308                 if (bit < 24)
2309                         bit = 24;
2310                 if (unlikely(bit >= (1ll << 32)))
2311                         goto max_err_out;
2312                 ntfs_debug("Found free record (#2), bit 0x%llx.",
2313                                 (long long)bit);
2314                 goto found_free_rec;
2315         }
2316         /*
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.
2320          */
2321         bit = old_data_initialized << 3;
2322         if (unlikely(bit >= (1ll << 32)))
2323                 goto max_err_out;
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);
2338                         goto err_out;
2339                 }
2340 #ifdef DEBUG
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);
2349 #endif /* DEBUG */
2350         }
2351         /*
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
2354          * zeroes.
2355          */
2356         err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2357         if (unlikely(err)) {
2358                 up_write(&vol->mftbmp_lock);
2359                 goto err_out;
2360         }
2361 #ifdef DEBUG
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);
2370 #endif /* DEBUG */
2371         ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2372 found_free_rec:
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);
2379                 goto err_out;
2380         }
2381         ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2382 have_alloc_rec:
2383         /*
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.
2390          */
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;
2398         }
2399         ntfs_debug("Initializing allocated mft record.");
2400         /*
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.
2405          */
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 "
2418                                         "allocation.");
2419                         goto undo_mftbmp_alloc_nolock;
2420                 }
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);
2428         }
2429         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2430         /*
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.
2436          */
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;
2442                 
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.",
2450                                 (long long)mft_no);
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;
2455                 }
2456                 write_lock_irqsave(&mft_ni->size_lock, flags);
2457                 mft_ni->initialized_size = new_initialized_size;
2458         }
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);
2463         if (IS_ERR(m)) {
2464                 ntfs_error(vol->sb, "Failed to map mft record.");
2465                 err = PTR_ERR(m);
2466                 goto undo_data_init;
2467         }
2468         ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2469         if (unlikely(!ctx)) {
2470                 ntfs_error(vol->sb, "Failed to get search context.");
2471                 err = -ENOMEM;
2472                 unmap_mft_record(mft_ni);
2473                 goto undo_data_init;
2474         }
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;
2483         }
2484         a = ctx->attr;
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:
2507         /*
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.
2515          */
2516         up_write(&vol->mftbmp_lock);
2517         /*
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.
2520          */
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;
2530         }
2531         lock_page(page);
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.",
2544                                         (long long)bit);
2545                         err = -EIO;
2546                         SetPageUptodate(page);
2547                         unlock_page(page);
2548                         ntfs_unmap_page(page);
2549                         NVolSetErrors(vol);
2550                         goto undo_mftbmp_alloc;
2551                 }
2552                 /*
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.
2558                  */
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);
2566                         unlock_page(page);
2567                         ntfs_unmap_page(page);
2568                         goto undo_mftbmp_alloc;
2569                 }
2570                 if (seq_no)
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;
2574         }
2575         /* Set the mft record itself in use. */
2576         m->flags |= MFT_RECORD_IN_USE;
2577         if (S_ISDIR(mode))
2578                 m->flags |= MFT_RECORD_IS_DIRECTORY;
2579         flush_dcache_page(page);
2580         SetPageUptodate(page);
2581         if (base_ni) {
2582                 /*
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().
2586                  */
2587                 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2588                                 base_ni->seq_no);
2589                 /*
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.
2593                  */
2594                 m = map_extent_mft_record(base_ni, bit, &ni);
2595                 if (IS_ERR(m)) {
2596                         ntfs_error(vol->sb, "Failed to map allocated extent "
2597                                         "mft record 0x%llx.", (long long)bit);
2598                         err = PTR_ERR(m);
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);
2605                         unlock_page(page);
2606                         ntfs_unmap_page(page);
2607                         goto undo_mftbmp_alloc;
2608                 }
2609                 /*
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
2614                  * the mft record.
2615                  */
2616                 mark_ntfs_record_dirty(page, ofs);
2617                 unlock_page(page);
2618                 /*
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.
2621                  */
2622                 ntfs_unmap_page(page);
2623         } else {
2624                 /*
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.
2628                  */
2629                 vi = new_inode(vol->sb);
2630                 if (unlikely(!vi)) {
2631                         err = -ENOMEM;
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);
2638                         unlock_page(page);
2639                         ntfs_unmap_page(page);
2640                         goto undo_mftbmp_alloc;
2641                 }
2642                 vi->i_ino = bit;
2643                 /*
2644                  * This is the optimal IO size (for stat), not the fs block
2645                  * size.
2646                  */
2647                 vi->i_blksize = PAGE_CACHE_SIZE;
2648                 /*
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
2651                  * with f_version).
2652                  */
2653                 vi->i_version = 1;
2654
2655                 /* The owner and group come from the ntfs volume. */
2656                 vi->i_uid = vol->uid;
2657                 vi->i_gid = vol->gid;
2658
2659                 /* Initialize the ntfs specific part of @vi. */
2660                 ntfs_init_big_inode(vi);
2661                 ni = NTFS_I(vi);
2662                 /*
2663                  * Set the appropriate mode, attribute type, and name.  For
2664                  * directories, also setup the index values to the defaults.
2665                  */
2666                 if (S_ISDIR(mode)) {
2667                         vi->i_mode = S_IFDIR | S_IRWXUGO;
2668                         vi->i_mode &= ~vol->dmask;
2669
2670                         NInoSetMstProtected(ni);
2671                         ni->type = AT_INDEX_ALLOCATION;
2672                         ni->name = I30;
2673                         ni->name_len = 4;
2674
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;
2682                         } else {
2683                                 ni->itype.index.vcn_size = vol->sector_size;
2684                                 ni->itype.index.vcn_size_bits =
2685                                                 vol->sector_size_bits;
2686                         }
2687                 } else {
2688                         vi->i_mode = S_IFREG | S_IRWXUGO;
2689                         vi->i_mode &= ~vol->fmask;
2690
2691                         ni->type = AT_DATA;
2692                         ni->name = NULL;
2693                         ni->name_len = 0;
2694                 }
2695                 if (IS_RDONLY(vi))
2696                         vi->i_mode &= ~S_IWUGO;
2697
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);
2701                 /*
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.
2704                  */
2705                 vi->i_size = 0;
2706                 vi->i_blocks = 0;
2707
2708                 /* Set the sequence number. */
2709                 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2710                 /*
2711                  * Manually map, pin, and lock the mft record as we already
2712                  * have its page mapped and it is very easy to do.
2713                  */
2714                 atomic_inc(&ni->count);
2715                 down(&ni->mrec_lock);
2716                 ni->page = page;
2717                 ni->page_ofs = ofs;
2718                 /*
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
2726                  * record.
2727                  */
2728                 mark_ntfs_record_dirty(page, ofs);
2729                 unlock_page(page);
2730
2731                 /* Add the inode to the inode hash for the superblock. */
2732                 insert_inode_hash(vi);
2733
2734                 /* Update the default mft allocation position. */
2735                 vol->mft_data_pos = bit + 1;
2736         }
2737         /*
2738          * Return the opened, allocated inode of the allocated mft record as
2739          * well as the mapped, pinned, and locked mft record.
2740          */
2741         ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2742                         base_ni ? "extent " : "", (long long)bit);
2743         *mrec = m;
2744         return ni;
2745 undo_data_init:
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;
2751 undo_mftbmp_alloc:
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);
2756                 NVolSetErrors(vol);
2757         }
2758         up_write(&vol->mftbmp_lock);
2759 err_out:
2760         return ERR_PTR(err);
2761 max_err_out:
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);
2766 }
2767
2768 /**
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
2772  *
2773  * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2774  *
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.
2778  *
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.
2781  *
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.
2788  */
2789 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2790 {
2791         unsigned long mft_no = ni->mft_no;
2792         ntfs_volume *vol = ni->vol;
2793         ntfs_inode *base_ni;
2794         ntfs_inode **extent_nis;
2795         int i, err;
2796         le16 old_seq_no;
2797         u16 seq_no;
2798         
2799         BUG_ON(NInoAttr(ni));
2800         BUG_ON(ni->nr_extents != -1);
2801
2802         down(&ni->extent_lock);
2803         base_ni = ni->ext.base_ntfs_ino;
2804         up(&ni->extent_lock);
2805
2806         BUG_ON(base_ni->nr_extents <= 0);
2807
2808         ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2809                         mft_no, base_ni->mft_no);
2810
2811         down(&base_ni->extent_lock);
2812
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);
2818                 return -EBUSY;
2819         }
2820
2821         /* Dissociate the ntfs inode from the base inode. */
2822         extent_nis = base_ni->ext.extent_ntfs_inos;
2823         err = -ENOENT;
2824         for (i = 0; i < base_ni->nr_extents; i++) {
2825                 if (ni != extent_nis[i])
2826                         continue;
2827                 extent_nis += i;
2828                 base_ni->nr_extents--;
2829                 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2830                                 sizeof(ntfs_inode*));
2831                 err = 0;
2832                 break;
2833         }
2834
2835         up(&base_ni->extent_lock);
2836
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,
2840                                 base_ni->mft_no);
2841                 BUG();
2842         }
2843
2844         /*
2845          * The extent inode is no longer attached to the base inode so no one
2846          * can get a reference to it any more.
2847          */
2848
2849         /* Mark the mft record as not in use. */
2850         m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2851
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)
2856                 seq_no = 1;
2857         else if (seq_no)
2858                 seq_no++;
2859         m->sequence_number = cpu_to_le16(seq_no);
2860
2861         /*
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.
2865          */
2866         NInoSetDirty(ni);
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);
2871                 goto rollback;
2872         }
2873 rollback_error:
2874         /* Unmap and throw away the now freed extent inode. */
2875         unmap_extent_mft_record(ni);
2876         ntfs_clear_extent_inode(ni);
2877
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)) {
2883                 /*
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
2886                  * dirty on umount.
2887                  */
2888                 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2889                 NVolSetErrors(vol);
2890         }
2891         return 0;
2892 rollback:
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*);
2898
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);
2904                         NVolSetErrors(vol);
2905                         goto rollback_error;
2906                 }
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);
2912                 }
2913                 base_ni->ext.extent_ntfs_inos = extent_nis;
2914         }
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);
2920         return err;
2921 }
2922 #endif /* NTFS_RW */