]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - fs/ntfs/mft.c
Merge Paulus' tree
[karo-tx-linux.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-2005 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         }
97 err_out:
98         ni->page = NULL;
99         ni->page_ofs = 0;
100         return (void*)page;
101 }
102
103 /**
104  * map_mft_record - map, pin and lock an mft record
105  * @ni:         ntfs inode whose MFT record to map
106  *
107  * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
108  * for the semaphore if it was already locked by someone else.
109  *
110  * The page of the record is mapped using map_mft_record_page() before being
111  * returned to the caller.
112  *
113  * This in turn uses ntfs_map_page() to get the page containing the wanted mft
114  * record (it in turn calls read_cache_page() which reads it in from disk if
115  * necessary, increments the use count on the page so that it cannot disappear
116  * under us and returns a reference to the page cache page).
117  *
118  * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
119  * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
120  * and the post-read mst fixups on each mft record in the page have been
121  * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
122  * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
123  * ntfs_map_page() waits for PG_locked to become clear and checks if
124  * PG_uptodate is set and returns an error code if not. This provides
125  * sufficient protection against races when reading/using the page.
126  *
127  * However there is the write mapping to think about. Doing the above described
128  * checking here will be fine, because when initiating the write we will set
129  * PG_locked and clear PG_uptodate making sure nobody is touching the page
130  * contents. Doing the locking this way means that the commit to disk code in
131  * the page cache code paths is automatically sufficiently locked with us as
132  * we will not touch a page that has been locked or is not uptodate. The only
133  * locking problem then is them locking the page while we are accessing it.
134  *
135  * So that code will end up having to own the mrec_lock of all mft
136  * records/inodes present in the page before I/O can proceed. In that case we
137  * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
138  * accessing anything without owning the mrec_lock semaphore. But we do need
139  * to use them because of the read_cache_page() invocation and the code becomes
140  * so much simpler this way that it is well worth it.
141  *
142  * The mft record is now ours and we return a pointer to it. You need to check
143  * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
144  * the error code.
145  *
146  * NOTE: Caller is responsible for setting the mft record dirty before calling
147  * unmap_mft_record(). This is obviously only necessary if the caller really
148  * modified the mft record...
149  * Q: Do we want to recycle one of the VFS inode state bits instead?
150  * A: No, the inode ones mean we want to change the mft record, not we want to
151  * write it out.
152  */
153 MFT_RECORD *map_mft_record(ntfs_inode *ni)
154 {
155         MFT_RECORD *m;
156
157         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
158
159         /* Make sure the ntfs inode doesn't go away. */
160         atomic_inc(&ni->count);
161
162         /* Serialize access to this mft record. */
163         down(&ni->mrec_lock);
164
165         m = map_mft_record_page(ni);
166         if (likely(!IS_ERR(m)))
167                 return m;
168
169         up(&ni->mrec_lock);
170         atomic_dec(&ni->count);
171         ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
172         return m;
173 }
174
175 /**
176  * unmap_mft_record_page - unmap the page in which a specific mft record resides
177  * @ni:         ntfs inode whose mft record page to unmap
178  *
179  * This unmaps the page in which the mft record of the ntfs inode @ni is
180  * situated and returns. This is a NOOP if highmem is not configured.
181  *
182  * The unmap happens via ntfs_unmap_page() which in turn decrements the use
183  * count on the page thus releasing it from the pinned state.
184  *
185  * We do not actually unmap the page from memory of course, as that will be
186  * done by the page cache code itself when memory pressure increases or
187  * whatever.
188  */
189 static inline void unmap_mft_record_page(ntfs_inode *ni)
190 {
191         BUG_ON(!ni->page);
192
193         // TODO: If dirty, blah...
194         ntfs_unmap_page(ni->page);
195         ni->page = NULL;
196         ni->page_ofs = 0;
197         return;
198 }
199
200 /**
201  * unmap_mft_record - release a mapped mft record
202  * @ni:         ntfs inode whose MFT record to unmap
203  *
204  * We release the page mapping and the mrec_lock mutex which unmaps the mft
205  * record and releases it for others to get hold of. We also release the ntfs
206  * inode by decrementing the ntfs inode reference count.
207  *
208  * NOTE: If caller has modified the mft record, it is imperative to set the mft
209  * record dirty BEFORE calling unmap_mft_record().
210  */
211 void unmap_mft_record(ntfs_inode *ni)
212 {
213         struct page *page = ni->page;
214
215         BUG_ON(!page);
216
217         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
218
219         unmap_mft_record_page(ni);
220         up(&ni->mrec_lock);
221         atomic_dec(&ni->count);
222         /*
223          * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
224          * ntfs_clear_extent_inode() in the extent inode case, and to the
225          * caller in the non-extent, yet pure ntfs inode case, to do the actual
226          * tear down of all structures and freeing of all allocated memory.
227          */
228         return;
229 }
230
231 /**
232  * map_extent_mft_record - load an extent inode and attach it to its base
233  * @base_ni:    base ntfs inode
234  * @mref:       mft reference of the extent inode to load
235  * @ntfs_ino:   on successful return, pointer to the ntfs_inode structure
236  *
237  * Load the extent mft record @mref and attach it to its base inode @base_ni.
238  * Return the mapped extent mft record if IS_ERR(result) is false.  Otherwise
239  * PTR_ERR(result) gives the negative error code.
240  *
241  * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
242  * structure of the mapped extent inode.
243  */
244 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
245                 ntfs_inode **ntfs_ino)
246 {
247         MFT_RECORD *m;
248         ntfs_inode *ni = NULL;
249         ntfs_inode **extent_nis = NULL;
250         int i;
251         unsigned long mft_no = MREF(mref);
252         u16 seq_no = MSEQNO(mref);
253         BOOL destroy_ni = FALSE;
254
255         ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
256                         mft_no, base_ni->mft_no);
257         /* Make sure the base ntfs inode doesn't go away. */
258         atomic_inc(&base_ni->count);
259         /*
260          * Check if this extent inode has already been added to the base inode,
261          * in which case just return it. If not found, add it to the base
262          * inode before returning it.
263          */
264         down(&base_ni->extent_lock);
265         if (base_ni->nr_extents > 0) {
266                 extent_nis = base_ni->ext.extent_ntfs_inos;
267                 for (i = 0; i < base_ni->nr_extents; i++) {
268                         if (mft_no != extent_nis[i]->mft_no)
269                                 continue;
270                         ni = extent_nis[i];
271                         /* Make sure the ntfs inode doesn't go away. */
272                         atomic_inc(&ni->count);
273                         break;
274                 }
275         }
276         if (likely(ni != NULL)) {
277                 up(&base_ni->extent_lock);
278                 atomic_dec(&base_ni->count);
279                 /* We found the record; just have to map and return it. */
280                 m = map_mft_record(ni);
281                 /* map_mft_record() has incremented this on success. */
282                 atomic_dec(&ni->count);
283                 if (likely(!IS_ERR(m))) {
284                         /* Verify the sequence number. */
285                         if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
286                                 ntfs_debug("Done 1.");
287                                 *ntfs_ino = ni;
288                                 return m;
289                         }
290                         unmap_mft_record(ni);
291                         ntfs_error(base_ni->vol->sb, "Found stale extent mft "
292                                         "reference! Corrupt filesystem. "
293                                         "Run chkdsk.");
294                         return ERR_PTR(-EIO);
295                 }
296 map_err_out:
297                 ntfs_error(base_ni->vol->sb, "Failed to map extent "
298                                 "mft record, error code %ld.", -PTR_ERR(m));
299                 return m;
300         }
301         /* Record wasn't there. Get a new ntfs inode and initialize it. */
302         ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
303         if (unlikely(!ni)) {
304                 up(&base_ni->extent_lock);
305                 atomic_dec(&base_ni->count);
306                 return ERR_PTR(-ENOMEM);
307         }
308         ni->vol = base_ni->vol;
309         ni->seq_no = seq_no;
310         ni->nr_extents = -1;
311         ni->ext.base_ntfs_ino = base_ni;
312         /* Now map the record. */
313         m = map_mft_record(ni);
314         if (IS_ERR(m)) {
315                 up(&base_ni->extent_lock);
316                 atomic_dec(&base_ni->count);
317                 ntfs_clear_extent_inode(ni);
318                 goto map_err_out;
319         }
320         /* Verify the sequence number if it is present. */
321         if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
322                 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
323                                 "reference! Corrupt filesystem. Run chkdsk.");
324                 destroy_ni = TRUE;
325                 m = ERR_PTR(-EIO);
326                 goto unm_err_out;
327         }
328         /* Attach extent inode to base inode, reallocating memory if needed. */
329         if (!(base_ni->nr_extents & 3)) {
330                 ntfs_inode **tmp;
331                 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
332
333                 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
334                 if (unlikely(!tmp)) {
335                         ntfs_error(base_ni->vol->sb, "Failed to allocate "
336                                         "internal buffer.");
337                         destroy_ni = TRUE;
338                         m = ERR_PTR(-ENOMEM);
339                         goto unm_err_out;
340                 }
341                 if (base_ni->nr_extents) {
342                         BUG_ON(!base_ni->ext.extent_ntfs_inos);
343                         memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
344                                         4 * sizeof(ntfs_inode *));
345                         kfree(base_ni->ext.extent_ntfs_inos);
346                 }
347                 base_ni->ext.extent_ntfs_inos = tmp;
348         }
349         base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
350         up(&base_ni->extent_lock);
351         atomic_dec(&base_ni->count);
352         ntfs_debug("Done 2.");
353         *ntfs_ino = ni;
354         return m;
355 unm_err_out:
356         unmap_mft_record(ni);
357         up(&base_ni->extent_lock);
358         atomic_dec(&base_ni->count);
359         /*
360          * If the extent inode was not attached to the base inode we need to
361          * release it or we will leak memory.
362          */
363         if (destroy_ni)
364                 ntfs_clear_extent_inode(ni);
365         return m;
366 }
367
368 #ifdef NTFS_RW
369
370 /**
371  * __mark_mft_record_dirty - set the mft record and the page containing it dirty
372  * @ni:         ntfs inode describing the mapped mft record
373  *
374  * Internal function.  Users should call mark_mft_record_dirty() instead.
375  *
376  * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
377  * as well as the page containing the mft record, dirty.  Also, mark the base
378  * vfs inode dirty.  This ensures that any changes to the mft record are
379  * written out to disk.
380  *
381  * NOTE:  We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
382  * on the base vfs inode, because even though file data may have been modified,
383  * it is dirty in the inode meta data rather than the data page cache of the
384  * inode, and thus there are no data pages that need writing out.  Therefore, a
385  * full mark_inode_dirty() is overkill.  A mark_inode_dirty_sync(), on the
386  * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
387  * ensure ->write_inode is called from generic_osync_inode() and this needs to
388  * happen or the file data would not necessarily hit the device synchronously,
389  * even though the vfs inode has the O_SYNC flag set.  Also, I_DIRTY_DATASYNC
390  * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
391  * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
392  * would suggest.
393  */
394 void __mark_mft_record_dirty(ntfs_inode *ni)
395 {
396         ntfs_inode *base_ni;
397
398         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
399         BUG_ON(NInoAttr(ni));
400         mark_ntfs_record_dirty(ni->page, ni->page_ofs);
401         /* Determine the base vfs inode and mark it dirty, too. */
402         down(&ni->extent_lock);
403         if (likely(ni->nr_extents >= 0))
404                 base_ni = ni;
405         else
406                 base_ni = ni->ext.base_ntfs_ino;
407         up(&ni->extent_lock);
408         __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
409 }
410
411 static const char *ntfs_please_email = "Please email "
412                 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
413                 "this message.  Thank you.";
414
415 /**
416  * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
417  * @vol:        ntfs volume on which the mft record to synchronize resides
418  * @mft_no:     mft record number of mft record to synchronize
419  * @m:          mapped, mst protected (extent) mft record to synchronize
420  *
421  * Write the mapped, mst protected (extent) mft record @m with mft record
422  * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
423  * bypassing the page cache and the $MFTMirr inode itself.
424  *
425  * This function is only for use at umount time when the mft mirror inode has
426  * already been disposed off.  We BUG() if we are called while the mft mirror
427  * inode is still attached to the volume.
428  *
429  * On success return 0.  On error return -errno.
430  *
431  * NOTE:  This function is not implemented yet as I am not convinced it can
432  * actually be triggered considering the sequence of commits we do in super.c::
433  * ntfs_put_super().  But just in case we provide this place holder as the
434  * alternative would be either to BUG() or to get a NULL pointer dereference
435  * and Oops.
436  */
437 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
438                 const unsigned long mft_no, MFT_RECORD *m)
439 {
440         BUG_ON(vol->mftmirr_ino);
441         ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
442                         "implemented yet.  %s", ntfs_please_email);
443         return -EOPNOTSUPP;
444 }
445
446 /**
447  * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
448  * @vol:        ntfs volume on which the mft record to synchronize resides
449  * @mft_no:     mft record number of mft record to synchronize
450  * @m:          mapped, mst protected (extent) mft record to synchronize
451  * @sync:       if true, wait for i/o completion
452  *
453  * Write the mapped, mst protected (extent) mft record @m with mft record
454  * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
455  *
456  * On success return 0.  On error return -errno and set the volume errors flag
457  * in the ntfs volume @vol.
458  *
459  * NOTE:  We always perform synchronous i/o and ignore the @sync parameter.
460  *
461  * TODO:  If @sync is false, want to do truly asynchronous i/o, i.e. just
462  * schedule i/o via ->writepage or do it via kntfsd or whatever.
463  */
464 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
465                 MFT_RECORD *m, int sync)
466 {
467         struct page *page;
468         unsigned int blocksize = vol->sb->s_blocksize;
469         int max_bhs = vol->mft_record_size / blocksize;
470         struct buffer_head *bhs[max_bhs];
471         struct buffer_head *bh, *head;
472         u8 *kmirr;
473         runlist_element *rl;
474         unsigned int block_start, block_end, m_start, m_end, page_ofs;
475         int i_bhs, nr_bhs, err = 0;
476         unsigned char blocksize_bits = vol->mftmirr_ino->i_blkbits;
477
478         ntfs_debug("Entering for inode 0x%lx.", mft_no);
479         BUG_ON(!max_bhs);
480         if (unlikely(!vol->mftmirr_ino)) {
481                 /* This could happen during umount... */
482                 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
483                 if (likely(!err))
484                         return err;
485                 goto err_out;
486         }
487         /* Get the page containing the mirror copy of the mft record @m. */
488         page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
489                         (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
490         if (IS_ERR(page)) {
491                 ntfs_error(vol->sb, "Failed to map mft mirror page.");
492                 err = PTR_ERR(page);
493                 goto err_out;
494         }
495         lock_page(page);
496         BUG_ON(!PageUptodate(page));
497         ClearPageUptodate(page);
498         /* Offset of the mft mirror record inside the page. */
499         page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
500         /* The address in the page of the mirror copy of the mft record @m. */
501         kmirr = page_address(page) + page_ofs;
502         /* Copy the mst protected mft record to the mirror. */
503         memcpy(kmirr, m, vol->mft_record_size);
504         /* Create uptodate buffers if not present. */
505         if (unlikely(!page_has_buffers(page))) {
506                 struct buffer_head *tail;
507
508                 bh = head = alloc_page_buffers(page, blocksize, 1);
509                 do {
510                         set_buffer_uptodate(bh);
511                         tail = bh;
512                         bh = bh->b_this_page;
513                 } while (bh);
514                 tail->b_this_page = head;
515                 attach_page_buffers(page, head);
516         }
517         bh = head = page_buffers(page);
518         BUG_ON(!bh);
519         rl = NULL;
520         nr_bhs = 0;
521         block_start = 0;
522         m_start = kmirr - (u8*)page_address(page);
523         m_end = m_start + vol->mft_record_size;
524         do {
525                 block_end = block_start + blocksize;
526                 /* If the buffer is outside the mft record, skip it. */
527                 if (block_end <= m_start)
528                         continue;
529                 if (unlikely(block_start >= m_end))
530                         break;
531                 /* Need to map the buffer if it is not mapped already. */
532                 if (unlikely(!buffer_mapped(bh))) {
533                         VCN vcn;
534                         LCN lcn;
535                         unsigned int vcn_ofs;
536
537                         bh->b_bdev = vol->sb->s_bdev;
538                         /* Obtain the vcn and offset of the current block. */
539                         vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
540                                         (block_start - m_start);
541                         vcn_ofs = vcn & vol->cluster_size_mask;
542                         vcn >>= vol->cluster_size_bits;
543                         if (!rl) {
544                                 down_read(&NTFS_I(vol->mftmirr_ino)->
545                                                 runlist.lock);
546                                 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
547                                 /*
548                                  * $MFTMirr always has the whole of its runlist
549                                  * in memory.
550                                  */
551                                 BUG_ON(!rl);
552                         }
553                         /* Seek to element containing target vcn. */
554                         while (rl->length && rl[1].vcn <= vcn)
555                                 rl++;
556                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
557                         /* For $MFTMirr, only lcn >= 0 is a successful remap. */
558                         if (likely(lcn >= 0)) {
559                                 /* Setup buffer head to correct block. */
560                                 bh->b_blocknr = ((lcn <<
561                                                 vol->cluster_size_bits) +
562                                                 vcn_ofs) >> blocksize_bits;
563                                 set_buffer_mapped(bh);
564                         } else {
565                                 bh->b_blocknr = -1;
566                                 ntfs_error(vol->sb, "Cannot write mft mirror "
567                                                 "record 0x%lx because its "
568                                                 "location on disk could not "
569                                                 "be determined (error code "
570                                                 "%lli).", mft_no,
571                                                 (long long)lcn);
572                                 err = -EIO;
573                         }
574                 }
575                 BUG_ON(!buffer_uptodate(bh));
576                 BUG_ON(!nr_bhs && (m_start != block_start));
577                 BUG_ON(nr_bhs >= max_bhs);
578                 bhs[nr_bhs++] = bh;
579                 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
580         } while (block_start = block_end, (bh = bh->b_this_page) != head);
581         if (unlikely(rl))
582                 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
583         if (likely(!err)) {
584                 /* Lock buffers and start synchronous write i/o on them. */
585                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
586                         struct buffer_head *tbh = bhs[i_bhs];
587
588                         if (unlikely(test_set_buffer_locked(tbh)))
589                                 BUG();
590                         BUG_ON(!buffer_uptodate(tbh));
591                         clear_buffer_dirty(tbh);
592                         get_bh(tbh);
593                         tbh->b_end_io = end_buffer_write_sync;
594                         submit_bh(WRITE, tbh);
595                 }
596                 /* Wait on i/o completion of buffers. */
597                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
598                         struct buffer_head *tbh = bhs[i_bhs];
599
600                         wait_on_buffer(tbh);
601                         if (unlikely(!buffer_uptodate(tbh))) {
602                                 err = -EIO;
603                                 /*
604                                  * Set the buffer uptodate so the page and
605                                  * buffer states do not become out of sync.
606                                  */
607                                 set_buffer_uptodate(tbh);
608                         }
609                 }
610         } else /* if (unlikely(err)) */ {
611                 /* Clean the buffers. */
612                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
613                         clear_buffer_dirty(bhs[i_bhs]);
614         }
615         /* Current state: all buffers are clean, unlocked, and uptodate. */
616         /* Remove the mst protection fixups again. */
617         post_write_mst_fixup((NTFS_RECORD*)kmirr);
618         flush_dcache_page(page);
619         SetPageUptodate(page);
620         unlock_page(page);
621         ntfs_unmap_page(page);
622         if (likely(!err)) {
623                 ntfs_debug("Done.");
624         } else {
625                 ntfs_error(vol->sb, "I/O error while writing mft mirror "
626                                 "record 0x%lx!", mft_no);
627 err_out:
628                 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
629                                 "code %i).  Volume will be left marked dirty "
630                                 "on umount.  Run ntfsfix on the partition "
631                                 "after umounting to correct this.", -err);
632                 NVolSetErrors(vol);
633         }
634         return err;
635 }
636
637 /**
638  * write_mft_record_nolock - write out a mapped (extent) mft record
639  * @ni:         ntfs inode describing the mapped (extent) mft record
640  * @m:          mapped (extent) mft record to write
641  * @sync:       if true, wait for i/o completion
642  *
643  * Write the mapped (extent) mft record @m described by the (regular or extent)
644  * ntfs inode @ni to backing store.  If the mft record @m has a counterpart in
645  * the mft mirror, that is also updated.
646  *
647  * We only write the mft record if the ntfs inode @ni is dirty and the first
648  * buffer belonging to its mft record is dirty, too.  We ignore the dirty state
649  * of subsequent buffers because we could have raced with
650  * fs/ntfs/aops.c::mark_ntfs_record_dirty().
651  *
652  * On success, clean the mft record and return 0.  On error, leave the mft
653  * record dirty and return -errno.  The caller should call make_bad_inode() on
654  * the base inode to ensure no more access happens to this inode.  We do not do
655  * it here as the caller may want to finish writing other extent mft records
656  * first to minimize on-disk metadata inconsistencies.
657  *
658  * NOTE:  We always perform synchronous i/o and ignore the @sync parameter.
659  * However, if the mft record has a counterpart in the mft mirror and @sync is
660  * true, we write the mft record, wait for i/o completion, and only then write
661  * the mft mirror copy.  This ensures that if the system crashes either the mft
662  * or the mft mirror will contain a self-consistent mft record @m.  If @sync is
663  * false on the other hand, we start i/o on both and then wait for completion
664  * on them.  This provides a speedup but no longer guarantees that you will end
665  * up with a self-consistent mft record in the case of a crash but if you asked
666  * for asynchronous writing you probably do not care about that anyway.
667  *
668  * TODO:  If @sync is false, want to do truly asynchronous i/o, i.e. just
669  * schedule i/o via ->writepage or do it via kntfsd or whatever.
670  */
671 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
672 {
673         ntfs_volume *vol = ni->vol;
674         struct page *page = ni->page;
675         unsigned char blocksize_bits = vol->mft_ino->i_blkbits;
676         unsigned int blocksize = 1 << blocksize_bits;
677         int max_bhs = vol->mft_record_size / blocksize;
678         struct buffer_head *bhs[max_bhs];
679         struct buffer_head *bh, *head;
680         runlist_element *rl;
681         unsigned int block_start, block_end, m_start, m_end;
682         int i_bhs, nr_bhs, err = 0;
683
684         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
685         BUG_ON(NInoAttr(ni));
686         BUG_ON(!max_bhs);
687         BUG_ON(!PageLocked(page));
688         /*
689          * If the ntfs_inode is clean no need to do anything.  If it is dirty,
690          * mark it as clean now so that it can be redirtied later on if needed.
691          * There is no danger of races since the caller is holding the locks
692          * for the mft record @m and the page it is in.
693          */
694         if (!NInoTestClearDirty(ni))
695                 goto done;
696         bh = head = page_buffers(page);
697         BUG_ON(!bh);
698         rl = NULL;
699         nr_bhs = 0;
700         block_start = 0;
701         m_start = ni->page_ofs;
702         m_end = m_start + vol->mft_record_size;
703         do {
704                 block_end = block_start + blocksize;
705                 /* If the buffer is outside the mft record, skip it. */
706                 if (block_end <= m_start)
707                         continue;
708                 if (unlikely(block_start >= m_end))
709                         break;
710                 /*
711                  * If this block is not the first one in the record, we ignore
712                  * the buffer's dirty state because we could have raced with a
713                  * parallel mark_ntfs_record_dirty().
714                  */
715                 if (block_start == m_start) {
716                         /* This block is the first one in the record. */
717                         if (!buffer_dirty(bh)) {
718                                 BUG_ON(nr_bhs);
719                                 /* Clean records are not written out. */
720                                 break;
721                         }
722                 }
723                 /* Need to map the buffer if it is not mapped already. */
724                 if (unlikely(!buffer_mapped(bh))) {
725                         VCN vcn;
726                         LCN lcn;
727                         unsigned int vcn_ofs;
728
729                         bh->b_bdev = vol->sb->s_bdev;
730                         /* Obtain the vcn and offset of the current block. */
731                         vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
732                                         (block_start - m_start);
733                         vcn_ofs = vcn & vol->cluster_size_mask;
734                         vcn >>= vol->cluster_size_bits;
735                         if (!rl) {
736                                 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
737                                 rl = NTFS_I(vol->mft_ino)->runlist.rl;
738                                 BUG_ON(!rl);
739                         }
740                         /* Seek to element containing target vcn. */
741                         while (rl->length && rl[1].vcn <= vcn)
742                                 rl++;
743                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
744                         /* For $MFT, only lcn >= 0 is a successful remap. */
745                         if (likely(lcn >= 0)) {
746                                 /* Setup buffer head to correct block. */
747                                 bh->b_blocknr = ((lcn <<
748                                                 vol->cluster_size_bits) +
749                                                 vcn_ofs) >> blocksize_bits;
750                                 set_buffer_mapped(bh);
751                         } else {
752                                 bh->b_blocknr = -1;
753                                 ntfs_error(vol->sb, "Cannot write mft record "
754                                                 "0x%lx because its location "
755                                                 "on disk could not be "
756                                                 "determined (error code %lli).",
757                                                 ni->mft_no, (long long)lcn);
758                                 err = -EIO;
759                         }
760                 }
761                 BUG_ON(!buffer_uptodate(bh));
762                 BUG_ON(!nr_bhs && (m_start != block_start));
763                 BUG_ON(nr_bhs >= max_bhs);
764                 bhs[nr_bhs++] = bh;
765                 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
766         } while (block_start = block_end, (bh = bh->b_this_page) != head);
767         if (unlikely(rl))
768                 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
769         if (!nr_bhs)
770                 goto done;
771         if (unlikely(err))
772                 goto cleanup_out;
773         /* Apply the mst protection fixups. */
774         err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
775         if (err) {
776                 ntfs_error(vol->sb, "Failed to apply mst fixups!");
777                 goto cleanup_out;
778         }
779         flush_dcache_mft_record_page(ni);
780         /* Lock buffers and start synchronous write i/o on them. */
781         for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
782                 struct buffer_head *tbh = bhs[i_bhs];
783
784                 if (unlikely(test_set_buffer_locked(tbh)))
785                         BUG();
786                 BUG_ON(!buffer_uptodate(tbh));
787                 clear_buffer_dirty(tbh);
788                 get_bh(tbh);
789                 tbh->b_end_io = end_buffer_write_sync;
790                 submit_bh(WRITE, tbh);
791         }
792         /* Synchronize the mft mirror now if not @sync. */
793         if (!sync && ni->mft_no < vol->mftmirr_size)
794                 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
795         /* Wait on i/o completion of buffers. */
796         for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
797                 struct buffer_head *tbh = bhs[i_bhs];
798
799                 wait_on_buffer(tbh);
800                 if (unlikely(!buffer_uptodate(tbh))) {
801                         err = -EIO;
802                         /*
803                          * Set the buffer uptodate so the page and buffer
804                          * states do not become out of sync.
805                          */
806                         if (PageUptodate(page))
807                                 set_buffer_uptodate(tbh);
808                 }
809         }
810         /* If @sync, now synchronize the mft mirror. */
811         if (sync && ni->mft_no < vol->mftmirr_size)
812                 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
813         /* Remove the mst protection fixups again. */
814         post_write_mst_fixup((NTFS_RECORD*)m);
815         flush_dcache_mft_record_page(ni);
816         if (unlikely(err)) {
817                 /* I/O error during writing.  This is really bad! */
818                 ntfs_error(vol->sb, "I/O error while writing mft record "
819                                 "0x%lx!  Marking base inode as bad.  You "
820                                 "should unmount the volume and run chkdsk.",
821                                 ni->mft_no);
822                 goto err_out;
823         }
824 done:
825         ntfs_debug("Done.");
826         return 0;
827 cleanup_out:
828         /* Clean the buffers. */
829         for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
830                 clear_buffer_dirty(bhs[i_bhs]);
831 err_out:
832         /*
833          * Current state: all buffers are clean, unlocked, and uptodate.
834          * The caller should mark the base inode as bad so that no more i/o
835          * happens.  ->clear_inode() will still be invoked so all extent inodes
836          * and other allocated memory will be freed.
837          */
838         if (err == -ENOMEM) {
839                 ntfs_error(vol->sb, "Not enough memory to write mft record.  "
840                                 "Redirtying so the write is retried later.");
841                 mark_mft_record_dirty(ni);
842                 err = 0;
843         } else
844                 NVolSetErrors(vol);
845         return err;
846 }
847
848 /**
849  * ntfs_may_write_mft_record - check if an mft record may be written out
850  * @vol:        [IN]  ntfs volume on which the mft record to check resides
851  * @mft_no:     [IN]  mft record number of the mft record to check
852  * @m:          [IN]  mapped mft record to check
853  * @locked_ni:  [OUT] caller has to unlock this ntfs inode if one is returned
854  *
855  * Check if the mapped (base or extent) mft record @m with mft record number
856  * @mft_no belonging to the ntfs volume @vol may be written out.  If necessary
857  * and possible the ntfs inode of the mft record is locked and the base vfs
858  * inode is pinned.  The locked ntfs inode is then returned in @locked_ni.  The
859  * caller is responsible for unlocking the ntfs inode and unpinning the base
860  * vfs inode.
861  *
862  * Return TRUE if the mft record may be written out and FALSE if not.
863  *
864  * The caller has locked the page and cleared the uptodate flag on it which
865  * means that we can safely write out any dirty mft records that do not have
866  * their inodes in icache as determined by ilookup5() as anyone
867  * opening/creating such an inode would block when attempting to map the mft
868  * record in read_cache_page() until we are finished with the write out.
869  *
870  * Here is a description of the tests we perform:
871  *
872  * If the inode is found in icache we know the mft record must be a base mft
873  * record.  If it is dirty, we do not write it and return FALSE as the vfs
874  * inode write paths will result in the access times being updated which would
875  * cause the base mft record to be redirtied and written out again.  (We know
876  * the access time update will modify the base mft record because Windows
877  * chkdsk complains if the standard information attribute is not in the base
878  * mft record.)
879  *
880  * If the inode is in icache and not dirty, we attempt to lock the mft record
881  * and if we find the lock was already taken, it is not safe to write the mft
882  * record and we return FALSE.
883  *
884  * If we manage to obtain the lock we have exclusive access to the mft record,
885  * which also allows us safe writeout of the mft record.  We then set
886  * @locked_ni to the locked ntfs inode and return TRUE.
887  *
888  * Note we cannot just lock the mft record and sleep while waiting for the lock
889  * because this would deadlock due to lock reversal (normally the mft record is
890  * locked before the page is locked but we already have the page locked here
891  * when we try to lock the mft record).
892  *
893  * If the inode is not in icache we need to perform further checks.
894  *
895  * If the mft record is not a FILE record or it is a base mft record, we can
896  * safely write it and return TRUE.
897  *
898  * We now know the mft record is an extent mft record.  We check if the inode
899  * corresponding to its base mft record is in icache and obtain a reference to
900  * it if it is.  If it is not, we can safely write it and return TRUE.
901  *
902  * We now have the base inode for the extent mft record.  We check if it has an
903  * ntfs inode for the extent mft record attached and if not it is safe to write
904  * the extent mft record and we return TRUE.
905  *
906  * The ntfs inode for the extent mft record is attached to the base inode so we
907  * attempt to lock the extent mft record and if we find the lock was already
908  * taken, it is not safe to write the extent mft record and we return FALSE.
909  *
910  * If we manage to obtain the lock we have exclusive access to the extent mft
911  * record, which also allows us safe writeout of the extent mft record.  We
912  * set the ntfs inode of the extent mft record clean and then set @locked_ni to
913  * the now locked ntfs inode and return TRUE.
914  *
915  * Note, the reason for actually writing dirty mft records here and not just
916  * relying on the vfs inode dirty code paths is that we can have mft records
917  * modified without them ever having actual inodes in memory.  Also we can have
918  * dirty mft records with clean ntfs inodes in memory.  None of the described
919  * cases would result in the dirty mft records being written out if we only
920  * relied on the vfs inode dirty code paths.  And these cases can really occur
921  * during allocation of new mft records and in particular when the
922  * initialized_size of the $MFT/$DATA attribute is extended and the new space
923  * is initialized using ntfs_mft_record_format().  The clean inode can then
924  * appear if the mft record is reused for a new inode before it got written
925  * out.
926  */
927 BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
928                 const MFT_RECORD *m, ntfs_inode **locked_ni)
929 {
930         struct super_block *sb = vol->sb;
931         struct inode *mft_vi = vol->mft_ino;
932         struct inode *vi;
933         ntfs_inode *ni, *eni, **extent_nis;
934         int i;
935         ntfs_attr na;
936
937         ntfs_debug("Entering for inode 0x%lx.", mft_no);
938         /*
939          * Normally we do not return a locked inode so set @locked_ni to NULL.
940          */
941         BUG_ON(!locked_ni);
942         *locked_ni = NULL;
943         /*
944          * Check if the inode corresponding to this mft record is in the VFS
945          * inode cache and obtain a reference to it if it is.
946          */
947         ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
948         na.mft_no = mft_no;
949         na.name = NULL;
950         na.name_len = 0;
951         na.type = AT_UNUSED;
952         /*
953          * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
954          * we get here for it rather often.
955          */
956         if (!mft_no) {
957                 /* Balance the below iput(). */
958                 vi = igrab(mft_vi);
959                 BUG_ON(vi != mft_vi);
960         } else {
961                 /*
962                  * Have to use ilookup5_nowait() since ilookup5() waits for the
963                  * inode lock which causes ntfs to deadlock when a concurrent
964                  * inode write via the inode dirty code paths and the page
965                  * dirty code path of the inode dirty code path when writing
966                  * $MFT occurs.
967                  */
968                 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
969         }
970         if (vi) {
971                 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
972                 /* The inode is in icache. */
973                 ni = NTFS_I(vi);
974                 /* Take a reference to the ntfs inode. */
975                 atomic_inc(&ni->count);
976                 /* If the inode is dirty, do not write this record. */
977                 if (NInoDirty(ni)) {
978                         ntfs_debug("Inode 0x%lx is dirty, do not write it.",
979                                         mft_no);
980                         atomic_dec(&ni->count);
981                         iput(vi);
982                         return FALSE;
983                 }
984                 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
985                 /* The inode is not dirty, try to take the mft record lock. */
986                 if (unlikely(down_trylock(&ni->mrec_lock))) {
987                         ntfs_debug("Mft record 0x%lx is already locked, do "
988                                         "not write it.", mft_no);
989                         atomic_dec(&ni->count);
990                         iput(vi);
991                         return FALSE;
992                 }
993                 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
994                                 mft_no);
995                 /*
996                  * The write has to occur while we hold the mft record lock so
997                  * return the locked ntfs inode.
998                  */
999                 *locked_ni = ni;
1000                 return TRUE;
1001         }
1002         ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1003         /* The inode is not in icache. */
1004         /* Write the record if it is not a mft record (type "FILE"). */
1005         if (!ntfs_is_mft_record(m->magic)) {
1006                 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1007                                 mft_no);
1008                 return TRUE;
1009         }
1010         /* Write the mft record if it is a base inode. */
1011         if (!m->base_mft_record) {
1012                 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1013                                 mft_no);
1014                 return TRUE;
1015         }
1016         /*
1017          * This is an extent mft record.  Check if the inode corresponding to
1018          * its base mft record is in icache and obtain a reference to it if it
1019          * is.
1020          */
1021         na.mft_no = MREF_LE(m->base_mft_record);
1022         ntfs_debug("Mft record 0x%lx is an extent record.  Looking for base "
1023                         "inode 0x%lx in icache.", mft_no, na.mft_no);
1024         if (!na.mft_no) {
1025                 /* Balance the below iput(). */
1026                 vi = igrab(mft_vi);
1027                 BUG_ON(vi != mft_vi);
1028         } else
1029                 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1030                                 &na);
1031         if (!vi) {
1032                 /*
1033                  * The base inode is not in icache, write this extent mft
1034                  * record.
1035                  */
1036                 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1037                                 "extent record.", na.mft_no);
1038                 return TRUE;
1039         }
1040         ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1041         /*
1042          * The base inode is in icache.  Check if it has the extent inode
1043          * corresponding to this extent mft record attached.
1044          */
1045         ni = NTFS_I(vi);
1046         down(&ni->extent_lock);
1047         if (ni->nr_extents <= 0) {
1048                 /*
1049                  * The base inode has no attached extent inodes, write this
1050                  * extent mft record.
1051                  */
1052                 up(&ni->extent_lock);
1053                 iput(vi);
1054                 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1055                                 "write the extent record.", na.mft_no);
1056                 return TRUE;
1057         }
1058         /* Iterate over the attached extent inodes. */
1059         extent_nis = ni->ext.extent_ntfs_inos;
1060         for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1061                 if (mft_no == extent_nis[i]->mft_no) {
1062                         /*
1063                          * Found the extent inode corresponding to this extent
1064                          * mft record.
1065                          */
1066                         eni = extent_nis[i];
1067                         break;
1068                 }
1069         }
1070         /*
1071          * If the extent inode was not attached to the base inode, write this
1072          * extent mft record.
1073          */
1074         if (!eni) {
1075                 up(&ni->extent_lock);
1076                 iput(vi);
1077                 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1078                                 "inode 0x%lx, write the extent record.",
1079                                 mft_no, na.mft_no);
1080                 return TRUE;
1081         }
1082         ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1083                         mft_no, na.mft_no);
1084         /* Take a reference to the extent ntfs inode. */
1085         atomic_inc(&eni->count);
1086         up(&ni->extent_lock);
1087         /*
1088          * Found the extent inode coresponding to this extent mft record.
1089          * Try to take the mft record lock.
1090          */
1091         if (unlikely(down_trylock(&eni->mrec_lock))) {
1092                 atomic_dec(&eni->count);
1093                 iput(vi);
1094                 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1095                                 "not write it.", mft_no);
1096                 return FALSE;
1097         }
1098         ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1099                         mft_no);
1100         if (NInoTestClearDirty(eni))
1101                 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1102                                 mft_no);
1103         /*
1104          * The write has to occur while we hold the mft record lock so return
1105          * the locked extent ntfs inode.
1106          */
1107         *locked_ni = eni;
1108         return TRUE;
1109 }
1110
1111 static const char *es = "  Leaving inconsistent metadata.  Unmount and run "
1112                 "chkdsk.";
1113
1114 /**
1115  * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1116  * @vol:        volume on which to search for a free mft record
1117  * @base_ni:    open base inode if allocating an extent mft record or NULL
1118  *
1119  * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1120  * @vol.
1121  *
1122  * If @base_ni is NULL start the search at the default allocator position.
1123  *
1124  * If @base_ni is not NULL start the search at the mft record after the base
1125  * mft record @base_ni.
1126  *
1127  * Return the free mft record on success and -errno on error.  An error code of
1128  * -ENOSPC means that there are no free mft records in the currently
1129  * initialized mft bitmap.
1130  *
1131  * Locking: Caller must hold vol->mftbmp_lock for writing.
1132  */
1133 static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1134                 ntfs_inode *base_ni)
1135 {
1136         s64 pass_end, ll, data_pos, pass_start, ofs, bit;
1137         unsigned long flags;
1138         struct address_space *mftbmp_mapping;
1139         u8 *buf, *byte;
1140         struct page *page;
1141         unsigned int page_ofs, size;
1142         u8 pass, b;
1143
1144         ntfs_debug("Searching for free mft record in the currently "
1145                         "initialized mft bitmap.");
1146         mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1147         /*
1148          * Set the end of the pass making sure we do not overflow the mft
1149          * bitmap.
1150          */
1151         read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
1152         pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1153                         vol->mft_record_size_bits;
1154         read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1155         read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1156         ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
1157         read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
1158         if (pass_end > ll)
1159                 pass_end = ll;
1160         pass = 1;
1161         if (!base_ni)
1162                 data_pos = vol->mft_data_pos;
1163         else
1164                 data_pos = base_ni->mft_no + 1;
1165         if (data_pos < 24)
1166                 data_pos = 24;
1167         if (data_pos >= pass_end) {
1168                 data_pos = 24;
1169                 pass = 2;
1170                 /* This happens on a freshly formatted volume. */
1171                 if (data_pos >= pass_end)
1172                         return -ENOSPC;
1173         }
1174         pass_start = data_pos;
1175         ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1176                         "pass_end 0x%llx, data_pos 0x%llx.", pass,
1177                         (long long)pass_start, (long long)pass_end,
1178                         (long long)data_pos);
1179         /* Loop until a free mft record is found. */
1180         for (; pass <= 2;) {
1181                 /* Cap size to pass_end. */
1182                 ofs = data_pos >> 3;
1183                 page_ofs = ofs & ~PAGE_CACHE_MASK;
1184                 size = PAGE_CACHE_SIZE - page_ofs;
1185                 ll = ((pass_end + 7) >> 3) - ofs;
1186                 if (size > ll)
1187                         size = ll;
1188                 size <<= 3;
1189                 /*
1190                  * If we are still within the active pass, search the next page
1191                  * for a zero bit.
1192                  */
1193                 if (size) {
1194                         page = ntfs_map_page(mftbmp_mapping,
1195                                         ofs >> PAGE_CACHE_SHIFT);
1196                         if (unlikely(IS_ERR(page))) {
1197                                 ntfs_error(vol->sb, "Failed to read mft "
1198                                                 "bitmap, aborting.");
1199                                 return PTR_ERR(page);
1200                         }
1201                         buf = (u8*)page_address(page) + page_ofs;
1202                         bit = data_pos & 7;
1203                         data_pos &= ~7ull;
1204                         ntfs_debug("Before inner for loop: size 0x%x, "
1205                                         "data_pos 0x%llx, bit 0x%llx", size,
1206                                         (long long)data_pos, (long long)bit);
1207                         for (; bit < size && data_pos + bit < pass_end;
1208                                         bit &= ~7ull, bit += 8) {
1209                                 byte = buf + (bit >> 3);
1210                                 if (*byte == 0xff)
1211                                         continue;
1212                                 b = ffz((unsigned long)*byte);
1213                                 if (b < 8 && b >= (bit & 7)) {
1214                                         ll = data_pos + (bit & ~7ull) + b;
1215                                         if (unlikely(ll > (1ll << 32))) {
1216                                                 ntfs_unmap_page(page);
1217                                                 return -ENOSPC;
1218                                         }
1219                                         *byte |= 1 << b;
1220                                         flush_dcache_page(page);
1221                                         set_page_dirty(page);
1222                                         ntfs_unmap_page(page);
1223                                         ntfs_debug("Done.  (Found and "
1224                                                         "allocated mft record "
1225                                                         "0x%llx.)",
1226                                                         (long long)ll);
1227                                         return ll;
1228                                 }
1229                         }
1230                         ntfs_debug("After inner for loop: size 0x%x, "
1231                                         "data_pos 0x%llx, bit 0x%llx", size,
1232                                         (long long)data_pos, (long long)bit);
1233                         data_pos += size;
1234                         ntfs_unmap_page(page);
1235                         /*
1236                          * If the end of the pass has not been reached yet,
1237                          * continue searching the mft bitmap for a zero bit.
1238                          */
1239                         if (data_pos < pass_end)
1240                                 continue;
1241                 }
1242                 /* Do the next pass. */
1243                 if (++pass == 2) {
1244                         /*
1245                          * Starting the second pass, in which we scan the first
1246                          * part of the zone which we omitted earlier.
1247                          */
1248                         pass_end = pass_start;
1249                         data_pos = pass_start = 24;
1250                         ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1251                                         "0x%llx.", pass, (long long)pass_start,
1252                                         (long long)pass_end);
1253                         if (data_pos >= pass_end)
1254                                 break;
1255                 }
1256         }
1257         /* No free mft records in currently initialized mft bitmap. */
1258         ntfs_debug("Done.  (No free mft records left in currently initialized "
1259                         "mft bitmap.)");
1260         return -ENOSPC;
1261 }
1262
1263 /**
1264  * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1265  * @vol:        volume on which to extend the mft bitmap attribute
1266  *
1267  * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1268  *
1269  * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1270  * data_size.
1271  *
1272  * Return 0 on success and -errno on error.
1273  *
1274  * Locking: - Caller must hold vol->mftbmp_lock for writing.
1275  *          - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1276  *            writing and releases it before returning.
1277  *          - This function takes vol->lcnbmp_lock for writing and releases it
1278  *            before returning.
1279  */
1280 static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1281 {
1282         LCN lcn;
1283         s64 ll;
1284         unsigned long flags;
1285         struct page *page;
1286         ntfs_inode *mft_ni, *mftbmp_ni;
1287         runlist_element *rl, *rl2 = NULL;
1288         ntfs_attr_search_ctx *ctx = NULL;
1289         MFT_RECORD *mrec;
1290         ATTR_RECORD *a = NULL;
1291         int ret, mp_size;
1292         u32 old_alen = 0;
1293         u8 *b, tb;
1294         struct {
1295                 u8 added_cluster:1;
1296                 u8 added_run:1;
1297                 u8 mp_rebuilt:1;
1298         } status = { 0, 0, 0 };
1299
1300         ntfs_debug("Extending mft bitmap allocation.");
1301         mft_ni = NTFS_I(vol->mft_ino);
1302         mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1303         /*
1304          * Determine the last lcn of the mft bitmap.  The allocated size of the
1305          * mft bitmap cannot be zero so we are ok to do this.
1306          */
1307         down_write(&mftbmp_ni->runlist.lock);
1308         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1309         ll = mftbmp_ni->allocated_size;
1310         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1311         rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
1312                         (ll - 1) >> vol->cluster_size_bits, NULL);
1313         if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1314                 up_write(&mftbmp_ni->runlist.lock);
1315                 ntfs_error(vol->sb, "Failed to determine last allocated "
1316                                 "cluster of mft bitmap attribute.");
1317                 if (!IS_ERR(rl))
1318                         ret = -EIO;
1319                 else
1320                         ret = PTR_ERR(rl);
1321                 return ret;
1322         }
1323         lcn = rl->lcn + rl->length;
1324         ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1325                         (long long)lcn);
1326         /*
1327          * Attempt to get the cluster following the last allocated cluster by
1328          * hand as it may be in the MFT zone so the allocator would not give it
1329          * to us.
1330          */
1331         ll = lcn >> 3;
1332         page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1333                         ll >> PAGE_CACHE_SHIFT);
1334         if (IS_ERR(page)) {
1335                 up_write(&mftbmp_ni->runlist.lock);
1336                 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1337                 return PTR_ERR(page);
1338         }
1339         b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1340         tb = 1 << (lcn & 7ull);
1341         down_write(&vol->lcnbmp_lock);
1342         if (*b != 0xff && !(*b & tb)) {
1343                 /* Next cluster is free, allocate it. */
1344                 *b |= tb;
1345                 flush_dcache_page(page);
1346                 set_page_dirty(page);
1347                 up_write(&vol->lcnbmp_lock);
1348                 ntfs_unmap_page(page);
1349                 /* Update the mft bitmap runlist. */
1350                 rl->length++;
1351                 rl[1].vcn++;
1352                 status.added_cluster = 1;
1353                 ntfs_debug("Appending one cluster to mft bitmap.");
1354         } else {
1355                 up_write(&vol->lcnbmp_lock);
1356                 ntfs_unmap_page(page);
1357                 /* Allocate a cluster from the DATA_ZONE. */
1358                 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
1359                                 TRUE);
1360                 if (IS_ERR(rl2)) {
1361                         up_write(&mftbmp_ni->runlist.lock);
1362                         ntfs_error(vol->sb, "Failed to allocate a cluster for "
1363                                         "the mft bitmap.");
1364                         return PTR_ERR(rl2);
1365                 }
1366                 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1367                 if (IS_ERR(rl)) {
1368                         up_write(&mftbmp_ni->runlist.lock);
1369                         ntfs_error(vol->sb, "Failed to merge runlists for mft "
1370                                         "bitmap.");
1371                         if (ntfs_cluster_free_from_rl(vol, rl2)) {
1372                                 ntfs_error(vol->sb, "Failed to dealocate "
1373                                                 "allocated cluster.%s", es);
1374                                 NVolSetErrors(vol);
1375                         }
1376                         ntfs_free(rl2);
1377                         return PTR_ERR(rl);
1378                 }
1379                 mftbmp_ni->runlist.rl = rl;
1380                 status.added_run = 1;
1381                 ntfs_debug("Adding one run to mft bitmap.");
1382                 /* Find the last run in the new runlist. */
1383                 for (; rl[1].length; rl++)
1384                         ;
1385         }
1386         /*
1387          * Update the attribute record as well.  Note: @rl is the last
1388          * (non-terminator) runlist element of mft bitmap.
1389          */
1390         mrec = map_mft_record(mft_ni);
1391         if (IS_ERR(mrec)) {
1392                 ntfs_error(vol->sb, "Failed to map mft record.");
1393                 ret = PTR_ERR(mrec);
1394                 goto undo_alloc;
1395         }
1396         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1397         if (unlikely(!ctx)) {
1398                 ntfs_error(vol->sb, "Failed to get search context.");
1399                 ret = -ENOMEM;
1400                 goto undo_alloc;
1401         }
1402         ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1403                         mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1404                         0, ctx);
1405         if (unlikely(ret)) {
1406                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1407                                 "mft bitmap attribute.");
1408                 if (ret == -ENOENT)
1409                         ret = -EIO;
1410                 goto undo_alloc;
1411         }
1412         a = ctx->attr;
1413         ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1414         /* Search back for the previous last allocated cluster of mft bitmap. */
1415         for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1416                 if (ll >= rl2->vcn)
1417                         break;
1418         }
1419         BUG_ON(ll < rl2->vcn);
1420         BUG_ON(ll >= rl2->vcn + rl2->length);
1421         /* Get the size for the new mapping pairs array for this extent. */
1422         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1423         if (unlikely(mp_size <= 0)) {
1424                 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1425                                 "mft bitmap attribute extent.");
1426                 ret = mp_size;
1427                 if (!ret)
1428                         ret = -EIO;
1429                 goto undo_alloc;
1430         }
1431         /* Expand the attribute record if necessary. */
1432         old_alen = le32_to_cpu(a->length);
1433         ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1434                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1435         if (unlikely(ret)) {
1436                 if (ret != -ENOSPC) {
1437                         ntfs_error(vol->sb, "Failed to resize attribute "
1438                                         "record for mft bitmap attribute.");
1439                         goto undo_alloc;
1440                 }
1441                 // TODO: Deal with this by moving this extent to a new mft
1442                 // record or by starting a new extent in a new mft record or by
1443                 // moving other attributes out of this mft record.
1444                 // Note: It will need to be a special mft record and if none of
1445                 // those are available it gets rather complicated...
1446                 ntfs_error(vol->sb, "Not enough space in this mft record to "
1447                                 "accomodate extended mft bitmap attribute "
1448                                 "extent.  Cannot handle this yet.");
1449                 ret = -EOPNOTSUPP;
1450                 goto undo_alloc;
1451         }
1452         status.mp_rebuilt = 1;
1453         /* Generate the mapping pairs array directly into the attr record. */
1454         ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1455                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1456                         mp_size, rl2, ll, -1, NULL);
1457         if (unlikely(ret)) {
1458                 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1459                                 "mft bitmap attribute.");
1460                 goto undo_alloc;
1461         }
1462         /* Update the highest_vcn. */
1463         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1464         /*
1465          * We now have extended the mft bitmap allocated_size by one cluster.
1466          * Reflect this in the ntfs_inode structure and the attribute record.
1467          */
1468         if (a->data.non_resident.lowest_vcn) {
1469                 /*
1470                  * We are not in the first attribute extent, switch to it, but
1471                  * first ensure the changes will make it to disk later.
1472                  */
1473                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1474                 mark_mft_record_dirty(ctx->ntfs_ino);
1475                 ntfs_attr_reinit_search_ctx(ctx);
1476                 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1477                                 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1478                                 0, ctx);
1479                 if (unlikely(ret)) {
1480                         ntfs_error(vol->sb, "Failed to find first attribute "
1481                                         "extent of mft bitmap attribute.");
1482                         goto restore_undo_alloc;
1483                 }
1484                 a = ctx->attr;
1485         }
1486         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1487         mftbmp_ni->allocated_size += vol->cluster_size;
1488         a->data.non_resident.allocated_size =
1489                         cpu_to_sle64(mftbmp_ni->allocated_size);
1490         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1491         /* Ensure the changes make it to disk. */
1492         flush_dcache_mft_record_page(ctx->ntfs_ino);
1493         mark_mft_record_dirty(ctx->ntfs_ino);
1494         ntfs_attr_put_search_ctx(ctx);
1495         unmap_mft_record(mft_ni);
1496         up_write(&mftbmp_ni->runlist.lock);
1497         ntfs_debug("Done.");
1498         return 0;
1499 restore_undo_alloc:
1500         ntfs_attr_reinit_search_ctx(ctx);
1501         if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1502                         mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1503                         0, ctx)) {
1504                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1505                                 "mft bitmap attribute.%s", es);
1506                 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1507                 mftbmp_ni->allocated_size += vol->cluster_size;
1508                 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1509                 ntfs_attr_put_search_ctx(ctx);
1510                 unmap_mft_record(mft_ni);
1511                 up_write(&mftbmp_ni->runlist.lock);
1512                 /*
1513                  * The only thing that is now wrong is ->allocated_size of the
1514                  * base attribute extent which chkdsk should be able to fix.
1515                  */
1516                 NVolSetErrors(vol);
1517                 return ret;
1518         }
1519         a = ctx->attr;
1520         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1521 undo_alloc:
1522         if (status.added_cluster) {
1523                 /* Truncate the last run in the runlist by one cluster. */
1524                 rl->length--;
1525                 rl[1].vcn--;
1526         } else if (status.added_run) {
1527                 lcn = rl->lcn;
1528                 /* Remove the last run from the runlist. */
1529                 rl->lcn = rl[1].lcn;
1530                 rl->length = 0;
1531         }
1532         /* Deallocate the cluster. */
1533         down_write(&vol->lcnbmp_lock);
1534         if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1535                 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1536                 NVolSetErrors(vol);
1537         }
1538         up_write(&vol->lcnbmp_lock);
1539         if (status.mp_rebuilt) {
1540                 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1541                                 a->data.non_resident.mapping_pairs_offset),
1542                                 old_alen - le16_to_cpu(
1543                                 a->data.non_resident.mapping_pairs_offset),
1544                                 rl2, ll, -1, NULL)) {
1545                         ntfs_error(vol->sb, "Failed to restore mapping pairs "
1546                                         "array.%s", es);
1547                         NVolSetErrors(vol);
1548                 }
1549                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1550                         ntfs_error(vol->sb, "Failed to restore attribute "
1551                                         "record.%s", es);
1552                         NVolSetErrors(vol);
1553                 }
1554                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1555                 mark_mft_record_dirty(ctx->ntfs_ino);
1556         }
1557         if (ctx)
1558                 ntfs_attr_put_search_ctx(ctx);
1559         if (!IS_ERR(mrec))
1560                 unmap_mft_record(mft_ni);
1561         up_write(&mftbmp_ni->runlist.lock);
1562         return ret;
1563 }
1564
1565 /**
1566  * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1567  * @vol:        volume on which to extend the mft bitmap attribute
1568  *
1569  * Extend the initialized portion of the mft bitmap attribute on the ntfs
1570  * volume @vol by 8 bytes.
1571  *
1572  * Note:  Only changes initialized_size and data_size, i.e. requires that
1573  * allocated_size is big enough to fit the new initialized_size.
1574  *
1575  * Return 0 on success and -error on error.
1576  *
1577  * Locking: Caller must hold vol->mftbmp_lock for writing.
1578  */
1579 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1580 {
1581         s64 old_data_size, old_initialized_size;
1582         unsigned long flags;
1583         struct inode *mftbmp_vi;
1584         ntfs_inode *mft_ni, *mftbmp_ni;
1585         ntfs_attr_search_ctx *ctx;
1586         MFT_RECORD *mrec;
1587         ATTR_RECORD *a;
1588         int ret;
1589
1590         ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1591         mft_ni = NTFS_I(vol->mft_ino);
1592         mftbmp_vi = vol->mftbmp_ino;
1593         mftbmp_ni = NTFS_I(mftbmp_vi);
1594         /* Get the attribute record. */
1595         mrec = map_mft_record(mft_ni);
1596         if (IS_ERR(mrec)) {
1597                 ntfs_error(vol->sb, "Failed to map mft record.");
1598                 return PTR_ERR(mrec);
1599         }
1600         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1601         if (unlikely(!ctx)) {
1602                 ntfs_error(vol->sb, "Failed to get search context.");
1603                 ret = -ENOMEM;
1604                 goto unm_err_out;
1605         }
1606         ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1607                         mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1608         if (unlikely(ret)) {
1609                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1610                                 "mft bitmap attribute.");
1611                 if (ret == -ENOENT)
1612                         ret = -EIO;
1613                 goto put_err_out;
1614         }
1615         a = ctx->attr;
1616         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1617         old_data_size = i_size_read(mftbmp_vi);
1618         old_initialized_size = mftbmp_ni->initialized_size;
1619         /*
1620          * We can simply update the initialized_size before filling the space
1621          * with zeroes because the caller is holding the mft bitmap lock for
1622          * writing which ensures that no one else is trying to access the data.
1623          */
1624         mftbmp_ni->initialized_size += 8;
1625         a->data.non_resident.initialized_size =
1626                         cpu_to_sle64(mftbmp_ni->initialized_size);
1627         if (mftbmp_ni->initialized_size > old_data_size) {
1628                 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1629                 a->data.non_resident.data_size =
1630                                 cpu_to_sle64(mftbmp_ni->initialized_size);
1631         }
1632         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1633         /* Ensure the changes make it to disk. */
1634         flush_dcache_mft_record_page(ctx->ntfs_ino);
1635         mark_mft_record_dirty(ctx->ntfs_ino);
1636         ntfs_attr_put_search_ctx(ctx);
1637         unmap_mft_record(mft_ni);
1638         /* Initialize the mft bitmap attribute value with zeroes. */
1639         ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1640         if (likely(!ret)) {
1641                 ntfs_debug("Done.  (Wrote eight initialized bytes to mft "
1642                                 "bitmap.");
1643                 return 0;
1644         }
1645         ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1646         /* Try to recover from the error. */
1647         mrec = map_mft_record(mft_ni);
1648         if (IS_ERR(mrec)) {
1649                 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1650                 NVolSetErrors(vol);
1651                 return ret;
1652         }
1653         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1654         if (unlikely(!ctx)) {
1655                 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1656                 NVolSetErrors(vol);
1657                 goto unm_err_out;
1658         }
1659         if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1660                         mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1661                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1662                                 "mft bitmap attribute.%s", es);
1663                 NVolSetErrors(vol);
1664 put_err_out:
1665                 ntfs_attr_put_search_ctx(ctx);
1666 unm_err_out:
1667                 unmap_mft_record(mft_ni);
1668                 goto err_out;
1669         }
1670         a = ctx->attr;
1671         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1672         mftbmp_ni->initialized_size = old_initialized_size;
1673         a->data.non_resident.initialized_size =
1674                         cpu_to_sle64(old_initialized_size);
1675         if (i_size_read(mftbmp_vi) != old_data_size) {
1676                 i_size_write(mftbmp_vi, old_data_size);
1677                 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1678         }
1679         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1680         flush_dcache_mft_record_page(ctx->ntfs_ino);
1681         mark_mft_record_dirty(ctx->ntfs_ino);
1682         ntfs_attr_put_search_ctx(ctx);
1683         unmap_mft_record(mft_ni);
1684 #ifdef DEBUG
1685         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1686         ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1687                         "data_size 0x%llx, initialized_size 0x%llx.",
1688                         (long long)mftbmp_ni->allocated_size,
1689                         (long long)i_size_read(mftbmp_vi),
1690                         (long long)mftbmp_ni->initialized_size);
1691         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1692 #endif /* DEBUG */
1693 err_out:
1694         return ret;
1695 }
1696
1697 /**
1698  * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1699  * @vol:        volume on which to extend the mft data attribute
1700  *
1701  * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1702  * worth of clusters or if not enough space for this by one mft record worth
1703  * of clusters.
1704  *
1705  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
1706  * data_size.
1707  *
1708  * Return 0 on success and -errno on error.
1709  *
1710  * Locking: - Caller must hold vol->mftbmp_lock for writing.
1711  *          - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1712  *            writing and releases it before returning.
1713  *          - This function calls functions which take vol->lcnbmp_lock for
1714  *            writing and release it before returning.
1715  */
1716 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1717 {
1718         LCN lcn;
1719         VCN old_last_vcn;
1720         s64 min_nr, nr, ll;
1721         unsigned long flags;
1722         ntfs_inode *mft_ni;
1723         runlist_element *rl, *rl2;
1724         ntfs_attr_search_ctx *ctx = NULL;
1725         MFT_RECORD *mrec;
1726         ATTR_RECORD *a = NULL;
1727         int ret, mp_size;
1728         u32 old_alen = 0;
1729         BOOL mp_rebuilt = FALSE;
1730
1731         ntfs_debug("Extending mft data allocation.");
1732         mft_ni = NTFS_I(vol->mft_ino);
1733         /*
1734          * Determine the preferred allocation location, i.e. the last lcn of
1735          * the mft data attribute.  The allocated size of the mft data
1736          * attribute cannot be zero so we are ok to do this.
1737          */
1738         down_write(&mft_ni->runlist.lock);
1739         read_lock_irqsave(&mft_ni->size_lock, flags);
1740         ll = mft_ni->allocated_size;
1741         read_unlock_irqrestore(&mft_ni->size_lock, flags);
1742         rl = ntfs_attr_find_vcn_nolock(mft_ni,
1743                         (ll - 1) >> vol->cluster_size_bits, NULL);
1744         if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1745                 up_write(&mft_ni->runlist.lock);
1746                 ntfs_error(vol->sb, "Failed to determine last allocated "
1747                                 "cluster of mft data attribute.");
1748                 if (!IS_ERR(rl))
1749                         ret = -EIO;
1750                 else
1751                         ret = PTR_ERR(rl);
1752                 return ret;
1753         }
1754         lcn = rl->lcn + rl->length;
1755         ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1756         /* Minimum allocation is one mft record worth of clusters. */
1757         min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1758         if (!min_nr)
1759                 min_nr = 1;
1760         /* Want to allocate 16 mft records worth of clusters. */
1761         nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1762         if (!nr)
1763                 nr = min_nr;
1764         /* Ensure we do not go above 2^32-1 mft records. */
1765         read_lock_irqsave(&mft_ni->size_lock, flags);
1766         ll = mft_ni->allocated_size;
1767         read_unlock_irqrestore(&mft_ni->size_lock, flags);
1768         if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1769                         vol->mft_record_size_bits >= (1ll << 32))) {
1770                 nr = min_nr;
1771                 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1772                                 vol->mft_record_size_bits >= (1ll << 32))) {
1773                         ntfs_warning(vol->sb, "Cannot allocate mft record "
1774                                         "because the maximum number of inodes "
1775                                         "(2^32) has already been reached.");
1776                         up_write(&mft_ni->runlist.lock);
1777                         return -ENOSPC;
1778                 }
1779         }
1780         ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1781                         nr > min_nr ? "default" : "minimal", (long long)nr);
1782         old_last_vcn = rl[1].vcn;
1783         do {
1784                 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
1785                                 TRUE);
1786                 if (likely(!IS_ERR(rl2)))
1787                         break;
1788                 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1789                         ntfs_error(vol->sb, "Failed to allocate the minimal "
1790                                         "number of clusters (%lli) for the "
1791                                         "mft data attribute.", (long long)nr);
1792                         up_write(&mft_ni->runlist.lock);
1793                         return PTR_ERR(rl2);
1794                 }
1795                 /*
1796                  * There is not enough space to do the allocation, but there
1797                  * might be enough space to do a minimal allocation so try that
1798                  * before failing.
1799                  */
1800                 nr = min_nr;
1801                 ntfs_debug("Retrying mft data allocation with minimal cluster "
1802                                 "count %lli.", (long long)nr);
1803         } while (1);
1804         rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1805         if (IS_ERR(rl)) {
1806                 up_write(&mft_ni->runlist.lock);
1807                 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1808                                 "attribute.");
1809                 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1810                         ntfs_error(vol->sb, "Failed to dealocate clusters "
1811                                         "from the mft data attribute.%s", es);
1812                         NVolSetErrors(vol);
1813                 }
1814                 ntfs_free(rl2);
1815                 return PTR_ERR(rl);
1816         }
1817         mft_ni->runlist.rl = rl;
1818         ntfs_debug("Allocated %lli clusters.", (long long)nr);
1819         /* Find the last run in the new runlist. */
1820         for (; rl[1].length; rl++)
1821                 ;
1822         /* Update the attribute record as well. */
1823         mrec = map_mft_record(mft_ni);
1824         if (IS_ERR(mrec)) {
1825                 ntfs_error(vol->sb, "Failed to map mft record.");
1826                 ret = PTR_ERR(mrec);
1827                 goto undo_alloc;
1828         }
1829         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1830         if (unlikely(!ctx)) {
1831                 ntfs_error(vol->sb, "Failed to get search context.");
1832                 ret = -ENOMEM;
1833                 goto undo_alloc;
1834         }
1835         ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1836                         CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1837         if (unlikely(ret)) {
1838                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1839                                 "mft data attribute.");
1840                 if (ret == -ENOENT)
1841                         ret = -EIO;
1842                 goto undo_alloc;
1843         }
1844         a = ctx->attr;
1845         ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1846         /* Search back for the previous last allocated cluster of mft bitmap. */
1847         for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1848                 if (ll >= rl2->vcn)
1849                         break;
1850         }
1851         BUG_ON(ll < rl2->vcn);
1852         BUG_ON(ll >= rl2->vcn + rl2->length);
1853         /* Get the size for the new mapping pairs array for this extent. */
1854         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1855         if (unlikely(mp_size <= 0)) {
1856                 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1857                                 "mft data attribute extent.");
1858                 ret = mp_size;
1859                 if (!ret)
1860                         ret = -EIO;
1861                 goto undo_alloc;
1862         }
1863         /* Expand the attribute record if necessary. */
1864         old_alen = le32_to_cpu(a->length);
1865         ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1866                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1867         if (unlikely(ret)) {
1868                 if (ret != -ENOSPC) {
1869                         ntfs_error(vol->sb, "Failed to resize attribute "
1870                                         "record for mft data attribute.");
1871                         goto undo_alloc;
1872                 }
1873                 // TODO: Deal with this by moving this extent to a new mft
1874                 // record or by starting a new extent in a new mft record or by
1875                 // moving other attributes out of this mft record.
1876                 // Note: Use the special reserved mft records and ensure that
1877                 // this extent is not required to find the mft record in
1878                 // question.  If no free special records left we would need to
1879                 // move an existing record away, insert ours in its place, and
1880                 // then place the moved record into the newly allocated space
1881                 // and we would then need to update all references to this mft
1882                 // record appropriately.  This is rather complicated...
1883                 ntfs_error(vol->sb, "Not enough space in this mft record to "
1884                                 "accomodate extended mft data attribute "
1885                                 "extent.  Cannot handle this yet.");
1886                 ret = -EOPNOTSUPP;
1887                 goto undo_alloc;
1888         }
1889         mp_rebuilt = TRUE;
1890         /* Generate the mapping pairs array directly into the attr record. */
1891         ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1892                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1893                         mp_size, rl2, ll, -1, NULL);
1894         if (unlikely(ret)) {
1895                 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1896                                 "mft data attribute.");
1897                 goto undo_alloc;
1898         }
1899         /* Update the highest_vcn. */
1900         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1901         /*
1902          * We now have extended the mft data allocated_size by nr clusters.
1903          * Reflect this in the ntfs_inode structure and the attribute record.
1904          * @rl is the last (non-terminator) runlist element of mft data
1905          * attribute.
1906          */
1907         if (a->data.non_resident.lowest_vcn) {
1908                 /*
1909                  * We are not in the first attribute extent, switch to it, but
1910                  * first ensure the changes will make it to disk later.
1911                  */
1912                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1913                 mark_mft_record_dirty(ctx->ntfs_ino);
1914                 ntfs_attr_reinit_search_ctx(ctx);
1915                 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1916                                 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1917                                 ctx);
1918                 if (unlikely(ret)) {
1919                         ntfs_error(vol->sb, "Failed to find first attribute "
1920                                         "extent of mft data attribute.");
1921                         goto restore_undo_alloc;
1922                 }
1923                 a = ctx->attr;
1924         }
1925         write_lock_irqsave(&mft_ni->size_lock, flags);
1926         mft_ni->allocated_size += nr << vol->cluster_size_bits;
1927         a->data.non_resident.allocated_size =
1928                         cpu_to_sle64(mft_ni->allocated_size);
1929         write_unlock_irqrestore(&mft_ni->size_lock, flags);
1930         /* Ensure the changes make it to disk. */
1931         flush_dcache_mft_record_page(ctx->ntfs_ino);
1932         mark_mft_record_dirty(ctx->ntfs_ino);
1933         ntfs_attr_put_search_ctx(ctx);
1934         unmap_mft_record(mft_ni);
1935         up_write(&mft_ni->runlist.lock);
1936         ntfs_debug("Done.");
1937         return 0;
1938 restore_undo_alloc:
1939         ntfs_attr_reinit_search_ctx(ctx);
1940         if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1941                         CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1942                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1943                                 "mft data attribute.%s", es);
1944                 write_lock_irqsave(&mft_ni->size_lock, flags);
1945                 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1946                 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1947                 ntfs_attr_put_search_ctx(ctx);
1948                 unmap_mft_record(mft_ni);
1949                 up_write(&mft_ni->runlist.lock);
1950                 /*
1951                  * The only thing that is now wrong is ->allocated_size of the
1952                  * base attribute extent which chkdsk should be able to fix.
1953                  */
1954                 NVolSetErrors(vol);
1955                 return ret;
1956         }
1957         ctx->attr->data.non_resident.highest_vcn =
1958                         cpu_to_sle64(old_last_vcn - 1);
1959 undo_alloc:
1960         if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
1961                 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1962                                 "attribute.%s", es);
1963                 NVolSetErrors(vol);
1964         }
1965         a = ctx->attr;
1966         if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1967                 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1968                                 "runlist.%s", es);
1969                 NVolSetErrors(vol);
1970         }
1971         if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
1972                 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1973                                 a->data.non_resident.mapping_pairs_offset),
1974                                 old_alen - le16_to_cpu(
1975                                 a->data.non_resident.mapping_pairs_offset),
1976                                 rl2, ll, -1, NULL)) {
1977                         ntfs_error(vol->sb, "Failed to restore mapping pairs "
1978                                         "array.%s", es);
1979                         NVolSetErrors(vol);
1980                 }
1981                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1982                         ntfs_error(vol->sb, "Failed to restore attribute "
1983                                         "record.%s", es);
1984                         NVolSetErrors(vol);
1985                 }
1986                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1987                 mark_mft_record_dirty(ctx->ntfs_ino);
1988         } else if (IS_ERR(ctx->mrec)) {
1989                 ntfs_error(vol->sb, "Failed to restore attribute search "
1990                                 "context.%s", es);
1991                 NVolSetErrors(vol);
1992         }
1993         if (ctx)
1994                 ntfs_attr_put_search_ctx(ctx);
1995         if (!IS_ERR(mrec))
1996                 unmap_mft_record(mft_ni);
1997         up_write(&mft_ni->runlist.lock);
1998         return ret;
1999 }
2000
2001 /**
2002  * ntfs_mft_record_layout - layout an mft record into a memory buffer
2003  * @vol:        volume to which the mft record will belong
2004  * @mft_no:     mft reference specifying the mft record number
2005  * @m:          destination buffer of size >= @vol->mft_record_size bytes
2006  *
2007  * Layout an empty, unused mft record with the mft record number @mft_no into
2008  * the buffer @m.  The volume @vol is needed because the mft record structure
2009  * was modified in NTFS 3.1 so we need to know which volume version this mft
2010  * record will be used on.
2011  *
2012  * Return 0 on success and -errno on error.
2013  */
2014 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2015                 MFT_RECORD *m)
2016 {
2017         ATTR_RECORD *a;
2018
2019         ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2020         if (mft_no >= (1ll << 32)) {
2021                 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2022                                 "maximum of 2^32.", (long long)mft_no);
2023                 return -ERANGE;
2024         }
2025         /* Start by clearing the whole mft record to gives us a clean slate. */
2026         memset(m, 0, vol->mft_record_size);
2027         /* Aligned to 2-byte boundary. */
2028         if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2029                 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2030         else {
2031                 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2032                 /*
2033                  * Set the NTFS 3.1+ specific fields while we know that the
2034                  * volume version is 3.1+.
2035                  */
2036                 m->reserved = 0;
2037                 m->mft_record_number = cpu_to_le32((u32)mft_no);
2038         }
2039         m->magic = magic_FILE;
2040         if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2041                 m->usa_count = cpu_to_le16(vol->mft_record_size /
2042                                 NTFS_BLOCK_SIZE + 1);
2043         else {
2044                 m->usa_count = cpu_to_le16(1);
2045                 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2046                                 "size.  Setting usa_count to 1.  If chkdsk "
2047                                 "reports this as corruption, please email "
2048                                 "linux-ntfs-dev@lists.sourceforge.net stating "
2049                                 "that you saw this message and that the "
2050                                 "modified filesystem created was corrupt.  "
2051                                 "Thank you.");
2052         }
2053         /* Set the update sequence number to 1. */
2054         *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2055         m->lsn = 0;
2056         m->sequence_number = cpu_to_le16(1);
2057         m->link_count = 0;
2058         /*
2059          * Place the attributes straight after the update sequence array,
2060          * aligned to 8-byte boundary.
2061          */
2062         m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2063                         (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2064         m->flags = 0;
2065         /*
2066          * Using attrs_offset plus eight bytes (for the termination attribute).
2067          * attrs_offset is already aligned to 8-byte boundary, so no need to
2068          * align again.
2069          */
2070         m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2071         m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2072         m->base_mft_record = 0;
2073         m->next_attr_instance = 0;
2074         /* Add the termination attribute. */
2075         a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2076         a->type = AT_END;
2077         a->length = 0;
2078         ntfs_debug("Done.");
2079         return 0;
2080 }
2081
2082 /**
2083  * ntfs_mft_record_format - format an mft record on an ntfs volume
2084  * @vol:        volume on which to format the mft record
2085  * @mft_no:     mft record number to format
2086  *
2087  * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2088  * mft record into the appropriate place of the mft data attribute.  This is
2089  * used when extending the mft data attribute.
2090  *
2091  * Return 0 on success and -errno on error.
2092  */
2093 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2094 {
2095         loff_t i_size;
2096         struct inode *mft_vi = vol->mft_ino;
2097         struct page *page;
2098         MFT_RECORD *m;
2099         pgoff_t index, end_index;
2100         unsigned int ofs;
2101         int err;
2102
2103         ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2104         /*
2105          * The index into the page cache and the offset within the page cache
2106          * page of the wanted mft record.
2107          */
2108         index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2109         ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2110         /* The maximum valid index into the page cache for $MFT's data. */
2111         i_size = i_size_read(mft_vi);
2112         end_index = i_size >> PAGE_CACHE_SHIFT;
2113         if (unlikely(index >= end_index)) {
2114                 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2115                                 (i_size & ~PAGE_CACHE_MASK))) {
2116                         ntfs_error(vol->sb, "Tried to format non-existing mft "
2117                                         "record 0x%llx.", (long long)mft_no);
2118                         return -ENOENT;
2119                 }
2120         }
2121         /* Read, map, and pin the page containing the mft record. */
2122         page = ntfs_map_page(mft_vi->i_mapping, index);
2123         if (unlikely(IS_ERR(page))) {
2124                 ntfs_error(vol->sb, "Failed to map page containing mft record "
2125                                 "to format 0x%llx.", (long long)mft_no);
2126                 return PTR_ERR(page);
2127         }
2128         lock_page(page);
2129         BUG_ON(!PageUptodate(page));
2130         ClearPageUptodate(page);
2131         m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2132         err = ntfs_mft_record_layout(vol, mft_no, m);
2133         if (unlikely(err)) {
2134                 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2135                                 (long long)mft_no);
2136                 SetPageUptodate(page);
2137                 unlock_page(page);
2138                 ntfs_unmap_page(page);
2139                 return err;
2140         }
2141         flush_dcache_page(page);
2142         SetPageUptodate(page);
2143         unlock_page(page);
2144         /*
2145          * Make sure the mft record is written out to disk.  We could use
2146          * ilookup5() to check if an inode is in icache and so on but this is
2147          * unnecessary as ntfs_writepage() will write the dirty record anyway.
2148          */
2149         mark_ntfs_record_dirty(page, ofs);
2150         ntfs_unmap_page(page);
2151         ntfs_debug("Done.");
2152         return 0;
2153 }
2154
2155 /**
2156  * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2157  * @vol:        [IN]  volume on which to allocate the mft record
2158  * @mode:       [IN]  mode if want a file or directory, i.e. base inode or 0
2159  * @base_ni:    [IN]  open base inode if allocating an extent mft record or NULL
2160  * @mrec:       [OUT] on successful return this is the mapped mft record
2161  *
2162  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2163  *
2164  * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2165  * direvctory inode, and allocate it at the default allocator position.  In
2166  * this case @mode is the file mode as given to us by the caller.  We in
2167  * particular use @mode to distinguish whether a file or a directory is being
2168  * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2169  *
2170  * If @base_ni is not NULL make the allocated mft record an extent record,
2171  * allocate it starting at the mft record after the base mft record and attach
2172  * the allocated and opened ntfs inode to the base inode @base_ni.  In this
2173  * case @mode must be 0 as it is meaningless for extent inodes.
2174  *
2175  * You need to check the return value with IS_ERR().  If false, the function
2176  * was successful and the return value is the now opened ntfs inode of the
2177  * allocated mft record.  *@mrec is then set to the allocated, mapped, pinned,
2178  * and locked mft record.  If IS_ERR() is true, the function failed and the
2179  * error code is obtained from PTR_ERR(return value).  *@mrec is undefined in
2180  * this case.
2181  *
2182  * Allocation strategy:
2183  *
2184  * To find a free mft record, we scan the mft bitmap for a zero bit.  To
2185  * optimize this we start scanning at the place specified by @base_ni or if
2186  * @base_ni is NULL we start where we last stopped and we perform wrap around
2187  * when we reach the end.  Note, we do not try to allocate mft records below
2188  * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2189  * to 24 are special in that they are used for storing extension mft records
2190  * for the $DATA attribute of $MFT.  This is required to avoid the possibility
2191  * of creating a runlist with a circular dependency which once written to disk
2192  * can never be read in again.  Windows will only use records 16 to 24 for
2193  * normal files if the volume is completely out of space.  We never use them
2194  * which means that when the volume is really out of space we cannot create any
2195  * more files while Windows can still create up to 8 small files.  We can start
2196  * doing this at some later time, it does not matter much for now.
2197  *
2198  * When scanning the mft bitmap, we only search up to the last allocated mft
2199  * record.  If there are no free records left in the range 24 to number of
2200  * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2201  * create free mft records.  We extend the allocated size of $MFT/$DATA by 16
2202  * records at a time or one cluster, if cluster size is above 16kiB.  If there
2203  * is not sufficient space to do this, we try to extend by a single mft record
2204  * or one cluster, if cluster size is above the mft record size.
2205  *
2206  * No matter how many mft records we allocate, we initialize only the first
2207  * allocated mft record, incrementing mft data size and initialized size
2208  * accordingly, open an ntfs_inode for it and return it to the caller, unless
2209  * there are less than 24 mft records, in which case we allocate and initialize
2210  * mft records until we reach record 24 which we consider as the first free mft
2211  * record for use by normal files.
2212  *
2213  * If during any stage we overflow the initialized data in the mft bitmap, we
2214  * extend the initialized size (and data size) by 8 bytes, allocating another
2215  * cluster if required.  The bitmap data size has to be at least equal to the
2216  * number of mft records in the mft, but it can be bigger, in which case the
2217  * superflous bits are padded with zeroes.
2218  *
2219  * Thus, when we return successfully (IS_ERR() is false), we will have:
2220  *      - initialized / extended the mft bitmap if necessary,
2221  *      - initialized / extended the mft data if necessary,
2222  *      - set the bit corresponding to the mft record being allocated in the
2223  *        mft bitmap,
2224  *      - opened an ntfs_inode for the allocated mft record, and we will have
2225  *      - returned the ntfs_inode as well as the allocated mapped, pinned, and
2226  *        locked mft record.
2227  *
2228  * On error, the volume will be left in a consistent state and no record will
2229  * be allocated.  If rolling back a partial operation fails, we may leave some
2230  * inconsistent metadata in which case we set NVolErrors() so the volume is
2231  * left dirty when unmounted.
2232  *
2233  * Note, this function cannot make use of most of the normal functions, like
2234  * for example for attribute resizing, etc, because when the run list overflows
2235  * the base mft record and an attribute list is used, it is very important that
2236  * the extension mft records used to store the $DATA attribute of $MFT can be
2237  * reached without having to read the information contained inside them, as
2238  * this would make it impossible to find them in the first place after the
2239  * volume is unmounted.  $MFT/$BITMAP probably does not need to follow this
2240  * rule because the bitmap is not essential for finding the mft records, but on
2241  * the other hand, handling the bitmap in this special way would make life
2242  * easier because otherwise there might be circular invocations of functions
2243  * when reading the bitmap.
2244  */
2245 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2246                 ntfs_inode *base_ni, MFT_RECORD **mrec)
2247 {
2248         s64 ll, bit, old_data_initialized, old_data_size;
2249         unsigned long flags;
2250         struct inode *vi;
2251         struct page *page;
2252         ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2253         ntfs_attr_search_ctx *ctx;
2254         MFT_RECORD *m;
2255         ATTR_RECORD *a;
2256         pgoff_t index;
2257         unsigned int ofs;
2258         int err;
2259         le16 seq_no, usn;
2260         BOOL record_formatted = FALSE;
2261
2262         if (base_ni) {
2263                 ntfs_debug("Entering (allocating an extent mft record for "
2264                                 "base mft record 0x%llx).",
2265                                 (long long)base_ni->mft_no);
2266                 /* @mode and @base_ni are mutually exclusive. */
2267                 BUG_ON(mode);
2268         } else
2269                 ntfs_debug("Entering (allocating a base mft record).");
2270         if (mode) {
2271                 /* @mode and @base_ni are mutually exclusive. */
2272                 BUG_ON(base_ni);
2273                 /* We only support creation of normal files and directories. */
2274                 if (!S_ISREG(mode) && !S_ISDIR(mode))
2275                         return ERR_PTR(-EOPNOTSUPP);
2276         }
2277         BUG_ON(!mrec);
2278         mft_ni = NTFS_I(vol->mft_ino);
2279         mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2280         down_write(&vol->mftbmp_lock);
2281         bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2282         if (bit >= 0) {
2283                 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2284                                 (long long)bit);
2285                 goto have_alloc_rec;
2286         }
2287         if (bit != -ENOSPC) {
2288                 up_write(&vol->mftbmp_lock);
2289                 return ERR_PTR(bit);
2290         }
2291         /*
2292          * No free mft records left.  If the mft bitmap already covers more
2293          * than the currently used mft records, the next records are all free,
2294          * so we can simply allocate the first unused mft record.
2295          * Note: We also have to make sure that the mft bitmap at least covers
2296          * the first 24 mft records as they are special and whilst they may not
2297          * be in use, we do not allocate from them.
2298          */
2299         read_lock_irqsave(&mft_ni->size_lock, flags);
2300         ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2301         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2302         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2303         old_data_initialized = mftbmp_ni->initialized_size;
2304         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2305         if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2306                 bit = ll;
2307                 if (bit < 24)
2308                         bit = 24;
2309                 if (unlikely(bit >= (1ll << 32)))
2310                         goto max_err_out;
2311                 ntfs_debug("Found free record (#2), bit 0x%llx.",
2312                                 (long long)bit);
2313                 goto found_free_rec;
2314         }
2315         /*
2316          * The mft bitmap needs to be expanded until it covers the first unused
2317          * mft record that we can allocate.
2318          * Note: The smallest mft record we allocate is mft record 24.
2319          */
2320         bit = old_data_initialized << 3;
2321         if (unlikely(bit >= (1ll << 32)))
2322                 goto max_err_out;
2323         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2324         old_data_size = mftbmp_ni->allocated_size;
2325         ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2326                         "data_size 0x%llx, initialized_size 0x%llx.",
2327                         (long long)old_data_size,
2328                         (long long)i_size_read(vol->mftbmp_ino),
2329                         (long long)old_data_initialized);
2330         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2331         if (old_data_initialized + 8 > old_data_size) {
2332                 /* Need to extend bitmap by one more cluster. */
2333                 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2334                 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2335                 if (unlikely(err)) {
2336                         up_write(&vol->mftbmp_lock);
2337                         goto err_out;
2338                 }
2339 #ifdef DEBUG
2340                 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2341                 ntfs_debug("Status of mftbmp after allocation extension: "
2342                                 "allocated_size 0x%llx, data_size 0x%llx, "
2343                                 "initialized_size 0x%llx.",
2344                                 (long long)mftbmp_ni->allocated_size,
2345                                 (long long)i_size_read(vol->mftbmp_ino),
2346                                 (long long)mftbmp_ni->initialized_size);
2347                 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2348 #endif /* DEBUG */
2349         }
2350         /*
2351          * We now have sufficient allocated space, extend the initialized_size
2352          * as well as the data_size if necessary and fill the new space with
2353          * zeroes.
2354          */
2355         err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2356         if (unlikely(err)) {
2357                 up_write(&vol->mftbmp_lock);
2358                 goto err_out;
2359         }
2360 #ifdef DEBUG
2361         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2362         ntfs_debug("Status of mftbmp after initialized extention: "
2363                         "allocated_size 0x%llx, data_size 0x%llx, "
2364                         "initialized_size 0x%llx.",
2365                         (long long)mftbmp_ni->allocated_size,
2366                         (long long)i_size_read(vol->mftbmp_ino),
2367                         (long long)mftbmp_ni->initialized_size);
2368         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2369 #endif /* DEBUG */
2370         ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2371 found_free_rec:
2372         /* @bit is the found free mft record, allocate it in the mft bitmap. */
2373         ntfs_debug("At found_free_rec.");
2374         err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2375         if (unlikely(err)) {
2376                 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2377                 up_write(&vol->mftbmp_lock);
2378                 goto err_out;
2379         }
2380         ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2381 have_alloc_rec:
2382         /*
2383          * The mft bitmap is now uptodate.  Deal with mft data attribute now.
2384          * Note, we keep hold of the mft bitmap lock for writing until all
2385          * modifications to the mft data attribute are complete, too, as they
2386          * will impact decisions for mft bitmap and mft record allocation done
2387          * by a parallel allocation and if the lock is not maintained a
2388          * parallel allocation could allocate the same mft record as this one.
2389          */
2390         ll = (bit + 1) << vol->mft_record_size_bits;
2391         read_lock_irqsave(&mft_ni->size_lock, flags);
2392         old_data_initialized = mft_ni->initialized_size;
2393         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2394         if (ll <= old_data_initialized) {
2395                 ntfs_debug("Allocated mft record already initialized.");
2396                 goto mft_rec_already_initialized;
2397         }
2398         ntfs_debug("Initializing allocated mft record.");
2399         /*
2400          * The mft record is outside the initialized data.  Extend the mft data
2401          * attribute until it covers the allocated record.  The loop is only
2402          * actually traversed more than once when a freshly formatted volume is
2403          * first written to so it optimizes away nicely in the common case.
2404          */
2405         read_lock_irqsave(&mft_ni->size_lock, flags);
2406         ntfs_debug("Status of mft data before extension: "
2407                         "allocated_size 0x%llx, data_size 0x%llx, "
2408                         "initialized_size 0x%llx.",
2409                         (long long)mft_ni->allocated_size,
2410                         (long long)i_size_read(vol->mft_ino),
2411                         (long long)mft_ni->initialized_size);
2412         while (ll > mft_ni->allocated_size) {
2413                 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2414                 err = ntfs_mft_data_extend_allocation_nolock(vol);
2415                 if (unlikely(err)) {
2416                         ntfs_error(vol->sb, "Failed to extend mft data "
2417                                         "allocation.");
2418                         goto undo_mftbmp_alloc_nolock;
2419                 }
2420                 read_lock_irqsave(&mft_ni->size_lock, flags);
2421                 ntfs_debug("Status of mft data after allocation extension: "
2422                                 "allocated_size 0x%llx, data_size 0x%llx, "
2423                                 "initialized_size 0x%llx.",
2424                                 (long long)mft_ni->allocated_size,
2425                                 (long long)i_size_read(vol->mft_ino),
2426                                 (long long)mft_ni->initialized_size);
2427         }
2428         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2429         /*
2430          * Extend mft data initialized size (and data size of course) to reach
2431          * the allocated mft record, formatting the mft records allong the way.
2432          * Note: We only modify the ntfs_inode structure as that is all that is
2433          * needed by ntfs_mft_record_format().  We will update the attribute
2434          * record itself in one fell swoop later on.
2435          */
2436         write_lock_irqsave(&mft_ni->size_lock, flags);
2437         old_data_initialized = mft_ni->initialized_size;
2438         old_data_size = vol->mft_ino->i_size;
2439         while (ll > mft_ni->initialized_size) {
2440                 s64 new_initialized_size, mft_no;
2441                 
2442                 new_initialized_size = mft_ni->initialized_size +
2443                                 vol->mft_record_size;
2444                 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2445                 if (new_initialized_size > i_size_read(vol->mft_ino))
2446                         i_size_write(vol->mft_ino, new_initialized_size);
2447                 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2448                 ntfs_debug("Initializing mft record 0x%llx.",
2449                                 (long long)mft_no);
2450                 err = ntfs_mft_record_format(vol, mft_no);
2451                 if (unlikely(err)) {
2452                         ntfs_error(vol->sb, "Failed to format mft record.");
2453                         goto undo_data_init;
2454                 }
2455                 write_lock_irqsave(&mft_ni->size_lock, flags);
2456                 mft_ni->initialized_size = new_initialized_size;
2457         }
2458         write_unlock_irqrestore(&mft_ni->size_lock, flags);
2459         record_formatted = TRUE;
2460         /* Update the mft data attribute record to reflect the new sizes. */
2461         m = map_mft_record(mft_ni);
2462         if (IS_ERR(m)) {
2463                 ntfs_error(vol->sb, "Failed to map mft record.");
2464                 err = PTR_ERR(m);
2465                 goto undo_data_init;
2466         }
2467         ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2468         if (unlikely(!ctx)) {
2469                 ntfs_error(vol->sb, "Failed to get search context.");
2470                 err = -ENOMEM;
2471                 unmap_mft_record(mft_ni);
2472                 goto undo_data_init;
2473         }
2474         err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2475                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2476         if (unlikely(err)) {
2477                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2478                                 "mft data attribute.");
2479                 ntfs_attr_put_search_ctx(ctx);
2480                 unmap_mft_record(mft_ni);
2481                 goto undo_data_init;
2482         }
2483         a = ctx->attr;
2484         read_lock_irqsave(&mft_ni->size_lock, flags);
2485         a->data.non_resident.initialized_size =
2486                         cpu_to_sle64(mft_ni->initialized_size);
2487         a->data.non_resident.data_size =
2488                         cpu_to_sle64(i_size_read(vol->mft_ino));
2489         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2490         /* Ensure the changes make it to disk. */
2491         flush_dcache_mft_record_page(ctx->ntfs_ino);
2492         mark_mft_record_dirty(ctx->ntfs_ino);
2493         ntfs_attr_put_search_ctx(ctx);
2494         unmap_mft_record(mft_ni);
2495         read_lock_irqsave(&mft_ni->size_lock, flags);
2496         ntfs_debug("Status of mft data after mft record initialization: "
2497                         "allocated_size 0x%llx, data_size 0x%llx, "
2498                         "initialized_size 0x%llx.",
2499                         (long long)mft_ni->allocated_size,
2500                         (long long)i_size_read(vol->mft_ino),
2501                         (long long)mft_ni->initialized_size);
2502         BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2503         BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2504         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2505 mft_rec_already_initialized:
2506         /*
2507          * We can finally drop the mft bitmap lock as the mft data attribute
2508          * has been fully updated.  The only disparity left is that the
2509          * allocated mft record still needs to be marked as in use to match the
2510          * set bit in the mft bitmap but this is actually not a problem since
2511          * this mft record is not referenced from anywhere yet and the fact
2512          * that it is allocated in the mft bitmap means that no-one will try to
2513          * allocate it either.
2514          */
2515         up_write(&vol->mftbmp_lock);
2516         /*
2517          * We now have allocated and initialized the mft record.  Calculate the
2518          * index of and the offset within the page cache page the record is in.
2519          */
2520         index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2521         ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2522         /* Read, map, and pin the page containing the mft record. */
2523         page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2524         if (unlikely(IS_ERR(page))) {
2525                 ntfs_error(vol->sb, "Failed to map page containing allocated "
2526                                 "mft record 0x%llx.", (long long)bit);
2527                 err = PTR_ERR(page);
2528                 goto undo_mftbmp_alloc;
2529         }
2530         lock_page(page);
2531         BUG_ON(!PageUptodate(page));
2532         ClearPageUptodate(page);
2533         m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2534         /* If we just formatted the mft record no need to do it again. */
2535         if (!record_formatted) {
2536                 /* Sanity check that the mft record is really not in use. */
2537                 if (ntfs_is_file_record(m->magic) &&
2538                                 (m->flags & MFT_RECORD_IN_USE)) {
2539                         ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2540                                         "free in mft bitmap but is marked "
2541                                         "used itself.  Corrupt filesystem.  "
2542                                         "Unmount and run chkdsk.",
2543                                         (long long)bit);
2544                         err = -EIO;
2545                         SetPageUptodate(page);
2546                         unlock_page(page);
2547                         ntfs_unmap_page(page);
2548                         NVolSetErrors(vol);
2549                         goto undo_mftbmp_alloc;
2550                 }
2551                 /*
2552                  * We need to (re-)format the mft record, preserving the
2553                  * sequence number if it is not zero as well as the update
2554                  * sequence number if it is not zero or -1 (0xffff).  This
2555                  * means we do not need to care whether or not something went
2556                  * wrong with the previous mft record.
2557                  */
2558                 seq_no = m->sequence_number;
2559                 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2560                 err = ntfs_mft_record_layout(vol, bit, m);
2561                 if (unlikely(err)) {
2562                         ntfs_error(vol->sb, "Failed to layout allocated mft "
2563                                         "record 0x%llx.", (long long)bit);
2564                         SetPageUptodate(page);
2565                         unlock_page(page);
2566                         ntfs_unmap_page(page);
2567                         goto undo_mftbmp_alloc;
2568                 }
2569                 if (seq_no)
2570                         m->sequence_number = seq_no;
2571                 if (usn && le16_to_cpu(usn) != 0xffff)
2572                         *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2573         }
2574         /* Set the mft record itself in use. */
2575         m->flags |= MFT_RECORD_IN_USE;
2576         if (S_ISDIR(mode))
2577                 m->flags |= MFT_RECORD_IS_DIRECTORY;
2578         flush_dcache_page(page);
2579         SetPageUptodate(page);
2580         if (base_ni) {
2581                 /*
2582                  * Setup the base mft record in the extent mft record.  This
2583                  * completes initialization of the allocated extent mft record
2584                  * and we can simply use it with map_extent_mft_record().
2585                  */
2586                 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2587                                 base_ni->seq_no);
2588                 /*
2589                  * Allocate an extent inode structure for the new mft record,
2590                  * attach it to the base inode @base_ni and map, pin, and lock
2591                  * its, i.e. the allocated, mft record.
2592                  */
2593                 m = map_extent_mft_record(base_ni, bit, &ni);
2594                 if (IS_ERR(m)) {
2595                         ntfs_error(vol->sb, "Failed to map allocated extent "
2596                                         "mft record 0x%llx.", (long long)bit);
2597                         err = PTR_ERR(m);
2598                         /* Set the mft record itself not in use. */
2599                         m->flags &= cpu_to_le16(
2600                                         ~le16_to_cpu(MFT_RECORD_IN_USE));
2601                         flush_dcache_page(page);
2602                         /* Make sure the mft record is written out to disk. */
2603                         mark_ntfs_record_dirty(page, ofs);
2604                         unlock_page(page);
2605                         ntfs_unmap_page(page);
2606                         goto undo_mftbmp_alloc;
2607                 }
2608                 /*
2609                  * Make sure the allocated mft record is written out to disk.
2610                  * No need to set the inode dirty because the caller is going
2611                  * to do that anyway after finishing with the new extent mft
2612                  * record (e.g. at a minimum a new attribute will be added to
2613                  * the mft record.
2614                  */
2615                 mark_ntfs_record_dirty(page, ofs);
2616                 unlock_page(page);
2617                 /*
2618                  * Need to unmap the page since map_extent_mft_record() mapped
2619                  * it as well so we have it mapped twice at the moment.
2620                  */
2621                 ntfs_unmap_page(page);
2622         } else {
2623                 /*
2624                  * Allocate a new VFS inode and set it up.  NOTE: @vi->i_nlink
2625                  * is set to 1 but the mft record->link_count is 0.  The caller
2626                  * needs to bear this in mind.
2627                  */
2628                 vi = new_inode(vol->sb);
2629                 if (unlikely(!vi)) {
2630                         err = -ENOMEM;
2631                         /* Set the mft record itself not in use. */
2632                         m->flags &= cpu_to_le16(
2633                                         ~le16_to_cpu(MFT_RECORD_IN_USE));
2634                         flush_dcache_page(page);
2635                         /* Make sure the mft record is written out to disk. */
2636                         mark_ntfs_record_dirty(page, ofs);
2637                         unlock_page(page);
2638                         ntfs_unmap_page(page);
2639                         goto undo_mftbmp_alloc;
2640                 }
2641                 vi->i_ino = bit;
2642                 /*
2643                  * This is the optimal IO size (for stat), not the fs block
2644                  * size.
2645                  */
2646                 vi->i_blksize = PAGE_CACHE_SIZE;
2647                 /*
2648                  * This is for checking whether an inode has changed w.r.t. a
2649                  * file so that the file can be updated if necessary (compare
2650                  * with f_version).
2651                  */
2652                 vi->i_version = 1;
2653
2654                 /* The owner and group come from the ntfs volume. */
2655                 vi->i_uid = vol->uid;
2656                 vi->i_gid = vol->gid;
2657
2658                 /* Initialize the ntfs specific part of @vi. */
2659                 ntfs_init_big_inode(vi);
2660                 ni = NTFS_I(vi);
2661                 /*
2662                  * Set the appropriate mode, attribute type, and name.  For
2663                  * directories, also setup the index values to the defaults.
2664                  */
2665                 if (S_ISDIR(mode)) {
2666                         vi->i_mode = S_IFDIR | S_IRWXUGO;
2667                         vi->i_mode &= ~vol->dmask;
2668
2669                         NInoSetMstProtected(ni);
2670                         ni->type = AT_INDEX_ALLOCATION;
2671                         ni->name = I30;
2672                         ni->name_len = 4;
2673
2674                         ni->itype.index.block_size = 4096;
2675                         ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2676                         ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2677                         if (vol->cluster_size <= ni->itype.index.block_size) {
2678                                 ni->itype.index.vcn_size = vol->cluster_size;
2679                                 ni->itype.index.vcn_size_bits =
2680                                                 vol->cluster_size_bits;
2681                         } else {
2682                                 ni->itype.index.vcn_size = vol->sector_size;
2683                                 ni->itype.index.vcn_size_bits =
2684                                                 vol->sector_size_bits;
2685                         }
2686                 } else {
2687                         vi->i_mode = S_IFREG | S_IRWXUGO;
2688                         vi->i_mode &= ~vol->fmask;
2689
2690                         ni->type = AT_DATA;
2691                         ni->name = NULL;
2692                         ni->name_len = 0;
2693                 }
2694                 if (IS_RDONLY(vi))
2695                         vi->i_mode &= ~S_IWUGO;
2696
2697                 /* Set the inode times to the current time. */
2698                 vi->i_atime = vi->i_mtime = vi->i_ctime =
2699                         current_fs_time(vi->i_sb);
2700                 /*
2701                  * Set the file size to 0, the ntfs inode sizes are set to 0 by
2702                  * the call to ntfs_init_big_inode() below.
2703                  */
2704                 vi->i_size = 0;
2705                 vi->i_blocks = 0;
2706
2707                 /* Set the sequence number. */
2708                 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2709                 /*
2710                  * Manually map, pin, and lock the mft record as we already
2711                  * have its page mapped and it is very easy to do.
2712                  */
2713                 atomic_inc(&ni->count);
2714                 down(&ni->mrec_lock);
2715                 ni->page = page;
2716                 ni->page_ofs = ofs;
2717                 /*
2718                  * Make sure the allocated mft record is written out to disk.
2719                  * NOTE: We do not set the ntfs inode dirty because this would
2720                  * fail in ntfs_write_inode() because the inode does not have a
2721                  * standard information attribute yet.  Also, there is no need
2722                  * to set the inode dirty because the caller is going to do
2723                  * that anyway after finishing with the new mft record (e.g. at
2724                  * a minimum some new attributes will be added to the mft
2725                  * record.
2726                  */
2727                 mark_ntfs_record_dirty(page, ofs);
2728                 unlock_page(page);
2729
2730                 /* Add the inode to the inode hash for the superblock. */
2731                 insert_inode_hash(vi);
2732
2733                 /* Update the default mft allocation position. */
2734                 vol->mft_data_pos = bit + 1;
2735         }
2736         /*
2737          * Return the opened, allocated inode of the allocated mft record as
2738          * well as the mapped, pinned, and locked mft record.
2739          */
2740         ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2741                         base_ni ? "extent " : "", (long long)bit);
2742         *mrec = m;
2743         return ni;
2744 undo_data_init:
2745         write_lock_irqsave(&mft_ni->size_lock, flags);
2746         mft_ni->initialized_size = old_data_initialized;
2747         i_size_write(vol->mft_ino, old_data_size);
2748         write_unlock_irqrestore(&mft_ni->size_lock, flags);
2749         goto undo_mftbmp_alloc_nolock;
2750 undo_mftbmp_alloc:
2751         down_write(&vol->mftbmp_lock);
2752 undo_mftbmp_alloc_nolock:
2753         if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2754                 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2755                 NVolSetErrors(vol);
2756         }
2757         up_write(&vol->mftbmp_lock);
2758 err_out:
2759         return ERR_PTR(err);
2760 max_err_out:
2761         ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2762                         "number of inodes (2^32) has already been reached.");
2763         up_write(&vol->mftbmp_lock);
2764         return ERR_PTR(-ENOSPC);
2765 }
2766
2767 /**
2768  * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2769  * @ni:         ntfs inode of the mapped extent mft record to free
2770  * @m:          mapped extent mft record of the ntfs inode @ni
2771  *
2772  * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2773  *
2774  * Note that this function unmaps the mft record and closes and destroys @ni
2775  * internally and hence you cannot use either @ni nor @m any more after this
2776  * function returns success.
2777  *
2778  * On success return 0 and on error return -errno.  @ni and @m are still valid
2779  * in this case and have not been freed.
2780  *
2781  * For some errors an error message is displayed and the success code 0 is
2782  * returned and the volume is then left dirty on umount.  This makes sense in
2783  * case we could not rollback the changes that were already done since the
2784  * caller no longer wants to reference this mft record so it does not matter to
2785  * the caller if something is wrong with it as long as it is properly detached
2786  * from the base inode.
2787  */
2788 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2789 {
2790         unsigned long mft_no = ni->mft_no;
2791         ntfs_volume *vol = ni->vol;
2792         ntfs_inode *base_ni;
2793         ntfs_inode **extent_nis;
2794         int i, err;
2795         le16 old_seq_no;
2796         u16 seq_no;
2797         
2798         BUG_ON(NInoAttr(ni));
2799         BUG_ON(ni->nr_extents != -1);
2800
2801         down(&ni->extent_lock);
2802         base_ni = ni->ext.base_ntfs_ino;
2803         up(&ni->extent_lock);
2804
2805         BUG_ON(base_ni->nr_extents <= 0);
2806
2807         ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2808                         mft_no, base_ni->mft_no);
2809
2810         down(&base_ni->extent_lock);
2811
2812         /* Make sure we are holding the only reference to the extent inode. */
2813         if (atomic_read(&ni->count) > 2) {
2814                 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2815                                 "not freeing.", base_ni->mft_no);
2816                 up(&base_ni->extent_lock);
2817                 return -EBUSY;
2818         }
2819
2820         /* Dissociate the ntfs inode from the base inode. */
2821         extent_nis = base_ni->ext.extent_ntfs_inos;
2822         err = -ENOENT;
2823         for (i = 0; i < base_ni->nr_extents; i++) {
2824                 if (ni != extent_nis[i])
2825                         continue;
2826                 extent_nis += i;
2827                 base_ni->nr_extents--;
2828                 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2829                                 sizeof(ntfs_inode*));
2830                 err = 0;
2831                 break;
2832         }
2833
2834         up(&base_ni->extent_lock);
2835
2836         if (unlikely(err)) {
2837                 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2838                                 "its base inode 0x%lx.", mft_no,
2839                                 base_ni->mft_no);
2840                 BUG();
2841         }
2842
2843         /*
2844          * The extent inode is no longer attached to the base inode so no one
2845          * can get a reference to it any more.
2846          */
2847
2848         /* Mark the mft record as not in use. */
2849         m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2850
2851         /* Increment the sequence number, skipping zero, if it is not zero. */
2852         old_seq_no = m->sequence_number;
2853         seq_no = le16_to_cpu(old_seq_no);
2854         if (seq_no == 0xffff)
2855                 seq_no = 1;
2856         else if (seq_no)
2857                 seq_no++;
2858         m->sequence_number = cpu_to_le16(seq_no);
2859
2860         /*
2861          * Set the ntfs inode dirty and write it out.  We do not need to worry
2862          * about the base inode here since whatever caused the extent mft
2863          * record to be freed is guaranteed to do it already.
2864          */
2865         NInoSetDirty(ni);
2866         err = write_mft_record(ni, m, 0);
2867         if (unlikely(err)) {
2868                 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2869                                 "freeing.", mft_no);
2870                 goto rollback;
2871         }
2872 rollback_error:
2873         /* Unmap and throw away the now freed extent inode. */
2874         unmap_extent_mft_record(ni);
2875         ntfs_clear_extent_inode(ni);
2876
2877         /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2878         down_write(&vol->mftbmp_lock);
2879         err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2880         up_write(&vol->mftbmp_lock);
2881         if (unlikely(err)) {
2882                 /*
2883                  * The extent inode is gone but we failed to deallocate it in
2884                  * the mft bitmap.  Just emit a warning and leave the volume
2885                  * dirty on umount.
2886                  */
2887                 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2888                 NVolSetErrors(vol);
2889         }
2890         return 0;
2891 rollback:
2892         /* Rollback what we did... */
2893         down(&base_ni->extent_lock);
2894         extent_nis = base_ni->ext.extent_ntfs_inos;
2895         if (!(base_ni->nr_extents & 3)) {
2896                 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2897
2898                 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2899                 if (unlikely(!extent_nis)) {
2900                         ntfs_error(vol->sb, "Failed to allocate internal "
2901                                         "buffer during rollback.%s", es);
2902                         up(&base_ni->extent_lock);
2903                         NVolSetErrors(vol);
2904                         goto rollback_error;
2905                 }
2906                 if (base_ni->nr_extents) {
2907                         BUG_ON(!base_ni->ext.extent_ntfs_inos);
2908                         memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2909                                         new_size - 4 * sizeof(ntfs_inode*));
2910                         kfree(base_ni->ext.extent_ntfs_inos);
2911                 }
2912                 base_ni->ext.extent_ntfs_inos = extent_nis;
2913         }
2914         m->flags |= MFT_RECORD_IN_USE;
2915         m->sequence_number = old_seq_no;
2916         extent_nis[base_ni->nr_extents++] = ni;
2917         up(&base_ni->extent_lock);
2918         mark_mft_record_dirty(ni);
2919         return err;
2920 }
2921 #endif /* NTFS_RW */