[ARM] 2894/1: Sharp Scoop driver pm_message_t type fix
[pandora-kernel.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, ofs, end_index;
53
54         BUG_ON(ni->page);
55         /*
56          * The index into the page cache and the offset within the page cache
57          * page of the wanted mft record. FIXME: We need to check for
58          * overflowing the unsigned long, but I don't think we would ever get
59          * here if the volume was that big...
60          */
61         index = ni->mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
62         ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
63
64         i_size = i_size_read(mft_vi);
65         /* The maximum valid index into the page cache for $MFT's data. */
66         end_index = i_size >> PAGE_CACHE_SHIFT;
67
68         /* If the wanted index is out of bounds the mft record doesn't exist. */
69         if (unlikely(index >= end_index)) {
70                 if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
71                                 vol->mft_record_size) {
72                         page = ERR_PTR(-ENOENT);
73                         ntfs_error(vol->sb, "Attemt to read mft record 0x%lx, "
74                                         "which is beyond the end of the mft.  "
75                                         "This is probably a bug in the ntfs "
76                                         "driver.", ni->mft_no);
77                         goto err_out;
78                 }
79         }
80         /* Read, map, and pin the page. */
81         page = ntfs_map_page(mft_vi->i_mapping, index);
82         if (likely(!IS_ERR(page))) {
83                 /* Catch multi sector transfer fixup errors. */
84                 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
85                                 ofs)))) {
86                         ni->page = page;
87                         ni->page_ofs = ofs;
88                         return page_address(page) + ofs;
89                 }
90                 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt.  "
91                                 "Run chkdsk.", ni->mft_no);
92                 ntfs_unmap_page(page);
93                 page = ERR_PTR(-EIO);
94         }
95 err_out:
96         ni->page = NULL;
97         ni->page_ofs = 0;
98         return (void*)page;
99 }
100
101 /**
102  * map_mft_record - map, pin and lock an mft record
103  * @ni:         ntfs inode whose MFT record to map
104  *
105  * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
106  * for the semaphore if it was already locked by someone else.
107  *
108  * The page of the record is mapped using map_mft_record_page() before being
109  * returned to the caller.
110  *
111  * This in turn uses ntfs_map_page() to get the page containing the wanted mft
112  * record (it in turn calls read_cache_page() which reads it in from disk if
113  * necessary, increments the use count on the page so that it cannot disappear
114  * under us and returns a reference to the page cache page).
115  *
116  * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
117  * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
118  * and the post-read mst fixups on each mft record in the page have been
119  * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
120  * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
121  * ntfs_map_page() waits for PG_locked to become clear and checks if
122  * PG_uptodate is set and returns an error code if not. This provides
123  * sufficient protection against races when reading/using the page.
124  *
125  * However there is the write mapping to think about. Doing the above described
126  * checking here will be fine, because when initiating the write we will set
127  * PG_locked and clear PG_uptodate making sure nobody is touching the page
128  * contents. Doing the locking this way means that the commit to disk code in
129  * the page cache code paths is automatically sufficiently locked with us as
130  * we will not touch a page that has been locked or is not uptodate. The only
131  * locking problem then is them locking the page while we are accessing it.
132  *
133  * So that code will end up having to own the mrec_lock of all mft
134  * records/inodes present in the page before I/O can proceed. In that case we
135  * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
136  * accessing anything without owning the mrec_lock semaphore. But we do need
137  * to use them because of the read_cache_page() invocation and the code becomes
138  * so much simpler this way that it is well worth it.
139  *
140  * The mft record is now ours and we return a pointer to it. You need to check
141  * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
142  * the error code.
143  *
144  * NOTE: Caller is responsible for setting the mft record dirty before calling
145  * unmap_mft_record(). This is obviously only necessary if the caller really
146  * modified the mft record...
147  * Q: Do we want to recycle one of the VFS inode state bits instead?
148  * A: No, the inode ones mean we want to change the mft record, not we want to
149  * write it out.
150  */
151 MFT_RECORD *map_mft_record(ntfs_inode *ni)
152 {
153         MFT_RECORD *m;
154
155         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
156
157         /* Make sure the ntfs inode doesn't go away. */
158         atomic_inc(&ni->count);
159
160         /* Serialize access to this mft record. */
161         down(&ni->mrec_lock);
162
163         m = map_mft_record_page(ni);
164         if (likely(!IS_ERR(m)))
165                 return m;
166
167         up(&ni->mrec_lock);
168         atomic_dec(&ni->count);
169         ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
170         return m;
171 }
172
173 /**
174  * unmap_mft_record_page - unmap the page in which a specific mft record resides
175  * @ni:         ntfs inode whose mft record page to unmap
176  *
177  * This unmaps the page in which the mft record of the ntfs inode @ni is
178  * situated and returns. This is a NOOP if highmem is not configured.
179  *
180  * The unmap happens via ntfs_unmap_page() which in turn decrements the use
181  * count on the page thus releasing it from the pinned state.
182  *
183  * We do not actually unmap the page from memory of course, as that will be
184  * done by the page cache code itself when memory pressure increases or
185  * whatever.
186  */
187 static inline void unmap_mft_record_page(ntfs_inode *ni)
188 {
189         BUG_ON(!ni->page);
190
191         // TODO: If dirty, blah...
192         ntfs_unmap_page(ni->page);
193         ni->page = NULL;
194         ni->page_ofs = 0;
195         return;
196 }
197
198 /**
199  * unmap_mft_record - release a mapped mft record
200  * @ni:         ntfs inode whose MFT record to unmap
201  *
202  * We release the page mapping and the mrec_lock mutex which unmaps the mft
203  * record and releases it for others to get hold of. We also release the ntfs
204  * inode by decrementing the ntfs inode reference count.
205  *
206  * NOTE: If caller has modified the mft record, it is imperative to set the mft
207  * record dirty BEFORE calling unmap_mft_record().
208  */
209 void unmap_mft_record(ntfs_inode *ni)
210 {
211         struct page *page = ni->page;
212
213         BUG_ON(!page);
214
215         ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
216
217         unmap_mft_record_page(ni);
218         up(&ni->mrec_lock);
219         atomic_dec(&ni->count);
220         /*
221          * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
222          * ntfs_clear_extent_inode() in the extent inode case, and to the
223          * caller in the non-extent, yet pure ntfs inode case, to do the actual
224          * tear down of all structures and freeing of all allocated memory.
225          */
226         return;
227 }
228
229 /**
230  * map_extent_mft_record - load an extent inode and attach it to its base
231  * @base_ni:    base ntfs inode
232  * @mref:       mft reference of the extent inode to load
233  * @ntfs_ino:   on successful return, pointer to the ntfs_inode structure
234  *
235  * Load the extent mft record @mref and attach it to its base inode @base_ni.
236  * Return the mapped extent mft record if IS_ERR(result) is false.  Otherwise
237  * PTR_ERR(result) gives the negative error code.
238  *
239  * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
240  * structure of the mapped extent inode.
241  */
242 MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
243                 ntfs_inode **ntfs_ino)
244 {
245         MFT_RECORD *m;
246         ntfs_inode *ni = NULL;
247         ntfs_inode **extent_nis = NULL;
248         int i;
249         unsigned long mft_no = MREF(mref);
250         u16 seq_no = MSEQNO(mref);
251         BOOL destroy_ni = FALSE;
252
253         ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
254                         mft_no, base_ni->mft_no);
255         /* Make sure the base ntfs inode doesn't go away. */
256         atomic_inc(&base_ni->count);
257         /*
258          * Check if this extent inode has already been added to the base inode,
259          * in which case just return it. If not found, add it to the base
260          * inode before returning it.
261          */
262         down(&base_ni->extent_lock);
263         if (base_ni->nr_extents > 0) {
264                 extent_nis = base_ni->ext.extent_ntfs_inos;
265                 for (i = 0; i < base_ni->nr_extents; i++) {
266                         if (mft_no != extent_nis[i]->mft_no)
267                                 continue;
268                         ni = extent_nis[i];
269                         /* Make sure the ntfs inode doesn't go away. */
270                         atomic_inc(&ni->count);
271                         break;
272                 }
273         }
274         if (likely(ni != NULL)) {
275                 up(&base_ni->extent_lock);
276                 atomic_dec(&base_ni->count);
277                 /* We found the record; just have to map and return it. */
278                 m = map_mft_record(ni);
279                 /* map_mft_record() has incremented this on success. */
280                 atomic_dec(&ni->count);
281                 if (likely(!IS_ERR(m))) {
282                         /* Verify the sequence number. */
283                         if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
284                                 ntfs_debug("Done 1.");
285                                 *ntfs_ino = ni;
286                                 return m;
287                         }
288                         unmap_mft_record(ni);
289                         ntfs_error(base_ni->vol->sb, "Found stale extent mft "
290                                         "reference! Corrupt filesystem. "
291                                         "Run chkdsk.");
292                         return ERR_PTR(-EIO);
293                 }
294 map_err_out:
295                 ntfs_error(base_ni->vol->sb, "Failed to map extent "
296                                 "mft record, error code %ld.", -PTR_ERR(m));
297                 return m;
298         }
299         /* Record wasn't there. Get a new ntfs inode and initialize it. */
300         ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
301         if (unlikely(!ni)) {
302                 up(&base_ni->extent_lock);
303                 atomic_dec(&base_ni->count);
304                 return ERR_PTR(-ENOMEM);
305         }
306         ni->vol = base_ni->vol;
307         ni->seq_no = seq_no;
308         ni->nr_extents = -1;
309         ni->ext.base_ntfs_ino = base_ni;
310         /* Now map the record. */
311         m = map_mft_record(ni);
312         if (IS_ERR(m)) {
313                 up(&base_ni->extent_lock);
314                 atomic_dec(&base_ni->count);
315                 ntfs_clear_extent_inode(ni);
316                 goto map_err_out;
317         }
318         /* Verify the sequence number if it is present. */
319         if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
320                 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
321                                 "reference! Corrupt filesystem. Run chkdsk.");
322                 destroy_ni = TRUE;
323                 m = ERR_PTR(-EIO);
324                 goto unm_err_out;
325         }
326         /* Attach extent inode to base inode, reallocating memory if needed. */
327         if (!(base_ni->nr_extents & 3)) {
328                 ntfs_inode **tmp;
329                 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
330
331                 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
332                 if (unlikely(!tmp)) {
333                         ntfs_error(base_ni->vol->sb, "Failed to allocate "
334                                         "internal buffer.");
335                         destroy_ni = TRUE;
336                         m = ERR_PTR(-ENOMEM);
337                         goto unm_err_out;
338                 }
339                 if (base_ni->nr_extents) {
340                         BUG_ON(!base_ni->ext.extent_ntfs_inos);
341                         memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
342                                         4 * sizeof(ntfs_inode *));
343                         kfree(base_ni->ext.extent_ntfs_inos);
344                 }
345                 base_ni->ext.extent_ntfs_inos = tmp;
346         }
347         base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
348         up(&base_ni->extent_lock);
349         atomic_dec(&base_ni->count);
350         ntfs_debug("Done 2.");
351         *ntfs_ino = ni;
352         return m;
353 unm_err_out:
354         unmap_mft_record(ni);
355         up(&base_ni->extent_lock);
356         atomic_dec(&base_ni->count);
357         /*
358          * If the extent inode was not attached to the base inode we need to
359          * release it or we will leak memory.
360          */
361         if (destroy_ni)
362                 ntfs_clear_extent_inode(ni);
363         return m;
364 }
365
366 #ifdef NTFS_RW
367
368 /**
369  * __mark_mft_record_dirty - set the mft record and the page containing it dirty
370  * @ni:         ntfs inode describing the mapped mft record
371  *
372  * Internal function.  Users should call mark_mft_record_dirty() instead.
373  *
374  * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
375  * as well as the page containing the mft record, dirty.  Also, mark the base
376  * vfs inode dirty.  This ensures that any changes to the mft record are
377  * written out to disk.
378  *
379  * NOTE:  We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
380  * on the base vfs inode, because even though file data may have been modified,
381  * it is dirty in the inode meta data rather than the data page cache of the
382  * inode, and thus there are no data pages that need writing out.  Therefore, a
383  * full mark_inode_dirty() is overkill.  A mark_inode_dirty_sync(), on the
384  * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
385  * ensure ->write_inode is called from generic_osync_inode() and this needs to
386  * happen or the file data would not necessarily hit the device synchronously,
387  * even though the vfs inode has the O_SYNC flag set.  Also, I_DIRTY_DATASYNC
388  * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
389  * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
390  * would suggest.
391  */
392 void __mark_mft_record_dirty(ntfs_inode *ni)
393 {
394         ntfs_inode *base_ni;
395
396         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
397         BUG_ON(NInoAttr(ni));
398         mark_ntfs_record_dirty(ni->page, ni->page_ofs);
399         /* Determine the base vfs inode and mark it dirty, too. */
400         down(&ni->extent_lock);
401         if (likely(ni->nr_extents >= 0))
402                 base_ni = ni;
403         else
404                 base_ni = ni->ext.base_ntfs_ino;
405         up(&ni->extent_lock);
406         __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
407 }
408
409 static const char *ntfs_please_email = "Please email "
410                 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
411                 "this message.  Thank you.";
412
413 /**
414  * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
415  * @vol:        ntfs volume on which the mft record to synchronize resides
416  * @mft_no:     mft record number of mft record to synchronize
417  * @m:          mapped, mst protected (extent) mft record to synchronize
418  *
419  * Write the mapped, mst protected (extent) mft record @m with mft record
420  * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
421  * bypassing the page cache and the $MFTMirr inode itself.
422  *
423  * This function is only for use at umount time when the mft mirror inode has
424  * already been disposed off.  We BUG() if we are called while the mft mirror
425  * inode is still attached to the volume.
426  *
427  * On success return 0.  On error return -errno.
428  *
429  * NOTE:  This function is not implemented yet as I am not convinced it can
430  * actually be triggered considering the sequence of commits we do in super.c::
431  * ntfs_put_super().  But just in case we provide this place holder as the
432  * alternative would be either to BUG() or to get a NULL pointer dereference
433  * and Oops.
434  */
435 static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
436                 const unsigned long mft_no, MFT_RECORD *m)
437 {
438         BUG_ON(vol->mftmirr_ino);
439         ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
440                         "implemented yet.  %s", ntfs_please_email);
441         return -EOPNOTSUPP;
442 }
443
444 /**
445  * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
446  * @vol:        ntfs volume on which the mft record to synchronize resides
447  * @mft_no:     mft record number of mft record to synchronize
448  * @m:          mapped, mst protected (extent) mft record to synchronize
449  * @sync:       if true, wait for i/o completion
450  *
451  * Write the mapped, mst protected (extent) mft record @m with mft record
452  * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
453  *
454  * On success return 0.  On error return -errno and set the volume errors flag
455  * in the ntfs volume @vol.
456  *
457  * NOTE:  We always perform synchronous i/o and ignore the @sync parameter.
458  *
459  * TODO:  If @sync is false, want to do truly asynchronous i/o, i.e. just
460  * schedule i/o via ->writepage or do it via kntfsd or whatever.
461  */
462 int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
463                 MFT_RECORD *m, int sync)
464 {
465         struct page *page;
466         unsigned int blocksize = vol->sb->s_blocksize;
467         int max_bhs = vol->mft_record_size / blocksize;
468         struct buffer_head *bhs[max_bhs];
469         struct buffer_head *bh, *head;
470         u8 *kmirr;
471         runlist_element *rl;
472         unsigned int block_start, block_end, m_start, m_end, page_ofs;
473         int i_bhs, nr_bhs, err = 0;
474         unsigned char blocksize_bits = vol->mftmirr_ino->i_blkbits;
475
476         ntfs_debug("Entering for inode 0x%lx.", mft_no);
477         BUG_ON(!max_bhs);
478         if (unlikely(!vol->mftmirr_ino)) {
479                 /* This could happen during umount... */
480                 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
481                 if (likely(!err))
482                         return err;
483                 goto err_out;
484         }
485         /* Get the page containing the mirror copy of the mft record @m. */
486         page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
487                         (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
488         if (IS_ERR(page)) {
489                 ntfs_error(vol->sb, "Failed to map mft mirror page.");
490                 err = PTR_ERR(page);
491                 goto err_out;
492         }
493         lock_page(page);
494         BUG_ON(!PageUptodate(page));
495         ClearPageUptodate(page);
496         /* Offset of the mft mirror record inside the page. */
497         page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
498         /* The address in the page of the mirror copy of the mft record @m. */
499         kmirr = page_address(page) + page_ofs;
500         /* Copy the mst protected mft record to the mirror. */
501         memcpy(kmirr, m, vol->mft_record_size);
502         /* Create uptodate buffers if not present. */
503         if (unlikely(!page_has_buffers(page))) {
504                 struct buffer_head *tail;
505
506                 bh = head = alloc_page_buffers(page, blocksize, 1);
507                 do {
508                         set_buffer_uptodate(bh);
509                         tail = bh;
510                         bh = bh->b_this_page;
511                 } while (bh);
512                 tail->b_this_page = head;
513                 attach_page_buffers(page, head);
514                 BUG_ON(!page_has_buffers(page));
515         }
516         bh = head = page_buffers(page);
517         BUG_ON(!bh);
518         rl = NULL;
519         nr_bhs = 0;
520         block_start = 0;
521         m_start = kmirr - (u8*)page_address(page);
522         m_end = m_start + vol->mft_record_size;
523         do {
524                 block_end = block_start + blocksize;
525                 /* If the buffer is outside the mft record, skip it. */
526                 if (block_end <= m_start)
527                         continue;
528                 if (unlikely(block_start >= m_end))
529                         break;
530                 /* Need to map the buffer if it is not mapped already. */
531                 if (unlikely(!buffer_mapped(bh))) {
532                         VCN vcn;
533                         LCN lcn;
534                         unsigned int vcn_ofs;
535
536                         bh->b_bdev = vol->sb->s_bdev;
537                         /* Obtain the vcn and offset of the current block. */
538                         vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
539                                         (block_start - m_start);
540                         vcn_ofs = vcn & vol->cluster_size_mask;
541                         vcn >>= vol->cluster_size_bits;
542                         if (!rl) {
543                                 down_read(&NTFS_I(vol->mftmirr_ino)->
544                                                 runlist.lock);
545                                 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
546                                 /*
547                                  * $MFTMirr always has the whole of its runlist
548                                  * in memory.
549                                  */
550                                 BUG_ON(!rl);
551                         }
552                         /* Seek to element containing target vcn. */
553                         while (rl->length && rl[1].vcn <= vcn)
554                                 rl++;
555                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
556                         /* For $MFTMirr, only lcn >= 0 is a successful remap. */
557                         if (likely(lcn >= 0)) {
558                                 /* Setup buffer head to correct block. */
559                                 bh->b_blocknr = ((lcn <<
560                                                 vol->cluster_size_bits) +
561                                                 vcn_ofs) >> blocksize_bits;
562                                 set_buffer_mapped(bh);
563                         } else {
564                                 bh->b_blocknr = -1;
565                                 ntfs_error(vol->sb, "Cannot write mft mirror "
566                                                 "record 0x%lx because its "
567                                                 "location on disk could not "
568                                                 "be determined (error code "
569                                                 "%lli).", mft_no,
570                                                 (long long)lcn);
571                                 err = -EIO;
572                         }
573                 }
574                 BUG_ON(!buffer_uptodate(bh));
575                 BUG_ON(!nr_bhs && (m_start != block_start));
576                 BUG_ON(nr_bhs >= max_bhs);
577                 bhs[nr_bhs++] = bh;
578                 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
579         } while (block_start = block_end, (bh = bh->b_this_page) != head);
580         if (unlikely(rl))
581                 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
582         if (likely(!err)) {
583                 /* Lock buffers and start synchronous write i/o on them. */
584                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
585                         struct buffer_head *tbh = bhs[i_bhs];
586
587                         if (unlikely(test_set_buffer_locked(tbh)))
588                                 BUG();
589                         BUG_ON(!buffer_uptodate(tbh));
590                         clear_buffer_dirty(tbh);
591                         get_bh(tbh);
592                         tbh->b_end_io = end_buffer_write_sync;
593                         submit_bh(WRITE, tbh);
594                 }
595                 /* Wait on i/o completion of buffers. */
596                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
597                         struct buffer_head *tbh = bhs[i_bhs];
598
599                         wait_on_buffer(tbh);
600                         if (unlikely(!buffer_uptodate(tbh))) {
601                                 err = -EIO;
602                                 /*
603                                  * Set the buffer uptodate so the page and
604                                  * buffer states do not become out of sync.
605                                  */
606                                 set_buffer_uptodate(tbh);
607                         }
608                 }
609         } else /* if (unlikely(err)) */ {
610                 /* Clean the buffers. */
611                 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
612                         clear_buffer_dirty(bhs[i_bhs]);
613         }
614         /* Current state: all buffers are clean, unlocked, and uptodate. */
615         /* Remove the mst protection fixups again. */
616         post_write_mst_fixup((NTFS_RECORD*)kmirr);
617         flush_dcache_page(page);
618         SetPageUptodate(page);
619         unlock_page(page);
620         ntfs_unmap_page(page);
621         if (likely(!err)) {
622                 ntfs_debug("Done.");
623         } else {
624                 ntfs_error(vol->sb, "I/O error while writing mft mirror "
625                                 "record 0x%lx!", mft_no);
626 err_out:
627                 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
628                                 "code %i).  Volume will be left marked dirty "
629                                 "on umount.  Run ntfsfix on the partition "
630                                 "after umounting to correct this.", -err);
631                 NVolSetErrors(vol);
632         }
633         return err;
634 }
635
636 /**
637  * write_mft_record_nolock - write out a mapped (extent) mft record
638  * @ni:         ntfs inode describing the mapped (extent) mft record
639  * @m:          mapped (extent) mft record to write
640  * @sync:       if true, wait for i/o completion
641  *
642  * Write the mapped (extent) mft record @m described by the (regular or extent)
643  * ntfs inode @ni to backing store.  If the mft record @m has a counterpart in
644  * the mft mirror, that is also updated.
645  *
646  * We only write the mft record if the ntfs inode @ni is dirty and the first
647  * buffer belonging to its mft record is dirty, too.  We ignore the dirty state
648  * of subsequent buffers because we could have raced with
649  * fs/ntfs/aops.c::mark_ntfs_record_dirty().
650  *
651  * On success, clean the mft record and return 0.  On error, leave the mft
652  * record dirty and return -errno.  The caller should call make_bad_inode() on
653  * the base inode to ensure no more access happens to this inode.  We do not do
654  * it here as the caller may want to finish writing other extent mft records
655  * first to minimize on-disk metadata inconsistencies.
656  *
657  * NOTE:  We always perform synchronous i/o and ignore the @sync parameter.
658  * However, if the mft record has a counterpart in the mft mirror and @sync is
659  * true, we write the mft record, wait for i/o completion, and only then write
660  * the mft mirror copy.  This ensures that if the system crashes either the mft
661  * or the mft mirror will contain a self-consistent mft record @m.  If @sync is
662  * false on the other hand, we start i/o on both and then wait for completion
663  * on them.  This provides a speedup but no longer guarantees that you will end
664  * up with a self-consistent mft record in the case of a crash but if you asked
665  * for asynchronous writing you probably do not care about that anyway.
666  *
667  * TODO:  If @sync is false, want to do truly asynchronous i/o, i.e. just
668  * schedule i/o via ->writepage or do it via kntfsd or whatever.
669  */
670 int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
671 {
672         ntfs_volume *vol = ni->vol;
673         struct page *page = ni->page;
674         unsigned char blocksize_bits = vol->mft_ino->i_blkbits;
675         unsigned int blocksize = 1 << blocksize_bits;
676         int max_bhs = vol->mft_record_size / blocksize;
677         struct buffer_head *bhs[max_bhs];
678         struct buffer_head *bh, *head;
679         runlist_element *rl;
680         unsigned int block_start, block_end, m_start, m_end;
681         int i_bhs, nr_bhs, err = 0;
682
683         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
684         BUG_ON(NInoAttr(ni));
685         BUG_ON(!max_bhs);
686         BUG_ON(!PageLocked(page));
687         /*
688          * If the ntfs_inode is clean no need to do anything.  If it is dirty,
689          * mark it as clean now so that it can be redirtied later on if needed.
690          * There is no danger of races since the caller is holding the locks
691          * for the mft record @m and the page it is in.
692          */
693         if (!NInoTestClearDirty(ni))
694                 goto done;
695         BUG_ON(!page_has_buffers(page));
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, TRUE);
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                 if (IS_ERR(rl2)) {
1360                         up_write(&mftbmp_ni->runlist.lock);
1361                         ntfs_error(vol->sb, "Failed to allocate a cluster for "
1362                                         "the mft bitmap.");
1363                         return PTR_ERR(rl2);
1364                 }
1365                 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1366                 if (IS_ERR(rl)) {
1367                         up_write(&mftbmp_ni->runlist.lock);
1368                         ntfs_error(vol->sb, "Failed to merge runlists for mft "
1369                                         "bitmap.");
1370                         if (ntfs_cluster_free_from_rl(vol, rl2)) {
1371                                 ntfs_error(vol->sb, "Failed to dealocate "
1372                                                 "allocated cluster.%s", es);
1373                                 NVolSetErrors(vol);
1374                         }
1375                         ntfs_free(rl2);
1376                         return PTR_ERR(rl);
1377                 }
1378                 mftbmp_ni->runlist.rl = rl;
1379                 status.added_run = 1;
1380                 ntfs_debug("Adding one run to mft bitmap.");
1381                 /* Find the last run in the new runlist. */
1382                 for (; rl[1].length; rl++)
1383                         ;
1384         }
1385         /*
1386          * Update the attribute record as well.  Note: @rl is the last
1387          * (non-terminator) runlist element of mft bitmap.
1388          */
1389         mrec = map_mft_record(mft_ni);
1390         if (IS_ERR(mrec)) {
1391                 ntfs_error(vol->sb, "Failed to map mft record.");
1392                 ret = PTR_ERR(mrec);
1393                 goto undo_alloc;
1394         }
1395         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1396         if (unlikely(!ctx)) {
1397                 ntfs_error(vol->sb, "Failed to get search context.");
1398                 ret = -ENOMEM;
1399                 goto undo_alloc;
1400         }
1401         ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1402                         mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1403                         0, ctx);
1404         if (unlikely(ret)) {
1405                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1406                                 "mft bitmap attribute.");
1407                 if (ret == -ENOENT)
1408                         ret = -EIO;
1409                 goto undo_alloc;
1410         }
1411         a = ctx->attr;
1412         ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1413         /* Search back for the previous last allocated cluster of mft bitmap. */
1414         for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1415                 if (ll >= rl2->vcn)
1416                         break;
1417         }
1418         BUG_ON(ll < rl2->vcn);
1419         BUG_ON(ll >= rl2->vcn + rl2->length);
1420         /* Get the size for the new mapping pairs array for this extent. */
1421         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1422         if (unlikely(mp_size <= 0)) {
1423                 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1424                                 "mft bitmap attribute extent.");
1425                 ret = mp_size;
1426                 if (!ret)
1427                         ret = -EIO;
1428                 goto undo_alloc;
1429         }
1430         /* Expand the attribute record if necessary. */
1431         old_alen = le32_to_cpu(a->length);
1432         ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1433                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1434         if (unlikely(ret)) {
1435                 if (ret != -ENOSPC) {
1436                         ntfs_error(vol->sb, "Failed to resize attribute "
1437                                         "record for mft bitmap attribute.");
1438                         goto undo_alloc;
1439                 }
1440                 // TODO: Deal with this by moving this extent to a new mft
1441                 // record or by starting a new extent in a new mft record or by
1442                 // moving other attributes out of this mft record.
1443                 // Note: It will need to be a special mft record and if none of
1444                 // those are available it gets rather complicated...
1445                 ntfs_error(vol->sb, "Not enough space in this mft record to "
1446                                 "accomodate extended mft bitmap attribute "
1447                                 "extent.  Cannot handle this yet.");
1448                 ret = -EOPNOTSUPP;
1449                 goto undo_alloc;
1450         }
1451         status.mp_rebuilt = 1;
1452         /* Generate the mapping pairs array directly into the attr record. */
1453         ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1454                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1455                         mp_size, rl2, ll, -1, NULL);
1456         if (unlikely(ret)) {
1457                 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1458                                 "mft bitmap attribute.");
1459                 goto undo_alloc;
1460         }
1461         /* Update the highest_vcn. */
1462         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1463         /*
1464          * We now have extended the mft bitmap allocated_size by one cluster.
1465          * Reflect this in the ntfs_inode structure and the attribute record.
1466          */
1467         if (a->data.non_resident.lowest_vcn) {
1468                 /*
1469                  * We are not in the first attribute extent, switch to it, but
1470                  * first ensure the changes will make it to disk later.
1471                  */
1472                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1473                 mark_mft_record_dirty(ctx->ntfs_ino);
1474                 ntfs_attr_reinit_search_ctx(ctx);
1475                 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1476                                 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1477                                 0, ctx);
1478                 if (unlikely(ret)) {
1479                         ntfs_error(vol->sb, "Failed to find first attribute "
1480                                         "extent of mft bitmap attribute.");
1481                         goto restore_undo_alloc;
1482                 }
1483                 a = ctx->attr;
1484         }
1485         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1486         mftbmp_ni->allocated_size += vol->cluster_size;
1487         a->data.non_resident.allocated_size =
1488                         cpu_to_sle64(mftbmp_ni->allocated_size);
1489         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1490         /* Ensure the changes make it to disk. */
1491         flush_dcache_mft_record_page(ctx->ntfs_ino);
1492         mark_mft_record_dirty(ctx->ntfs_ino);
1493         ntfs_attr_put_search_ctx(ctx);
1494         unmap_mft_record(mft_ni);
1495         up_write(&mftbmp_ni->runlist.lock);
1496         ntfs_debug("Done.");
1497         return 0;
1498 restore_undo_alloc:
1499         ntfs_attr_reinit_search_ctx(ctx);
1500         if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1501                         mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1502                         0, ctx)) {
1503                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1504                                 "mft bitmap attribute.%s", es);
1505                 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1506                 mftbmp_ni->allocated_size += vol->cluster_size;
1507                 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1508                 ntfs_attr_put_search_ctx(ctx);
1509                 unmap_mft_record(mft_ni);
1510                 up_write(&mftbmp_ni->runlist.lock);
1511                 /*
1512                  * The only thing that is now wrong is ->allocated_size of the
1513                  * base attribute extent which chkdsk should be able to fix.
1514                  */
1515                 NVolSetErrors(vol);
1516                 return ret;
1517         }
1518         a = ctx->attr;
1519         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1520 undo_alloc:
1521         if (status.added_cluster) {
1522                 /* Truncate the last run in the runlist by one cluster. */
1523                 rl->length--;
1524                 rl[1].vcn--;
1525         } else if (status.added_run) {
1526                 lcn = rl->lcn;
1527                 /* Remove the last run from the runlist. */
1528                 rl->lcn = rl[1].lcn;
1529                 rl->length = 0;
1530         }
1531         /* Deallocate the cluster. */
1532         down_write(&vol->lcnbmp_lock);
1533         if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1534                 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1535                 NVolSetErrors(vol);
1536         }
1537         up_write(&vol->lcnbmp_lock);
1538         if (status.mp_rebuilt) {
1539                 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1540                                 a->data.non_resident.mapping_pairs_offset),
1541                                 old_alen - le16_to_cpu(
1542                                 a->data.non_resident.mapping_pairs_offset),
1543                                 rl2, ll, -1, NULL)) {
1544                         ntfs_error(vol->sb, "Failed to restore mapping pairs "
1545                                         "array.%s", es);
1546                         NVolSetErrors(vol);
1547                 }
1548                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1549                         ntfs_error(vol->sb, "Failed to restore attribute "
1550                                         "record.%s", es);
1551                         NVolSetErrors(vol);
1552                 }
1553                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1554                 mark_mft_record_dirty(ctx->ntfs_ino);
1555         }
1556         if (ctx)
1557                 ntfs_attr_put_search_ctx(ctx);
1558         if (!IS_ERR(mrec))
1559                 unmap_mft_record(mft_ni);
1560         up_write(&mftbmp_ni->runlist.lock);
1561         return ret;
1562 }
1563
1564 /**
1565  * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1566  * @vol:        volume on which to extend the mft bitmap attribute
1567  *
1568  * Extend the initialized portion of the mft bitmap attribute on the ntfs
1569  * volume @vol by 8 bytes.
1570  *
1571  * Note:  Only changes initialized_size and data_size, i.e. requires that
1572  * allocated_size is big enough to fit the new initialized_size.
1573  *
1574  * Return 0 on success and -error on error.
1575  *
1576  * Locking: Caller must hold vol->mftbmp_lock for writing.
1577  */
1578 static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1579 {
1580         s64 old_data_size, old_initialized_size;
1581         unsigned long flags;
1582         struct inode *mftbmp_vi;
1583         ntfs_inode *mft_ni, *mftbmp_ni;
1584         ntfs_attr_search_ctx *ctx;
1585         MFT_RECORD *mrec;
1586         ATTR_RECORD *a;
1587         int ret;
1588
1589         ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1590         mft_ni = NTFS_I(vol->mft_ino);
1591         mftbmp_vi = vol->mftbmp_ino;
1592         mftbmp_ni = NTFS_I(mftbmp_vi);
1593         /* Get the attribute record. */
1594         mrec = map_mft_record(mft_ni);
1595         if (IS_ERR(mrec)) {
1596                 ntfs_error(vol->sb, "Failed to map mft record.");
1597                 return PTR_ERR(mrec);
1598         }
1599         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1600         if (unlikely(!ctx)) {
1601                 ntfs_error(vol->sb, "Failed to get search context.");
1602                 ret = -ENOMEM;
1603                 goto unm_err_out;
1604         }
1605         ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1606                         mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1607         if (unlikely(ret)) {
1608                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1609                                 "mft bitmap attribute.");
1610                 if (ret == -ENOENT)
1611                         ret = -EIO;
1612                 goto put_err_out;
1613         }
1614         a = ctx->attr;
1615         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1616         old_data_size = i_size_read(mftbmp_vi);
1617         old_initialized_size = mftbmp_ni->initialized_size;
1618         /*
1619          * We can simply update the initialized_size before filling the space
1620          * with zeroes because the caller is holding the mft bitmap lock for
1621          * writing which ensures that no one else is trying to access the data.
1622          */
1623         mftbmp_ni->initialized_size += 8;
1624         a->data.non_resident.initialized_size =
1625                         cpu_to_sle64(mftbmp_ni->initialized_size);
1626         if (mftbmp_ni->initialized_size > old_data_size) {
1627                 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
1628                 a->data.non_resident.data_size =
1629                                 cpu_to_sle64(mftbmp_ni->initialized_size);
1630         }
1631         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1632         /* Ensure the changes make it to disk. */
1633         flush_dcache_mft_record_page(ctx->ntfs_ino);
1634         mark_mft_record_dirty(ctx->ntfs_ino);
1635         ntfs_attr_put_search_ctx(ctx);
1636         unmap_mft_record(mft_ni);
1637         /* Initialize the mft bitmap attribute value with zeroes. */
1638         ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1639         if (likely(!ret)) {
1640                 ntfs_debug("Done.  (Wrote eight initialized bytes to mft "
1641                                 "bitmap.");
1642                 return 0;
1643         }
1644         ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1645         /* Try to recover from the error. */
1646         mrec = map_mft_record(mft_ni);
1647         if (IS_ERR(mrec)) {
1648                 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1649                 NVolSetErrors(vol);
1650                 return ret;
1651         }
1652         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1653         if (unlikely(!ctx)) {
1654                 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1655                 NVolSetErrors(vol);
1656                 goto unm_err_out;
1657         }
1658         if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1659                         mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1660                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1661                                 "mft bitmap attribute.%s", es);
1662                 NVolSetErrors(vol);
1663 put_err_out:
1664                 ntfs_attr_put_search_ctx(ctx);
1665 unm_err_out:
1666                 unmap_mft_record(mft_ni);
1667                 goto err_out;
1668         }
1669         a = ctx->attr;
1670         write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1671         mftbmp_ni->initialized_size = old_initialized_size;
1672         a->data.non_resident.initialized_size =
1673                         cpu_to_sle64(old_initialized_size);
1674         if (i_size_read(mftbmp_vi) != old_data_size) {
1675                 i_size_write(mftbmp_vi, old_data_size);
1676                 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1677         }
1678         write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1679         flush_dcache_mft_record_page(ctx->ntfs_ino);
1680         mark_mft_record_dirty(ctx->ntfs_ino);
1681         ntfs_attr_put_search_ctx(ctx);
1682         unmap_mft_record(mft_ni);
1683 #ifdef DEBUG
1684         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1685         ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1686                         "data_size 0x%llx, initialized_size 0x%llx.",
1687                         (long long)mftbmp_ni->allocated_size,
1688                         (long long)i_size_read(mftbmp_vi),
1689                         (long long)mftbmp_ni->initialized_size);
1690         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1691 #endif /* DEBUG */
1692 err_out:
1693         return ret;
1694 }
1695
1696 /**
1697  * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1698  * @vol:        volume on which to extend the mft data attribute
1699  *
1700  * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1701  * worth of clusters or if not enough space for this by one mft record worth
1702  * of clusters.
1703  *
1704  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
1705  * data_size.
1706  *
1707  * Return 0 on success and -errno on error.
1708  *
1709  * Locking: - Caller must hold vol->mftbmp_lock for writing.
1710  *          - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1711  *            writing and releases it before returning.
1712  *          - This function calls functions which take vol->lcnbmp_lock for
1713  *            writing and release it before returning.
1714  */
1715 static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1716 {
1717         LCN lcn;
1718         VCN old_last_vcn;
1719         s64 min_nr, nr, ll;
1720         unsigned long flags;
1721         ntfs_inode *mft_ni;
1722         runlist_element *rl, *rl2;
1723         ntfs_attr_search_ctx *ctx = NULL;
1724         MFT_RECORD *mrec;
1725         ATTR_RECORD *a = NULL;
1726         int ret, mp_size;
1727         u32 old_alen = 0;
1728         BOOL mp_rebuilt = FALSE;
1729
1730         ntfs_debug("Extending mft data allocation.");
1731         mft_ni = NTFS_I(vol->mft_ino);
1732         /*
1733          * Determine the preferred allocation location, i.e. the last lcn of
1734          * the mft data attribute.  The allocated size of the mft data
1735          * attribute cannot be zero so we are ok to do this.
1736          */
1737         down_write(&mft_ni->runlist.lock);
1738         read_lock_irqsave(&mft_ni->size_lock, flags);
1739         ll = mft_ni->allocated_size;
1740         read_unlock_irqrestore(&mft_ni->size_lock, flags);
1741         rl = ntfs_attr_find_vcn_nolock(mft_ni,
1742                         (ll - 1) >> vol->cluster_size_bits, TRUE);
1743         if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
1744                 up_write(&mft_ni->runlist.lock);
1745                 ntfs_error(vol->sb, "Failed to determine last allocated "
1746                                 "cluster of mft data attribute.");
1747                 if (!IS_ERR(rl))
1748                         ret = -EIO;
1749                 else
1750                         ret = PTR_ERR(rl);
1751                 return ret;
1752         }
1753         lcn = rl->lcn + rl->length;
1754         ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
1755         /* Minimum allocation is one mft record worth of clusters. */
1756         min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1757         if (!min_nr)
1758                 min_nr = 1;
1759         /* Want to allocate 16 mft records worth of clusters. */
1760         nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1761         if (!nr)
1762                 nr = min_nr;
1763         /* Ensure we do not go above 2^32-1 mft records. */
1764         read_lock_irqsave(&mft_ni->size_lock, flags);
1765         ll = mft_ni->allocated_size;
1766         read_unlock_irqrestore(&mft_ni->size_lock, flags);
1767         if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1768                         vol->mft_record_size_bits >= (1ll << 32))) {
1769                 nr = min_nr;
1770                 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
1771                                 vol->mft_record_size_bits >= (1ll << 32))) {
1772                         ntfs_warning(vol->sb, "Cannot allocate mft record "
1773                                         "because the maximum number of inodes "
1774                                         "(2^32) has already been reached.");
1775                         up_write(&mft_ni->runlist.lock);
1776                         return -ENOSPC;
1777                 }
1778         }
1779         ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1780                         nr > min_nr ? "default" : "minimal", (long long)nr);
1781         old_last_vcn = rl[1].vcn;
1782         do {
1783                 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1784                 if (likely(!IS_ERR(rl2)))
1785                         break;
1786                 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1787                         ntfs_error(vol->sb, "Failed to allocate the minimal "
1788                                         "number of clusters (%lli) for the "
1789                                         "mft data attribute.", (long long)nr);
1790                         up_write(&mft_ni->runlist.lock);
1791                         return PTR_ERR(rl2);
1792                 }
1793                 /*
1794                  * There is not enough space to do the allocation, but there
1795                  * might be enough space to do a minimal allocation so try that
1796                  * before failing.
1797                  */
1798                 nr = min_nr;
1799                 ntfs_debug("Retrying mft data allocation with minimal cluster "
1800                                 "count %lli.", (long long)nr);
1801         } while (1);
1802         rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1803         if (IS_ERR(rl)) {
1804                 up_write(&mft_ni->runlist.lock);
1805                 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1806                                 "attribute.");
1807                 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1808                         ntfs_error(vol->sb, "Failed to dealocate clusters "
1809                                         "from the mft data attribute.%s", es);
1810                         NVolSetErrors(vol);
1811                 }
1812                 ntfs_free(rl2);
1813                 return PTR_ERR(rl);
1814         }
1815         mft_ni->runlist.rl = rl;
1816         ntfs_debug("Allocated %lli clusters.", (long long)nr);
1817         /* Find the last run in the new runlist. */
1818         for (; rl[1].length; rl++)
1819                 ;
1820         /* Update the attribute record as well. */
1821         mrec = map_mft_record(mft_ni);
1822         if (IS_ERR(mrec)) {
1823                 ntfs_error(vol->sb, "Failed to map mft record.");
1824                 ret = PTR_ERR(mrec);
1825                 goto undo_alloc;
1826         }
1827         ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1828         if (unlikely(!ctx)) {
1829                 ntfs_error(vol->sb, "Failed to get search context.");
1830                 ret = -ENOMEM;
1831                 goto undo_alloc;
1832         }
1833         ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1834                         CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
1835         if (unlikely(ret)) {
1836                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1837                                 "mft data attribute.");
1838                 if (ret == -ENOENT)
1839                         ret = -EIO;
1840                 goto undo_alloc;
1841         }
1842         a = ctx->attr;
1843         ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1844         /* Search back for the previous last allocated cluster of mft bitmap. */
1845         for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
1846                 if (ll >= rl2->vcn)
1847                         break;
1848         }
1849         BUG_ON(ll < rl2->vcn);
1850         BUG_ON(ll >= rl2->vcn + rl2->length);
1851         /* Get the size for the new mapping pairs array for this extent. */
1852         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
1853         if (unlikely(mp_size <= 0)) {
1854                 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1855                                 "mft data attribute extent.");
1856                 ret = mp_size;
1857                 if (!ret)
1858                         ret = -EIO;
1859                 goto undo_alloc;
1860         }
1861         /* Expand the attribute record if necessary. */
1862         old_alen = le32_to_cpu(a->length);
1863         ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1864                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1865         if (unlikely(ret)) {
1866                 if (ret != -ENOSPC) {
1867                         ntfs_error(vol->sb, "Failed to resize attribute "
1868                                         "record for mft data attribute.");
1869                         goto undo_alloc;
1870                 }
1871                 // TODO: Deal with this by moving this extent to a new mft
1872                 // record or by starting a new extent in a new mft record or by
1873                 // moving other attributes out of this mft record.
1874                 // Note: Use the special reserved mft records and ensure that
1875                 // this extent is not required to find the mft record in
1876                 // question.  If no free special records left we would need to
1877                 // move an existing record away, insert ours in its place, and
1878                 // then place the moved record into the newly allocated space
1879                 // and we would then need to update all references to this mft
1880                 // record appropriately.  This is rather complicated...
1881                 ntfs_error(vol->sb, "Not enough space in this mft record to "
1882                                 "accomodate extended mft data attribute "
1883                                 "extent.  Cannot handle this yet.");
1884                 ret = -EOPNOTSUPP;
1885                 goto undo_alloc;
1886         }
1887         mp_rebuilt = TRUE;
1888         /* Generate the mapping pairs array directly into the attr record. */
1889         ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1890                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
1891                         mp_size, rl2, ll, -1, NULL);
1892         if (unlikely(ret)) {
1893                 ntfs_error(vol->sb, "Failed to build mapping pairs array of "
1894                                 "mft data attribute.");
1895                 goto undo_alloc;
1896         }
1897         /* Update the highest_vcn. */
1898         a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1899         /*
1900          * We now have extended the mft data allocated_size by nr clusters.
1901          * Reflect this in the ntfs_inode structure and the attribute record.
1902          * @rl is the last (non-terminator) runlist element of mft data
1903          * attribute.
1904          */
1905         if (a->data.non_resident.lowest_vcn) {
1906                 /*
1907                  * We are not in the first attribute extent, switch to it, but
1908                  * first ensure the changes will make it to disk later.
1909                  */
1910                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1911                 mark_mft_record_dirty(ctx->ntfs_ino);
1912                 ntfs_attr_reinit_search_ctx(ctx);
1913                 ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
1914                                 mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
1915                                 ctx);
1916                 if (unlikely(ret)) {
1917                         ntfs_error(vol->sb, "Failed to find first attribute "
1918                                         "extent of mft data attribute.");
1919                         goto restore_undo_alloc;
1920                 }
1921                 a = ctx->attr;
1922         }
1923         write_lock_irqsave(&mft_ni->size_lock, flags);
1924         mft_ni->allocated_size += nr << vol->cluster_size_bits;
1925         a->data.non_resident.allocated_size =
1926                         cpu_to_sle64(mft_ni->allocated_size);
1927         write_unlock_irqrestore(&mft_ni->size_lock, flags);
1928         /* Ensure the changes make it to disk. */
1929         flush_dcache_mft_record_page(ctx->ntfs_ino);
1930         mark_mft_record_dirty(ctx->ntfs_ino);
1931         ntfs_attr_put_search_ctx(ctx);
1932         unmap_mft_record(mft_ni);
1933         up_write(&mft_ni->runlist.lock);
1934         ntfs_debug("Done.");
1935         return 0;
1936 restore_undo_alloc:
1937         ntfs_attr_reinit_search_ctx(ctx);
1938         if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
1939                         CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
1940                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1941                                 "mft data attribute.%s", es);
1942                 write_lock_irqsave(&mft_ni->size_lock, flags);
1943                 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1944                 write_unlock_irqrestore(&mft_ni->size_lock, flags);
1945                 ntfs_attr_put_search_ctx(ctx);
1946                 unmap_mft_record(mft_ni);
1947                 up_write(&mft_ni->runlist.lock);
1948                 /*
1949                  * The only thing that is now wrong is ->allocated_size of the
1950                  * base attribute extent which chkdsk should be able to fix.
1951                  */
1952                 NVolSetErrors(vol);
1953                 return ret;
1954         }
1955         a = ctx->attr;
1956         a->data.non_resident.highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1957 undo_alloc:
1958         if (ntfs_cluster_free(vol->mft_ino, old_last_vcn, -1) < 0) {
1959                 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1960                                 "attribute.%s", es);
1961                 NVolSetErrors(vol);
1962         }
1963         if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
1964                 ntfs_error(vol->sb, "Failed to truncate mft data attribute "
1965                                 "runlist.%s", es);
1966                 NVolSetErrors(vol);
1967         }
1968         if (mp_rebuilt) {
1969                 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1970                                 a->data.non_resident.mapping_pairs_offset),
1971                                 old_alen - le16_to_cpu(
1972                                 a->data.non_resident.mapping_pairs_offset),
1973                                 rl2, ll, -1, NULL)) {
1974                         ntfs_error(vol->sb, "Failed to restore mapping pairs "
1975                                         "array.%s", es);
1976                         NVolSetErrors(vol);
1977                 }
1978                 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1979                         ntfs_error(vol->sb, "Failed to restore attribute "
1980                                         "record.%s", es);
1981                         NVolSetErrors(vol);
1982                 }
1983                 flush_dcache_mft_record_page(ctx->ntfs_ino);
1984                 mark_mft_record_dirty(ctx->ntfs_ino);
1985         }
1986         if (ctx)
1987                 ntfs_attr_put_search_ctx(ctx);
1988         if (!IS_ERR(mrec))
1989                 unmap_mft_record(mft_ni);
1990         up_write(&mft_ni->runlist.lock);
1991         return ret;
1992 }
1993
1994 /**
1995  * ntfs_mft_record_layout - layout an mft record into a memory buffer
1996  * @vol:        volume to which the mft record will belong
1997  * @mft_no:     mft reference specifying the mft record number
1998  * @m:          destination buffer of size >= @vol->mft_record_size bytes
1999  *
2000  * Layout an empty, unused mft record with the mft record number @mft_no into
2001  * the buffer @m.  The volume @vol is needed because the mft record structure
2002  * was modified in NTFS 3.1 so we need to know which volume version this mft
2003  * record will be used on.
2004  *
2005  * Return 0 on success and -errno on error.
2006  */
2007 static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
2008                 MFT_RECORD *m)
2009 {
2010         ATTR_RECORD *a;
2011
2012         ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2013         if (mft_no >= (1ll << 32)) {
2014                 ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
2015                                 "maximum of 2^32.", (long long)mft_no);
2016                 return -ERANGE;
2017         }
2018         /* Start by clearing the whole mft record to gives us a clean slate. */
2019         memset(m, 0, vol->mft_record_size);
2020         /* Aligned to 2-byte boundary. */
2021         if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
2022                 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
2023         else {
2024                 m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
2025                 /*
2026                  * Set the NTFS 3.1+ specific fields while we know that the
2027                  * volume version is 3.1+.
2028                  */
2029                 m->reserved = 0;
2030                 m->mft_record_number = cpu_to_le32((u32)mft_no);
2031         }
2032         m->magic = magic_FILE;
2033         if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
2034                 m->usa_count = cpu_to_le16(vol->mft_record_size /
2035                                 NTFS_BLOCK_SIZE + 1);
2036         else {
2037                 m->usa_count = cpu_to_le16(1);
2038                 ntfs_warning(vol->sb, "Sector size is bigger than mft record "
2039                                 "size.  Setting usa_count to 1.  If chkdsk "
2040                                 "reports this as corruption, please email "
2041                                 "linux-ntfs-dev@lists.sourceforge.net stating "
2042                                 "that you saw this message and that the "
2043                                 "modified filesystem created was corrupt.  "
2044                                 "Thank you.");
2045         }
2046         /* Set the update sequence number to 1. */
2047         *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
2048         m->lsn = 0;
2049         m->sequence_number = cpu_to_le16(1);
2050         m->link_count = 0;
2051         /*
2052          * Place the attributes straight after the update sequence array,
2053          * aligned to 8-byte boundary.
2054          */
2055         m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
2056                         (le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
2057         m->flags = 0;
2058         /*
2059          * Using attrs_offset plus eight bytes (for the termination attribute).
2060          * attrs_offset is already aligned to 8-byte boundary, so no need to
2061          * align again.
2062          */
2063         m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
2064         m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
2065         m->base_mft_record = 0;
2066         m->next_attr_instance = 0;
2067         /* Add the termination attribute. */
2068         a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
2069         a->type = AT_END;
2070         a->length = 0;
2071         ntfs_debug("Done.");
2072         return 0;
2073 }
2074
2075 /**
2076  * ntfs_mft_record_format - format an mft record on an ntfs volume
2077  * @vol:        volume on which to format the mft record
2078  * @mft_no:     mft record number to format
2079  *
2080  * Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
2081  * mft record into the appropriate place of the mft data attribute.  This is
2082  * used when extending the mft data attribute.
2083  *
2084  * Return 0 on success and -errno on error.
2085  */
2086 static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
2087 {
2088         loff_t i_size;
2089         struct inode *mft_vi = vol->mft_ino;
2090         struct page *page;
2091         MFT_RECORD *m;
2092         pgoff_t index, end_index;
2093         unsigned int ofs;
2094         int err;
2095
2096         ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
2097         /*
2098          * The index into the page cache and the offset within the page cache
2099          * page of the wanted mft record.
2100          */
2101         index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2102         ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2103         /* The maximum valid index into the page cache for $MFT's data. */
2104         i_size = i_size_read(mft_vi);
2105         end_index = i_size >> PAGE_CACHE_SHIFT;
2106         if (unlikely(index >= end_index)) {
2107                 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
2108                                 (i_size & ~PAGE_CACHE_MASK))) {
2109                         ntfs_error(vol->sb, "Tried to format non-existing mft "
2110                                         "record 0x%llx.", (long long)mft_no);
2111                         return -ENOENT;
2112                 }
2113         }
2114         /* Read, map, and pin the page containing the mft record. */
2115         page = ntfs_map_page(mft_vi->i_mapping, index);
2116         if (unlikely(IS_ERR(page))) {
2117                 ntfs_error(vol->sb, "Failed to map page containing mft record "
2118                                 "to format 0x%llx.", (long long)mft_no);
2119                 return PTR_ERR(page);
2120         }
2121         lock_page(page);
2122         BUG_ON(!PageUptodate(page));
2123         ClearPageUptodate(page);
2124         m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2125         err = ntfs_mft_record_layout(vol, mft_no, m);
2126         if (unlikely(err)) {
2127                 ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
2128                                 (long long)mft_no);
2129                 SetPageUptodate(page);
2130                 unlock_page(page);
2131                 ntfs_unmap_page(page);
2132                 return err;
2133         }
2134         flush_dcache_page(page);
2135         SetPageUptodate(page);
2136         unlock_page(page);
2137         /*
2138          * Make sure the mft record is written out to disk.  We could use
2139          * ilookup5() to check if an inode is in icache and so on but this is
2140          * unnecessary as ntfs_writepage() will write the dirty record anyway.
2141          */
2142         mark_ntfs_record_dirty(page, ofs);
2143         ntfs_unmap_page(page);
2144         ntfs_debug("Done.");
2145         return 0;
2146 }
2147
2148 /**
2149  * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
2150  * @vol:        [IN]  volume on which to allocate the mft record
2151  * @mode:       [IN]  mode if want a file or directory, i.e. base inode or 0
2152  * @base_ni:    [IN]  open base inode if allocating an extent mft record or NULL
2153  * @mrec:       [OUT] on successful return this is the mapped mft record
2154  *
2155  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
2156  *
2157  * If @base_ni is NULL make the mft record a base mft record, i.e. a file or
2158  * direvctory inode, and allocate it at the default allocator position.  In
2159  * this case @mode is the file mode as given to us by the caller.  We in
2160  * particular use @mode to distinguish whether a file or a directory is being
2161  * created (S_IFDIR(mode) and S_IFREG(mode), respectively).
2162  *
2163  * If @base_ni is not NULL make the allocated mft record an extent record,
2164  * allocate it starting at the mft record after the base mft record and attach
2165  * the allocated and opened ntfs inode to the base inode @base_ni.  In this
2166  * case @mode must be 0 as it is meaningless for extent inodes.
2167  *
2168  * You need to check the return value with IS_ERR().  If false, the function
2169  * was successful and the return value is the now opened ntfs inode of the
2170  * allocated mft record.  *@mrec is then set to the allocated, mapped, pinned,
2171  * and locked mft record.  If IS_ERR() is true, the function failed and the
2172  * error code is obtained from PTR_ERR(return value).  *@mrec is undefined in
2173  * this case.
2174  *
2175  * Allocation strategy:
2176  *
2177  * To find a free mft record, we scan the mft bitmap for a zero bit.  To
2178  * optimize this we start scanning at the place specified by @base_ni or if
2179  * @base_ni is NULL we start where we last stopped and we perform wrap around
2180  * when we reach the end.  Note, we do not try to allocate mft records below
2181  * number 24 because numbers 0 to 15 are the defined system files anyway and 16
2182  * to 24 are special in that they are used for storing extension mft records
2183  * for the $DATA attribute of $MFT.  This is required to avoid the possibility
2184  * of creating a runlist with a circular dependency which once written to disk
2185  * can never be read in again.  Windows will only use records 16 to 24 for
2186  * normal files if the volume is completely out of space.  We never use them
2187  * which means that when the volume is really out of space we cannot create any
2188  * more files while Windows can still create up to 8 small files.  We can start
2189  * doing this at some later time, it does not matter much for now.
2190  *
2191  * When scanning the mft bitmap, we only search up to the last allocated mft
2192  * record.  If there are no free records left in the range 24 to number of
2193  * allocated mft records, then we extend the $MFT/$DATA attribute in order to
2194  * create free mft records.  We extend the allocated size of $MFT/$DATA by 16
2195  * records at a time or one cluster, if cluster size is above 16kiB.  If there
2196  * is not sufficient space to do this, we try to extend by a single mft record
2197  * or one cluster, if cluster size is above the mft record size.
2198  *
2199  * No matter how many mft records we allocate, we initialize only the first
2200  * allocated mft record, incrementing mft data size and initialized size
2201  * accordingly, open an ntfs_inode for it and return it to the caller, unless
2202  * there are less than 24 mft records, in which case we allocate and initialize
2203  * mft records until we reach record 24 which we consider as the first free mft
2204  * record for use by normal files.
2205  *
2206  * If during any stage we overflow the initialized data in the mft bitmap, we
2207  * extend the initialized size (and data size) by 8 bytes, allocating another
2208  * cluster if required.  The bitmap data size has to be at least equal to the
2209  * number of mft records in the mft, but it can be bigger, in which case the
2210  * superflous bits are padded with zeroes.
2211  *
2212  * Thus, when we return successfully (IS_ERR() is false), we will have:
2213  *      - initialized / extended the mft bitmap if necessary,
2214  *      - initialized / extended the mft data if necessary,
2215  *      - set the bit corresponding to the mft record being allocated in the
2216  *        mft bitmap,
2217  *      - opened an ntfs_inode for the allocated mft record, and we will have
2218  *      - returned the ntfs_inode as well as the allocated mapped, pinned, and
2219  *        locked mft record.
2220  *
2221  * On error, the volume will be left in a consistent state and no record will
2222  * be allocated.  If rolling back a partial operation fails, we may leave some
2223  * inconsistent metadata in which case we set NVolErrors() so the volume is
2224  * left dirty when unmounted.
2225  *
2226  * Note, this function cannot make use of most of the normal functions, like
2227  * for example for attribute resizing, etc, because when the run list overflows
2228  * the base mft record and an attribute list is used, it is very important that
2229  * the extension mft records used to store the $DATA attribute of $MFT can be
2230  * reached without having to read the information contained inside them, as
2231  * this would make it impossible to find them in the first place after the
2232  * volume is unmounted.  $MFT/$BITMAP probably does not need to follow this
2233  * rule because the bitmap is not essential for finding the mft records, but on
2234  * the other hand, handling the bitmap in this special way would make life
2235  * easier because otherwise there might be circular invocations of functions
2236  * when reading the bitmap.
2237  */
2238 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
2239                 ntfs_inode *base_ni, MFT_RECORD **mrec)
2240 {
2241         s64 ll, bit, old_data_initialized, old_data_size;
2242         unsigned long flags;
2243         struct inode *vi;
2244         struct page *page;
2245         ntfs_inode *mft_ni, *mftbmp_ni, *ni;
2246         ntfs_attr_search_ctx *ctx;
2247         MFT_RECORD *m;
2248         ATTR_RECORD *a;
2249         pgoff_t index;
2250         unsigned int ofs;
2251         int err;
2252         le16 seq_no, usn;
2253         BOOL record_formatted = FALSE;
2254
2255         if (base_ni) {
2256                 ntfs_debug("Entering (allocating an extent mft record for "
2257                                 "base mft record 0x%llx).",
2258                                 (long long)base_ni->mft_no);
2259                 /* @mode and @base_ni are mutually exclusive. */
2260                 BUG_ON(mode);
2261         } else
2262                 ntfs_debug("Entering (allocating a base mft record).");
2263         if (mode) {
2264                 /* @mode and @base_ni are mutually exclusive. */
2265                 BUG_ON(base_ni);
2266                 /* We only support creation of normal files and directories. */
2267                 if (!S_ISREG(mode) && !S_ISDIR(mode))
2268                         return ERR_PTR(-EOPNOTSUPP);
2269         }
2270         BUG_ON(!mrec);
2271         mft_ni = NTFS_I(vol->mft_ino);
2272         mftbmp_ni = NTFS_I(vol->mftbmp_ino);
2273         down_write(&vol->mftbmp_lock);
2274         bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
2275         if (bit >= 0) {
2276                 ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
2277                                 (long long)bit);
2278                 goto have_alloc_rec;
2279         }
2280         if (bit != -ENOSPC) {
2281                 up_write(&vol->mftbmp_lock);
2282                 return ERR_PTR(bit);
2283         }
2284         /*
2285          * No free mft records left.  If the mft bitmap already covers more
2286          * than the currently used mft records, the next records are all free,
2287          * so we can simply allocate the first unused mft record.
2288          * Note: We also have to make sure that the mft bitmap at least covers
2289          * the first 24 mft records as they are special and whilst they may not
2290          * be in use, we do not allocate from them.
2291          */
2292         read_lock_irqsave(&mft_ni->size_lock, flags);
2293         ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
2294         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2295         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2296         old_data_initialized = mftbmp_ni->initialized_size;
2297         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2298         if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
2299                 bit = ll;
2300                 if (bit < 24)
2301                         bit = 24;
2302                 if (unlikely(bit >= (1ll << 32)))
2303                         goto max_err_out;
2304                 ntfs_debug("Found free record (#2), bit 0x%llx.",
2305                                 (long long)bit);
2306                 goto found_free_rec;
2307         }
2308         /*
2309          * The mft bitmap needs to be expanded until it covers the first unused
2310          * mft record that we can allocate.
2311          * Note: The smallest mft record we allocate is mft record 24.
2312          */
2313         bit = old_data_initialized << 3;
2314         if (unlikely(bit >= (1ll << 32)))
2315                 goto max_err_out;
2316         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2317         old_data_size = mftbmp_ni->allocated_size;
2318         ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2319                         "data_size 0x%llx, initialized_size 0x%llx.",
2320                         (long long)old_data_size,
2321                         (long long)i_size_read(vol->mftbmp_ino),
2322                         (long long)old_data_initialized);
2323         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2324         if (old_data_initialized + 8 > old_data_size) {
2325                 /* Need to extend bitmap by one more cluster. */
2326                 ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
2327                 err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
2328                 if (unlikely(err)) {
2329                         up_write(&vol->mftbmp_lock);
2330                         goto err_out;
2331                 }
2332 #ifdef DEBUG
2333                 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2334                 ntfs_debug("Status of mftbmp after allocation extension: "
2335                                 "allocated_size 0x%llx, data_size 0x%llx, "
2336                                 "initialized_size 0x%llx.",
2337                                 (long long)mftbmp_ni->allocated_size,
2338                                 (long long)i_size_read(vol->mftbmp_ino),
2339                                 (long long)mftbmp_ni->initialized_size);
2340                 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2341 #endif /* DEBUG */
2342         }
2343         /*
2344          * We now have sufficient allocated space, extend the initialized_size
2345          * as well as the data_size if necessary and fill the new space with
2346          * zeroes.
2347          */
2348         err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
2349         if (unlikely(err)) {
2350                 up_write(&vol->mftbmp_lock);
2351                 goto err_out;
2352         }
2353 #ifdef DEBUG
2354         read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2355         ntfs_debug("Status of mftbmp after initialized extention: "
2356                         "allocated_size 0x%llx, data_size 0x%llx, "
2357                         "initialized_size 0x%llx.",
2358                         (long long)mftbmp_ni->allocated_size,
2359                         (long long)i_size_read(vol->mftbmp_ino),
2360                         (long long)mftbmp_ni->initialized_size);
2361         read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2362 #endif /* DEBUG */
2363         ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
2364 found_free_rec:
2365         /* @bit is the found free mft record, allocate it in the mft bitmap. */
2366         ntfs_debug("At found_free_rec.");
2367         err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
2368         if (unlikely(err)) {
2369                 ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
2370                 up_write(&vol->mftbmp_lock);
2371                 goto err_out;
2372         }
2373         ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
2374 have_alloc_rec:
2375         /*
2376          * The mft bitmap is now uptodate.  Deal with mft data attribute now.
2377          * Note, we keep hold of the mft bitmap lock for writing until all
2378          * modifications to the mft data attribute are complete, too, as they
2379          * will impact decisions for mft bitmap and mft record allocation done
2380          * by a parallel allocation and if the lock is not maintained a
2381          * parallel allocation could allocate the same mft record as this one.
2382          */
2383         ll = (bit + 1) << vol->mft_record_size_bits;
2384         read_lock_irqsave(&mft_ni->size_lock, flags);
2385         old_data_initialized = mft_ni->initialized_size;
2386         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2387         if (ll <= old_data_initialized) {
2388                 ntfs_debug("Allocated mft record already initialized.");
2389                 goto mft_rec_already_initialized;
2390         }
2391         ntfs_debug("Initializing allocated mft record.");
2392         /*
2393          * The mft record is outside the initialized data.  Extend the mft data
2394          * attribute until it covers the allocated record.  The loop is only
2395          * actually traversed more than once when a freshly formatted volume is
2396          * first written to so it optimizes away nicely in the common case.
2397          */
2398         read_lock_irqsave(&mft_ni->size_lock, flags);
2399         ntfs_debug("Status of mft data before extension: "
2400                         "allocated_size 0x%llx, data_size 0x%llx, "
2401                         "initialized_size 0x%llx.",
2402                         (long long)mft_ni->allocated_size,
2403                         (long long)i_size_read(vol->mft_ino),
2404                         (long long)mft_ni->initialized_size);
2405         while (ll > mft_ni->allocated_size) {
2406                 read_unlock_irqrestore(&mft_ni->size_lock, flags);
2407                 err = ntfs_mft_data_extend_allocation_nolock(vol);
2408                 if (unlikely(err)) {
2409                         ntfs_error(vol->sb, "Failed to extend mft data "
2410                                         "allocation.");
2411                         goto undo_mftbmp_alloc_nolock;
2412                 }
2413                 read_lock_irqsave(&mft_ni->size_lock, flags);
2414                 ntfs_debug("Status of mft data after allocation extension: "
2415                                 "allocated_size 0x%llx, data_size 0x%llx, "
2416                                 "initialized_size 0x%llx.",
2417                                 (long long)mft_ni->allocated_size,
2418                                 (long long)i_size_read(vol->mft_ino),
2419                                 (long long)mft_ni->initialized_size);
2420         }
2421         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2422         /*
2423          * Extend mft data initialized size (and data size of course) to reach
2424          * the allocated mft record, formatting the mft records allong the way.
2425          * Note: We only modify the ntfs_inode structure as that is all that is
2426          * needed by ntfs_mft_record_format().  We will update the attribute
2427          * record itself in one fell swoop later on.
2428          */
2429         write_lock_irqsave(&mft_ni->size_lock, flags);
2430         old_data_initialized = mft_ni->initialized_size;
2431         old_data_size = vol->mft_ino->i_size;
2432         while (ll > mft_ni->initialized_size) {
2433                 s64 new_initialized_size, mft_no;
2434                 
2435                 new_initialized_size = mft_ni->initialized_size +
2436                                 vol->mft_record_size;
2437                 mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
2438                 if (new_initialized_size > i_size_read(vol->mft_ino))
2439                         i_size_write(vol->mft_ino, new_initialized_size);
2440                 write_unlock_irqrestore(&mft_ni->size_lock, flags);
2441                 ntfs_debug("Initializing mft record 0x%llx.",
2442                                 (long long)mft_no);
2443                 err = ntfs_mft_record_format(vol, mft_no);
2444                 if (unlikely(err)) {
2445                         ntfs_error(vol->sb, "Failed to format mft record.");
2446                         goto undo_data_init;
2447                 }
2448                 write_lock_irqsave(&mft_ni->size_lock, flags);
2449                 mft_ni->initialized_size = new_initialized_size;
2450         }
2451         write_unlock_irqrestore(&mft_ni->size_lock, flags);
2452         record_formatted = TRUE;
2453         /* Update the mft data attribute record to reflect the new sizes. */
2454         m = map_mft_record(mft_ni);
2455         if (IS_ERR(m)) {
2456                 ntfs_error(vol->sb, "Failed to map mft record.");
2457                 err = PTR_ERR(m);
2458                 goto undo_data_init;
2459         }
2460         ctx = ntfs_attr_get_search_ctx(mft_ni, m);
2461         if (unlikely(!ctx)) {
2462                 ntfs_error(vol->sb, "Failed to get search context.");
2463                 err = -ENOMEM;
2464                 unmap_mft_record(mft_ni);
2465                 goto undo_data_init;
2466         }
2467         err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
2468                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2469         if (unlikely(err)) {
2470                 ntfs_error(vol->sb, "Failed to find first attribute extent of "
2471                                 "mft data attribute.");
2472                 ntfs_attr_put_search_ctx(ctx);
2473                 unmap_mft_record(mft_ni);
2474                 goto undo_data_init;
2475         }
2476         a = ctx->attr;
2477         read_lock_irqsave(&mft_ni->size_lock, flags);
2478         a->data.non_resident.initialized_size =
2479                         cpu_to_sle64(mft_ni->initialized_size);
2480         a->data.non_resident.data_size =
2481                         cpu_to_sle64(i_size_read(vol->mft_ino));
2482         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2483         /* Ensure the changes make it to disk. */
2484         flush_dcache_mft_record_page(ctx->ntfs_ino);
2485         mark_mft_record_dirty(ctx->ntfs_ino);
2486         ntfs_attr_put_search_ctx(ctx);
2487         unmap_mft_record(mft_ni);
2488         read_lock_irqsave(&mft_ni->size_lock, flags);
2489         ntfs_debug("Status of mft data after mft record initialization: "
2490                         "allocated_size 0x%llx, data_size 0x%llx, "
2491                         "initialized_size 0x%llx.",
2492                         (long long)mft_ni->allocated_size,
2493                         (long long)i_size_read(vol->mft_ino),
2494                         (long long)mft_ni->initialized_size);
2495         BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
2496         BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
2497         read_unlock_irqrestore(&mft_ni->size_lock, flags);
2498 mft_rec_already_initialized:
2499         /*
2500          * We can finally drop the mft bitmap lock as the mft data attribute
2501          * has been fully updated.  The only disparity left is that the
2502          * allocated mft record still needs to be marked as in use to match the
2503          * set bit in the mft bitmap but this is actually not a problem since
2504          * this mft record is not referenced from anywhere yet and the fact
2505          * that it is allocated in the mft bitmap means that no-one will try to
2506          * allocate it either.
2507          */
2508         up_write(&vol->mftbmp_lock);
2509         /*
2510          * We now have allocated and initialized the mft record.  Calculate the
2511          * index of and the offset within the page cache page the record is in.
2512          */
2513         index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
2514         ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
2515         /* Read, map, and pin the page containing the mft record. */
2516         page = ntfs_map_page(vol->mft_ino->i_mapping, index);
2517         if (unlikely(IS_ERR(page))) {
2518                 ntfs_error(vol->sb, "Failed to map page containing allocated "
2519                                 "mft record 0x%llx.", (long long)bit);
2520                 err = PTR_ERR(page);
2521                 goto undo_mftbmp_alloc;
2522         }
2523         lock_page(page);
2524         BUG_ON(!PageUptodate(page));
2525         ClearPageUptodate(page);
2526         m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
2527         /* If we just formatted the mft record no need to do it again. */
2528         if (!record_formatted) {
2529                 /* Sanity check that the mft record is really not in use. */
2530                 if (ntfs_is_file_record(m->magic) &&
2531                                 (m->flags & MFT_RECORD_IN_USE)) {
2532                         ntfs_error(vol->sb, "Mft record 0x%llx was marked "
2533                                         "free in mft bitmap but is marked "
2534                                         "used itself.  Corrupt filesystem.  "
2535                                         "Unmount and run chkdsk.",
2536                                         (long long)bit);
2537                         err = -EIO;
2538                         SetPageUptodate(page);
2539                         unlock_page(page);
2540                         ntfs_unmap_page(page);
2541                         NVolSetErrors(vol);
2542                         goto undo_mftbmp_alloc;
2543                 }
2544                 /*
2545                  * We need to (re-)format the mft record, preserving the
2546                  * sequence number if it is not zero as well as the update
2547                  * sequence number if it is not zero or -1 (0xffff).  This
2548                  * means we do not need to care whether or not something went
2549                  * wrong with the previous mft record.
2550                  */
2551                 seq_no = m->sequence_number;
2552                 usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
2553                 err = ntfs_mft_record_layout(vol, bit, m);
2554                 if (unlikely(err)) {
2555                         ntfs_error(vol->sb, "Failed to layout allocated mft "
2556                                         "record 0x%llx.", (long long)bit);
2557                         SetPageUptodate(page);
2558                         unlock_page(page);
2559                         ntfs_unmap_page(page);
2560                         goto undo_mftbmp_alloc;
2561                 }
2562                 if (seq_no)
2563                         m->sequence_number = seq_no;
2564                 if (usn && le16_to_cpu(usn) != 0xffff)
2565                         *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
2566         }
2567         /* Set the mft record itself in use. */
2568         m->flags |= MFT_RECORD_IN_USE;
2569         if (S_ISDIR(mode))
2570                 m->flags |= MFT_RECORD_IS_DIRECTORY;
2571         flush_dcache_page(page);
2572         SetPageUptodate(page);
2573         if (base_ni) {
2574                 /*
2575                  * Setup the base mft record in the extent mft record.  This
2576                  * completes initialization of the allocated extent mft record
2577                  * and we can simply use it with map_extent_mft_record().
2578                  */
2579                 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2580                                 base_ni->seq_no);
2581                 /*
2582                  * Allocate an extent inode structure for the new mft record,
2583                  * attach it to the base inode @base_ni and map, pin, and lock
2584                  * its, i.e. the allocated, mft record.
2585                  */
2586                 m = map_extent_mft_record(base_ni, bit, &ni);
2587                 if (IS_ERR(m)) {
2588                         ntfs_error(vol->sb, "Failed to map allocated extent "
2589                                         "mft record 0x%llx.", (long long)bit);
2590                         err = PTR_ERR(m);
2591                         /* Set the mft record itself not in use. */
2592                         m->flags &= cpu_to_le16(
2593                                         ~le16_to_cpu(MFT_RECORD_IN_USE));
2594                         flush_dcache_page(page);
2595                         /* Make sure the mft record is written out to disk. */
2596                         mark_ntfs_record_dirty(page, ofs);
2597                         unlock_page(page);
2598                         ntfs_unmap_page(page);
2599                         goto undo_mftbmp_alloc;
2600                 }
2601                 /*
2602                  * Make sure the allocated mft record is written out to disk.
2603                  * No need to set the inode dirty because the caller is going
2604                  * to do that anyway after finishing with the new extent mft
2605                  * record (e.g. at a minimum a new attribute will be added to
2606                  * the mft record.
2607                  */
2608                 mark_ntfs_record_dirty(page, ofs);
2609                 unlock_page(page);
2610                 /*
2611                  * Need to unmap the page since map_extent_mft_record() mapped
2612                  * it as well so we have it mapped twice at the moment.
2613                  */
2614                 ntfs_unmap_page(page);
2615         } else {
2616                 /*
2617                  * Allocate a new VFS inode and set it up.  NOTE: @vi->i_nlink
2618                  * is set to 1 but the mft record->link_count is 0.  The caller
2619                  * needs to bear this in mind.
2620                  */
2621                 vi = new_inode(vol->sb);
2622                 if (unlikely(!vi)) {
2623                         err = -ENOMEM;
2624                         /* Set the mft record itself not in use. */
2625                         m->flags &= cpu_to_le16(
2626                                         ~le16_to_cpu(MFT_RECORD_IN_USE));
2627                         flush_dcache_page(page);
2628                         /* Make sure the mft record is written out to disk. */
2629                         mark_ntfs_record_dirty(page, ofs);
2630                         unlock_page(page);
2631                         ntfs_unmap_page(page);
2632                         goto undo_mftbmp_alloc;
2633                 }
2634                 vi->i_ino = bit;
2635                 /*
2636                  * This is the optimal IO size (for stat), not the fs block
2637                  * size.
2638                  */
2639                 vi->i_blksize = PAGE_CACHE_SIZE;
2640                 /*
2641                  * This is for checking whether an inode has changed w.r.t. a
2642                  * file so that the file can be updated if necessary (compare
2643                  * with f_version).
2644                  */
2645                 vi->i_version = 1;
2646
2647                 /* The owner and group come from the ntfs volume. */
2648                 vi->i_uid = vol->uid;
2649                 vi->i_gid = vol->gid;
2650
2651                 /* Initialize the ntfs specific part of @vi. */
2652                 ntfs_init_big_inode(vi);
2653                 ni = NTFS_I(vi);
2654                 /*
2655                  * Set the appropriate mode, attribute type, and name.  For
2656                  * directories, also setup the index values to the defaults.
2657                  */
2658                 if (S_ISDIR(mode)) {
2659                         vi->i_mode = S_IFDIR | S_IRWXUGO;
2660                         vi->i_mode &= ~vol->dmask;
2661
2662                         NInoSetMstProtected(ni);
2663                         ni->type = AT_INDEX_ALLOCATION;
2664                         ni->name = I30;
2665                         ni->name_len = 4;
2666
2667                         ni->itype.index.block_size = 4096;
2668                         ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2669                         ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2670                         if (vol->cluster_size <= ni->itype.index.block_size) {
2671                                 ni->itype.index.vcn_size = vol->cluster_size;
2672                                 ni->itype.index.vcn_size_bits =
2673                                                 vol->cluster_size_bits;
2674                         } else {
2675                                 ni->itype.index.vcn_size = vol->sector_size;
2676                                 ni->itype.index.vcn_size_bits =
2677                                                 vol->sector_size_bits;
2678                         }
2679                 } else {
2680                         vi->i_mode = S_IFREG | S_IRWXUGO;
2681                         vi->i_mode &= ~vol->fmask;
2682
2683                         ni->type = AT_DATA;
2684                         ni->name = NULL;
2685                         ni->name_len = 0;
2686                 }
2687                 if (IS_RDONLY(vi))
2688                         vi->i_mode &= ~S_IWUGO;
2689
2690                 /* Set the inode times to the current time. */
2691                 vi->i_atime = vi->i_mtime = vi->i_ctime =
2692                         current_fs_time(vi->i_sb);
2693                 /*
2694                  * Set the file size to 0, the ntfs inode sizes are set to 0 by
2695                  * the call to ntfs_init_big_inode() below.
2696                  */
2697                 vi->i_size = 0;
2698                 vi->i_blocks = 0;
2699
2700                 /* Set the sequence number. */
2701                 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2702                 /*
2703                  * Manually map, pin, and lock the mft record as we already
2704                  * have its page mapped and it is very easy to do.
2705                  */
2706                 atomic_inc(&ni->count);
2707                 down(&ni->mrec_lock);
2708                 ni->page = page;
2709                 ni->page_ofs = ofs;
2710                 /*
2711                  * Make sure the allocated mft record is written out to disk.
2712                  * NOTE: We do not set the ntfs inode dirty because this would
2713                  * fail in ntfs_write_inode() because the inode does not have a
2714                  * standard information attribute yet.  Also, there is no need
2715                  * to set the inode dirty because the caller is going to do
2716                  * that anyway after finishing with the new mft record (e.g. at
2717                  * a minimum some new attributes will be added to the mft
2718                  * record.
2719                  */
2720                 mark_ntfs_record_dirty(page, ofs);
2721                 unlock_page(page);
2722
2723                 /* Add the inode to the inode hash for the superblock. */
2724                 insert_inode_hash(vi);
2725
2726                 /* Update the default mft allocation position. */
2727                 vol->mft_data_pos = bit + 1;
2728         }
2729         /*
2730          * Return the opened, allocated inode of the allocated mft record as
2731          * well as the mapped, pinned, and locked mft record.
2732          */
2733         ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2734                         base_ni ? "extent " : "", (long long)bit);
2735         *mrec = m;
2736         return ni;
2737 undo_data_init:
2738         write_lock_irqsave(&mft_ni->size_lock, flags);
2739         mft_ni->initialized_size = old_data_initialized;
2740         i_size_write(vol->mft_ino, old_data_size);
2741         write_unlock_irqrestore(&mft_ni->size_lock, flags);
2742         goto undo_mftbmp_alloc_nolock;
2743 undo_mftbmp_alloc:
2744         down_write(&vol->mftbmp_lock);
2745 undo_mftbmp_alloc_nolock:
2746         if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2747                 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2748                 NVolSetErrors(vol);
2749         }
2750         up_write(&vol->mftbmp_lock);
2751 err_out:
2752         return ERR_PTR(err);
2753 max_err_out:
2754         ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2755                         "number of inodes (2^32) has already been reached.");
2756         up_write(&vol->mftbmp_lock);
2757         return ERR_PTR(-ENOSPC);
2758 }
2759
2760 /**
2761  * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2762  * @ni:         ntfs inode of the mapped extent mft record to free
2763  * @m:          mapped extent mft record of the ntfs inode @ni
2764  *
2765  * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2766  *
2767  * Note that this function unmaps the mft record and closes and destroys @ni
2768  * internally and hence you cannot use either @ni nor @m any more after this
2769  * function returns success.
2770  *
2771  * On success return 0 and on error return -errno.  @ni and @m are still valid
2772  * in this case and have not been freed.
2773  *
2774  * For some errors an error message is displayed and the success code 0 is
2775  * returned and the volume is then left dirty on umount.  This makes sense in
2776  * case we could not rollback the changes that were already done since the
2777  * caller no longer wants to reference this mft record so it does not matter to
2778  * the caller if something is wrong with it as long as it is properly detached
2779  * from the base inode.
2780  */
2781 int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2782 {
2783         unsigned long mft_no = ni->mft_no;
2784         ntfs_volume *vol = ni->vol;
2785         ntfs_inode *base_ni;
2786         ntfs_inode **extent_nis;
2787         int i, err;
2788         le16 old_seq_no;
2789         u16 seq_no;
2790         
2791         BUG_ON(NInoAttr(ni));
2792         BUG_ON(ni->nr_extents != -1);
2793
2794         down(&ni->extent_lock);
2795         base_ni = ni->ext.base_ntfs_ino;
2796         up(&ni->extent_lock);
2797
2798         BUG_ON(base_ni->nr_extents <= 0);
2799
2800         ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2801                         mft_no, base_ni->mft_no);
2802
2803         down(&base_ni->extent_lock);
2804
2805         /* Make sure we are holding the only reference to the extent inode. */
2806         if (atomic_read(&ni->count) > 2) {
2807                 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2808                                 "not freeing.", base_ni->mft_no);
2809                 up(&base_ni->extent_lock);
2810                 return -EBUSY;
2811         }
2812
2813         /* Dissociate the ntfs inode from the base inode. */
2814         extent_nis = base_ni->ext.extent_ntfs_inos;
2815         err = -ENOENT;
2816         for (i = 0; i < base_ni->nr_extents; i++) {
2817                 if (ni != extent_nis[i])
2818                         continue;
2819                 extent_nis += i;
2820                 base_ni->nr_extents--;
2821                 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2822                                 sizeof(ntfs_inode*));
2823                 err = 0;
2824                 break;
2825         }
2826
2827         up(&base_ni->extent_lock);
2828
2829         if (unlikely(err)) {
2830                 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2831                                 "its base inode 0x%lx.", mft_no,
2832                                 base_ni->mft_no);
2833                 BUG();
2834         }
2835
2836         /*
2837          * The extent inode is no longer attached to the base inode so no one
2838          * can get a reference to it any more.
2839          */
2840
2841         /* Mark the mft record as not in use. */
2842         m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2843
2844         /* Increment the sequence number, skipping zero, if it is not zero. */
2845         old_seq_no = m->sequence_number;
2846         seq_no = le16_to_cpu(old_seq_no);
2847         if (seq_no == 0xffff)
2848                 seq_no = 1;
2849         else if (seq_no)
2850                 seq_no++;
2851         m->sequence_number = cpu_to_le16(seq_no);
2852
2853         /*
2854          * Set the ntfs inode dirty and write it out.  We do not need to worry
2855          * about the base inode here since whatever caused the extent mft
2856          * record to be freed is guaranteed to do it already.
2857          */
2858         NInoSetDirty(ni);
2859         err = write_mft_record(ni, m, 0);
2860         if (unlikely(err)) {
2861                 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2862                                 "freeing.", mft_no);
2863                 goto rollback;
2864         }
2865 rollback_error:
2866         /* Unmap and throw away the now freed extent inode. */
2867         unmap_extent_mft_record(ni);
2868         ntfs_clear_extent_inode(ni);
2869
2870         /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2871         down_write(&vol->mftbmp_lock);
2872         err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2873         up_write(&vol->mftbmp_lock);
2874         if (unlikely(err)) {
2875                 /*
2876                  * The extent inode is gone but we failed to deallocate it in
2877                  * the mft bitmap.  Just emit a warning and leave the volume
2878                  * dirty on umount.
2879                  */
2880                 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2881                 NVolSetErrors(vol);
2882         }
2883         return 0;
2884 rollback:
2885         /* Rollback what we did... */
2886         down(&base_ni->extent_lock);
2887         extent_nis = base_ni->ext.extent_ntfs_inos;
2888         if (!(base_ni->nr_extents & 3)) {
2889                 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2890
2891                 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2892                 if (unlikely(!extent_nis)) {
2893                         ntfs_error(vol->sb, "Failed to allocate internal "
2894                                         "buffer during rollback.%s", es);
2895                         up(&base_ni->extent_lock);
2896                         NVolSetErrors(vol);
2897                         goto rollback_error;
2898                 }
2899                 if (base_ni->nr_extents) {
2900                         BUG_ON(!base_ni->ext.extent_ntfs_inos);
2901                         memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2902                                         new_size - 4 * sizeof(ntfs_inode*));
2903                         kfree(base_ni->ext.extent_ntfs_inos);
2904                 }
2905                 base_ni->ext.extent_ntfs_inos = extent_nis;
2906         }
2907         m->flags |= MFT_RECORD_IN_USE;
2908         m->sequence_number = old_seq_no;
2909         extent_nis[base_ni->nr_extents++] = ni;
2910         up(&base_ni->extent_lock);
2911         mark_mft_record_dirty(ni);
2912         return err;
2913 }
2914 #endif /* NTFS_RW */