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