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