blob: 5577fc6e190f1fe784effd55432798afd4b27dae [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/**
2 * mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
3 *
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00004 * Copyright (c) 2001-2005 Anton Altaparmakov
Linus Torvalds1da177e2005-04-16 15:20:36 -07005 * Copyright (c) 2002 Richard Russon
6 *
7 * This program/include file is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program/include file is distributed in the hope that it will be
13 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program (in the main directory of the Linux-NTFS
19 * distribution in the file COPYING); if not, write to the Free Software
20 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22
23#include <linux/buffer_head.h>
24#include <linux/swap.h>
25
26#include "attrib.h"
27#include "aops.h"
28#include "bitmap.h"
29#include "debug.h"
30#include "dir.h"
31#include "lcnalloc.h"
32#include "malloc.h"
33#include "mft.h"
34#include "ntfs.h"
35
36/**
37 * map_mft_record_page - map the page in which a specific mft record resides
38 * @ni: ntfs inode whose mft record page to map
39 *
40 * This maps the page in which the mft record of the ntfs inode @ni is situated
41 * and returns a pointer to the mft record within the mapped page.
42 *
43 * Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
44 * contains the negative error code returned.
45 */
46static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
47{
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +000048 loff_t i_size;
Linus Torvalds1da177e2005-04-16 15:20:36 -070049 ntfs_volume *vol = ni->vol;
50 struct inode *mft_vi = vol->mft_ino;
51 struct page *page;
Anton Altaparmakov69b41e32005-10-04 14:01:14 +010052 unsigned long index, end_index;
53 unsigned ofs;
Linus Torvalds1da177e2005-04-16 15:20:36 -070054
55 BUG_ON(ni->page);
56 /*
57 * The index into the page cache and the offset within the page cache
58 * page of the wanted mft record. FIXME: We need to check for
59 * overflowing the unsigned long, but I don't think we would ever get
60 * here if the volume was that big...
61 */
Anton Altaparmakovc394e452005-10-04 13:08:53 +010062 index = (u64)ni->mft_no << vol->mft_record_size_bits >>
63 PAGE_CACHE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -070064 ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
65
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +000066 i_size = i_size_read(mft_vi);
Linus Torvalds1da177e2005-04-16 15:20:36 -070067 /* The maximum valid index into the page cache for $MFT's data. */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +000068 end_index = i_size >> PAGE_CACHE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -070069
70 /* If the wanted index is out of bounds the mft record doesn't exist. */
71 if (unlikely(index >= end_index)) {
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +000072 if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
73 vol->mft_record_size) {
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 page = ERR_PTR(-ENOENT);
75 ntfs_error(vol->sb, "Attemt to read mft record 0x%lx, "
76 "which is beyond the end of the mft. "
77 "This is probably a bug in the ntfs "
78 "driver.", ni->mft_no);
79 goto err_out;
80 }
81 }
82 /* Read, map, and pin the page. */
83 page = ntfs_map_page(mft_vi->i_mapping, index);
84 if (likely(!IS_ERR(page))) {
85 /* Catch multi sector transfer fixup errors. */
86 if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
87 ofs)))) {
88 ni->page = page;
89 ni->page_ofs = ofs;
90 return page_address(page) + ofs;
91 }
92 ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
93 "Run chkdsk.", ni->mft_no);
94 ntfs_unmap_page(page);
95 page = ERR_PTR(-EIO);
96 }
97err_out:
98 ni->page = NULL;
99 ni->page_ofs = 0;
100 return (void*)page;
101}
102
103/**
104 * map_mft_record - map, pin and lock an mft record
105 * @ni: ntfs inode whose MFT record to map
106 *
107 * First, take the mrec_lock semaphore. We might now be sleeping, while waiting
108 * for the semaphore if it was already locked by someone else.
109 *
110 * The page of the record is mapped using map_mft_record_page() before being
111 * returned to the caller.
112 *
113 * This in turn uses ntfs_map_page() to get the page containing the wanted mft
114 * record (it in turn calls read_cache_page() which reads it in from disk if
115 * necessary, increments the use count on the page so that it cannot disappear
116 * under us and returns a reference to the page cache page).
117 *
118 * If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
119 * sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
120 * and the post-read mst fixups on each mft record in the page have been
121 * performed, the page gets PG_uptodate set and PG_locked cleared (this is done
122 * in our asynchronous I/O completion handler end_buffer_read_mft_async()).
123 * ntfs_map_page() waits for PG_locked to become clear and checks if
124 * PG_uptodate is set and returns an error code if not. This provides
125 * sufficient protection against races when reading/using the page.
126 *
127 * However there is the write mapping to think about. Doing the above described
128 * checking here will be fine, because when initiating the write we will set
129 * PG_locked and clear PG_uptodate making sure nobody is touching the page
130 * contents. Doing the locking this way means that the commit to disk code in
131 * the page cache code paths is automatically sufficiently locked with us as
132 * we will not touch a page that has been locked or is not uptodate. The only
133 * locking problem then is them locking the page while we are accessing it.
134 *
135 * So that code will end up having to own the mrec_lock of all mft
136 * records/inodes present in the page before I/O can proceed. In that case we
137 * wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
138 * accessing anything without owning the mrec_lock semaphore. But we do need
139 * to use them because of the read_cache_page() invocation and the code becomes
140 * so much simpler this way that it is well worth it.
141 *
142 * The mft record is now ours and we return a pointer to it. You need to check
143 * the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
144 * the error code.
145 *
146 * NOTE: Caller is responsible for setting the mft record dirty before calling
147 * unmap_mft_record(). This is obviously only necessary if the caller really
148 * modified the mft record...
149 * Q: Do we want to recycle one of the VFS inode state bits instead?
150 * A: No, the inode ones mean we want to change the mft record, not we want to
151 * write it out.
152 */
153MFT_RECORD *map_mft_record(ntfs_inode *ni)
154{
155 MFT_RECORD *m;
156
157 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
158
159 /* Make sure the ntfs inode doesn't go away. */
160 atomic_inc(&ni->count);
161
162 /* Serialize access to this mft record. */
163 down(&ni->mrec_lock);
164
165 m = map_mft_record_page(ni);
166 if (likely(!IS_ERR(m)))
167 return m;
168
169 up(&ni->mrec_lock);
170 atomic_dec(&ni->count);
171 ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
172 return m;
173}
174
175/**
176 * unmap_mft_record_page - unmap the page in which a specific mft record resides
177 * @ni: ntfs inode whose mft record page to unmap
178 *
179 * This unmaps the page in which the mft record of the ntfs inode @ni is
180 * situated and returns. This is a NOOP if highmem is not configured.
181 *
182 * The unmap happens via ntfs_unmap_page() which in turn decrements the use
183 * count on the page thus releasing it from the pinned state.
184 *
185 * We do not actually unmap the page from memory of course, as that will be
186 * done by the page cache code itself when memory pressure increases or
187 * whatever.
188 */
189static inline void unmap_mft_record_page(ntfs_inode *ni)
190{
191 BUG_ON(!ni->page);
192
193 // TODO: If dirty, blah...
194 ntfs_unmap_page(ni->page);
195 ni->page = NULL;
196 ni->page_ofs = 0;
197 return;
198}
199
200/**
201 * unmap_mft_record - release a mapped mft record
202 * @ni: ntfs inode whose MFT record to unmap
203 *
204 * We release the page mapping and the mrec_lock mutex which unmaps the mft
205 * record and releases it for others to get hold of. We also release the ntfs
206 * inode by decrementing the ntfs inode reference count.
207 *
208 * NOTE: If caller has modified the mft record, it is imperative to set the mft
209 * record dirty BEFORE calling unmap_mft_record().
210 */
211void unmap_mft_record(ntfs_inode *ni)
212{
213 struct page *page = ni->page;
214
215 BUG_ON(!page);
216
217 ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
218
219 unmap_mft_record_page(ni);
220 up(&ni->mrec_lock);
221 atomic_dec(&ni->count);
222 /*
223 * If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
224 * ntfs_clear_extent_inode() in the extent inode case, and to the
225 * caller in the non-extent, yet pure ntfs inode case, to do the actual
226 * tear down of all structures and freeing of all allocated memory.
227 */
228 return;
229}
230
231/**
232 * map_extent_mft_record - load an extent inode and attach it to its base
233 * @base_ni: base ntfs inode
234 * @mref: mft reference of the extent inode to load
235 * @ntfs_ino: on successful return, pointer to the ntfs_inode structure
236 *
237 * Load the extent mft record @mref and attach it to its base inode @base_ni.
238 * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
239 * PTR_ERR(result) gives the negative error code.
240 *
241 * On successful return, @ntfs_ino contains a pointer to the ntfs_inode
242 * structure of the mapped extent inode.
243 */
244MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
245 ntfs_inode **ntfs_ino)
246{
247 MFT_RECORD *m;
248 ntfs_inode *ni = NULL;
249 ntfs_inode **extent_nis = NULL;
250 int i;
251 unsigned long mft_no = MREF(mref);
252 u16 seq_no = MSEQNO(mref);
253 BOOL destroy_ni = FALSE;
254
255 ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
256 mft_no, base_ni->mft_no);
257 /* Make sure the base ntfs inode doesn't go away. */
258 atomic_inc(&base_ni->count);
259 /*
260 * Check if this extent inode has already been added to the base inode,
261 * in which case just return it. If not found, add it to the base
262 * inode before returning it.
263 */
264 down(&base_ni->extent_lock);
265 if (base_ni->nr_extents > 0) {
266 extent_nis = base_ni->ext.extent_ntfs_inos;
267 for (i = 0; i < base_ni->nr_extents; i++) {
268 if (mft_no != extent_nis[i]->mft_no)
269 continue;
270 ni = extent_nis[i];
271 /* Make sure the ntfs inode doesn't go away. */
272 atomic_inc(&ni->count);
273 break;
274 }
275 }
276 if (likely(ni != NULL)) {
277 up(&base_ni->extent_lock);
278 atomic_dec(&base_ni->count);
279 /* We found the record; just have to map and return it. */
280 m = map_mft_record(ni);
281 /* map_mft_record() has incremented this on success. */
282 atomic_dec(&ni->count);
283 if (likely(!IS_ERR(m))) {
284 /* Verify the sequence number. */
285 if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
286 ntfs_debug("Done 1.");
287 *ntfs_ino = ni;
288 return m;
289 }
290 unmap_mft_record(ni);
291 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +0000292 "reference! Corrupt filesystem. "
Linus Torvalds1da177e2005-04-16 15:20:36 -0700293 "Run chkdsk.");
294 return ERR_PTR(-EIO);
295 }
296map_err_out:
297 ntfs_error(base_ni->vol->sb, "Failed to map extent "
298 "mft record, error code %ld.", -PTR_ERR(m));
299 return m;
300 }
301 /* Record wasn't there. Get a new ntfs inode and initialize it. */
302 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
303 if (unlikely(!ni)) {
304 up(&base_ni->extent_lock);
305 atomic_dec(&base_ni->count);
306 return ERR_PTR(-ENOMEM);
307 }
308 ni->vol = base_ni->vol;
309 ni->seq_no = seq_no;
310 ni->nr_extents = -1;
311 ni->ext.base_ntfs_ino = base_ni;
312 /* Now map the record. */
313 m = map_mft_record(ni);
314 if (IS_ERR(m)) {
315 up(&base_ni->extent_lock);
316 atomic_dec(&base_ni->count);
317 ntfs_clear_extent_inode(ni);
318 goto map_err_out;
319 }
320 /* Verify the sequence number if it is present. */
321 if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
322 ntfs_error(base_ni->vol->sb, "Found stale extent mft "
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +0000323 "reference! Corrupt filesystem. Run chkdsk.");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700324 destroy_ni = TRUE;
325 m = ERR_PTR(-EIO);
326 goto unm_err_out;
327 }
328 /* Attach extent inode to base inode, reallocating memory if needed. */
329 if (!(base_ni->nr_extents & 3)) {
330 ntfs_inode **tmp;
331 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
332
333 tmp = (ntfs_inode **)kmalloc(new_size, GFP_NOFS);
334 if (unlikely(!tmp)) {
335 ntfs_error(base_ni->vol->sb, "Failed to allocate "
336 "internal buffer.");
337 destroy_ni = TRUE;
338 m = ERR_PTR(-ENOMEM);
339 goto unm_err_out;
340 }
341 if (base_ni->nr_extents) {
342 BUG_ON(!base_ni->ext.extent_ntfs_inos);
343 memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
344 4 * sizeof(ntfs_inode *));
345 kfree(base_ni->ext.extent_ntfs_inos);
346 }
347 base_ni->ext.extent_ntfs_inos = tmp;
348 }
349 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
350 up(&base_ni->extent_lock);
351 atomic_dec(&base_ni->count);
352 ntfs_debug("Done 2.");
353 *ntfs_ino = ni;
354 return m;
355unm_err_out:
356 unmap_mft_record(ni);
357 up(&base_ni->extent_lock);
358 atomic_dec(&base_ni->count);
359 /*
360 * If the extent inode was not attached to the base inode we need to
361 * release it or we will leak memory.
362 */
363 if (destroy_ni)
364 ntfs_clear_extent_inode(ni);
365 return m;
366}
367
368#ifdef NTFS_RW
369
370/**
371 * __mark_mft_record_dirty - set the mft record and the page containing it dirty
372 * @ni: ntfs inode describing the mapped mft record
373 *
374 * Internal function. Users should call mark_mft_record_dirty() instead.
375 *
376 * Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
377 * as well as the page containing the mft record, dirty. Also, mark the base
378 * vfs inode dirty. This ensures that any changes to the mft record are
379 * written out to disk.
380 *
381 * NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
382 * on the base vfs inode, because even though file data may have been modified,
383 * it is dirty in the inode meta data rather than the data page cache of the
384 * inode, and thus there are no data pages that need writing out. Therefore, a
385 * full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
386 * other hand, is not sufficient, because I_DIRTY_DATASYNC needs to be set to
387 * ensure ->write_inode is called from generic_osync_inode() and this needs to
388 * happen or the file data would not necessarily hit the device synchronously,
389 * even though the vfs inode has the O_SYNC flag set. Also, I_DIRTY_DATASYNC
390 * simply "feels" better than just I_DIRTY_SYNC, since the file data has not
391 * actually hit the block device yet, which is not what I_DIRTY_SYNC on its own
392 * would suggest.
393 */
394void __mark_mft_record_dirty(ntfs_inode *ni)
395{
396 ntfs_inode *base_ni;
397
398 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
399 BUG_ON(NInoAttr(ni));
400 mark_ntfs_record_dirty(ni->page, ni->page_ofs);
401 /* Determine the base vfs inode and mark it dirty, too. */
402 down(&ni->extent_lock);
403 if (likely(ni->nr_extents >= 0))
404 base_ni = ni;
405 else
406 base_ni = ni->ext.base_ntfs_ino;
407 up(&ni->extent_lock);
408 __mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
409}
410
411static const char *ntfs_please_email = "Please email "
412 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
413 "this message. Thank you.";
414
415/**
416 * ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
417 * @vol: ntfs volume on which the mft record to synchronize resides
418 * @mft_no: mft record number of mft record to synchronize
419 * @m: mapped, mst protected (extent) mft record to synchronize
420 *
421 * Write the mapped, mst protected (extent) mft record @m with mft record
422 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
423 * bypassing the page cache and the $MFTMirr inode itself.
424 *
425 * This function is only for use at umount time when the mft mirror inode has
426 * already been disposed off. We BUG() if we are called while the mft mirror
427 * inode is still attached to the volume.
428 *
429 * On success return 0. On error return -errno.
430 *
431 * NOTE: This function is not implemented yet as I am not convinced it can
432 * actually be triggered considering the sequence of commits we do in super.c::
433 * ntfs_put_super(). But just in case we provide this place holder as the
434 * alternative would be either to BUG() or to get a NULL pointer dereference
435 * and Oops.
436 */
437static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
438 const unsigned long mft_no, MFT_RECORD *m)
439{
440 BUG_ON(vol->mftmirr_ino);
441 ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
442 "implemented yet. %s", ntfs_please_email);
443 return -EOPNOTSUPP;
444}
445
446/**
447 * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
448 * @vol: ntfs volume on which the mft record to synchronize resides
449 * @mft_no: mft record number of mft record to synchronize
450 * @m: mapped, mst protected (extent) mft record to synchronize
451 * @sync: if true, wait for i/o completion
452 *
453 * Write the mapped, mst protected (extent) mft record @m with mft record
454 * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
455 *
456 * On success return 0. On error return -errno and set the volume errors flag
457 * in the ntfs volume @vol.
458 *
459 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
460 *
461 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
462 * schedule i/o via ->writepage or do it via kntfsd or whatever.
463 */
464int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
465 MFT_RECORD *m, int sync)
466{
467 struct page *page;
468 unsigned int blocksize = vol->sb->s_blocksize;
469 int max_bhs = vol->mft_record_size / blocksize;
470 struct buffer_head *bhs[max_bhs];
471 struct buffer_head *bh, *head;
472 u8 *kmirr;
473 runlist_element *rl;
474 unsigned int block_start, block_end, m_start, m_end, page_ofs;
475 int i_bhs, nr_bhs, err = 0;
476 unsigned char blocksize_bits = vol->mftmirr_ino->i_blkbits;
477
478 ntfs_debug("Entering for inode 0x%lx.", mft_no);
479 BUG_ON(!max_bhs);
480 if (unlikely(!vol->mftmirr_ino)) {
481 /* This could happen during umount... */
482 err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
483 if (likely(!err))
484 return err;
485 goto err_out;
486 }
487 /* Get the page containing the mirror copy of the mft record @m. */
488 page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
489 (PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
490 if (IS_ERR(page)) {
491 ntfs_error(vol->sb, "Failed to map mft mirror page.");
492 err = PTR_ERR(page);
493 goto err_out;
494 }
495 lock_page(page);
496 BUG_ON(!PageUptodate(page));
497 ClearPageUptodate(page);
498 /* Offset of the mft mirror record inside the page. */
499 page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
500 /* The address in the page of the mirror copy of the mft record @m. */
501 kmirr = page_address(page) + page_ofs;
502 /* Copy the mst protected mft record to the mirror. */
503 memcpy(kmirr, m, vol->mft_record_size);
504 /* Create uptodate buffers if not present. */
505 if (unlikely(!page_has_buffers(page))) {
506 struct buffer_head *tail;
507
508 bh = head = alloc_page_buffers(page, blocksize, 1);
509 do {
510 set_buffer_uptodate(bh);
511 tail = bh;
512 bh = bh->b_this_page;
513 } while (bh);
514 tail->b_this_page = head;
515 attach_page_buffers(page, head);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700516 }
517 bh = head = page_buffers(page);
518 BUG_ON(!bh);
519 rl = NULL;
520 nr_bhs = 0;
521 block_start = 0;
522 m_start = kmirr - (u8*)page_address(page);
523 m_end = m_start + vol->mft_record_size;
524 do {
525 block_end = block_start + blocksize;
526 /* If the buffer is outside the mft record, skip it. */
527 if (block_end <= m_start)
528 continue;
529 if (unlikely(block_start >= m_end))
530 break;
531 /* Need to map the buffer if it is not mapped already. */
532 if (unlikely(!buffer_mapped(bh))) {
533 VCN vcn;
534 LCN lcn;
535 unsigned int vcn_ofs;
536
Anton Altaparmakove74589a2005-08-16 16:38:28 +0100537 bh->b_bdev = vol->sb->s_bdev;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700538 /* Obtain the vcn and offset of the current block. */
539 vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
540 (block_start - m_start);
541 vcn_ofs = vcn & vol->cluster_size_mask;
542 vcn >>= vol->cluster_size_bits;
543 if (!rl) {
544 down_read(&NTFS_I(vol->mftmirr_ino)->
545 runlist.lock);
546 rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
547 /*
548 * $MFTMirr always has the whole of its runlist
549 * in memory.
550 */
551 BUG_ON(!rl);
552 }
553 /* Seek to element containing target vcn. */
554 while (rl->length && rl[1].vcn <= vcn)
555 rl++;
556 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
557 /* For $MFTMirr, only lcn >= 0 is a successful remap. */
558 if (likely(lcn >= 0)) {
559 /* Setup buffer head to correct block. */
560 bh->b_blocknr = ((lcn <<
561 vol->cluster_size_bits) +
562 vcn_ofs) >> blocksize_bits;
563 set_buffer_mapped(bh);
564 } else {
565 bh->b_blocknr = -1;
566 ntfs_error(vol->sb, "Cannot write mft mirror "
567 "record 0x%lx because its "
568 "location on disk could not "
569 "be determined (error code "
570 "%lli).", mft_no,
571 (long long)lcn);
572 err = -EIO;
573 }
574 }
575 BUG_ON(!buffer_uptodate(bh));
576 BUG_ON(!nr_bhs && (m_start != block_start));
577 BUG_ON(nr_bhs >= max_bhs);
578 bhs[nr_bhs++] = bh;
579 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
580 } while (block_start = block_end, (bh = bh->b_this_page) != head);
581 if (unlikely(rl))
582 up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
583 if (likely(!err)) {
584 /* Lock buffers and start synchronous write i/o on them. */
585 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
586 struct buffer_head *tbh = bhs[i_bhs];
587
588 if (unlikely(test_set_buffer_locked(tbh)))
589 BUG();
590 BUG_ON(!buffer_uptodate(tbh));
591 clear_buffer_dirty(tbh);
592 get_bh(tbh);
593 tbh->b_end_io = end_buffer_write_sync;
594 submit_bh(WRITE, tbh);
595 }
596 /* Wait on i/o completion of buffers. */
597 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
598 struct buffer_head *tbh = bhs[i_bhs];
599
600 wait_on_buffer(tbh);
601 if (unlikely(!buffer_uptodate(tbh))) {
602 err = -EIO;
603 /*
604 * Set the buffer uptodate so the page and
605 * buffer states do not become out of sync.
606 */
607 set_buffer_uptodate(tbh);
608 }
609 }
610 } else /* if (unlikely(err)) */ {
611 /* Clean the buffers. */
612 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
613 clear_buffer_dirty(bhs[i_bhs]);
614 }
615 /* Current state: all buffers are clean, unlocked, and uptodate. */
616 /* Remove the mst protection fixups again. */
617 post_write_mst_fixup((NTFS_RECORD*)kmirr);
618 flush_dcache_page(page);
619 SetPageUptodate(page);
620 unlock_page(page);
621 ntfs_unmap_page(page);
622 if (likely(!err)) {
623 ntfs_debug("Done.");
624 } else {
625 ntfs_error(vol->sb, "I/O error while writing mft mirror "
626 "record 0x%lx!", mft_no);
627err_out:
628 ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
629 "code %i). Volume will be left marked dirty "
630 "on umount. Run ntfsfix on the partition "
631 "after umounting to correct this.", -err);
632 NVolSetErrors(vol);
633 }
634 return err;
635}
636
637/**
638 * write_mft_record_nolock - write out a mapped (extent) mft record
639 * @ni: ntfs inode describing the mapped (extent) mft record
640 * @m: mapped (extent) mft record to write
641 * @sync: if true, wait for i/o completion
642 *
643 * Write the mapped (extent) mft record @m described by the (regular or extent)
644 * ntfs inode @ni to backing store. If the mft record @m has a counterpart in
645 * the mft mirror, that is also updated.
646 *
647 * We only write the mft record if the ntfs inode @ni is dirty and the first
648 * buffer belonging to its mft record is dirty, too. We ignore the dirty state
649 * of subsequent buffers because we could have raced with
650 * fs/ntfs/aops.c::mark_ntfs_record_dirty().
651 *
652 * On success, clean the mft record and return 0. On error, leave the mft
653 * record dirty and return -errno. The caller should call make_bad_inode() on
654 * the base inode to ensure no more access happens to this inode. We do not do
655 * it here as the caller may want to finish writing other extent mft records
656 * first to minimize on-disk metadata inconsistencies.
657 *
658 * NOTE: We always perform synchronous i/o and ignore the @sync parameter.
659 * However, if the mft record has a counterpart in the mft mirror and @sync is
660 * true, we write the mft record, wait for i/o completion, and only then write
661 * the mft mirror copy. This ensures that if the system crashes either the mft
662 * or the mft mirror will contain a self-consistent mft record @m. If @sync is
663 * false on the other hand, we start i/o on both and then wait for completion
664 * on them. This provides a speedup but no longer guarantees that you will end
665 * up with a self-consistent mft record in the case of a crash but if you asked
666 * for asynchronous writing you probably do not care about that anyway.
667 *
668 * TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
669 * schedule i/o via ->writepage or do it via kntfsd or whatever.
670 */
671int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
672{
673 ntfs_volume *vol = ni->vol;
674 struct page *page = ni->page;
675 unsigned char blocksize_bits = vol->mft_ino->i_blkbits;
676 unsigned int blocksize = 1 << blocksize_bits;
677 int max_bhs = vol->mft_record_size / blocksize;
678 struct buffer_head *bhs[max_bhs];
679 struct buffer_head *bh, *head;
680 runlist_element *rl;
681 unsigned int block_start, block_end, m_start, m_end;
682 int i_bhs, nr_bhs, err = 0;
683
684 ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
685 BUG_ON(NInoAttr(ni));
686 BUG_ON(!max_bhs);
687 BUG_ON(!PageLocked(page));
688 /*
689 * If the ntfs_inode is clean no need to do anything. If it is dirty,
690 * mark it as clean now so that it can be redirtied later on if needed.
691 * There is no danger of races since the caller is holding the locks
692 * for the mft record @m and the page it is in.
693 */
694 if (!NInoTestClearDirty(ni))
695 goto done;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696 bh = head = page_buffers(page);
697 BUG_ON(!bh);
698 rl = NULL;
699 nr_bhs = 0;
700 block_start = 0;
701 m_start = ni->page_ofs;
702 m_end = m_start + vol->mft_record_size;
703 do {
704 block_end = block_start + blocksize;
705 /* If the buffer is outside the mft record, skip it. */
706 if (block_end <= m_start)
707 continue;
708 if (unlikely(block_start >= m_end))
709 break;
710 /*
711 * If this block is not the first one in the record, we ignore
712 * the buffer's dirty state because we could have raced with a
713 * parallel mark_ntfs_record_dirty().
714 */
715 if (block_start == m_start) {
716 /* This block is the first one in the record. */
717 if (!buffer_dirty(bh)) {
718 BUG_ON(nr_bhs);
719 /* Clean records are not written out. */
720 break;
721 }
722 }
723 /* Need to map the buffer if it is not mapped already. */
724 if (unlikely(!buffer_mapped(bh))) {
725 VCN vcn;
726 LCN lcn;
727 unsigned int vcn_ofs;
728
Anton Altaparmakove74589a2005-08-16 16:38:28 +0100729 bh->b_bdev = vol->sb->s_bdev;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700730 /* Obtain the vcn and offset of the current block. */
731 vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
732 (block_start - m_start);
733 vcn_ofs = vcn & vol->cluster_size_mask;
734 vcn >>= vol->cluster_size_bits;
735 if (!rl) {
736 down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
737 rl = NTFS_I(vol->mft_ino)->runlist.rl;
738 BUG_ON(!rl);
739 }
740 /* Seek to element containing target vcn. */
741 while (rl->length && rl[1].vcn <= vcn)
742 rl++;
743 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
744 /* For $MFT, only lcn >= 0 is a successful remap. */
745 if (likely(lcn >= 0)) {
746 /* Setup buffer head to correct block. */
747 bh->b_blocknr = ((lcn <<
748 vol->cluster_size_bits) +
749 vcn_ofs) >> blocksize_bits;
750 set_buffer_mapped(bh);
751 } else {
752 bh->b_blocknr = -1;
753 ntfs_error(vol->sb, "Cannot write mft record "
754 "0x%lx because its location "
755 "on disk could not be "
756 "determined (error code %lli).",
757 ni->mft_no, (long long)lcn);
758 err = -EIO;
759 }
760 }
761 BUG_ON(!buffer_uptodate(bh));
762 BUG_ON(!nr_bhs && (m_start != block_start));
763 BUG_ON(nr_bhs >= max_bhs);
764 bhs[nr_bhs++] = bh;
765 BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
766 } while (block_start = block_end, (bh = bh->b_this_page) != head);
767 if (unlikely(rl))
768 up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
769 if (!nr_bhs)
770 goto done;
771 if (unlikely(err))
772 goto cleanup_out;
773 /* Apply the mst protection fixups. */
774 err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
775 if (err) {
776 ntfs_error(vol->sb, "Failed to apply mst fixups!");
777 goto cleanup_out;
778 }
779 flush_dcache_mft_record_page(ni);
780 /* Lock buffers and start synchronous write i/o on them. */
781 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
782 struct buffer_head *tbh = bhs[i_bhs];
783
784 if (unlikely(test_set_buffer_locked(tbh)))
785 BUG();
786 BUG_ON(!buffer_uptodate(tbh));
787 clear_buffer_dirty(tbh);
788 get_bh(tbh);
789 tbh->b_end_io = end_buffer_write_sync;
790 submit_bh(WRITE, tbh);
791 }
792 /* Synchronize the mft mirror now if not @sync. */
793 if (!sync && ni->mft_no < vol->mftmirr_size)
794 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
795 /* Wait on i/o completion of buffers. */
796 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
797 struct buffer_head *tbh = bhs[i_bhs];
798
799 wait_on_buffer(tbh);
800 if (unlikely(!buffer_uptodate(tbh))) {
801 err = -EIO;
802 /*
803 * Set the buffer uptodate so the page and buffer
804 * states do not become out of sync.
805 */
806 if (PageUptodate(page))
807 set_buffer_uptodate(tbh);
808 }
809 }
810 /* If @sync, now synchronize the mft mirror. */
811 if (sync && ni->mft_no < vol->mftmirr_size)
812 ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
813 /* Remove the mst protection fixups again. */
814 post_write_mst_fixup((NTFS_RECORD*)m);
815 flush_dcache_mft_record_page(ni);
816 if (unlikely(err)) {
817 /* I/O error during writing. This is really bad! */
818 ntfs_error(vol->sb, "I/O error while writing mft record "
819 "0x%lx! Marking base inode as bad. You "
820 "should unmount the volume and run chkdsk.",
821 ni->mft_no);
822 goto err_out;
823 }
824done:
825 ntfs_debug("Done.");
826 return 0;
827cleanup_out:
828 /* Clean the buffers. */
829 for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
830 clear_buffer_dirty(bhs[i_bhs]);
831err_out:
832 /*
833 * Current state: all buffers are clean, unlocked, and uptodate.
834 * The caller should mark the base inode as bad so that no more i/o
835 * happens. ->clear_inode() will still be invoked so all extent inodes
836 * and other allocated memory will be freed.
837 */
838 if (err == -ENOMEM) {
839 ntfs_error(vol->sb, "Not enough memory to write mft record. "
840 "Redirtying so the write is retried later.");
841 mark_mft_record_dirty(ni);
842 err = 0;
843 } else
844 NVolSetErrors(vol);
845 return err;
846}
847
848/**
849 * ntfs_may_write_mft_record - check if an mft record may be written out
850 * @vol: [IN] ntfs volume on which the mft record to check resides
851 * @mft_no: [IN] mft record number of the mft record to check
852 * @m: [IN] mapped mft record to check
853 * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
854 *
855 * Check if the mapped (base or extent) mft record @m with mft record number
856 * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
857 * and possible the ntfs inode of the mft record is locked and the base vfs
858 * inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
859 * caller is responsible for unlocking the ntfs inode and unpinning the base
860 * vfs inode.
861 *
862 * Return TRUE if the mft record may be written out and FALSE if not.
863 *
864 * The caller has locked the page and cleared the uptodate flag on it which
865 * means that we can safely write out any dirty mft records that do not have
866 * their inodes in icache as determined by ilookup5() as anyone
867 * opening/creating such an inode would block when attempting to map the mft
868 * record in read_cache_page() until we are finished with the write out.
869 *
870 * Here is a description of the tests we perform:
871 *
872 * If the inode is found in icache we know the mft record must be a base mft
873 * record. If it is dirty, we do not write it and return FALSE as the vfs
874 * inode write paths will result in the access times being updated which would
875 * cause the base mft record to be redirtied and written out again. (We know
876 * the access time update will modify the base mft record because Windows
877 * chkdsk complains if the standard information attribute is not in the base
878 * mft record.)
879 *
880 * If the inode is in icache and not dirty, we attempt to lock the mft record
881 * and if we find the lock was already taken, it is not safe to write the mft
882 * record and we return FALSE.
883 *
884 * If we manage to obtain the lock we have exclusive access to the mft record,
885 * which also allows us safe writeout of the mft record. We then set
886 * @locked_ni to the locked ntfs inode and return TRUE.
887 *
888 * Note we cannot just lock the mft record and sleep while waiting for the lock
889 * because this would deadlock due to lock reversal (normally the mft record is
890 * locked before the page is locked but we already have the page locked here
891 * when we try to lock the mft record).
892 *
893 * If the inode is not in icache we need to perform further checks.
894 *
895 * If the mft record is not a FILE record or it is a base mft record, we can
896 * safely write it and return TRUE.
897 *
898 * We now know the mft record is an extent mft record. We check if the inode
899 * corresponding to its base mft record is in icache and obtain a reference to
900 * it if it is. If it is not, we can safely write it and return TRUE.
901 *
902 * We now have the base inode for the extent mft record. We check if it has an
903 * ntfs inode for the extent mft record attached and if not it is safe to write
904 * the extent mft record and we return TRUE.
905 *
906 * The ntfs inode for the extent mft record is attached to the base inode so we
907 * attempt to lock the extent mft record and if we find the lock was already
908 * taken, it is not safe to write the extent mft record and we return FALSE.
909 *
910 * If we manage to obtain the lock we have exclusive access to the extent mft
911 * record, which also allows us safe writeout of the extent mft record. We
912 * set the ntfs inode of the extent mft record clean and then set @locked_ni to
913 * the now locked ntfs inode and return TRUE.
914 *
915 * Note, the reason for actually writing dirty mft records here and not just
916 * relying on the vfs inode dirty code paths is that we can have mft records
917 * modified without them ever having actual inodes in memory. Also we can have
918 * dirty mft records with clean ntfs inodes in memory. None of the described
919 * cases would result in the dirty mft records being written out if we only
920 * relied on the vfs inode dirty code paths. And these cases can really occur
921 * during allocation of new mft records and in particular when the
922 * initialized_size of the $MFT/$DATA attribute is extended and the new space
923 * is initialized using ntfs_mft_record_format(). The clean inode can then
924 * appear if the mft record is reused for a new inode before it got written
925 * out.
926 */
927BOOL ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
928 const MFT_RECORD *m, ntfs_inode **locked_ni)
929{
930 struct super_block *sb = vol->sb;
931 struct inode *mft_vi = vol->mft_ino;
932 struct inode *vi;
933 ntfs_inode *ni, *eni, **extent_nis;
934 int i;
935 ntfs_attr na;
936
937 ntfs_debug("Entering for inode 0x%lx.", mft_no);
938 /*
939 * Normally we do not return a locked inode so set @locked_ni to NULL.
940 */
941 BUG_ON(!locked_ni);
942 *locked_ni = NULL;
943 /*
944 * Check if the inode corresponding to this mft record is in the VFS
945 * inode cache and obtain a reference to it if it is.
946 */
947 ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
948 na.mft_no = mft_no;
949 na.name = NULL;
950 na.name_len = 0;
951 na.type = AT_UNUSED;
952 /*
Anton Altaparmakovba6d2372005-06-26 22:12:02 +0100953 * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
954 * we get here for it rather often.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955 */
956 if (!mft_no) {
957 /* Balance the below iput(). */
958 vi = igrab(mft_vi);
959 BUG_ON(vi != mft_vi);
Anton Altaparmakovba6d2372005-06-26 22:12:02 +0100960 } else {
961 /*
962 * Have to use ilookup5_nowait() since ilookup5() waits for the
963 * inode lock which causes ntfs to deadlock when a concurrent
964 * inode write via the inode dirty code paths and the page
965 * dirty code path of the inode dirty code path when writing
966 * $MFT occurs.
967 */
968 vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
969 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700970 if (vi) {
971 ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
972 /* The inode is in icache. */
973 ni = NTFS_I(vi);
974 /* Take a reference to the ntfs inode. */
975 atomic_inc(&ni->count);
976 /* If the inode is dirty, do not write this record. */
977 if (NInoDirty(ni)) {
978 ntfs_debug("Inode 0x%lx is dirty, do not write it.",
979 mft_no);
980 atomic_dec(&ni->count);
981 iput(vi);
982 return FALSE;
983 }
984 ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
985 /* The inode is not dirty, try to take the mft record lock. */
986 if (unlikely(down_trylock(&ni->mrec_lock))) {
987 ntfs_debug("Mft record 0x%lx is already locked, do "
988 "not write it.", mft_no);
989 atomic_dec(&ni->count);
990 iput(vi);
991 return FALSE;
992 }
993 ntfs_debug("Managed to lock mft record 0x%lx, write it.",
994 mft_no);
995 /*
996 * The write has to occur while we hold the mft record lock so
997 * return the locked ntfs inode.
998 */
999 *locked_ni = ni;
1000 return TRUE;
1001 }
1002 ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
1003 /* The inode is not in icache. */
1004 /* Write the record if it is not a mft record (type "FILE"). */
1005 if (!ntfs_is_mft_record(m->magic)) {
1006 ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
1007 mft_no);
1008 return TRUE;
1009 }
1010 /* Write the mft record if it is a base inode. */
1011 if (!m->base_mft_record) {
1012 ntfs_debug("Mft record 0x%lx is a base record, write it.",
1013 mft_no);
1014 return TRUE;
1015 }
1016 /*
1017 * This is an extent mft record. Check if the inode corresponding to
1018 * its base mft record is in icache and obtain a reference to it if it
1019 * is.
1020 */
1021 na.mft_no = MREF_LE(m->base_mft_record);
1022 ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
1023 "inode 0x%lx in icache.", mft_no, na.mft_no);
Anton Altaparmakovba6d2372005-06-26 22:12:02 +01001024 if (!na.mft_no) {
1025 /* Balance the below iput(). */
1026 vi = igrab(mft_vi);
1027 BUG_ON(vi != mft_vi);
1028 } else
1029 vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
1030 &na);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001031 if (!vi) {
1032 /*
1033 * The base inode is not in icache, write this extent mft
1034 * record.
1035 */
1036 ntfs_debug("Base inode 0x%lx is not in icache, write the "
1037 "extent record.", na.mft_no);
1038 return TRUE;
1039 }
1040 ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
1041 /*
1042 * The base inode is in icache. Check if it has the extent inode
1043 * corresponding to this extent mft record attached.
1044 */
1045 ni = NTFS_I(vi);
1046 down(&ni->extent_lock);
1047 if (ni->nr_extents <= 0) {
1048 /*
1049 * The base inode has no attached extent inodes, write this
1050 * extent mft record.
1051 */
1052 up(&ni->extent_lock);
1053 iput(vi);
1054 ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
1055 "write the extent record.", na.mft_no);
1056 return TRUE;
1057 }
1058 /* Iterate over the attached extent inodes. */
1059 extent_nis = ni->ext.extent_ntfs_inos;
1060 for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
1061 if (mft_no == extent_nis[i]->mft_no) {
1062 /*
1063 * Found the extent inode corresponding to this extent
1064 * mft record.
1065 */
1066 eni = extent_nis[i];
1067 break;
1068 }
1069 }
1070 /*
1071 * If the extent inode was not attached to the base inode, write this
1072 * extent mft record.
1073 */
1074 if (!eni) {
1075 up(&ni->extent_lock);
1076 iput(vi);
1077 ntfs_debug("Extent inode 0x%lx is not attached to its base "
1078 "inode 0x%lx, write the extent record.",
1079 mft_no, na.mft_no);
1080 return TRUE;
1081 }
1082 ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
1083 mft_no, na.mft_no);
1084 /* Take a reference to the extent ntfs inode. */
1085 atomic_inc(&eni->count);
1086 up(&ni->extent_lock);
1087 /*
1088 * Found the extent inode coresponding to this extent mft record.
1089 * Try to take the mft record lock.
1090 */
1091 if (unlikely(down_trylock(&eni->mrec_lock))) {
1092 atomic_dec(&eni->count);
1093 iput(vi);
1094 ntfs_debug("Extent mft record 0x%lx is already locked, do "
1095 "not write it.", mft_no);
1096 return FALSE;
1097 }
1098 ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
1099 mft_no);
1100 if (NInoTestClearDirty(eni))
1101 ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
1102 mft_no);
1103 /*
1104 * The write has to occur while we hold the mft record lock so return
1105 * the locked extent ntfs inode.
1106 */
1107 *locked_ni = eni;
1108 return TRUE;
1109}
1110
1111static const char *es = " Leaving inconsistent metadata. Unmount and run "
1112 "chkdsk.";
1113
1114/**
1115 * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
1116 * @vol: volume on which to search for a free mft record
1117 * @base_ni: open base inode if allocating an extent mft record or NULL
1118 *
1119 * Search for a free mft record in the mft bitmap attribute on the ntfs volume
1120 * @vol.
1121 *
1122 * If @base_ni is NULL start the search at the default allocator position.
1123 *
1124 * If @base_ni is not NULL start the search at the mft record after the base
1125 * mft record @base_ni.
1126 *
1127 * Return the free mft record on success and -errno on error. An error code of
1128 * -ENOSPC means that there are no free mft records in the currently
1129 * initialized mft bitmap.
1130 *
1131 * Locking: Caller must hold vol->mftbmp_lock for writing.
1132 */
1133static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
1134 ntfs_inode *base_ni)
1135{
1136 s64 pass_end, ll, data_pos, pass_start, ofs, bit;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001137 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001138 struct address_space *mftbmp_mapping;
1139 u8 *buf, *byte;
1140 struct page *page;
1141 unsigned int page_ofs, size;
1142 u8 pass, b;
1143
1144 ntfs_debug("Searching for free mft record in the currently "
1145 "initialized mft bitmap.");
1146 mftbmp_mapping = vol->mftbmp_ino->i_mapping;
1147 /*
1148 * Set the end of the pass making sure we do not overflow the mft
1149 * bitmap.
1150 */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001151 read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001152 pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
1153 vol->mft_record_size_bits;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001154 read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
1155 read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001156 ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001157 read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001158 if (pass_end > ll)
1159 pass_end = ll;
1160 pass = 1;
1161 if (!base_ni)
1162 data_pos = vol->mft_data_pos;
1163 else
1164 data_pos = base_ni->mft_no + 1;
1165 if (data_pos < 24)
1166 data_pos = 24;
1167 if (data_pos >= pass_end) {
1168 data_pos = 24;
1169 pass = 2;
1170 /* This happens on a freshly formatted volume. */
1171 if (data_pos >= pass_end)
1172 return -ENOSPC;
1173 }
1174 pass_start = data_pos;
1175 ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
1176 "pass_end 0x%llx, data_pos 0x%llx.", pass,
1177 (long long)pass_start, (long long)pass_end,
1178 (long long)data_pos);
1179 /* Loop until a free mft record is found. */
1180 for (; pass <= 2;) {
1181 /* Cap size to pass_end. */
1182 ofs = data_pos >> 3;
1183 page_ofs = ofs & ~PAGE_CACHE_MASK;
1184 size = PAGE_CACHE_SIZE - page_ofs;
1185 ll = ((pass_end + 7) >> 3) - ofs;
1186 if (size > ll)
1187 size = ll;
1188 size <<= 3;
1189 /*
1190 * If we are still within the active pass, search the next page
1191 * for a zero bit.
1192 */
1193 if (size) {
1194 page = ntfs_map_page(mftbmp_mapping,
1195 ofs >> PAGE_CACHE_SHIFT);
1196 if (unlikely(IS_ERR(page))) {
1197 ntfs_error(vol->sb, "Failed to read mft "
1198 "bitmap, aborting.");
1199 return PTR_ERR(page);
1200 }
1201 buf = (u8*)page_address(page) + page_ofs;
1202 bit = data_pos & 7;
1203 data_pos &= ~7ull;
1204 ntfs_debug("Before inner for loop: size 0x%x, "
1205 "data_pos 0x%llx, bit 0x%llx", size,
1206 (long long)data_pos, (long long)bit);
1207 for (; bit < size && data_pos + bit < pass_end;
1208 bit &= ~7ull, bit += 8) {
1209 byte = buf + (bit >> 3);
1210 if (*byte == 0xff)
1211 continue;
1212 b = ffz((unsigned long)*byte);
1213 if (b < 8 && b >= (bit & 7)) {
1214 ll = data_pos + (bit & ~7ull) + b;
1215 if (unlikely(ll > (1ll << 32))) {
1216 ntfs_unmap_page(page);
1217 return -ENOSPC;
1218 }
1219 *byte |= 1 << b;
1220 flush_dcache_page(page);
1221 set_page_dirty(page);
1222 ntfs_unmap_page(page);
1223 ntfs_debug("Done. (Found and "
1224 "allocated mft record "
1225 "0x%llx.)",
1226 (long long)ll);
1227 return ll;
1228 }
1229 }
1230 ntfs_debug("After inner for loop: size 0x%x, "
1231 "data_pos 0x%llx, bit 0x%llx", size,
1232 (long long)data_pos, (long long)bit);
1233 data_pos += size;
1234 ntfs_unmap_page(page);
1235 /*
1236 * If the end of the pass has not been reached yet,
1237 * continue searching the mft bitmap for a zero bit.
1238 */
1239 if (data_pos < pass_end)
1240 continue;
1241 }
1242 /* Do the next pass. */
1243 if (++pass == 2) {
1244 /*
1245 * Starting the second pass, in which we scan the first
1246 * part of the zone which we omitted earlier.
1247 */
1248 pass_end = pass_start;
1249 data_pos = pass_start = 24;
1250 ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
1251 "0x%llx.", pass, (long long)pass_start,
1252 (long long)pass_end);
1253 if (data_pos >= pass_end)
1254 break;
1255 }
1256 }
1257 /* No free mft records in currently initialized mft bitmap. */
1258 ntfs_debug("Done. (No free mft records left in currently initialized "
1259 "mft bitmap.)");
1260 return -ENOSPC;
1261}
1262
1263/**
1264 * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
1265 * @vol: volume on which to extend the mft bitmap attribute
1266 *
1267 * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
1268 *
1269 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1270 * data_size.
1271 *
1272 * Return 0 on success and -errno on error.
1273 *
1274 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1275 * - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
1276 * writing and releases it before returning.
1277 * - This function takes vol->lcnbmp_lock for writing and releases it
1278 * before returning.
1279 */
1280static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
1281{
1282 LCN lcn;
1283 s64 ll;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001284 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001285 struct page *page;
1286 ntfs_inode *mft_ni, *mftbmp_ni;
1287 runlist_element *rl, *rl2 = NULL;
1288 ntfs_attr_search_ctx *ctx = NULL;
1289 MFT_RECORD *mrec;
1290 ATTR_RECORD *a = NULL;
1291 int ret, mp_size;
1292 u32 old_alen = 0;
1293 u8 *b, tb;
1294 struct {
1295 u8 added_cluster:1;
1296 u8 added_run:1;
1297 u8 mp_rebuilt:1;
1298 } status = { 0, 0, 0 };
1299
1300 ntfs_debug("Extending mft bitmap allocation.");
1301 mft_ni = NTFS_I(vol->mft_ino);
1302 mftbmp_ni = NTFS_I(vol->mftbmp_ino);
1303 /*
1304 * Determine the last lcn of the mft bitmap. The allocated size of the
1305 * mft bitmap cannot be zero so we are ok to do this.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001306 */
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001307 down_write(&mftbmp_ni->runlist.lock);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001308 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
1309 ll = mftbmp_ni->allocated_size;
1310 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
Anton Altaparmakovc0c1cc02005-03-07 21:43:38 +00001311 rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
Anton Altaparmakov69b41e32005-10-04 14:01:14 +01001312 (ll - 1) >> vol->cluster_size_bits, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001313 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001314 up_write(&mftbmp_ni->runlist.lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001315 ntfs_error(vol->sb, "Failed to determine last allocated "
1316 "cluster of mft bitmap attribute.");
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001317 if (!IS_ERR(rl))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001318 ret = -EIO;
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001319 else
Linus Torvalds1da177e2005-04-16 15:20:36 -07001320 ret = PTR_ERR(rl);
1321 return ret;
1322 }
1323 lcn = rl->lcn + rl->length;
1324 ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
1325 (long long)lcn);
1326 /*
1327 * Attempt to get the cluster following the last allocated cluster by
1328 * hand as it may be in the MFT zone so the allocator would not give it
1329 * to us.
1330 */
1331 ll = lcn >> 3;
1332 page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
1333 ll >> PAGE_CACHE_SHIFT);
1334 if (IS_ERR(page)) {
1335 up_write(&mftbmp_ni->runlist.lock);
1336 ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
1337 return PTR_ERR(page);
1338 }
1339 b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
1340 tb = 1 << (lcn & 7ull);
1341 down_write(&vol->lcnbmp_lock);
1342 if (*b != 0xff && !(*b & tb)) {
1343 /* Next cluster is free, allocate it. */
1344 *b |= tb;
1345 flush_dcache_page(page);
1346 set_page_dirty(page);
1347 up_write(&vol->lcnbmp_lock);
1348 ntfs_unmap_page(page);
1349 /* Update the mft bitmap runlist. */
1350 rl->length++;
1351 rl[1].vcn++;
1352 status.added_cluster = 1;
1353 ntfs_debug("Appending one cluster to mft bitmap.");
1354 } else {
1355 up_write(&vol->lcnbmp_lock);
1356 ntfs_unmap_page(page);
1357 /* Allocate a cluster from the DATA_ZONE. */
1358 rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE);
1359 if (IS_ERR(rl2)) {
1360 up_write(&mftbmp_ni->runlist.lock);
1361 ntfs_error(vol->sb, "Failed to allocate a cluster for "
1362 "the mft bitmap.");
1363 return PTR_ERR(rl2);
1364 }
1365 rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
1366 if (IS_ERR(rl)) {
1367 up_write(&mftbmp_ni->runlist.lock);
1368 ntfs_error(vol->sb, "Failed to merge runlists for mft "
1369 "bitmap.");
1370 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1371 ntfs_error(vol->sb, "Failed to dealocate "
1372 "allocated cluster.%s", es);
1373 NVolSetErrors(vol);
1374 }
1375 ntfs_free(rl2);
1376 return PTR_ERR(rl);
1377 }
1378 mftbmp_ni->runlist.rl = rl;
1379 status.added_run = 1;
1380 ntfs_debug("Adding one run to mft bitmap.");
1381 /* Find the last run in the new runlist. */
1382 for (; rl[1].length; rl++)
1383 ;
1384 }
1385 /*
1386 * Update the attribute record as well. Note: @rl is the last
1387 * (non-terminator) runlist element of mft bitmap.
1388 */
1389 mrec = map_mft_record(mft_ni);
1390 if (IS_ERR(mrec)) {
1391 ntfs_error(vol->sb, "Failed to map mft record.");
1392 ret = PTR_ERR(mrec);
1393 goto undo_alloc;
1394 }
1395 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1396 if (unlikely(!ctx)) {
1397 ntfs_error(vol->sb, "Failed to get search context.");
1398 ret = -ENOMEM;
1399 goto undo_alloc;
1400 }
1401 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1402 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1403 0, ctx);
1404 if (unlikely(ret)) {
1405 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1406 "mft bitmap attribute.");
1407 if (ret == -ENOENT)
1408 ret = -EIO;
1409 goto undo_alloc;
1410 }
1411 a = ctx->attr;
1412 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1413 /* Search back for the previous last allocated cluster of mft bitmap. */
1414 for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
1415 if (ll >= rl2->vcn)
1416 break;
1417 }
1418 BUG_ON(ll < rl2->vcn);
1419 BUG_ON(ll >= rl2->vcn + rl2->length);
1420 /* Get the size for the new mapping pairs array for this extent. */
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001421 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422 if (unlikely(mp_size <= 0)) {
1423 ntfs_error(vol->sb, "Get size for mapping pairs failed for "
1424 "mft bitmap attribute extent.");
1425 ret = mp_size;
1426 if (!ret)
1427 ret = -EIO;
1428 goto undo_alloc;
1429 }
1430 /* Expand the attribute record if necessary. */
1431 old_alen = le32_to_cpu(a->length);
1432 ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
1433 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
1434 if (unlikely(ret)) {
1435 if (ret != -ENOSPC) {
1436 ntfs_error(vol->sb, "Failed to resize attribute "
1437 "record for mft bitmap attribute.");
1438 goto undo_alloc;
1439 }
1440 // TODO: Deal with this by moving this extent to a new mft
1441 // record or by starting a new extent in a new mft record or by
1442 // moving other attributes out of this mft record.
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001443 // Note: It will need to be a special mft record and if none of
1444 // those are available it gets rather complicated...
Linus Torvalds1da177e2005-04-16 15:20:36 -07001445 ntfs_error(vol->sb, "Not enough space in this mft record to "
1446 "accomodate extended mft bitmap attribute "
1447 "extent. Cannot handle this yet.");
1448 ret = -EOPNOTSUPP;
1449 goto undo_alloc;
1450 }
1451 status.mp_rebuilt = 1;
1452 /* Generate the mapping pairs array directly into the attr record. */
1453 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1454 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001455 mp_size, rl2, ll, -1, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001456 if (unlikely(ret)) {
1457 ntfs_error(vol->sb, "Failed to build mapping pairs array for "
1458 "mft bitmap attribute.");
1459 goto undo_alloc;
1460 }
1461 /* Update the highest_vcn. */
1462 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1463 /*
1464 * We now have extended the mft bitmap allocated_size by one cluster.
1465 * Reflect this in the ntfs_inode structure and the attribute record.
1466 */
1467 if (a->data.non_resident.lowest_vcn) {
1468 /*
1469 * We are not in the first attribute extent, switch to it, but
1470 * first ensure the changes will make it to disk later.
1471 */
1472 flush_dcache_mft_record_page(ctx->ntfs_ino);
1473 mark_mft_record_dirty(ctx->ntfs_ino);
1474 ntfs_attr_reinit_search_ctx(ctx);
1475 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1476 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
1477 0, ctx);
1478 if (unlikely(ret)) {
1479 ntfs_error(vol->sb, "Failed to find first attribute "
1480 "extent of mft bitmap attribute.");
1481 goto restore_undo_alloc;
1482 }
1483 a = ctx->attr;
1484 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001485 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001486 mftbmp_ni->allocated_size += vol->cluster_size;
1487 a->data.non_resident.allocated_size =
1488 cpu_to_sle64(mftbmp_ni->allocated_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001489 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001490 /* Ensure the changes make it to disk. */
1491 flush_dcache_mft_record_page(ctx->ntfs_ino);
1492 mark_mft_record_dirty(ctx->ntfs_ino);
1493 ntfs_attr_put_search_ctx(ctx);
1494 unmap_mft_record(mft_ni);
1495 up_write(&mftbmp_ni->runlist.lock);
1496 ntfs_debug("Done.");
1497 return 0;
1498restore_undo_alloc:
1499 ntfs_attr_reinit_search_ctx(ctx);
1500 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1501 mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
1502 0, ctx)) {
1503 ntfs_error(vol->sb, "Failed to find last attribute extent of "
1504 "mft bitmap attribute.%s", es);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001505 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001506 mftbmp_ni->allocated_size += vol->cluster_size;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001507 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001508 ntfs_attr_put_search_ctx(ctx);
1509 unmap_mft_record(mft_ni);
1510 up_write(&mftbmp_ni->runlist.lock);
1511 /*
1512 * The only thing that is now wrong is ->allocated_size of the
1513 * base attribute extent which chkdsk should be able to fix.
1514 */
1515 NVolSetErrors(vol);
1516 return ret;
1517 }
1518 a = ctx->attr;
1519 a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
1520undo_alloc:
1521 if (status.added_cluster) {
1522 /* Truncate the last run in the runlist by one cluster. */
1523 rl->length--;
1524 rl[1].vcn--;
1525 } else if (status.added_run) {
1526 lcn = rl->lcn;
1527 /* Remove the last run from the runlist. */
1528 rl->lcn = rl[1].lcn;
1529 rl->length = 0;
1530 }
1531 /* Deallocate the cluster. */
1532 down_write(&vol->lcnbmp_lock);
1533 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1534 ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
1535 NVolSetErrors(vol);
1536 }
1537 up_write(&vol->lcnbmp_lock);
1538 if (status.mp_rebuilt) {
1539 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1540 a->data.non_resident.mapping_pairs_offset),
1541 old_alen - le16_to_cpu(
1542 a->data.non_resident.mapping_pairs_offset),
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001543 rl2, ll, -1, NULL)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001544 ntfs_error(vol->sb, "Failed to restore mapping pairs "
1545 "array.%s", es);
1546 NVolSetErrors(vol);
1547 }
1548 if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
1549 ntfs_error(vol->sb, "Failed to restore attribute "
1550 "record.%s", es);
1551 NVolSetErrors(vol);
1552 }
1553 flush_dcache_mft_record_page(ctx->ntfs_ino);
1554 mark_mft_record_dirty(ctx->ntfs_ino);
1555 }
1556 if (ctx)
1557 ntfs_attr_put_search_ctx(ctx);
1558 if (!IS_ERR(mrec))
1559 unmap_mft_record(mft_ni);
1560 up_write(&mftbmp_ni->runlist.lock);
1561 return ret;
1562}
1563
1564/**
1565 * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
1566 * @vol: volume on which to extend the mft bitmap attribute
1567 *
1568 * Extend the initialized portion of the mft bitmap attribute on the ntfs
1569 * volume @vol by 8 bytes.
1570 *
1571 * Note: Only changes initialized_size and data_size, i.e. requires that
1572 * allocated_size is big enough to fit the new initialized_size.
1573 *
1574 * Return 0 on success and -error on error.
1575 *
1576 * Locking: Caller must hold vol->mftbmp_lock for writing.
1577 */
1578static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
1579{
1580 s64 old_data_size, old_initialized_size;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001581 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001582 struct inode *mftbmp_vi;
1583 ntfs_inode *mft_ni, *mftbmp_ni;
1584 ntfs_attr_search_ctx *ctx;
1585 MFT_RECORD *mrec;
1586 ATTR_RECORD *a;
1587 int ret;
1588
1589 ntfs_debug("Extending mft bitmap initiailized (and data) size.");
1590 mft_ni = NTFS_I(vol->mft_ino);
1591 mftbmp_vi = vol->mftbmp_ino;
1592 mftbmp_ni = NTFS_I(mftbmp_vi);
1593 /* Get the attribute record. */
1594 mrec = map_mft_record(mft_ni);
1595 if (IS_ERR(mrec)) {
1596 ntfs_error(vol->sb, "Failed to map mft record.");
1597 return PTR_ERR(mrec);
1598 }
1599 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1600 if (unlikely(!ctx)) {
1601 ntfs_error(vol->sb, "Failed to get search context.");
1602 ret = -ENOMEM;
1603 goto unm_err_out;
1604 }
1605 ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1606 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
1607 if (unlikely(ret)) {
1608 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1609 "mft bitmap attribute.");
1610 if (ret == -ENOENT)
1611 ret = -EIO;
1612 goto put_err_out;
1613 }
1614 a = ctx->attr;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001615 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
1616 old_data_size = i_size_read(mftbmp_vi);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001617 old_initialized_size = mftbmp_ni->initialized_size;
1618 /*
1619 * We can simply update the initialized_size before filling the space
1620 * with zeroes because the caller is holding the mft bitmap lock for
1621 * writing which ensures that no one else is trying to access the data.
1622 */
1623 mftbmp_ni->initialized_size += 8;
1624 a->data.non_resident.initialized_size =
1625 cpu_to_sle64(mftbmp_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001626 if (mftbmp_ni->initialized_size > old_data_size) {
1627 i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001628 a->data.non_resident.data_size =
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001629 cpu_to_sle64(mftbmp_ni->initialized_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001631 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 /* Ensure the changes make it to disk. */
1633 flush_dcache_mft_record_page(ctx->ntfs_ino);
1634 mark_mft_record_dirty(ctx->ntfs_ino);
1635 ntfs_attr_put_search_ctx(ctx);
1636 unmap_mft_record(mft_ni);
1637 /* Initialize the mft bitmap attribute value with zeroes. */
1638 ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
1639 if (likely(!ret)) {
1640 ntfs_debug("Done. (Wrote eight initialized bytes to mft "
1641 "bitmap.");
1642 return 0;
1643 }
1644 ntfs_error(vol->sb, "Failed to write to mft bitmap.");
1645 /* Try to recover from the error. */
1646 mrec = map_mft_record(mft_ni);
1647 if (IS_ERR(mrec)) {
1648 ntfs_error(vol->sb, "Failed to map mft record.%s", es);
1649 NVolSetErrors(vol);
1650 return ret;
1651 }
1652 ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
1653 if (unlikely(!ctx)) {
1654 ntfs_error(vol->sb, "Failed to get search context.%s", es);
1655 NVolSetErrors(vol);
1656 goto unm_err_out;
1657 }
1658 if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
1659 mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1660 ntfs_error(vol->sb, "Failed to find first attribute extent of "
1661 "mft bitmap attribute.%s", es);
1662 NVolSetErrors(vol);
1663put_err_out:
1664 ntfs_attr_put_search_ctx(ctx);
1665unm_err_out:
1666 unmap_mft_record(mft_ni);
1667 goto err_out;
1668 }
1669 a = ctx->attr;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001670 write_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671 mftbmp_ni->initialized_size = old_initialized_size;
1672 a->data.non_resident.initialized_size =
1673 cpu_to_sle64(old_initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001674 if (i_size_read(mftbmp_vi) != old_data_size) {
1675 i_size_write(mftbmp_vi, old_data_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001676 a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
1677 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001678 write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001679 flush_dcache_mft_record_page(ctx->ntfs_ino);
1680 mark_mft_record_dirty(ctx->ntfs_ino);
1681 ntfs_attr_put_search_ctx(ctx);
1682 unmap_mft_record(mft_ni);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001683#ifdef DEBUG
1684 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
1686 "data_size 0x%llx, initialized_size 0x%llx.",
1687 (long long)mftbmp_ni->allocated_size,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001688 (long long)i_size_read(mftbmp_vi),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001689 (long long)mftbmp_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001690 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
1691#endif /* DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001692err_out:
1693 return ret;
1694}
1695
1696/**
1697 * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
1698 * @vol: volume on which to extend the mft data attribute
1699 *
1700 * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
1701 * worth of clusters or if not enough space for this by one mft record worth
1702 * of clusters.
1703 *
1704 * Note: Only changes allocated_size, i.e. does not touch initialized_size or
1705 * data_size.
1706 *
1707 * Return 0 on success and -errno on error.
1708 *
1709 * Locking: - Caller must hold vol->mftbmp_lock for writing.
1710 * - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
1711 * writing and releases it before returning.
1712 * - This function calls functions which take vol->lcnbmp_lock for
1713 * writing and release it before returning.
1714 */
1715static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
1716{
1717 LCN lcn;
1718 VCN old_last_vcn;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001719 s64 min_nr, nr, ll;
1720 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001721 ntfs_inode *mft_ni;
1722 runlist_element *rl, *rl2;
1723 ntfs_attr_search_ctx *ctx = NULL;
1724 MFT_RECORD *mrec;
1725 ATTR_RECORD *a = NULL;
1726 int ret, mp_size;
1727 u32 old_alen = 0;
1728 BOOL mp_rebuilt = FALSE;
1729
1730 ntfs_debug("Extending mft data allocation.");
1731 mft_ni = NTFS_I(vol->mft_ino);
1732 /*
1733 * Determine the preferred allocation location, i.e. the last lcn of
1734 * the mft data attribute. The allocated size of the mft data
1735 * attribute cannot be zero so we are ok to do this.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736 */
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001737 down_write(&mft_ni->runlist.lock);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001738 read_lock_irqsave(&mft_ni->size_lock, flags);
1739 ll = mft_ni->allocated_size;
1740 read_unlock_irqrestore(&mft_ni->size_lock, flags);
Anton Altaparmakovc0c1cc02005-03-07 21:43:38 +00001741 rl = ntfs_attr_find_vcn_nolock(mft_ni,
Anton Altaparmakov69b41e32005-10-04 14:01:14 +01001742 (ll - 1) >> vol->cluster_size_bits, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001743 if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001744 up_write(&mft_ni->runlist.lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001745 ntfs_error(vol->sb, "Failed to determine last allocated "
1746 "cluster of mft data attribute.");
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001747 if (!IS_ERR(rl))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001748 ret = -EIO;
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001749 else
Linus Torvalds1da177e2005-04-16 15:20:36 -07001750 ret = PTR_ERR(rl);
1751 return ret;
1752 }
1753 lcn = rl->lcn + rl->length;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001754 ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001755 /* Minimum allocation is one mft record worth of clusters. */
1756 min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1757 if (!min_nr)
1758 min_nr = 1;
1759 /* Want to allocate 16 mft records worth of clusters. */
1760 nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1761 if (!nr)
1762 nr = min_nr;
1763 /* Ensure we do not go above 2^32-1 mft records. */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001764 read_lock_irqsave(&mft_ni->size_lock, flags);
1765 ll = mft_ni->allocated_size;
1766 read_unlock_irqrestore(&mft_ni->size_lock, flags);
1767 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
Linus Torvalds1da177e2005-04-16 15:20:36 -07001768 vol->mft_record_size_bits >= (1ll << 32))) {
1769 nr = min_nr;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001770 if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
Linus Torvalds1da177e2005-04-16 15:20:36 -07001771 vol->mft_record_size_bits >= (1ll << 32))) {
1772 ntfs_warning(vol->sb, "Cannot allocate mft record "
1773 "because the maximum number of inodes "
1774 "(2^32) has already been reached.");
1775 up_write(&mft_ni->runlist.lock);
1776 return -ENOSPC;
1777 }
1778 }
1779 ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
1780 nr > min_nr ? "default" : "minimal", (long long)nr);
1781 old_last_vcn = rl[1].vcn;
1782 do {
1783 rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1784 if (likely(!IS_ERR(rl2)))
1785 break;
1786 if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
1787 ntfs_error(vol->sb, "Failed to allocate the minimal "
1788 "number of clusters (%lli) for the "
1789 "mft data attribute.", (long long)nr);
1790 up_write(&mft_ni->runlist.lock);
1791 return PTR_ERR(rl2);
1792 }
1793 /*
1794 * There is not enough space to do the allocation, but there
1795 * might be enough space to do a minimal allocation so try that
1796 * before failing.
1797 */
1798 nr = min_nr;
1799 ntfs_debug("Retrying mft data allocation with minimal cluster "
1800 "count %lli.", (long long)nr);
1801 } while (1);
1802 rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
1803 if (IS_ERR(rl)) {
1804 up_write(&mft_ni->runlist.lock);
1805 ntfs_error(vol->sb, "Failed to merge runlists for mft data "
1806 "attribute.");
1807 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1808 ntfs_error(vol->sb, "Failed to dealocate clusters "
1809 "from the mft data attribute.%s", es);
1810 NVolSetErrors(vol);
1811 }
1812 ntfs_free(rl2);
1813 return PTR_ERR(rl);
1814 }
1815 mft_ni->runlist.rl = rl;
Randy Dunlap89075472005-03-03 11:19:53 +00001816 ntfs_debug("Allocated %lli clusters.", (long long)nr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001817 /* 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. */
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001852 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001853 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
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00001876 // 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...
Linus Torvalds1da177e2005-04-16 15:20:36 -07001881 ntfs_error(vol->sb, "Not enough space in this mft record to "
1882 "accomodate extended mft data attribute "
1883 "extent. Cannot handle this yet.");
1884 ret = -EOPNOTSUPP;
1885 goto undo_alloc;
1886 }
1887 mp_rebuilt = TRUE;
1888 /* Generate the mapping pairs array directly into the attr record. */
1889 ret = ntfs_mapping_pairs_build(vol, (u8*)a +
1890 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001891 mp_size, rl2, ll, -1, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001892 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 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001923 write_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001924 mft_ni->allocated_size += nr << vol->cluster_size_bits;
1925 a->data.non_resident.allocated_size =
1926 cpu_to_sle64(mft_ni->allocated_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001927 write_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001928 /* 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);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001942 write_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001943 mft_ni->allocated_size += nr << vol->cluster_size_bits;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00001944 write_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001945 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 }
Anton Altaparmakov511bea52005-10-04 14:24:21 +01001955 ctx->attr->data.non_resident.highest_vcn =
1956 cpu_to_sle64(old_last_vcn - 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001957undo_alloc:
Anton Altaparmakov511bea52005-10-04 14:24:21 +01001958 if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001959 ntfs_error(vol->sb, "Failed to free clusters from mft data "
1960 "attribute.%s", es);
1961 NVolSetErrors(vol);
1962 }
Anton Altaparmakov511bea52005-10-04 14:24:21 +01001963 a = ctx->attr;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001964 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 }
Anton Altaparmakov511bea52005-10-04 14:24:21 +01001969 if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001970 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),
Anton Altaparmakovfa3be9232005-06-25 17:15:36 +01001974 rl2, ll, -1, NULL)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001975 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);
Anton Altaparmakov511bea52005-10-04 14:24:21 +01001986 } else if (IS_ERR(ctx->mrec)) {
1987 ntfs_error(vol->sb, "Failed to restore attribute search "
1988 "context.%s", es);
1989 NVolSetErrors(vol);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001990 }
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 "
Anton Altaparmakovb6ad6c52005-02-15 10:08:43 +00002048 "modified filesystem created was corrupt. "
Linus Torvalds1da177e2005-04-16 15:20:36 -07002049 "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{
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002093 loff_t i_size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002094 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. */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002109 i_size = i_size_read(mft_vi);
2110 end_index = i_size >> PAGE_CACHE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002111 if (unlikely(index >= end_index)) {
2112 if (unlikely(index > end_index || ofs + vol->mft_record_size >=
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002113 (i_size & ~PAGE_CACHE_MASK))) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002114 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 (unlikely(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;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002247 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002248 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 */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002297 read_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002298 ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002299 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) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002304 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 */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002318 bit = old_data_initialized << 3;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002319 if (unlikely(bit >= (1ll << 32)))
2320 goto max_err_out;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002321 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
2322 old_data_size = mftbmp_ni->allocated_size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002323 ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
2324 "data_size 0x%llx, initialized_size 0x%llx.",
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002325 (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) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002330 /* 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 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002337#ifdef DEBUG
2338 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002339 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,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002343 (long long)i_size_read(vol->mftbmp_ino),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002344 (long long)mftbmp_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002345 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2346#endif /* DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002347 }
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 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002358#ifdef DEBUG
2359 read_lock_irqsave(&mftbmp_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002360 ntfs_debug("Status of mftbmp after initialized extention: "
2361 "allocated_size 0x%llx, data_size 0x%llx, "
2362 "initialized_size 0x%llx.",
2363 (long long)mftbmp_ni->allocated_size,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002364 (long long)i_size_read(vol->mftbmp_ino),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002365 (long long)mftbmp_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002366 read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
2367#endif /* DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002368 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;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002389 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) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002393 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 */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002403 read_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 ntfs_debug("Status of mft data before extension: "
2405 "allocated_size 0x%llx, data_size 0x%llx, "
2406 "initialized_size 0x%llx.",
Anton Altaparmakov3834c3f2005-01-13 11:04:39 +00002407 (long long)mft_ni->allocated_size,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002408 (long long)i_size_read(vol->mft_ino),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002409 (long long)mft_ni->initialized_size);
Anton Altaparmakov3834c3f2005-01-13 11:04:39 +00002410 while (ll > mft_ni->allocated_size) {
2411 read_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002412 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 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002418 read_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002419 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,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002423 (long long)i_size_read(vol->mft_ino),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002424 (long long)mft_ni->initialized_size);
2425 }
Anton Altaparmakov3834c3f2005-01-13 11:04:39 +00002426 read_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002427 /*
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 */
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002434 write_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002435 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;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002443 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);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 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 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002453 write_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002454 mft_ni->initialized_size = new_initialized_size;
2455 }
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002456 write_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002457 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;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002482 read_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002483 a->data.non_resident.initialized_size =
2484 cpu_to_sle64(mft_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002485 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);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002488 /* 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);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002493 read_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002494 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,
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002498 (long long)i_size_read(vol->mft_ino),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002499 (long long)mft_ni->initialized_size);
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002500 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);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002503mft_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 (unlikely(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 /*
2580 * Setup the base mft record in the extent mft record. This
2581 * completes initialization of the allocated extent mft record
2582 * and we can simply use it with map_extent_mft_record().
2583 */
2584 m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
2585 base_ni->seq_no);
2586 /*
2587 * Allocate an extent inode structure for the new mft record,
2588 * attach it to the base inode @base_ni and map, pin, and lock
2589 * its, i.e. the allocated, mft record.
2590 */
2591 m = map_extent_mft_record(base_ni, bit, &ni);
2592 if (IS_ERR(m)) {
2593 ntfs_error(vol->sb, "Failed to map allocated extent "
2594 "mft record 0x%llx.", (long long)bit);
2595 err = PTR_ERR(m);
2596 /* Set the mft record itself not in use. */
2597 m->flags &= cpu_to_le16(
2598 ~le16_to_cpu(MFT_RECORD_IN_USE));
2599 flush_dcache_page(page);
2600 /* Make sure the mft record is written out to disk. */
2601 mark_ntfs_record_dirty(page, ofs);
2602 unlock_page(page);
2603 ntfs_unmap_page(page);
2604 goto undo_mftbmp_alloc;
2605 }
2606 /*
2607 * Make sure the allocated mft record is written out to disk.
2608 * No need to set the inode dirty because the caller is going
2609 * to do that anyway after finishing with the new extent mft
2610 * record (e.g. at a minimum a new attribute will be added to
2611 * the mft record.
2612 */
2613 mark_ntfs_record_dirty(page, ofs);
2614 unlock_page(page);
2615 /*
2616 * Need to unmap the page since map_extent_mft_record() mapped
2617 * it as well so we have it mapped twice at the moment.
2618 */
2619 ntfs_unmap_page(page);
2620 } else {
2621 /*
2622 * Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
2623 * is set to 1 but the mft record->link_count is 0. The caller
2624 * needs to bear this in mind.
2625 */
2626 vi = new_inode(vol->sb);
2627 if (unlikely(!vi)) {
2628 err = -ENOMEM;
2629 /* Set the mft record itself not in use. */
2630 m->flags &= cpu_to_le16(
2631 ~le16_to_cpu(MFT_RECORD_IN_USE));
2632 flush_dcache_page(page);
2633 /* Make sure the mft record is written out to disk. */
2634 mark_ntfs_record_dirty(page, ofs);
2635 unlock_page(page);
2636 ntfs_unmap_page(page);
2637 goto undo_mftbmp_alloc;
2638 }
2639 vi->i_ino = bit;
2640 /*
2641 * This is the optimal IO size (for stat), not the fs block
2642 * size.
2643 */
2644 vi->i_blksize = PAGE_CACHE_SIZE;
2645 /*
2646 * This is for checking whether an inode has changed w.r.t. a
2647 * file so that the file can be updated if necessary (compare
2648 * with f_version).
2649 */
2650 vi->i_version = 1;
2651
2652 /* The owner and group come from the ntfs volume. */
2653 vi->i_uid = vol->uid;
2654 vi->i_gid = vol->gid;
2655
2656 /* Initialize the ntfs specific part of @vi. */
2657 ntfs_init_big_inode(vi);
2658 ni = NTFS_I(vi);
2659 /*
2660 * Set the appropriate mode, attribute type, and name. For
2661 * directories, also setup the index values to the defaults.
2662 */
2663 if (S_ISDIR(mode)) {
2664 vi->i_mode = S_IFDIR | S_IRWXUGO;
2665 vi->i_mode &= ~vol->dmask;
2666
2667 NInoSetMstProtected(ni);
2668 ni->type = AT_INDEX_ALLOCATION;
2669 ni->name = I30;
2670 ni->name_len = 4;
2671
2672 ni->itype.index.block_size = 4096;
2673 ni->itype.index.block_size_bits = generic_ffs(4096) - 1;
2674 ni->itype.index.collation_rule = COLLATION_FILE_NAME;
2675 if (vol->cluster_size <= ni->itype.index.block_size) {
2676 ni->itype.index.vcn_size = vol->cluster_size;
2677 ni->itype.index.vcn_size_bits =
2678 vol->cluster_size_bits;
2679 } else {
2680 ni->itype.index.vcn_size = vol->sector_size;
2681 ni->itype.index.vcn_size_bits =
2682 vol->sector_size_bits;
2683 }
2684 } else {
2685 vi->i_mode = S_IFREG | S_IRWXUGO;
2686 vi->i_mode &= ~vol->fmask;
2687
2688 ni->type = AT_DATA;
2689 ni->name = NULL;
2690 ni->name_len = 0;
2691 }
2692 if (IS_RDONLY(vi))
2693 vi->i_mode &= ~S_IWUGO;
2694
2695 /* Set the inode times to the current time. */
2696 vi->i_atime = vi->i_mtime = vi->i_ctime =
2697 current_fs_time(vi->i_sb);
2698 /*
2699 * Set the file size to 0, the ntfs inode sizes are set to 0 by
2700 * the call to ntfs_init_big_inode() below.
2701 */
2702 vi->i_size = 0;
2703 vi->i_blocks = 0;
2704
2705 /* Set the sequence number. */
2706 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
2707 /*
2708 * Manually map, pin, and lock the mft record as we already
2709 * have its page mapped and it is very easy to do.
2710 */
2711 atomic_inc(&ni->count);
2712 down(&ni->mrec_lock);
2713 ni->page = page;
2714 ni->page_ofs = ofs;
2715 /*
2716 * Make sure the allocated mft record is written out to disk.
2717 * NOTE: We do not set the ntfs inode dirty because this would
2718 * fail in ntfs_write_inode() because the inode does not have a
2719 * standard information attribute yet. Also, there is no need
2720 * to set the inode dirty because the caller is going to do
2721 * that anyway after finishing with the new mft record (e.g. at
2722 * a minimum some new attributes will be added to the mft
2723 * record.
2724 */
2725 mark_ntfs_record_dirty(page, ofs);
2726 unlock_page(page);
2727
2728 /* Add the inode to the inode hash for the superblock. */
2729 insert_inode_hash(vi);
2730
2731 /* Update the default mft allocation position. */
2732 vol->mft_data_pos = bit + 1;
2733 }
2734 /*
2735 * Return the opened, allocated inode of the allocated mft record as
2736 * well as the mapped, pinned, and locked mft record.
2737 */
2738 ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
2739 base_ni ? "extent " : "", (long long)bit);
2740 *mrec = m;
2741 return ni;
2742undo_data_init:
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002743 write_lock_irqsave(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002744 mft_ni->initialized_size = old_data_initialized;
Anton Altaparmakov07a4e2d2005-01-12 13:08:26 +00002745 i_size_write(vol->mft_ino, old_data_size);
2746 write_unlock_irqrestore(&mft_ni->size_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002747 goto undo_mftbmp_alloc_nolock;
2748undo_mftbmp_alloc:
2749 down_write(&vol->mftbmp_lock);
2750undo_mftbmp_alloc_nolock:
2751 if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
2752 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2753 NVolSetErrors(vol);
2754 }
2755 up_write(&vol->mftbmp_lock);
2756err_out:
2757 return ERR_PTR(err);
2758max_err_out:
2759 ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
2760 "number of inodes (2^32) has already been reached.");
2761 up_write(&vol->mftbmp_lock);
2762 return ERR_PTR(-ENOSPC);
2763}
2764
2765/**
2766 * ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
2767 * @ni: ntfs inode of the mapped extent mft record to free
2768 * @m: mapped extent mft record of the ntfs inode @ni
2769 *
2770 * Free the mapped extent mft record @m of the extent ntfs inode @ni.
2771 *
2772 * Note that this function unmaps the mft record and closes and destroys @ni
2773 * internally and hence you cannot use either @ni nor @m any more after this
2774 * function returns success.
2775 *
2776 * On success return 0 and on error return -errno. @ni and @m are still valid
2777 * in this case and have not been freed.
2778 *
2779 * For some errors an error message is displayed and the success code 0 is
2780 * returned and the volume is then left dirty on umount. This makes sense in
2781 * case we could not rollback the changes that were already done since the
2782 * caller no longer wants to reference this mft record so it does not matter to
2783 * the caller if something is wrong with it as long as it is properly detached
2784 * from the base inode.
2785 */
2786int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
2787{
2788 unsigned long mft_no = ni->mft_no;
2789 ntfs_volume *vol = ni->vol;
2790 ntfs_inode *base_ni;
2791 ntfs_inode **extent_nis;
2792 int i, err;
2793 le16 old_seq_no;
2794 u16 seq_no;
2795
2796 BUG_ON(NInoAttr(ni));
2797 BUG_ON(ni->nr_extents != -1);
2798
2799 down(&ni->extent_lock);
2800 base_ni = ni->ext.base_ntfs_ino;
2801 up(&ni->extent_lock);
2802
2803 BUG_ON(base_ni->nr_extents <= 0);
2804
2805 ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
2806 mft_no, base_ni->mft_no);
2807
2808 down(&base_ni->extent_lock);
2809
2810 /* Make sure we are holding the only reference to the extent inode. */
2811 if (atomic_read(&ni->count) > 2) {
2812 ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
2813 "not freeing.", base_ni->mft_no);
2814 up(&base_ni->extent_lock);
2815 return -EBUSY;
2816 }
2817
2818 /* Dissociate the ntfs inode from the base inode. */
2819 extent_nis = base_ni->ext.extent_ntfs_inos;
2820 err = -ENOENT;
2821 for (i = 0; i < base_ni->nr_extents; i++) {
2822 if (ni != extent_nis[i])
2823 continue;
2824 extent_nis += i;
2825 base_ni->nr_extents--;
2826 memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
2827 sizeof(ntfs_inode*));
2828 err = 0;
2829 break;
2830 }
2831
2832 up(&base_ni->extent_lock);
2833
2834 if (unlikely(err)) {
2835 ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
2836 "its base inode 0x%lx.", mft_no,
2837 base_ni->mft_no);
2838 BUG();
2839 }
2840
2841 /*
2842 * The extent inode is no longer attached to the base inode so no one
2843 * can get a reference to it any more.
2844 */
2845
2846 /* Mark the mft record as not in use. */
2847 m->flags &= const_cpu_to_le16(~const_le16_to_cpu(MFT_RECORD_IN_USE));
2848
2849 /* Increment the sequence number, skipping zero, if it is not zero. */
2850 old_seq_no = m->sequence_number;
2851 seq_no = le16_to_cpu(old_seq_no);
2852 if (seq_no == 0xffff)
2853 seq_no = 1;
2854 else if (seq_no)
2855 seq_no++;
2856 m->sequence_number = cpu_to_le16(seq_no);
2857
2858 /*
2859 * Set the ntfs inode dirty and write it out. We do not need to worry
2860 * about the base inode here since whatever caused the extent mft
2861 * record to be freed is guaranteed to do it already.
2862 */
2863 NInoSetDirty(ni);
2864 err = write_mft_record(ni, m, 0);
2865 if (unlikely(err)) {
2866 ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
2867 "freeing.", mft_no);
2868 goto rollback;
2869 }
2870rollback_error:
2871 /* Unmap and throw away the now freed extent inode. */
2872 unmap_extent_mft_record(ni);
2873 ntfs_clear_extent_inode(ni);
2874
2875 /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
2876 down_write(&vol->mftbmp_lock);
2877 err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
2878 up_write(&vol->mftbmp_lock);
2879 if (unlikely(err)) {
2880 /*
2881 * The extent inode is gone but we failed to deallocate it in
2882 * the mft bitmap. Just emit a warning and leave the volume
2883 * dirty on umount.
2884 */
2885 ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
2886 NVolSetErrors(vol);
2887 }
2888 return 0;
2889rollback:
2890 /* Rollback what we did... */
2891 down(&base_ni->extent_lock);
2892 extent_nis = base_ni->ext.extent_ntfs_inos;
2893 if (!(base_ni->nr_extents & 3)) {
2894 int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
2895
2896 extent_nis = (ntfs_inode**)kmalloc(new_size, GFP_NOFS);
2897 if (unlikely(!extent_nis)) {
2898 ntfs_error(vol->sb, "Failed to allocate internal "
2899 "buffer during rollback.%s", es);
2900 up(&base_ni->extent_lock);
2901 NVolSetErrors(vol);
2902 goto rollback_error;
2903 }
2904 if (base_ni->nr_extents) {
2905 BUG_ON(!base_ni->ext.extent_ntfs_inos);
2906 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2907 new_size - 4 * sizeof(ntfs_inode*));
2908 kfree(base_ni->ext.extent_ntfs_inos);
2909 }
2910 base_ni->ext.extent_ntfs_inos = extent_nis;
2911 }
2912 m->flags |= MFT_RECORD_IN_USE;
2913 m->sequence_number = old_seq_no;
2914 extent_nis[base_ni->nr_extents++] = ni;
2915 up(&base_ni->extent_lock);
2916 mark_mft_record_dirty(ni);
2917 return err;
2918}
2919#endif /* NTFS_RW */