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