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