xref: /haiku/src/add-ons/kernel/file_systems/ntfs/libntfs/mft.c (revision 1e60bdeab63fa7a57bc9a55b032052e95a18bd2c)
1 /**
2  * mft.c - Mft record handling code. Originated from the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2004 Anton Altaparmakov
5  * Copyright (c) 2004-2005 Richard Russon
6  * Copyright (c) 2004-2008 Szabolcs Szakacsits
7  * Copyright (c)      2005 Yura Pakhuchiy
8  * Copyright (c) 2014-2015 Jean-Pierre Andre
9  *
10  * This program/include file is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as published
12  * by the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program/include file is distributed in the hope that it will be
16  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program (in the main directory of the NTFS-3G
22  * distribution in the file COPYING); if not, write to the Free Software
23  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29 
30 #ifdef HAVE_STDLIB_H
31 #include <stdlib.h>
32 #endif
33 #ifdef HAVE_STDIO_H
34 #include <stdio.h>
35 #endif
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42 #ifdef HAVE_LIMITS_H
43 #include <limits.h>
44 #endif
45 #include <time.h>
46 
47 #include "compat.h"
48 #include "types.h"
49 #include "device.h"
50 #include "debug.h"
51 #include "bitmap.h"
52 #include "attrib.h"
53 #include "inode.h"
54 #include "volume.h"
55 #include "layout.h"
56 #include "lcnalloc.h"
57 #include "mft.h"
58 #include "logging.h"
59 #include "misc.h"
60 
61 /**
62  * ntfs_mft_records_read - read records from the mft from disk
63  * @vol:	volume to read from
64  * @mref:	starting mft record number to read
65  * @count:	number of mft records to read
66  * @b:		output data buffer
67  *
68  * Read @count mft records starting at @mref from volume @vol into buffer
69  * @b. Return 0 on success or -1 on error, with errno set to the error
70  * code.
71  *
72  * If any of the records exceed the initialized size of the $MFT/$DATA
73  * attribute, i.e. they cannot possibly be allocated mft records, assume this
74  * is a bug and return error code ESPIPE.
75  *
76  * The read mft records are mst deprotected and are hence ready to use. The
77  * caller should check each record with is_baad_record() in case mst
78  * deprotection failed.
79  *
80  * NOTE: @b has to be at least of size @count * vol->mft_record_size.
81  */
82 int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref,
83 		const s64 count, MFT_RECORD *b)
84 {
85 	s64 br;
86 	VCN m;
87 
88 	ntfs_log_trace("inode %llu\n", (unsigned long long)MREF(mref));
89 
90 	if (!vol || !vol->mft_na || !b || count < 0) {
91 		errno = EINVAL;
92 		ntfs_log_perror("%s: b=%p  count=%lld  mft=%llu", __FUNCTION__,
93 			b, (long long)count, (unsigned long long)MREF(mref));
94 		return -1;
95 	}
96 	m = MREF(mref);
97 	/* Refuse to read non-allocated mft records. */
98 	if (m + count > vol->mft_na->initialized_size >>
99 			vol->mft_record_size_bits) {
100 		errno = ESPIPE;
101 		ntfs_log_perror("Trying to read non-allocated mft records "
102 				"(%lld > %lld)", (long long)m + count,
103 				(long long)vol->mft_na->initialized_size >>
104 				vol->mft_record_size_bits);
105 		return -1;
106 	}
107 	br = ntfs_attr_mst_pread(vol->mft_na, m << vol->mft_record_size_bits,
108 			count, vol->mft_record_size, b);
109 	if (br != count) {
110 		if (br != -1)
111 			errno = EIO;
112 		ntfs_log_perror("Failed to read of MFT, mft=%llu count=%lld "
113 				"br=%lld", (long long)m, (long long)count,
114 				(long long)br);
115 		return -1;
116 	}
117 	return 0;
118 }
119 
120 /**
121  * ntfs_mft_records_write - write mft records to disk
122  * @vol:	volume to write to
123  * @mref:	starting mft record number to write
124  * @count:	number of mft records to write
125  * @b:		data buffer containing the mft records to write
126  *
127  * Write @count mft records starting at @mref from data buffer @b to volume
128  * @vol. Return 0 on success or -1 on error, with errno set to the error code.
129  *
130  * If any of the records exceed the initialized size of the $MFT/$DATA
131  * attribute, i.e. they cannot possibly be allocated mft records, assume this
132  * is a bug and return error code ESPIPE.
133  *
134  * Before the mft records are written, they are mst protected. After the write,
135  * they are deprotected again, thus resulting in an increase in the update
136  * sequence number inside the data buffer @b.
137  *
138  * If any mft records are written which are also represented in the mft mirror
139  * $MFTMirr, we make a copy of the relevant parts of the data buffer @b into a
140  * temporary buffer before we do the actual write. Then if at least one mft
141  * record was successfully written, we write the appropriate mft records from
142  * the copied buffer to the mft mirror, too.
143  */
144 int ntfs_mft_records_write(const ntfs_volume *vol, const MFT_REF mref,
145 		const s64 count, MFT_RECORD *b)
146 {
147 	s64 bw;
148 	VCN m;
149 	void *bmirr = NULL;
150 	int cnt = 0, res = 0;
151 
152 	if (!vol || !vol->mft_na || vol->mftmirr_size <= 0 || !b || count < 0) {
153 		errno = EINVAL;
154 		return -1;
155 	}
156 	m = MREF(mref);
157 	/* Refuse to write non-allocated mft records. */
158 	if (m + count > vol->mft_na->initialized_size >>
159 			vol->mft_record_size_bits) {
160 		errno = ESPIPE;
161 		ntfs_log_perror("Trying to write non-allocated mft records "
162 				"(%lld > %lld)", (long long)m + count,
163 				(long long)vol->mft_na->initialized_size >>
164 				vol->mft_record_size_bits);
165 		return -1;
166 	}
167 	if (m < vol->mftmirr_size) {
168 		if (!vol->mftmirr_na) {
169 			errno = EINVAL;
170 			return -1;
171 		}
172 		cnt = vol->mftmirr_size - m;
173 		if (cnt > count)
174 			cnt = count;
175 		bmirr = ntfs_malloc(cnt * vol->mft_record_size);
176 		if (!bmirr)
177 			return -1;
178 		memcpy(bmirr, b, cnt * vol->mft_record_size);
179 	}
180 	bw = ntfs_attr_mst_pwrite(vol->mft_na, m << vol->mft_record_size_bits,
181 			count, vol->mft_record_size, b);
182 	if (bw != count) {
183 		if (bw != -1)
184 			errno = EIO;
185 		if (bw >= 0)
186 			ntfs_log_debug("Error: partial write while writing $Mft "
187 					"record(s)!\n");
188 		else
189 			ntfs_log_perror("Error writing $Mft record(s)");
190 		res = errno;
191 	}
192 	if (bmirr && bw > 0) {
193 		if (bw < cnt)
194 			cnt = bw;
195 		bw = ntfs_attr_mst_pwrite(vol->mftmirr_na,
196 				m << vol->mft_record_size_bits, cnt,
197 				vol->mft_record_size, bmirr);
198 		if (bw != cnt) {
199 			if (bw != -1)
200 				errno = EIO;
201 			ntfs_log_debug("Error: failed to sync $MFTMirr! Run "
202 					"chkdsk.\n");
203 			res = errno;
204 		}
205 	}
206 	free(bmirr);
207 	if (!res)
208 		return res;
209 	errno = res;
210 	return -1;
211 }
212 
213 int ntfs_mft_record_check(const ntfs_volume *vol, const MFT_REF mref,
214 			  MFT_RECORD *m)
215 {
216 	ATTR_RECORD *a;
217 	int ret = -1;
218 
219 	if (!ntfs_is_file_record(m->magic)) {
220 		if (!NVolNoFixupWarn(vol))
221 			ntfs_log_error("Record %llu has no FILE magic (0x%x)\n",
222 				(unsigned long long)MREF(mref),
223 				(int)le32_to_cpu(*(le32*)m));
224 		goto err_out;
225 	}
226 
227 	if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) {
228 		ntfs_log_error("Record %llu has corrupt allocation size "
229 			       "(%u <> %u)\n", (unsigned long long)MREF(mref),
230 			       vol->mft_record_size,
231 			       le32_to_cpu(m->bytes_allocated));
232 		goto err_out;
233 	}
234 
235 	a = (ATTR_RECORD *)((char *)m + le16_to_cpu(m->attrs_offset));
236 	if (p2n(a) < p2n(m) || (char *)a > (char *)m + vol->mft_record_size) {
237 		ntfs_log_error("Record %llu is corrupt\n",
238 			       (unsigned long long)MREF(mref));
239 		goto err_out;
240 	}
241 
242 	ret = 0;
243 err_out:
244 	if (ret)
245 		errno = EIO;
246 	return ret;
247 }
248 
249 /**
250  * ntfs_file_record_read - read a FILE record from the mft from disk
251  * @vol:	volume to read from
252  * @mref:	mft reference specifying mft record to read
253  * @mrec:	address of pointer in which to return the mft record
254  * @attr:	address of pointer in which to return the first attribute
255  *
256  * Read a FILE record from the mft of @vol from the storage medium. @mref
257  * specifies the mft record to read, including the sequence number, which can
258  * be 0 if no sequence number checking is to be performed.
259  *
260  * The function allocates a buffer large enough to hold the mft record and
261  * reads the record into the buffer (mst deprotecting it in the process).
262  * *@mrec is then set to point to the buffer.
263  *
264  * If @attr is not NULL, *@attr is set to point to the first attribute in the
265  * mft record, i.e. *@attr is a pointer into *@mrec.
266  *
267  * Return 0 on success, or -1 on error, with errno set to the error code.
268  *
269  * The read mft record is checked for having the magic FILE,
270  * and for having a matching sequence number (if MSEQNO(*@mref) != 0).
271  * If either of these fails, -1 is returned and errno is set to EIO. If you get
272  * this, but you still want to read the mft record (e.g. in order to correct
273  * it), use ntfs_mft_record_read() directly.
274  *
275  * Note: Caller has to free *@mrec when finished.
276  *
277  * Note: We do not check if the mft record is flagged in use. The caller can
278  *	 check if desired.
279  */
280 int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref,
281 		MFT_RECORD **mrec, ATTR_RECORD **attr)
282 {
283 	MFT_RECORD *m;
284 
285 	if (!vol || !mrec) {
286 		errno = EINVAL;
287 		ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec);
288 		return -1;
289 	}
290 
291 	m = *mrec;
292 	if (!m) {
293 		m = ntfs_malloc(vol->mft_record_size);
294 		if (!m)
295 			return -1;
296 	}
297 	if (ntfs_mft_record_read(vol, mref, m))
298 		goto err_out;
299 
300 	if (ntfs_mft_record_check(vol, mref, m))
301 		goto err_out;
302 
303 	if (MSEQNO(mref) && MSEQNO(mref) != le16_to_cpu(m->sequence_number)) {
304 		ntfs_log_error("Record %llu has wrong SeqNo (%d <> %d)\n",
305 			       (unsigned long long)MREF(mref), MSEQNO(mref),
306 			       le16_to_cpu(m->sequence_number));
307 		errno = EIO;
308 		goto err_out;
309 	}
310 	*mrec = m;
311 	if (attr)
312 		*attr = (ATTR_RECORD*)((char*)m + le16_to_cpu(m->attrs_offset));
313 	return 0;
314 err_out:
315 	if (m != *mrec)
316 		free(m);
317 	return -1;
318 }
319 
320 /**
321  * ntfs_mft_record_layout - layout an mft record into a memory buffer
322  * @vol:	volume to which the mft record will belong
323  * @mref:	mft reference specifying the mft record number
324  * @mrec:	destination buffer of size >= @vol->mft_record_size bytes
325  *
326  * Layout an empty, unused mft record with the mft reference @mref into the
327  * buffer @m.  The volume @vol is needed because the mft record structure was
328  * modified in NTFS 3.1 so we need to know which volume version this mft record
329  * will be used on.
330  *
331  * On success return 0 and on error return -1 with errno set to the error code.
332  */
333 int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref,
334 		MFT_RECORD *mrec)
335 {
336 	ATTR_RECORD *a;
337 
338 	if (!vol || !mrec) {
339 		errno = EINVAL;
340 		ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec);
341 		return -1;
342 	}
343 	/* Aligned to 2-byte boundary. */
344 	if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
345 		mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
346 	else {
347 		/* Abort if mref is > 32 bits. */
348 		if (MREF(mref) & 0x0000ffff00000000ull) {
349 			errno = ERANGE;
350 			ntfs_log_perror("Mft reference exceeds 32 bits");
351 			return -1;
352 		}
353 		mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
354 		/*
355 		 * Set the NTFS 3.1+ specific fields while we know that the
356 		 * volume version is 3.1+.
357 		 */
358 		mrec->reserved = const_cpu_to_le16(0);
359 		mrec->mft_record_number = cpu_to_le32(MREF(mref));
360 	}
361 	mrec->magic = magic_FILE;
362 	if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
363 		mrec->usa_count = cpu_to_le16(vol->mft_record_size /
364 				NTFS_BLOCK_SIZE + 1);
365 	else {
366 		mrec->usa_count = const_cpu_to_le16(1);
367 		ntfs_log_error("Sector size is bigger than MFT record size.  "
368 				"Setting usa_count to 1.  If Windows chkdsk "
369 				"reports this as corruption, please email %s "
370 				"stating that you saw this message and that "
371 				"the file system created was corrupt.  "
372 				"Thank you.\n", NTFS_DEV_LIST);
373 	}
374 	/* Set the update sequence number to 1. */
375 	*(le16*)((u8*)mrec + le16_to_cpu(mrec->usa_ofs)) = const_cpu_to_le16(1);
376 	mrec->lsn = const_cpu_to_sle64(0ll);
377 	mrec->sequence_number = const_cpu_to_le16(1);
378 	mrec->link_count = const_cpu_to_le16(0);
379 	/* Aligned to 8-byte boundary. */
380 	mrec->attrs_offset = cpu_to_le16((le16_to_cpu(mrec->usa_ofs) +
381 			(le16_to_cpu(mrec->usa_count) << 1) + 7) & ~7);
382 	mrec->flags = const_cpu_to_le16(0);
383 	/*
384 	 * Using attrs_offset plus eight bytes (for the termination attribute),
385 	 * aligned to 8-byte boundary.
386 	 */
387 	mrec->bytes_in_use = cpu_to_le32((le16_to_cpu(mrec->attrs_offset) + 8 +
388 			7) & ~7);
389 	mrec->bytes_allocated = cpu_to_le32(vol->mft_record_size);
390 	mrec->base_mft_record = const_cpu_to_le64((MFT_REF)0);
391 	mrec->next_attr_instance = const_cpu_to_le16(0);
392 	a = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset));
393 	a->type = AT_END;
394 	a->length = const_cpu_to_le32(0);
395 	/* Finally, clear the unused part of the mft record. */
396 	memset((u8*)a + 8, 0, vol->mft_record_size - ((u8*)a + 8 - (u8*)mrec));
397 	return 0;
398 }
399 
400 /**
401  * ntfs_mft_record_format - format an mft record on an ntfs volume
402  * @vol:	volume on which to format the mft record
403  * @mref:	mft reference specifying mft record to format
404  *
405  * Format the mft record with the mft reference @mref in $MFT/$DATA, i.e. lay
406  * out an empty, unused mft record in memory and write it to the volume @vol.
407  *
408  * On success return 0 and on error return -1 with errno set to the error code.
409  */
410 int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref)
411 {
412 	MFT_RECORD *m;
413 	int ret = -1;
414 
415 	ntfs_log_enter("Entering\n");
416 
417 	m = ntfs_calloc(vol->mft_record_size);
418 	if (!m)
419 		goto out;
420 
421 	if (ntfs_mft_record_layout(vol, mref, m))
422 		goto free_m;
423 
424 	if (ntfs_mft_record_write(vol, mref, m))
425 		goto free_m;
426 
427 	ret = 0;
428 free_m:
429 	free(m);
430 out:
431 	ntfs_log_leave("\n");
432 	return ret;
433 }
434 
435 static const char *es = "  Leaving inconsistent metadata.  Run chkdsk.";
436 
437 /**
438  * ntfs_ffz - Find the first unset (zero) bit in a word
439  * @word:
440  *
441  * Description...
442  *
443  * Returns:
444  */
445 static inline unsigned int ntfs_ffz(unsigned int word)
446 {
447 	return ffs(~word) - 1;
448 }
449 
450 static int ntfs_is_mft(ntfs_inode *ni)
451 {
452 	if (ni && ni->mft_no == FILE_MFT)
453 		return 1;
454 	return 0;
455 }
456 
457 #ifndef PAGE_SIZE
458 #define PAGE_SIZE 4096
459 #endif
460 
461 #define RESERVED_MFT_RECORDS   64
462 
463 /**
464  * ntfs_mft_bitmap_find_free_rec - find a free mft record in the mft bitmap
465  * @vol:	volume on which to search for a free mft record
466  * @base_ni:	open base inode if allocating an extent mft record or NULL
467  *
468  * Search for a free mft record in the mft bitmap attribute on the ntfs volume
469  * @vol.
470  *
471  * If @base_ni is NULL start the search at the default allocator position.
472  *
473  * If @base_ni is not NULL start the search at the mft record after the base
474  * mft record @base_ni.
475  *
476  * Return the free mft record on success and -1 on error with errno set to the
477  * error code.  An error code of ENOSPC means that there are no free mft
478  * records in the currently initialized mft bitmap.
479  */
480 static int ntfs_mft_bitmap_find_free_rec(ntfs_volume *vol, ntfs_inode *base_ni)
481 {
482 	s64 pass_end, ll, data_pos, pass_start, ofs, bit;
483 	ntfs_attr *mftbmp_na;
484 	u8 *buf, *byte;
485 	unsigned int size;
486 	u8 pass, b;
487 	int ret = -1;
488 
489 	ntfs_log_enter("Entering\n");
490 
491 	mftbmp_na = vol->mftbmp_na;
492 	/*
493 	 * Set the end of the pass making sure we do not overflow the mft
494 	 * bitmap.
495 	 */
496 	size = PAGE_SIZE;
497 	pass_end = vol->mft_na->allocated_size >> vol->mft_record_size_bits;
498 	ll = mftbmp_na->initialized_size << 3;
499 	if (pass_end > ll)
500 		pass_end = ll;
501 	pass = 1;
502 	if (!base_ni)
503 		data_pos = vol->mft_data_pos;
504 	else
505 		data_pos = base_ni->mft_no + 1;
506 	if (data_pos < RESERVED_MFT_RECORDS)
507 		data_pos = RESERVED_MFT_RECORDS;
508 	if (data_pos >= pass_end) {
509 		data_pos = RESERVED_MFT_RECORDS;
510 		pass = 2;
511 		/* This happens on a freshly formatted volume. */
512 		if (data_pos >= pass_end) {
513 			errno = ENOSPC;
514 			goto leave;
515 		}
516 	}
517 	if (ntfs_is_mft(base_ni)) {
518 		data_pos = 0;
519 		pass = 2;
520 	}
521 	pass_start = data_pos;
522 	buf = ntfs_malloc(PAGE_SIZE);
523 	if (!buf)
524 		goto leave;
525 
526 	ntfs_log_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
527 			"pass_end 0x%llx, data_pos 0x%llx.\n", pass,
528 			(long long)pass_start, (long long)pass_end,
529 			(long long)data_pos);
530 #ifdef DEBUG
531 	byte = NULL;
532 	b = 0;
533 #endif
534 	/* Loop until a free mft record is found. */
535 	for (; pass <= 2; size = PAGE_SIZE) {
536 		/* Cap size to pass_end. */
537 		ofs = data_pos >> 3;
538 		ll = ((pass_end + 7) >> 3) - ofs;
539 		if (size > ll)
540 			size = ll;
541 		ll = ntfs_attr_pread(mftbmp_na, ofs, size, buf);
542 		if (ll < 0) {
543 			ntfs_log_perror("Failed to read $MFT bitmap");
544 			free(buf);
545 			goto leave;
546 		}
547 		ntfs_log_debug("Read 0x%llx bytes.\n", (long long)ll);
548 		/* If we read at least one byte, search @buf for a zero bit. */
549 		if (ll) {
550 			size = ll << 3;
551 			bit = data_pos & 7;
552 			data_pos &= ~7ull;
553 			ntfs_log_debug("Before inner for loop: size 0x%x, "
554 					"data_pos 0x%llx, bit 0x%llx, "
555 					"*byte 0x%hhx, b %u.\n", size,
556 					(long long)data_pos, (long long)bit,
557 					(u8) (byte ? *byte : -1), b);
558 			for (; bit < size && data_pos + bit < pass_end;
559 					bit &= ~7ull, bit += 8) {
560 				/*
561 				 * If we're extending $MFT and running out of the first
562 				 * mft record (base record) then give up searching since
563 				 * no guarantee that the found record will be accessible.
564 				 */
565 				if (ntfs_is_mft(base_ni) && bit > 400)
566 					goto out;
567 
568 				byte = buf + (bit >> 3);
569 				if (*byte == 0xff)
570 					continue;
571 
572 				/* Note: ffz() result must be zero based. */
573 				b = ntfs_ffz((unsigned long)*byte);
574 				if (b < 8 && b >= (bit & 7)) {
575 					free(buf);
576 					ret = data_pos + (bit & ~7ull) + b;
577 					goto leave;
578 				}
579 			}
580 			ntfs_log_debug("After inner for loop: size 0x%x, "
581 					"data_pos 0x%llx, bit 0x%llx, "
582 					"*byte 0x%hhx, b %u.\n", size,
583 					(long long)data_pos, (long long)bit,
584 					(u8) (byte ? *byte : -1), b);
585 			data_pos += size;
586 			/*
587 			 * If the end of the pass has not been reached yet,
588 			 * continue searching the mft bitmap for a zero bit.
589 			 */
590 			if (data_pos < pass_end)
591 				continue;
592 		}
593 		/* Do the next pass. */
594 		pass++;
595 		if (pass == 2) {
596 			/*
597 			 * Starting the second pass, in which we scan the first
598 			 * part of the zone which we omitted earlier.
599 			 */
600 			pass_end = pass_start;
601 			data_pos = pass_start = RESERVED_MFT_RECORDS;
602 			ntfs_log_debug("pass %i, pass_start 0x%llx, pass_end "
603 					"0x%llx.\n", pass, (long long)pass_start,
604 					(long long)pass_end);
605 			if (data_pos >= pass_end)
606 				break;
607 		}
608 	}
609 	/* No free mft records in currently initialized mft bitmap. */
610 out:
611 	free(buf);
612 	errno = ENOSPC;
613 leave:
614 	ntfs_log_leave("\n");
615 	return ret;
616 }
617 
618 static int ntfs_mft_attr_extend(ntfs_attr *na)
619 {
620 	int ret = STATUS_ERROR;
621 	ntfs_log_enter("Entering\n");
622 
623 	if (!NInoAttrList(na->ni)) {
624 		if (ntfs_inode_add_attrlist(na->ni)) {
625 			ntfs_log_perror("%s: Can not add attrlist #3", __FUNCTION__);
626 			goto out;
627 		}
628 		/* We can't sync the $MFT inode since its runlist is bogus. */
629 		ret = STATUS_KEEP_SEARCHING;
630 		goto out;
631 	}
632 
633 	if (ntfs_attr_update_mapping_pairs(na, 0)) {
634 		ntfs_log_perror("%s: MP update failed", __FUNCTION__);
635 		goto out;
636 	}
637 
638 	ret = STATUS_OK;
639 out:
640 	ntfs_log_leave("\n");
641 	return ret;
642 }
643 
644 /**
645  * ntfs_mft_bitmap_extend_allocation_i - see ntfs_mft_bitmap_extend_allocation
646  */
647 static int ntfs_mft_bitmap_extend_allocation_i(ntfs_volume *vol)
648 {
649 	LCN lcn;
650 	s64 ll = 0; /* silence compiler warning */
651 	ntfs_attr *mftbmp_na;
652 	runlist_element *rl, *rl2 = NULL; /* silence compiler warning */
653 	ntfs_attr_search_ctx *ctx;
654 	MFT_RECORD *m = NULL; /* silence compiler warning */
655 	ATTR_RECORD *a = NULL; /* silence compiler warning */
656 	int err, mp_size;
657 	int ret = STATUS_ERROR;
658 	u32 old_alen = 0; /* silence compiler warning */
659 	BOOL mp_rebuilt = FALSE;
660 	BOOL update_mp = FALSE;
661 
662 	mftbmp_na = vol->mftbmp_na;
663 	/*
664 	 * Determine the last lcn of the mft bitmap.  The allocated size of the
665 	 * mft bitmap cannot be zero so we are ok to do this.
666 	 */
667 	rl = ntfs_attr_find_vcn(mftbmp_na, (mftbmp_na->allocated_size - 1) >>
668 			vol->cluster_size_bits);
669 	if (!rl || !rl->length || rl->lcn < 0) {
670 		ntfs_log_error("Failed to determine last allocated "
671 				"cluster of mft bitmap attribute.\n");
672 		if (rl)
673 			errno = EIO;
674 		return STATUS_ERROR;
675 	}
676 	lcn = rl->lcn + rl->length;
677 
678 	rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE);
679 	if (!rl2) {
680 		ntfs_log_error("Failed to allocate a cluster for "
681 				"the mft bitmap.\n");
682 		return STATUS_ERROR;
683 	}
684 	rl = ntfs_runlists_merge(mftbmp_na->rl, rl2);
685 	if (!rl) {
686 		err = errno;
687 		ntfs_log_error("Failed to merge runlists for mft "
688 				"bitmap.\n");
689 		if (ntfs_cluster_free_from_rl(vol, rl2))
690 			ntfs_log_error("Failed to deallocate "
691 					"cluster.%s\n", es);
692 		free(rl2);
693 		errno = err;
694 		return STATUS_ERROR;
695 	}
696 	mftbmp_na->rl = rl;
697 	ntfs_log_debug("Adding one run to mft bitmap.\n");
698 	/* Find the last run in the new runlist. */
699 	for (; rl[1].length; rl++)
700 		;
701 	/*
702 	 * Update the attribute record as well.  Note: @rl is the last
703 	 * (non-terminator) runlist element of mft bitmap.
704 	 */
705 	ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL);
706 	if (!ctx)
707 		goto undo_alloc;
708 
709 	if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name,
710 			mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) {
711 		ntfs_log_error("Failed to find last attribute extent of "
712 				"mft bitmap attribute.\n");
713 		goto undo_alloc;
714 	}
715 	m = ctx->mrec;
716 	a = ctx->attr;
717 	ll = sle64_to_cpu(a->lowest_vcn);
718 	rl2 = ntfs_attr_find_vcn(mftbmp_na, ll);
719 	if (!rl2 || !rl2->length) {
720 		ntfs_log_error("Failed to determine previous last "
721 				"allocated cluster of mft bitmap attribute.\n");
722 		if (rl2)
723 			errno = EIO;
724 		goto undo_alloc;
725 	}
726 	/* Get the size for the new mapping pairs array for this extent. */
727 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX);
728 	if (mp_size <= 0) {
729 		ntfs_log_error("Get size for mapping pairs failed for "
730 				"mft bitmap attribute extent.\n");
731 		goto undo_alloc;
732 	}
733 	/* Expand the attribute record if necessary. */
734 	old_alen = le32_to_cpu(a->length);
735 	if (ntfs_attr_record_resize(m, a, mp_size +
736 			le16_to_cpu(a->mapping_pairs_offset))) {
737 		ntfs_log_info("extending $MFT bitmap\n");
738 		ret = ntfs_mft_attr_extend(vol->mftbmp_na);
739 		if (ret == STATUS_OK)
740 			goto ok;
741 		if (ret == STATUS_ERROR) {
742 			ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__);
743 			update_mp = TRUE;
744 		}
745 		goto undo_alloc;
746 	}
747 	mp_rebuilt = TRUE;
748 	/* Generate the mapping pairs array directly into the attr record. */
749 	if (ntfs_mapping_pairs_build(vol, (u8*)a +
750 			le16_to_cpu(a->mapping_pairs_offset), mp_size, rl2, ll,
751 			NULL)) {
752 		ntfs_log_error("Failed to build mapping pairs array for "
753 				"mft bitmap attribute.\n");
754 		errno = EIO;
755 		goto undo_alloc;
756 	}
757 	/* Update the highest_vcn. */
758 	a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
759 	/*
760 	 * We now have extended the mft bitmap allocated_size by one cluster.
761 	 * Reflect this in the ntfs_attr structure and the attribute record.
762 	 */
763 	if (a->lowest_vcn) {
764 		/*
765 		 * We are not in the first attribute extent, switch to it, but
766 		 * first ensure the changes will make it to disk later.
767 		 */
768 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
769 		ntfs_attr_reinit_search_ctx(ctx);
770 		if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name,
771 				mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) {
772 			ntfs_log_error("Failed to find first attribute "
773 					"extent of mft bitmap attribute.\n");
774 			goto restore_undo_alloc;
775 		}
776 		a = ctx->attr;
777 	}
778 ok:
779 	mftbmp_na->allocated_size += vol->cluster_size;
780 	a->allocated_size = cpu_to_sle64(mftbmp_na->allocated_size);
781 	/* Ensure the changes make it to disk. */
782 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
783 	ntfs_attr_put_search_ctx(ctx);
784 	return STATUS_OK;
785 
786 restore_undo_alloc:
787 	err = errno;
788 	ntfs_attr_reinit_search_ctx(ctx);
789 	if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name,
790 			mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) {
791 		ntfs_log_error("Failed to find last attribute extent of "
792 				"mft bitmap attribute.%s\n", es);
793 		ntfs_attr_put_search_ctx(ctx);
794 		mftbmp_na->allocated_size += vol->cluster_size;
795 		/*
796 		 * The only thing that is now wrong is ->allocated_size of the
797 		 * base attribute extent which chkdsk should be able to fix.
798 		 */
799 		errno = err;
800 		return STATUS_ERROR;
801 	}
802 	m = ctx->mrec;
803 	a = ctx->attr;
804 	a->highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
805 	errno = err;
806 undo_alloc:
807 	err = errno;
808 
809 	/* Remove the last run from the runlist. */
810 	lcn = rl->lcn;
811 	rl->lcn = rl[1].lcn;
812 	rl->length = 0;
813 
814 	/* FIXME: use an ntfs_cluster_free_* function */
815 	if (ntfs_bitmap_clear_bit(vol->lcnbmp_na, lcn))
816 		ntfs_log_error("Failed to free cluster.%s\n", es);
817 	else
818 		vol->free_clusters++;
819 	if (mp_rebuilt) {
820 		if (ntfs_mapping_pairs_build(vol, (u8*)a +
821 				le16_to_cpu(a->mapping_pairs_offset),
822 				old_alen - le16_to_cpu(a->mapping_pairs_offset),
823 				rl2, ll, NULL))
824 			ntfs_log_error("Failed to restore mapping "
825 					"pairs array.%s\n", es);
826 		if (ntfs_attr_record_resize(m, a, old_alen))
827 			ntfs_log_error("Failed to restore attribute "
828 					"record.%s\n", es);
829 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
830 	}
831 	if (update_mp) {
832 		if (ntfs_attr_update_mapping_pairs(vol->mftbmp_na, 0))
833 			ntfs_log_perror("%s: MP update failed", __FUNCTION__);
834 	}
835 	if (ctx)
836 		ntfs_attr_put_search_ctx(ctx);
837 	errno = err;
838 	return ret;
839 }
840 
841 /**
842  * ntfs_mft_bitmap_extend_allocation - extend mft bitmap attribute by a cluster
843  * @vol:	volume on which to extend the mft bitmap attribute
844  *
845  * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
846  *
847  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
848  * data_size.
849  *
850  * Return 0 on success and -1 on error with errno set to the error code.
851  */
852 static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol)
853 {
854 	int ret;
855 
856 	ntfs_log_enter("Entering\n");
857 	ret = ntfs_mft_bitmap_extend_allocation_i(vol);
858 	ntfs_log_leave("\n");
859 	return ret;
860 }
861 /**
862  * ntfs_mft_bitmap_extend_initialized - extend mft bitmap initialized data
863  * @vol:	volume on which to extend the mft bitmap attribute
864  *
865  * Extend the initialized portion of the mft bitmap attribute on the ntfs
866  * volume @vol by 8 bytes.
867  *
868  * Note:  Only changes initialized_size and data_size, i.e. requires that
869  * allocated_size is big enough to fit the new initialized_size.
870  *
871  * Return 0 on success and -1 on error with errno set to the error code.
872  */
873 static int ntfs_mft_bitmap_extend_initialized(ntfs_volume *vol)
874 {
875 	s64 old_data_size, old_initialized_size, ll;
876 	ntfs_attr *mftbmp_na;
877 	ntfs_attr_search_ctx *ctx;
878 	ATTR_RECORD *a;
879 	int err;
880 	int ret = -1;
881 
882 	ntfs_log_enter("Entering\n");
883 
884 	mftbmp_na = vol->mftbmp_na;
885 	ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL);
886 	if (!ctx)
887 		goto out;
888 
889 	if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name,
890 			mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) {
891 		ntfs_log_error("Failed to find first attribute extent of "
892 				"mft bitmap attribute.\n");
893 		err = errno;
894 		goto put_err_out;
895 	}
896 	a = ctx->attr;
897 	old_data_size = mftbmp_na->data_size;
898 	old_initialized_size = mftbmp_na->initialized_size;
899 	mftbmp_na->initialized_size += 8;
900 	a->initialized_size = cpu_to_sle64(mftbmp_na->initialized_size);
901 	if (mftbmp_na->initialized_size > mftbmp_na->data_size) {
902 		mftbmp_na->data_size = mftbmp_na->initialized_size;
903 		a->data_size = cpu_to_sle64(mftbmp_na->data_size);
904 	}
905 	/* Ensure the changes make it to disk. */
906 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
907 	ntfs_attr_put_search_ctx(ctx);
908 	/* Initialize the mft bitmap attribute value with zeroes. */
909 	ll = 0;
910 	ll = ntfs_attr_pwrite(mftbmp_na, old_initialized_size, 8, &ll);
911 	if (ll == 8) {
912 		ntfs_log_debug("Wrote eight initialized bytes to mft bitmap.\n");
913 		vol->free_mft_records += (8 * 8);
914 		ret = 0;
915 		goto out;
916 	}
917 	ntfs_log_error("Failed to write to mft bitmap.\n");
918 	err = errno;
919 	if (ll >= 0)
920 		err = EIO;
921 	/* Try to recover from the error. */
922 	ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL);
923 	if (!ctx)
924 		goto err_out;
925 
926 	if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name,
927 			mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) {
928 		ntfs_log_error("Failed to find first attribute extent of "
929 				"mft bitmap attribute.%s\n", es);
930 put_err_out:
931 		ntfs_attr_put_search_ctx(ctx);
932 		goto err_out;
933 	}
934 	a = ctx->attr;
935 	mftbmp_na->initialized_size = old_initialized_size;
936 	a->initialized_size = cpu_to_sle64(old_initialized_size);
937 	if (mftbmp_na->data_size != old_data_size) {
938 		mftbmp_na->data_size = old_data_size;
939 		a->data_size = cpu_to_sle64(old_data_size);
940 	}
941 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
942 	ntfs_attr_put_search_ctx(ctx);
943 	ntfs_log_debug("Restored status of mftbmp: allocated_size 0x%llx, "
944 			"data_size 0x%llx, initialized_size 0x%llx.\n",
945 			(long long)mftbmp_na->allocated_size,
946 			(long long)mftbmp_na->data_size,
947 			(long long)mftbmp_na->initialized_size);
948 err_out:
949 	errno = err;
950 out:
951 	ntfs_log_leave("\n");
952 	return ret;
953 }
954 
955 /**
956  * ntfs_mft_data_extend_allocation - extend mft data attribute
957  * @vol:	volume on which to extend the mft data attribute
958  *
959  * Extend the mft data attribute on the ntfs volume @vol by 16 mft records
960  * worth of clusters or if not enough space for this by one mft record worth
961  * of clusters.
962  *
963  * Note:  Only changes allocated_size, i.e. does not touch initialized_size or
964  * data_size.
965  *
966  * Return 0 on success and -1 on error with errno set to the error code.
967  */
968 static int ntfs_mft_data_extend_allocation(ntfs_volume *vol)
969 {
970 	LCN lcn;
971 	VCN old_last_vcn;
972 	s64 min_nr, nr, ll = 0; /* silence compiler warning */
973 	ntfs_attr *mft_na;
974 	runlist_element *rl, *rl2;
975 	ntfs_attr_search_ctx *ctx;
976 	MFT_RECORD *m = NULL; /* silence compiler warning */
977 	ATTR_RECORD *a = NULL; /* silence compiler warning */
978 	int err, mp_size;
979 	int ret = STATUS_ERROR;
980 	u32 old_alen = 0; /* silence compiler warning */
981 	BOOL mp_rebuilt = FALSE;
982 	BOOL update_mp = FALSE;
983 
984 	ntfs_log_enter("Extending mft data allocation.\n");
985 
986 	mft_na = vol->mft_na;
987 	/*
988 	 * Determine the preferred allocation location, i.e. the last lcn of
989 	 * the mft data attribute.  The allocated size of the mft data
990 	 * attribute cannot be zero so we are ok to do this.
991 	 */
992 	rl = ntfs_attr_find_vcn(mft_na,
993 			(mft_na->allocated_size - 1) >> vol->cluster_size_bits);
994 
995 	if (!rl || !rl->length || rl->lcn < 0) {
996 		ntfs_log_error("Failed to determine last allocated "
997 				"cluster of mft data attribute.\n");
998 		if (rl)
999 			errno = EIO;
1000 		goto out;
1001 	}
1002 
1003 	lcn = rl->lcn + rl->length;
1004 	ntfs_log_debug("Last lcn of mft data attribute is 0x%llx.\n", (long long)lcn);
1005 	/* Minimum allocation is one mft record worth of clusters. */
1006 	min_nr = vol->mft_record_size >> vol->cluster_size_bits;
1007 	if (!min_nr)
1008 		min_nr = 1;
1009 	/* Want to allocate 16 mft records worth of clusters. */
1010 	nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
1011 	if (!nr)
1012 		nr = min_nr;
1013 
1014 	old_last_vcn = rl[1].vcn;
1015 	do {
1016 		rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE);
1017 		if (rl2)
1018 			break;
1019 		if (errno != ENOSPC || nr == min_nr) {
1020 			ntfs_log_perror("Failed to allocate (%lld) clusters "
1021 					"for $MFT", (long long)nr);
1022 			goto out;
1023 		}
1024 		/*
1025 		 * There is not enough space to do the allocation, but there
1026 		 * might be enough space to do a minimal allocation so try that
1027 		 * before failing.
1028 		 */
1029 		nr = min_nr;
1030 		ntfs_log_debug("Retrying mft data allocation with minimal cluster "
1031 				"count %lli.\n", (long long)nr);
1032 	} while (1);
1033 
1034 	ntfs_log_debug("Allocated %lld clusters.\n", (long long)nr);
1035 
1036 	rl = ntfs_runlists_merge(mft_na->rl, rl2);
1037 	if (!rl) {
1038 		err = errno;
1039 		ntfs_log_error("Failed to merge runlists for mft data "
1040 				"attribute.\n");
1041 		if (ntfs_cluster_free_from_rl(vol, rl2))
1042 			ntfs_log_error("Failed to deallocate clusters "
1043 					"from the mft data attribute.%s\n", es);
1044 		free(rl2);
1045 		errno = err;
1046 		goto out;
1047 	}
1048 	mft_na->rl = rl;
1049 
1050 	/* Find the last run in the new runlist. */
1051 	for (; rl[1].length; rl++)
1052 		;
1053 	/* Update the attribute record as well. */
1054 	ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL);
1055 	if (!ctx)
1056 		goto undo_alloc;
1057 
1058 	if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0,
1059 			rl[1].vcn, NULL, 0, ctx)) {
1060 		ntfs_log_error("Failed to find last attribute extent of "
1061 				"mft data attribute.\n");
1062 		goto undo_alloc;
1063 	}
1064 	m = ctx->mrec;
1065 	a = ctx->attr;
1066 	ll = sle64_to_cpu(a->lowest_vcn);
1067 	rl2 = ntfs_attr_find_vcn(mft_na, ll);
1068 	if (!rl2 || !rl2->length) {
1069 		ntfs_log_error("Failed to determine previous last "
1070 				"allocated cluster of mft data attribute.\n");
1071 		if (rl2)
1072 			errno = EIO;
1073 		goto undo_alloc;
1074 	}
1075 	/* Get the size for the new mapping pairs array for this extent. */
1076 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX);
1077 	if (mp_size <= 0) {
1078 		ntfs_log_error("Get size for mapping pairs failed for "
1079 				"mft data attribute extent.\n");
1080 		goto undo_alloc;
1081 	}
1082 	/* Expand the attribute record if necessary. */
1083 	old_alen = le32_to_cpu(a->length);
1084 	if (ntfs_attr_record_resize(m, a,
1085 			mp_size + le16_to_cpu(a->mapping_pairs_offset))) {
1086 		ret = ntfs_mft_attr_extend(vol->mft_na);
1087 		if (ret == STATUS_OK)
1088 			goto ok;
1089 		if (ret == STATUS_ERROR) {
1090 			ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__);
1091 			update_mp = TRUE;
1092 		}
1093 		goto undo_alloc;
1094 	}
1095 	mp_rebuilt = TRUE;
1096 	/*
1097 	 * Generate the mapping pairs array directly into the attribute record.
1098 	 */
1099 	if (ntfs_mapping_pairs_build(vol,
1100 			(u8*)a + le16_to_cpu(a->mapping_pairs_offset), mp_size,
1101 			rl2, ll, NULL)) {
1102 		ntfs_log_error("Failed to build mapping pairs array of "
1103 				"mft data attribute.\n");
1104 		errno = EIO;
1105 		goto undo_alloc;
1106 	}
1107 	/* Update the highest_vcn. */
1108 	a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1109 	/*
1110 	 * We now have extended the mft data allocated_size by nr clusters.
1111 	 * Reflect this in the ntfs_attr structure and the attribute record.
1112 	 * @rl is the last (non-terminator) runlist element of mft data
1113 	 * attribute.
1114 	 */
1115 	if (a->lowest_vcn) {
1116 		/*
1117 		 * We are not in the first attribute extent, switch to it, but
1118 		 * first ensure the changes will make it to disk later.
1119 		 */
1120 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
1121 		ntfs_attr_reinit_search_ctx(ctx);
1122 		if (ntfs_attr_lookup(mft_na->type, mft_na->name,
1123 				mft_na->name_len, 0, 0, NULL, 0, ctx)) {
1124 			ntfs_log_error("Failed to find first attribute "
1125 					"extent of mft data attribute.\n");
1126 			goto restore_undo_alloc;
1127 		}
1128 		a = ctx->attr;
1129 	}
1130 ok:
1131 	mft_na->allocated_size += nr << vol->cluster_size_bits;
1132 	a->allocated_size = cpu_to_sle64(mft_na->allocated_size);
1133 	/* Ensure the changes make it to disk. */
1134 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
1135 	ntfs_attr_put_search_ctx(ctx);
1136 	ret = STATUS_OK;
1137 out:
1138 	ntfs_log_leave("\n");
1139 	return ret;
1140 
1141 restore_undo_alloc:
1142 	err = errno;
1143 	ntfs_attr_reinit_search_ctx(ctx);
1144 	if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0,
1145 			rl[1].vcn, NULL, 0, ctx)) {
1146 		ntfs_log_error("Failed to find last attribute extent of "
1147 				"mft data attribute.%s\n", es);
1148 		ntfs_attr_put_search_ctx(ctx);
1149 		mft_na->allocated_size += nr << vol->cluster_size_bits;
1150 		/*
1151 		 * The only thing that is now wrong is ->allocated_size of the
1152 		 * base attribute extent which chkdsk should be able to fix.
1153 		 */
1154 		errno = err;
1155 		ret = STATUS_ERROR;
1156 		goto out;
1157 	}
1158 	m = ctx->mrec;
1159 	a = ctx->attr;
1160 	a->highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1161 	errno = err;
1162 undo_alloc:
1163 	err = errno;
1164 	if (ntfs_cluster_free(vol, mft_na, old_last_vcn, -1) < 0)
1165 		ntfs_log_error("Failed to free clusters from mft data "
1166 				"attribute.%s\n", es);
1167 	if (ntfs_rl_truncate(&mft_na->rl, old_last_vcn))
1168 		ntfs_log_error("Failed to truncate mft data attribute "
1169 				"runlist.%s\n", es);
1170 	if (mp_rebuilt) {
1171 		if (ntfs_mapping_pairs_build(vol, (u8*)a +
1172 				le16_to_cpu(a->mapping_pairs_offset),
1173 				old_alen - le16_to_cpu(a->mapping_pairs_offset),
1174 				rl2, ll, NULL))
1175 			ntfs_log_error("Failed to restore mapping pairs "
1176 					"array.%s\n", es);
1177 		if (ntfs_attr_record_resize(m, a, old_alen))
1178 			ntfs_log_error("Failed to restore attribute "
1179 					"record.%s\n", es);
1180 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
1181 	}
1182 	if (update_mp) {
1183 		if (ntfs_attr_update_mapping_pairs(vol->mft_na, 0))
1184 			ntfs_log_perror("%s: MP update failed", __FUNCTION__);
1185 	}
1186 	if (ctx)
1187 		ntfs_attr_put_search_ctx(ctx);
1188 	errno = err;
1189 	goto out;
1190 }
1191 
1192 
1193 static int ntfs_mft_record_init(ntfs_volume *vol, s64 size)
1194 {
1195 	int ret = -1;
1196 	ntfs_attr *mft_na;
1197 	s64 old_data_initialized, old_data_size;
1198 	ntfs_attr_search_ctx *ctx;
1199 
1200 	ntfs_log_enter("Entering\n");
1201 
1202 	/* NOTE: Caller must sanity check vol, vol->mft_na and vol->mftbmp_na */
1203 
1204 	mft_na = vol->mft_na;
1205 
1206 	/*
1207 	 * The mft record is outside the initialized data. Extend the mft data
1208 	 * attribute until it covers the allocated record. The loop is only
1209 	 * actually traversed more than once when a freshly formatted volume
1210 	 * is first written to so it optimizes away nicely in the common case.
1211 	 */
1212 	ntfs_log_debug("Status of mft data before extension: "
1213 			"allocated_size 0x%llx, data_size 0x%llx, "
1214 			"initialized_size 0x%llx.\n",
1215 			(long long)mft_na->allocated_size,
1216 			(long long)mft_na->data_size,
1217 			(long long)mft_na->initialized_size);
1218 	while (size > mft_na->allocated_size) {
1219 		if (ntfs_mft_data_extend_allocation(vol) == STATUS_ERROR)
1220 			goto out;
1221 		ntfs_log_debug("Status of mft data after allocation extension: "
1222 				"allocated_size 0x%llx, data_size 0x%llx, "
1223 				"initialized_size 0x%llx.\n",
1224 				(long long)mft_na->allocated_size,
1225 				(long long)mft_na->data_size,
1226 				(long long)mft_na->initialized_size);
1227 	}
1228 
1229 	old_data_initialized = mft_na->initialized_size;
1230 	old_data_size = mft_na->data_size;
1231 
1232 	/*
1233 	 * Extend mft data initialized size (and data size of course) to reach
1234 	 * the allocated mft record, formatting the mft records along the way.
1235 	 * Note: We only modify the ntfs_attr structure as that is all that is
1236 	 * needed by ntfs_mft_record_format().  We will update the attribute
1237 	 * record itself in one fell swoop later on.
1238 	 */
1239 	while (size > mft_na->initialized_size) {
1240 		s64 ll2 = mft_na->initialized_size >> vol->mft_record_size_bits;
1241 		mft_na->initialized_size += vol->mft_record_size;
1242 		if (mft_na->initialized_size > mft_na->data_size)
1243 			mft_na->data_size = mft_na->initialized_size;
1244 		ntfs_log_debug("Initializing mft record 0x%llx.\n", (long long)ll2);
1245 		if (ntfs_mft_record_format(vol, ll2) < 0) {
1246 			ntfs_log_perror("Failed to format mft record");
1247 			goto undo_data_init;
1248 		}
1249 	}
1250 
1251 	/* Update the mft data attribute record to reflect the new sizes. */
1252 	ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL);
1253 	if (!ctx)
1254 		goto undo_data_init;
1255 
1256 	if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0,
1257 			0, NULL, 0, ctx)) {
1258 		ntfs_log_error("Failed to find first attribute extent of "
1259 				"mft data attribute.\n");
1260 		ntfs_attr_put_search_ctx(ctx);
1261 		goto undo_data_init;
1262 	}
1263 	ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size);
1264 	ctx->attr->data_size = cpu_to_sle64(mft_na->data_size);
1265 	ctx->attr->allocated_size = cpu_to_sle64(mft_na->allocated_size);
1266 
1267 	/* Ensure the changes make it to disk. */
1268 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
1269 	ntfs_attr_put_search_ctx(ctx);
1270 	ntfs_log_debug("Status of mft data after mft record initialization: "
1271 			"allocated_size 0x%llx, data_size 0x%llx, "
1272 			"initialized_size 0x%llx.\n",
1273 			(long long)mft_na->allocated_size,
1274 			(long long)mft_na->data_size,
1275 			(long long)mft_na->initialized_size);
1276 
1277 	/* Sanity checks. */
1278 	if (mft_na->data_size > mft_na->allocated_size ||
1279 	    mft_na->initialized_size > mft_na->data_size)
1280 		NTFS_BUG("mft_na sanity checks failed");
1281 
1282 	/* Sync MFT to minimize data loss if there won't be clean unmount. */
1283 	if (ntfs_inode_sync(mft_na->ni))
1284 		goto undo_data_init;
1285 
1286 	ret = 0;
1287 out:
1288 	ntfs_log_leave("\n");
1289 	return ret;
1290 
1291 undo_data_init:
1292 	mft_na->initialized_size = old_data_initialized;
1293 	mft_na->data_size = old_data_size;
1294 	goto out;
1295 }
1296 
1297 static int ntfs_mft_rec_init(ntfs_volume *vol, s64 size)
1298 {
1299 	int ret = -1;
1300 	ntfs_attr *mft_na;
1301 	s64 old_data_initialized, old_data_size;
1302 	ntfs_attr_search_ctx *ctx;
1303 
1304 	ntfs_log_enter("Entering\n");
1305 
1306 	mft_na = vol->mft_na;
1307 
1308 	if (size > mft_na->allocated_size || size > mft_na->initialized_size) {
1309 		errno = EIO;
1310 		ntfs_log_perror("%s: unexpected $MFT sizes, see below", __FUNCTION__);
1311 		ntfs_log_error("$MFT: size=%lld  allocated_size=%lld  "
1312 			       "data_size=%lld  initialized_size=%lld\n",
1313 			       (long long)size,
1314 			       (long long)mft_na->allocated_size,
1315 			       (long long)mft_na->data_size,
1316 			       (long long)mft_na->initialized_size);
1317 		goto out;
1318 	}
1319 
1320 	old_data_initialized = mft_na->initialized_size;
1321 	old_data_size = mft_na->data_size;
1322 
1323 	/* Update the mft data attribute record to reflect the new sizes. */
1324 	ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL);
1325 	if (!ctx)
1326 		goto undo_data_init;
1327 
1328 	if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0,
1329 			0, NULL, 0, ctx)) {
1330 		ntfs_log_error("Failed to find first attribute extent of "
1331 				"mft data attribute.\n");
1332 		ntfs_attr_put_search_ctx(ctx);
1333 		goto undo_data_init;
1334 	}
1335 	ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size);
1336 	ctx->attr->data_size = cpu_to_sle64(mft_na->data_size);
1337 
1338 	/* CHECKME: ctx->attr->allocation_size is already ok? */
1339 
1340 	/* Ensure the changes make it to disk. */
1341 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
1342 	ntfs_attr_put_search_ctx(ctx);
1343 
1344 	/* Sanity checks. */
1345 	if (mft_na->data_size > mft_na->allocated_size ||
1346 	    mft_na->initialized_size > mft_na->data_size)
1347 		NTFS_BUG("mft_na sanity checks failed");
1348 out:
1349 	ntfs_log_leave("\n");
1350 	return ret;
1351 
1352 undo_data_init:
1353 	mft_na->initialized_size = old_data_initialized;
1354 	mft_na->data_size = old_data_size;
1355 	goto out;
1356 }
1357 
1358 ntfs_inode *ntfs_mft_rec_alloc(ntfs_volume *vol, BOOL mft_data)
1359 {
1360 	s64 ll, bit;
1361 	ntfs_attr *mft_na, *mftbmp_na;
1362 	MFT_RECORD *m;
1363 	ntfs_inode *ni = NULL;
1364 	ntfs_inode *base_ni;
1365 	int err;
1366 	le16 seq_no, usn;
1367 	BOOL forced_mft_data;
1368 
1369 	ntfs_log_enter("Entering\n");
1370 
1371 	mft_na = vol->mft_na;
1372 	mftbmp_na = vol->mftbmp_na;
1373 
1374 	base_ni = mft_na->ni;
1375 
1376 	/*
1377 	 * The first extent containing $MFT:$AT_DATA is better located
1378 	 * in record 15 to make sure it can be read at mount time.
1379 	 * The record 15 is prereserved as a base inode with no
1380 	 * extents and no name, and it is marked in use.
1381 	 */
1382 	forced_mft_data = FALSE;
1383 	if (mft_data) {
1384 		ntfs_inode *ext_ni = ntfs_inode_open(vol, FILE_mft_data);
1385 			/*
1386 			 * If record 15 cannot be opened, it is probably in
1387 			 * use as an extent. Apply standard procedure for
1388 			 * further extents.
1389 			 */
1390 		if (ext_ni) {
1391 			/*
1392 			 * Make sure record 15 is a base extent and has
1393 			 * no extents.
1394 			 * Also make sure it has no name : a base inode with
1395 			 * no extents and no name cannot be in use.
1396 			 * Otherwise apply standard procedure.
1397 			 */
1398    			if (!ext_ni->mrec->base_mft_record
1399 			    && !ext_ni->nr_extents)
1400 				forced_mft_data = TRUE;
1401 			ntfs_inode_close(ext_ni);
1402 		}
1403 	}
1404 	if (forced_mft_data)
1405 		bit = FILE_mft_data;
1406 	else
1407 		bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni);
1408 	if (bit >= 0)
1409 		goto found_free_rec;
1410 
1411 	if (errno != ENOSPC)
1412 		goto out;
1413 
1414 	errno = ENOSPC;
1415 	/* strerror() is intentionally used below, we want to log this error. */
1416 	ntfs_log_error("No free mft record for $MFT: %s\n", strerror(errno));
1417 	goto err_out;
1418 
1419 found_free_rec:
1420 	if (ntfs_bitmap_set_bit(mftbmp_na, bit)) {
1421 		ntfs_log_error("Failed to allocate bit in mft bitmap #2\n");
1422 		goto err_out;
1423 	}
1424 
1425 	ll = (bit + 1) << vol->mft_record_size_bits;
1426 	if (ll > mft_na->initialized_size)
1427 		if (ntfs_mft_rec_init(vol, ll) < 0)
1428 			goto undo_mftbmp_alloc;
1429 	/*
1430 	 * We now have allocated and initialized the mft record.  Need to read
1431 	 * it from disk and re-format it, preserving the sequence number if it
1432 	 * is not zero as well as the update sequence number if it is not zero
1433 	 * or -1 (0xffff).
1434 	 */
1435 	m = ntfs_malloc(vol->mft_record_size);
1436 	if (!m)
1437 		goto undo_mftbmp_alloc;
1438 
1439 	if (ntfs_mft_record_read(vol, bit, m)) {
1440 		free(m);
1441 		goto undo_mftbmp_alloc;
1442 	}
1443 	/* Sanity check that the mft record is really not in use. */
1444 	if (!forced_mft_data
1445 	    && (ntfs_is_file_record(m->magic)
1446 	    && (m->flags & MFT_RECORD_IN_USE))) {
1447 		ntfs_log_error("Inode %lld is used but it wasn't marked in "
1448 			       "$MFT bitmap. Fixed.\n", (long long)bit);
1449 		free(m);
1450 		goto undo_mftbmp_alloc;
1451 	}
1452 
1453 	seq_no = m->sequence_number;
1454 	usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
1455 	if (ntfs_mft_record_layout(vol, bit, m)) {
1456 		ntfs_log_error("Failed to re-format mft record.\n");
1457 		free(m);
1458 		goto undo_mftbmp_alloc;
1459 	}
1460 	if (seq_no)
1461 		m->sequence_number = seq_no;
1462 	seq_no = usn;
1463 	if (seq_no && seq_no != const_cpu_to_le16(0xffff))
1464 		*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
1465 	/* Set the mft record itself in use. */
1466 	m->flags |= MFT_RECORD_IN_USE;
1467 	/* Now need to open an ntfs inode for the mft record. */
1468 	ni = ntfs_inode_allocate(vol);
1469 	if (!ni) {
1470 		ntfs_log_error("Failed to allocate buffer for inode.\n");
1471 		free(m);
1472 		goto undo_mftbmp_alloc;
1473 	}
1474 	ni->mft_no = bit;
1475 	ni->mrec = m;
1476 	/*
1477 	 * If we are allocating an extent mft record, make the opened inode an
1478 	 * extent inode and attach it to the base inode.  Also, set the base
1479 	 * mft record reference in the extent inode.
1480 	 */
1481 	ni->nr_extents = -1;
1482 	ni->base_ni = base_ni;
1483 	m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
1484 					le16_to_cpu(base_ni->mrec->sequence_number));
1485 	/*
1486 	 * Attach the extent inode to the base inode, reallocating
1487 	 * memory if needed.
1488 	 */
1489 	if (!(base_ni->nr_extents & 3)) {
1490 		ntfs_inode **extent_nis;
1491 		int i;
1492 
1493 		i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
1494 		extent_nis = ntfs_malloc(i);
1495 		if (!extent_nis) {
1496 			free(m);
1497 			free(ni);
1498 			goto undo_mftbmp_alloc;
1499 		}
1500 		if (base_ni->nr_extents) {
1501 			memcpy(extent_nis, base_ni->extent_nis,
1502 					i - 4 * sizeof(ntfs_inode *));
1503 			free(base_ni->extent_nis);
1504 		}
1505 		base_ni->extent_nis = extent_nis;
1506 	}
1507 	base_ni->extent_nis[base_ni->nr_extents++] = ni;
1508 
1509 	/* Make sure the allocated inode is written out to disk later. */
1510 	ntfs_inode_mark_dirty(ni);
1511 	/* Initialize time, allocated and data size in ntfs_inode struct. */
1512 	ni->data_size = ni->allocated_size = 0;
1513 	ni->flags = const_cpu_to_le32(0);
1514 	ni->creation_time = ni->last_data_change_time =
1515 			ni->last_mft_change_time =
1516 			ni->last_access_time = ntfs_current_time();
1517 	/* Update the default mft allocation position if it was used. */
1518 	if (!base_ni)
1519 		vol->mft_data_pos = bit + 1;
1520 	/* Return the opened, allocated inode of the allocated mft record. */
1521 	ntfs_log_error("allocated %sinode %lld\n",
1522 			base_ni ? "extent " : "", (long long)bit);
1523 out:
1524 	ntfs_log_leave("\n");
1525 	return ni;
1526 
1527 undo_mftbmp_alloc:
1528 	err = errno;
1529 	if (ntfs_bitmap_clear_bit(mftbmp_na, bit))
1530 		ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es);
1531 	errno = err;
1532 err_out:
1533 	if (!errno)
1534 		errno = EIO;
1535 	ni = NULL;
1536 	goto out;
1537 }
1538 
1539 /**
1540  * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
1541  * @vol:	volume on which to allocate the mft record
1542  * @base_ni:	open base inode if allocating an extent mft record or NULL
1543  *
1544  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
1545  *
1546  * If @base_ni is NULL make the mft record a base mft record and allocate it at
1547  * the default allocator position.
1548  *
1549  * If @base_ni is not NULL make the allocated mft record an extent record,
1550  * allocate it starting at the mft record after the base mft record and attach
1551  * the allocated and opened ntfs inode to the base inode @base_ni.
1552  *
1553  * On success return the now opened ntfs (extent) inode of the mft record.
1554  *
1555  * On error return NULL with errno set to the error code.
1556  *
1557  * To find a free mft record, we scan the mft bitmap for a zero bit.  To
1558  * optimize this we start scanning at the place specified by @base_ni or if
1559  * @base_ni is NULL we start where we last stopped and we perform wrap around
1560  * when we reach the end.  Note, we do not try to allocate mft records below
1561  * number 24 because numbers 0 to 15 are the defined system files anyway and 16
1562  * to 24 are used for storing extension mft records or used by chkdsk to store
1563  * its log. However the record number 15 is dedicated to the first extent to
1564  * the $DATA attribute of $MFT.  This is required to avoid the possibility
1565  * of creating a run list with a circular dependence which once written to disk
1566  * can never be read in again.  Windows will only use records 16 to 24 for
1567  * normal files if the volume is completely out of space.  We never use them
1568  * which means that when the volume is really out of space we cannot create any
1569  * more files while Windows can still create up to 8 small files.  We can start
1570  * doing this at some later time, it does not matter much for now.
1571  *
1572  * When scanning the mft bitmap, we only search up to the last allocated mft
1573  * record.  If there are no free records left in the range 24 to number of
1574  * allocated mft records, then we extend the $MFT/$DATA attribute in order to
1575  * create free mft records.  We extend the allocated size of $MFT/$DATA by 16
1576  * records at a time or one cluster, if cluster size is above 16kiB.  If there
1577  * is not sufficient space to do this, we try to extend by a single mft record
1578  * or one cluster, if cluster size is above the mft record size, but we only do
1579  * this if there is enough free space, which we know from the values returned
1580  * by the failed cluster allocation function when we tried to do the first
1581  * allocation.
1582  *
1583  * No matter how many mft records we allocate, we initialize only the first
1584  * allocated mft record, incrementing mft data size and initialized size
1585  * accordingly, open an ntfs_inode for it and return it to the caller, unless
1586  * there are less than 24 mft records, in which case we allocate and initialize
1587  * mft records until we reach record 24 which we consider as the first free mft
1588  * record for use by normal files.
1589  *
1590  * If during any stage we overflow the initialized data in the mft bitmap, we
1591  * extend the initialized size (and data size) by 8 bytes, allocating another
1592  * cluster if required.  The bitmap data size has to be at least equal to the
1593  * number of mft records in the mft, but it can be bigger, in which case the
1594  * superfluous bits are padded with zeroes.
1595  *
1596  * Thus, when we return successfully (return value non-zero), we will have:
1597  *	- initialized / extended the mft bitmap if necessary,
1598  *	- initialized / extended the mft data if necessary,
1599  *	- set the bit corresponding to the mft record being allocated in the
1600  *	  mft bitmap,
1601  *	- open an ntfs_inode for the allocated mft record, and we will
1602  *	- return the ntfs_inode.
1603  *
1604  * On error (return value zero), nothing will have changed.  If we had changed
1605  * anything before the error occurred, we will have reverted back to the
1606  * starting state before returning to the caller.  Thus, except for bugs, we
1607  * should always leave the volume in a consistent state when returning from
1608  * this function.
1609  *
1610  * Note, this function cannot make use of most of the normal functions, like
1611  * for example for attribute resizing, etc, because when the run list overflows
1612  * the base mft record and an attribute list is used, it is very important that
1613  * the extension mft records used to store the $DATA attribute of $MFT can be
1614  * reached without having to read the information contained inside them, as
1615  * this would make it impossible to find them in the first place after the
1616  * volume is dismounted.  $MFT/$BITMAP probably does not need to follow this
1617  * rule because the bitmap is not essential for finding the mft records, but on
1618  * the other hand, handling the bitmap in this special way would make life
1619  * easier because otherwise there might be circular invocations of functions
1620  * when reading the bitmap but if we are careful, we should be able to avoid
1621  * all problems.
1622  */
1623 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni)
1624 {
1625 	s64 ll, bit;
1626 	ntfs_attr *mft_na, *mftbmp_na;
1627 	MFT_RECORD *m;
1628 	ntfs_inode *ni = NULL;
1629 	int err;
1630 	u32 usa_ofs;
1631 	le16 seq_no, usn;
1632 	BOOL oldwarn;
1633 
1634 	if (base_ni)
1635 		ntfs_log_enter("Entering (allocating an extent mft record for "
1636 			       "base mft record %lld).\n",
1637 			       (long long)base_ni->mft_no);
1638 	else
1639 		ntfs_log_enter("Entering (allocating a base mft record)\n");
1640 	if (!vol || !vol->mft_na || !vol->mftbmp_na) {
1641 		errno = EINVAL;
1642 		goto out;
1643 	}
1644 
1645 	if (ntfs_is_mft(base_ni)) {
1646 		ni = ntfs_mft_rec_alloc(vol, FALSE);
1647 		goto out;
1648 	}
1649 
1650 	mft_na = vol->mft_na;
1651 	mftbmp_na = vol->mftbmp_na;
1652 retry:
1653 	bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni);
1654 	if (bit >= 0) {
1655 		ntfs_log_debug("found free record (#1) at %lld\n",
1656 				(long long)bit);
1657 		goto found_free_rec;
1658 	}
1659 	if (errno != ENOSPC)
1660 		goto out;
1661 	/*
1662 	 * No free mft records left.  If the mft bitmap already covers more
1663 	 * than the currently used mft records, the next records are all free,
1664 	 * so we can simply allocate the first unused mft record.
1665 	 * Note: We also have to make sure that the mft bitmap at least covers
1666 	 * the first 24 mft records as they are special and whilst they may not
1667 	 * be in use, we do not allocate from them.
1668 	 */
1669 	ll = mft_na->initialized_size >> vol->mft_record_size_bits;
1670 	if (mftbmp_na->initialized_size << 3 > ll &&
1671 			mftbmp_na->initialized_size > RESERVED_MFT_RECORDS / 8) {
1672 		bit = ll;
1673 		if (bit < RESERVED_MFT_RECORDS)
1674 			bit = RESERVED_MFT_RECORDS;
1675 		ntfs_log_debug("found free record (#2) at %lld\n",
1676 				(long long)bit);
1677 		goto found_free_rec;
1678 	}
1679 	/*
1680 	 * The mft bitmap needs to be expanded until it covers the first unused
1681 	 * mft record that we can allocate.
1682 	 * Note: The smallest mft record we allocate is mft record 24.
1683 	 */
1684 	ntfs_log_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
1685 			"data_size 0x%llx, initialized_size 0x%llx.\n",
1686 			(long long)mftbmp_na->allocated_size,
1687 			(long long)mftbmp_na->data_size,
1688 			(long long)mftbmp_na->initialized_size);
1689 	if (mftbmp_na->initialized_size + 8 > mftbmp_na->allocated_size) {
1690 
1691 		int ret = ntfs_mft_bitmap_extend_allocation(vol);
1692 
1693 		if (ret == STATUS_ERROR)
1694 			goto err_out;
1695 		if (ret == STATUS_KEEP_SEARCHING) {
1696 			ret = ntfs_mft_bitmap_extend_allocation(vol);
1697 			if (ret != STATUS_OK)
1698 				goto err_out;
1699 		}
1700 
1701 		ntfs_log_debug("Status of mftbmp after allocation extension: "
1702 				"allocated_size 0x%llx, data_size 0x%llx, "
1703 				"initialized_size 0x%llx.\n",
1704 				(long long)mftbmp_na->allocated_size,
1705 				(long long)mftbmp_na->data_size,
1706 				(long long)mftbmp_na->initialized_size);
1707 	}
1708 	/*
1709 	 * We now have sufficient allocated space, extend the initialized_size
1710 	 * as well as the data_size if necessary and fill the new space with
1711 	 * zeroes.
1712 	 */
1713 	bit = mftbmp_na->initialized_size << 3;
1714 	if (ntfs_mft_bitmap_extend_initialized(vol))
1715 		goto err_out;
1716 	ntfs_log_debug("Status of mftbmp after initialized extension: "
1717 			"allocated_size 0x%llx, data_size 0x%llx, "
1718 			"initialized_size 0x%llx.\n",
1719 			(long long)mftbmp_na->allocated_size,
1720 			(long long)mftbmp_na->data_size,
1721 			(long long)mftbmp_na->initialized_size);
1722 	ntfs_log_debug("found free record (#3) at %lld\n", (long long)bit);
1723 found_free_rec:
1724 	/* @bit is the found free mft record, allocate it in the mft bitmap. */
1725 	if (ntfs_bitmap_set_bit(mftbmp_na, bit)) {
1726 		ntfs_log_error("Failed to allocate bit in mft bitmap.\n");
1727 		goto err_out;
1728 	}
1729 
1730 	/* The mft bitmap is now uptodate.  Deal with mft data attribute now. */
1731 	ll = (bit + 1) << vol->mft_record_size_bits;
1732 	if (ll > mft_na->initialized_size)
1733 		if (ntfs_mft_record_init(vol, ll) < 0)
1734 			goto undo_mftbmp_alloc;
1735 
1736 	/*
1737 	 * We now have allocated and initialized the mft record.  Need to read
1738 	 * it from disk and re-format it, preserving the sequence number if it
1739 	 * is not zero as well as the update sequence number if it is not zero
1740 	 * or -1 (0xffff).
1741 	 */
1742 	m = ntfs_malloc(vol->mft_record_size);
1743 	if (!m)
1744 		goto undo_mftbmp_alloc;
1745 
1746 	/*
1747 	 * As this is allocating a new record, do not expect it to have
1748 	 * been initialized previously, so do not warn over bad fixups
1749 	 * (hence avoid warn flooding when an NTFS partition has been wiped).
1750 	 */
1751 	oldwarn = !NVolNoFixupWarn(vol);
1752 	NVolSetNoFixupWarn(vol);
1753 	if (ntfs_mft_record_read(vol, bit, m)) {
1754 		if (oldwarn)
1755 			NVolClearNoFixupWarn(vol);
1756 		free(m);
1757 		goto undo_mftbmp_alloc;
1758 	}
1759 	if (oldwarn)
1760 		NVolClearNoFixupWarn(vol);
1761 
1762 	/* Sanity check that the mft record is really not in use. */
1763 	if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) {
1764 		ntfs_log_error("Inode %lld is used but it wasn't marked in "
1765 			       "$MFT bitmap. Fixed.\n", (long long)bit);
1766 		free(m);
1767 		goto retry;
1768 	}
1769 	seq_no = m->sequence_number;
1770 		/*
1771 		 * As ntfs_mft_record_read() returns what has been read
1772 		 * even when the fixups have been found bad, we have to
1773 		 * check where we fetch the initial usn from.
1774 		 */
1775 	usa_ofs = le16_to_cpu(m->usa_ofs);
1776 	if (!(usa_ofs & 1) && (usa_ofs < NTFS_BLOCK_SIZE)) {
1777 		usn = *(le16*)((u8*)m + usa_ofs);
1778 	} else
1779 		usn = const_cpu_to_le16(1);
1780 	if (ntfs_mft_record_layout(vol, bit, m)) {
1781 		ntfs_log_error("Failed to re-format mft record.\n");
1782 		free(m);
1783 		goto undo_mftbmp_alloc;
1784 	}
1785 	if (seq_no)
1786 		m->sequence_number = seq_no;
1787 	seq_no = usn;
1788 	if (seq_no && seq_no != const_cpu_to_le16(0xffff))
1789 		*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
1790 	/* Set the mft record itself in use. */
1791 	m->flags |= MFT_RECORD_IN_USE;
1792 	/* Now need to open an ntfs inode for the mft record. */
1793 	ni = ntfs_inode_allocate(vol);
1794 	if (!ni) {
1795 		ntfs_log_error("Failed to allocate buffer for inode.\n");
1796 		free(m);
1797 		goto undo_mftbmp_alloc;
1798 	}
1799 	ni->mft_no = bit;
1800 	ni->mrec = m;
1801 	/*
1802 	 * If we are allocating an extent mft record, make the opened inode an
1803 	 * extent inode and attach it to the base inode.  Also, set the base
1804 	 * mft record reference in the extent inode.
1805 	 */
1806 	if (base_ni) {
1807 		ni->nr_extents = -1;
1808 		ni->base_ni = base_ni;
1809 		m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
1810 				le16_to_cpu(base_ni->mrec->sequence_number));
1811 		/*
1812 		 * Attach the extent inode to the base inode, reallocating
1813 		 * memory if needed.
1814 		 */
1815 		if (!(base_ni->nr_extents & 3)) {
1816 			ntfs_inode **extent_nis;
1817 			int i;
1818 
1819 			i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
1820 			extent_nis = ntfs_malloc(i);
1821 			if (!extent_nis) {
1822 				free(m);
1823 				free(ni);
1824 				goto undo_mftbmp_alloc;
1825 			}
1826 			if (base_ni->nr_extents) {
1827 				memcpy(extent_nis, base_ni->extent_nis,
1828 						i - 4 * sizeof(ntfs_inode *));
1829 				free(base_ni->extent_nis);
1830 			}
1831 			base_ni->extent_nis = extent_nis;
1832 		}
1833 		base_ni->extent_nis[base_ni->nr_extents++] = ni;
1834 	}
1835 	/* Make sure the allocated inode is written out to disk later. */
1836 	ntfs_inode_mark_dirty(ni);
1837 	/* Initialize time, allocated and data size in ntfs_inode struct. */
1838 	ni->data_size = ni->allocated_size = 0;
1839 	ni->flags = const_cpu_to_le32(0);
1840 	ni->creation_time = ni->last_data_change_time =
1841 			ni->last_mft_change_time =
1842 			ni->last_access_time = ntfs_current_time();
1843 	/* Update the default mft allocation position if it was used. */
1844 	if (!base_ni)
1845 		vol->mft_data_pos = bit + 1;
1846 	/* Return the opened, allocated inode of the allocated mft record. */
1847 	ntfs_log_debug("allocated %sinode 0x%llx.\n",
1848 			base_ni ? "extent " : "", (long long)bit);
1849 	vol->free_mft_records--;
1850 out:
1851 	ntfs_log_leave("\n");
1852 	return ni;
1853 
1854 undo_mftbmp_alloc:
1855 	err = errno;
1856 	if (ntfs_bitmap_clear_bit(mftbmp_na, bit))
1857 		ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es);
1858 	errno = err;
1859 err_out:
1860 	if (!errno)
1861 		errno = EIO;
1862 	ni = NULL;
1863 	goto out;
1864 }
1865 
1866 /**
1867  * ntfs_mft_record_free - free an mft record on an ntfs volume
1868  * @vol:	volume on which to free the mft record
1869  * @ni:		open ntfs inode of the mft record to free
1870  *
1871  * Free the mft record of the open inode @ni on the mounted ntfs volume @vol.
1872  * Note that this function calls ntfs_inode_close() internally and hence you
1873  * cannot use the pointer @ni any more after this function returns success.
1874  *
1875  * On success return 0 and on error return -1 with errno set to the error code.
1876  */
1877 int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni)
1878 {
1879 	u64 mft_no;
1880 	int err;
1881 	u16 seq_no;
1882 	le16 old_seq_no;
1883 
1884 	ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no);
1885 
1886 	if (!vol || !vol->mftbmp_na || !ni) {
1887 		errno = EINVAL;
1888 		return -1;
1889 	}
1890 
1891 	/* Cache the mft reference for later. */
1892 	mft_no = ni->mft_no;
1893 
1894 	/* Mark the mft record as not in use. */
1895 	ni->mrec->flags &= ~MFT_RECORD_IN_USE;
1896 
1897 	/* Increment the sequence number, skipping zero, if it is not zero. */
1898 	old_seq_no = ni->mrec->sequence_number;
1899 	seq_no = le16_to_cpu(old_seq_no);
1900 	if (seq_no == 0xffff)
1901 		seq_no = 1;
1902 	else if (seq_no)
1903 		seq_no++;
1904 	ni->mrec->sequence_number = cpu_to_le16(seq_no);
1905 
1906 	/* Set the inode dirty and write it out. */
1907 	ntfs_inode_mark_dirty(ni);
1908 	if (ntfs_inode_sync(ni)) {
1909 		err = errno;
1910 		goto sync_rollback;
1911 	}
1912 
1913 	/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
1914 	if (ntfs_bitmap_clear_bit(vol->mftbmp_na, mft_no)) {
1915 		err = errno;
1916 		// FIXME: If ntfs_bitmap_clear_run() guarantees rollback on
1917 		//	  error, this could be changed to goto sync_rollback;
1918 		goto bitmap_rollback;
1919 	}
1920 
1921 	/* Throw away the now freed inode. */
1922 #if CACHE_NIDATA_SIZE
1923 	if (!ntfs_inode_real_close(ni)) {
1924 #else
1925 	if (!ntfs_inode_close(ni)) {
1926 #endif
1927 		vol->free_mft_records++;
1928 		return 0;
1929 	}
1930 	err = errno;
1931 
1932 	/* Rollback what we did... */
1933 bitmap_rollback:
1934 	if (ntfs_bitmap_set_bit(vol->mftbmp_na, mft_no))
1935 		ntfs_log_debug("Eeek! Rollback failed in ntfs_mft_record_free().  "
1936 				"Leaving inconsistent metadata!\n");
1937 sync_rollback:
1938 	ni->mrec->flags |= MFT_RECORD_IN_USE;
1939 	ni->mrec->sequence_number = old_seq_no;
1940 	ntfs_inode_mark_dirty(ni);
1941 	errno = err;
1942 	return -1;
1943 }
1944 
1945 /**
1946  * ntfs_mft_usn_dec - Decrement USN by one
1947  * @mrec:	pointer to an mft record
1948  *
1949  * On success return 0 and on error return -1 with errno set.
1950  */
1951 int ntfs_mft_usn_dec(MFT_RECORD *mrec)
1952 {
1953 	u16 usn;
1954 	le16 *usnp;
1955 
1956 	if (!mrec) {
1957 		errno = EINVAL;
1958 		return -1;
1959 	}
1960 	usnp = (le16*)((char*)mrec + le16_to_cpu(mrec->usa_ofs));
1961 	usn = le16_to_cpup(usnp);
1962 	if (usn-- <= 1)
1963 		usn = 0xfffe;
1964 	*usnp = cpu_to_le16(usn);
1965 
1966 	return 0;
1967 }
1968 
1969