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