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