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