xref: /haiku/src/add-ons/kernel/file_systems/ntfs/libntfs/mft.c (revision be3db2942c0e8dda63cdd226ec3c99309d3eab0c)
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)", m + count,
96 				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)", m + count,
159 				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 				"attribute.\n");
1012 		goto undo_alloc;
1013 	}
1014 	mp_rebuilt = TRUE;
1015 	/*
1016 	 * Generate the mapping pairs array directly into the attribute record.
1017 	 */
1018 	if (ntfs_mapping_pairs_build(vol,
1019 			(u8*)a + le16_to_cpu(a->mapping_pairs_offset), mp_size,
1020 			rl2, ll, NULL)) {
1021 		ntfs_log_error("Failed to build mapping pairs array of "
1022 				"mft data attribute.\n");
1023 		errno = EIO;
1024 		goto undo_alloc;
1025 	}
1026 	/* Update the highest_vcn. */
1027 	a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
1028 	/*
1029 	 * We now have extended the mft data allocated_size by nr clusters.
1030 	 * Reflect this in the ntfs_attr structure and the attribute record.
1031 	 * @rl is the last (non-terminator) runlist element of mft data
1032 	 * attribute.
1033 	 */
1034 	if (a->lowest_vcn) {
1035 		/*
1036 		 * We are not in the first attribute extent, switch to it, but
1037 		 * first ensure the changes will make it to disk later.
1038 		 */
1039 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
1040 		ntfs_attr_reinit_search_ctx(ctx);
1041 		if (ntfs_attr_lookup(mft_na->type, mft_na->name,
1042 				mft_na->name_len, 0, 0, NULL, 0, ctx)) {
1043 			ntfs_log_error("Failed to find first attribute "
1044 					"extent of mft data attribute.\n");
1045 			goto restore_undo_alloc;
1046 		}
1047 		a = ctx->attr;
1048 	}
1049 	mft_na->allocated_size += nr << vol->cluster_size_bits;
1050 	a->allocated_size = cpu_to_sle64(mft_na->allocated_size);
1051 	/* Ensure the changes make it to disk. */
1052 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
1053 	ntfs_attr_put_search_ctx(ctx);
1054 	return 0;
1055 restore_undo_alloc:
1056 	err = errno;
1057 	ntfs_attr_reinit_search_ctx(ctx);
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.%s\n", es);
1062 		ntfs_attr_put_search_ctx(ctx);
1063 		mft_na->allocated_size += nr << vol->cluster_size_bits;
1064 		/*
1065 		 * The only thing that is now wrong is ->allocated_size of the
1066 		 * base attribute extent which chkdsk should be able to fix.
1067 		 */
1068 		errno = err;
1069 		return -1;
1070 	}
1071 	m = ctx->mrec;
1072 	a = ctx->attr;
1073 	a->highest_vcn = cpu_to_sle64(old_last_vcn - 1);
1074 	errno = err;
1075 undo_alloc:
1076 	err = errno;
1077 	if (ntfs_cluster_free(vol, mft_na, old_last_vcn, -1) < 0)
1078 		ntfs_log_error("Failed to free clusters from mft data "
1079 				"attribute.%s\n", es);
1080 	if (ntfs_rl_truncate(&mft_na->rl, old_last_vcn))
1081 		ntfs_log_error("Failed to truncate mft data attribute "
1082 				"runlist.%s\n", es);
1083 	if (mp_rebuilt) {
1084 		if (ntfs_mapping_pairs_build(vol, (u8*)a +
1085 				le16_to_cpu(a->mapping_pairs_offset),
1086 				old_alen - le16_to_cpu(a->mapping_pairs_offset),
1087 				rl2, ll, NULL))
1088 			ntfs_log_error("Failed to restore mapping pairs "
1089 					"array.%s\n", es);
1090 		if (ntfs_attr_record_resize(m, a, old_alen))
1091 			ntfs_log_error("Failed to restore attribute "
1092 					"record.%s\n", es);
1093 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
1094 	}
1095 	if (ctx)
1096 		ntfs_attr_put_search_ctx(ctx);
1097 	errno = err;
1098 	return -1;
1099 }
1100 
1101 /**
1102  * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
1103  * @vol:	volume on which to allocate the mft record
1104  * @base_ni:	open base inode if allocating an extent mft record or NULL
1105  *
1106  * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
1107  *
1108  * If @base_ni is NULL make the mft record a base mft record and allocate it at
1109  * the default allocator position.
1110  *
1111  * If @base_ni is not NULL make the allocated mft record an extent record,
1112  * allocate it starting at the mft record after the base mft record and attach
1113  * the allocated and opened ntfs inode to the base inode @base_ni.
1114  *
1115  * On success return the now opened ntfs (extent) inode of the mft record.
1116  *
1117  * On error return NULL with errno set to the error code.
1118  *
1119  * To find a free mft record, we scan the mft bitmap for a zero bit.  To
1120  * optimize this we start scanning at the place specified by @base_ni or if
1121  * @base_ni is NULL we start where we last stopped and we perform wrap around
1122  * when we reach the end.  Note, we do not try to allocate mft records below
1123  * number 24 because numbers 0 to 15 are the defined system files anyway and 16
1124  * to 24 are special in that they are used for storing extension mft records
1125  * for the $DATA attribute of $MFT.  This is required to avoid the possibility
1126  * of creating a run list with a circular dependence which once written to disk
1127  * can never be read in again.  Windows will only use records 16 to 24 for
1128  * normal files if the volume is completely out of space.  We never use them
1129  * which means that when the volume is really out of space we cannot create any
1130  * more files while Windows can still create up to 8 small files.  We can start
1131  * doing this at some later time, it does not matter much for now.
1132  *
1133  * When scanning the mft bitmap, we only search up to the last allocated mft
1134  * record.  If there are no free records left in the range 24 to number of
1135  * allocated mft records, then we extend the $MFT/$DATA attribute in order to
1136  * create free mft records.  We extend the allocated size of $MFT/$DATA by 16
1137  * records at a time or one cluster, if cluster size is above 16kiB.  If there
1138  * is not sufficient space to do this, we try to extend by a single mft record
1139  * or one cluster, if cluster size is above the mft record size, but we only do
1140  * this if there is enough free space, which we know from the values returned
1141  * by the failed cluster allocation function when we tried to do the first
1142  * allocation.
1143  *
1144  * No matter how many mft records we allocate, we initialize only the first
1145  * allocated mft record, incrementing mft data size and initialized size
1146  * accordingly, open an ntfs_inode for it and return it to the caller, unless
1147  * there are less than 24 mft records, in which case we allocate and initialize
1148  * mft records until we reach record 24 which we consider as the first free mft
1149  * record for use by normal files.
1150  *
1151  * If during any stage we overflow the initialized data in the mft bitmap, we
1152  * extend the initialized size (and data size) by 8 bytes, allocating another
1153  * cluster if required.  The bitmap data size has to be at least equal to the
1154  * number of mft records in the mft, but it can be bigger, in which case the
1155  * superfluous bits are padded with zeroes.
1156  *
1157  * Thus, when we return successfully (return value non-zero), we will have:
1158  *	- initialized / extended the mft bitmap if necessary,
1159  *	- initialized / extended the mft data if necessary,
1160  *	- set the bit corresponding to the mft record being allocated in the
1161  *	  mft bitmap,
1162  *	- open an ntfs_inode for the allocated mft record, and we will
1163  *	- return the ntfs_inode.
1164  *
1165  * On error (return value zero), nothing will have changed.  If we had changed
1166  * anything before the error occurred, we will have reverted back to the
1167  * starting state before returning to the caller.  Thus, except for bugs, we
1168  * should always leave the volume in a consistent state when returning from
1169  * this function.
1170  *
1171  * Note, this function cannot make use of most of the normal functions, like
1172  * for example for attribute resizing, etc, because when the run list overflows
1173  * the base mft record and an attribute list is used, it is very important that
1174  * the extension mft records used to store the $DATA attribute of $MFT can be
1175  * reached without having to read the information contained inside them, as
1176  * this would make it impossible to find them in the first place after the
1177  * volume is dismounted.  $MFT/$BITMAP probably does not need to follow this
1178  * rule because the bitmap is not essential for finding the mft records, but on
1179  * the other hand, handling the bitmap in this special way would make life
1180  * easier because otherwise there might be circular invocations of functions
1181  * when reading the bitmap but if we are careful, we should be able to avoid
1182  * all problems.
1183  */
1184 ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni)
1185 {
1186 	s64 ll, bit, old_data_initialized, old_data_size;
1187 	ntfs_attr *mft_na, *mftbmp_na;
1188 	ntfs_attr_search_ctx *ctx;
1189 	MFT_RECORD *m;
1190 	ATTR_RECORD *a;
1191 	ntfs_inode *ni;
1192 	int err;
1193 	u16 seq_no, usn;
1194 
1195 	if (base_ni)
1196 		ntfs_log_trace("Entering (allocating an extent mft record for "
1197 				"base mft record 0x%llx).\n",
1198 				(long long)base_ni->mft_no);
1199 	else
1200 		ntfs_log_trace("Entering (allocating a base mft record).\n");
1201 	if (!vol || !vol->mft_na || !vol->mftbmp_na) {
1202 		errno = EINVAL;
1203 		return NULL;
1204 	}
1205 	mft_na = vol->mft_na;
1206 	mftbmp_na = vol->mftbmp_na;
1207 	bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni);
1208 	if (bit >= 0) {
1209 		ntfs_log_debug("Found free record (#1), bit 0x%llx.\n",
1210 				(long long)bit);
1211 		goto found_free_rec;
1212 	}
1213 	if (errno != ENOSPC)
1214 		return NULL;
1215 	/*
1216 	 * No free mft records left.  If the mft bitmap already covers more
1217 	 * than the currently used mft records, the next records are all free,
1218 	 * so we can simply allocate the first unused mft record.
1219 	 * Note: We also have to make sure that the mft bitmap at least covers
1220 	 * the first 24 mft records as they are special and whilst they may not
1221 	 * be in use, we do not allocate from them.
1222 	 */
1223 	ll = mft_na->initialized_size >> vol->mft_record_size_bits;
1224 	if (mftbmp_na->initialized_size << 3 > ll &&
1225 			mftbmp_na->initialized_size > 3) {
1226 		bit = ll;
1227 		if (bit < 24)
1228 			bit = 24;
1229 		ntfs_log_debug("Found free record (#2), bit 0x%llx.\n",
1230 				(long long)bit);
1231 		goto found_free_rec;
1232 	}
1233 	/*
1234 	 * The mft bitmap needs to be expanded until it covers the first unused
1235 	 * mft record that we can allocate.
1236 	 * Note: The smallest mft record we allocate is mft record 24.
1237 	 */
1238 	ntfs_log_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
1239 			"data_size 0x%llx, initialized_size 0x%llx.\n",
1240 			(long long)mftbmp_na->allocated_size,
1241 			(long long)mftbmp_na->data_size,
1242 			(long long)mftbmp_na->initialized_size);
1243 	if (mftbmp_na->initialized_size + 8 > mftbmp_na->allocated_size) {
1244 		/* Need to extend bitmap by one more cluster. */
1245 		ntfs_log_debug("mftbmp: initialized_size + 8 > allocated_size.\n");
1246 		if (ntfs_mft_bitmap_extend_allocation(vol))
1247 			goto err_out;
1248 		ntfs_log_debug("Status of mftbmp after allocation extension: "
1249 				"allocated_size 0x%llx, data_size 0x%llx, "
1250 				"initialized_size 0x%llx.\n",
1251 				(long long)mftbmp_na->allocated_size,
1252 				(long long)mftbmp_na->data_size,
1253 				(long long)mftbmp_na->initialized_size);
1254 	}
1255 	/*
1256 	 * We now have sufficient allocated space, extend the initialized_size
1257 	 * as well as the data_size if necessary and fill the new space with
1258 	 * zeroes.
1259 	 */
1260 	bit = mftbmp_na->initialized_size << 3;
1261 	if (ntfs_mft_bitmap_extend_initialized(vol))
1262 		goto err_out;
1263 	ntfs_log_debug("Status of mftbmp after initialized extension: "
1264 			"allocated_size 0x%llx, data_size 0x%llx, "
1265 			"initialized_size 0x%llx.\n",
1266 			(long long)mftbmp_na->allocated_size,
1267 			(long long)mftbmp_na->data_size,
1268 			(long long)mftbmp_na->initialized_size);
1269 	ntfs_log_debug("Found free record (#3), bit 0x%llx.\n", (long long)bit);
1270 found_free_rec:
1271 	/* @bit is the found free mft record, allocate it in the mft bitmap. */
1272 	ntfs_log_debug("At found_free_rec.\n");
1273 	if (ntfs_bitmap_set_bit(mftbmp_na, bit)) {
1274 		ntfs_log_error("Failed to allocate bit in mft bitmap.\n");
1275 		goto err_out;
1276 	}
1277 	ntfs_log_debug("Set bit 0x%llx in mft bitmap.\n", (long long)bit);
1278 	/* The mft bitmap is now uptodate.  Deal with mft data attribute now. */
1279 	ll = (bit + 1) << vol->mft_record_size_bits;
1280 	if (ll <= mft_na->initialized_size) {
1281 		ntfs_log_debug("Allocated mft record already initialized.\n");
1282 		goto mft_rec_already_initialized;
1283 	}
1284 	ntfs_log_debug("Initializing allocated mft record.\n");
1285 	/*
1286 	 * The mft record is outside the initialized data.  Extend the mft data
1287 	 * attribute until it covers the allocated record.  The loop is only
1288 	 * actually traversed more than once when a freshly formatted volume is
1289 	 * first written to so it optimizes away nicely in the common case.
1290 	 */
1291 	ntfs_log_debug("Status of mft data before extension: "
1292 			"allocated_size 0x%llx, data_size 0x%llx, "
1293 			"initialized_size 0x%llx.\n",
1294 			(long long)mft_na->allocated_size,
1295 			(long long)mft_na->data_size,
1296 			(long long)mft_na->initialized_size);
1297 	while (ll > mft_na->allocated_size) {
1298 		if (ntfs_mft_data_extend_allocation(vol))
1299 			goto undo_mftbmp_alloc;
1300 		ntfs_log_debug("Status of mft data after allocation extension: "
1301 				"allocated_size 0x%llx, data_size 0x%llx, "
1302 				"initialized_size 0x%llx.\n",
1303 				(long long)mft_na->allocated_size,
1304 				(long long)mft_na->data_size,
1305 				(long long)mft_na->initialized_size);
1306 	}
1307 	old_data_initialized = mft_na->initialized_size;
1308 	old_data_size = mft_na->data_size;
1309 	/*
1310 	 * Extend mft data initialized size (and data size of course) to reach
1311 	 * the allocated mft record, formatting the mft records along the way.
1312 	 * Note: We only modify the ntfs_attr structure as that is all that is
1313 	 * needed by ntfs_mft_record_format().  We will update the attribute
1314 	 * record itself in one fell swoop later on.
1315 	 */
1316 	while (ll > mft_na->initialized_size) {
1317 		s64 ll2 = mft_na->initialized_size >> vol->mft_record_size_bits;
1318 		mft_na->initialized_size += vol->mft_record_size;
1319 		if (mft_na->initialized_size > mft_na->data_size)
1320 			mft_na->data_size = mft_na->initialized_size;
1321 		ntfs_log_debug("Initializing mft record 0x%llx.\n", (long long)ll2);
1322 		err = ntfs_mft_record_format(vol, ll2);
1323 		if (err) {
1324 			ntfs_log_error("Failed to format mft record.\n");
1325 			goto undo_data_init;
1326 		}
1327 	}
1328 	/* Update the mft data attribute record to reflect the new sizes. */
1329 	ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL);
1330 	if (!ctx) {
1331 		ntfs_log_error("Failed to get search context.\n");
1332 		goto undo_data_init;
1333 	}
1334 	if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0,
1335 			0, NULL, 0, ctx)) {
1336 		ntfs_log_error("Failed to find first attribute extent of "
1337 				"mft data attribute.\n");
1338 		ntfs_attr_put_search_ctx(ctx);
1339 		goto undo_data_init;
1340 	}
1341 	a = ctx->attr;
1342 	a->initialized_size = cpu_to_sle64(mft_na->initialized_size);
1343 	a->data_size = cpu_to_sle64(mft_na->data_size);
1344 	/* Ensure the changes make it to disk. */
1345 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
1346 	ntfs_attr_put_search_ctx(ctx);
1347 	ntfs_log_debug("Status of mft data after mft record initialization: "
1348 			"allocated_size 0x%llx, data_size 0x%llx, "
1349 			"initialized_size 0x%llx.\n",
1350 			(long long)mft_na->allocated_size,
1351 			(long long)mft_na->data_size,
1352 			(long long)mft_na->initialized_size);
1353 	/* Sanity checks. */
1354 	if (mft_na->data_size > mft_na->allocated_size ||
1355 			mft_na->initialized_size > mft_na->data_size)
1356 		NTFS_BUG("mft_na sanity checks failed");
1357 	// BUG_ON(mft_na->initialized_size > mft_na->data_size);
1358 	// BUG_ON(mft_na->data_size > mft_na->allocated_size);
1359 	/* Sync MFT to minimize data loss if there won't be clean unmount. */
1360 	if (ntfs_inode_sync(mft_na->ni)) {
1361 		ntfs_log_error("Failed to sync $MFT.");
1362 		goto undo_data_init;
1363 	}
1364 mft_rec_already_initialized:
1365 	/*
1366 	 * We now have allocated and initialized the mft record.  Need to read
1367 	 * it from disk and re-format it, preserving the sequence number if it
1368 	 * is not zero as well as the update sequence number if it is not zero
1369 	 * or -1 (0xffff).
1370 	 */
1371 	m = ntfs_malloc(vol->mft_record_size);
1372 	if (!m)
1373 		goto undo_mftbmp_alloc;
1374 
1375 	if (ntfs_mft_record_read(vol, bit, m)) {
1376 		err = errno;
1377 		ntfs_log_error("Failed to read mft record.\n");
1378 		free(m);
1379 		errno = err;
1380 		goto undo_mftbmp_alloc;
1381 	}
1382 	/* Sanity check that the mft record is really not in use. */
1383 	if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) {
1384 		ntfs_log_error("Mft record 0x%llx was marked unused in "
1385 				"mft bitmap but is marked used itself.  "
1386 				"Corrupt filesystem or library bug!  "
1387 				"Run chkdsk immediately!\n", (long long)bit);
1388 		free(m);
1389 		errno = EIO;
1390 		goto undo_mftbmp_alloc;
1391 	}
1392 	seq_no = m->sequence_number;
1393 	usn = *(u16*)((u8*)m + le16_to_cpu(m->usa_ofs));
1394 	if (ntfs_mft_record_layout(vol, bit, m)) {
1395 		err = errno;
1396 		ntfs_log_error("Failed to re-format mft record.\n");
1397 		free(m);
1398 		errno = err;
1399 		goto undo_mftbmp_alloc;
1400 	}
1401 	if (le16_to_cpu(seq_no))
1402 		m->sequence_number = seq_no;
1403 	seq_no = le16_to_cpu(usn);
1404 	if (seq_no && seq_no != 0xffff)
1405 		*(u16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
1406 	/* Set the mft record itself in use. */
1407 	m->flags |= MFT_RECORD_IN_USE;
1408 	/* Now need to open an ntfs inode for the mft record. */
1409 	ni = ntfs_inode_allocate(vol);
1410 	if (!ni) {
1411 		err = errno;
1412 		ntfs_log_error("Failed to allocate buffer for inode.\n");
1413 		free(m);
1414 		errno = err;
1415 		goto undo_mftbmp_alloc;
1416 	}
1417 	ni->mft_no = bit;
1418 	ni->mrec = m;
1419 	/*
1420 	 * If we are allocating an extent mft record, make the opened inode an
1421 	 * extent inode and attach it to the base inode.  Also, set the base
1422 	 * mft record reference in the extent inode.
1423 	 */
1424 	if (base_ni) {
1425 		ni->nr_extents = -1;
1426 		ni->base_ni = base_ni;
1427 		m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
1428 				le16_to_cpu(base_ni->mrec->sequence_number));
1429 		/*
1430 		 * Attach the extent inode to the base inode, reallocating
1431 		 * memory if needed.
1432 		 */
1433 		if (!(base_ni->nr_extents & 3)) {
1434 			ntfs_inode **extent_nis;
1435 			int i;
1436 
1437 			i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
1438 			extent_nis = ntfs_malloc(i);
1439 			if (!extent_nis) {
1440 				free(m);
1441 				free(ni);
1442 				goto undo_mftbmp_alloc;
1443 			}
1444 			if (base_ni->extent_nis) {
1445 				memcpy(extent_nis, base_ni->extent_nis,
1446 						i - 4 * sizeof(ntfs_inode *));
1447 				free(base_ni->extent_nis);
1448 			}
1449 			base_ni->extent_nis = extent_nis;
1450 		}
1451 		base_ni->extent_nis[base_ni->nr_extents++] = ni;
1452 	}
1453 	/* Make sure the allocated inode is written out to disk later. */
1454 	ntfs_inode_mark_dirty(ni);
1455 	/* Initialize time, allocated and data size in ntfs_inode struct. */
1456 	ni->data_size = ni->allocated_size = 0;
1457 	ni->flags = 0;
1458 	ni->creation_time = ni->last_data_change_time =
1459 			ni->last_mft_change_time =
1460 			ni->last_access_time = time(NULL);
1461 	/* Update the default mft allocation position if it was used. */
1462 	if (!base_ni)
1463 		vol->mft_data_pos = bit + 1;
1464 	/* Return the opened, allocated inode of the allocated mft record. */
1465 	ntfs_log_debug("Returning opened, allocated %sinode 0x%llx.\n",
1466 			base_ni ? "extent " : "", (long long)bit);
1467 	return ni;
1468 undo_data_init:
1469 	mft_na->initialized_size = old_data_initialized;
1470 	mft_na->data_size = old_data_size;
1471 undo_mftbmp_alloc:
1472 	err = errno;
1473 	if (ntfs_bitmap_clear_bit(mftbmp_na, bit))
1474 		ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es);
1475 	errno = err;
1476 err_out:
1477 	if (!errno)
1478 		errno = EIO;
1479 	return NULL;
1480 }
1481 
1482 /**
1483  * ntfs_mft_record_free - free an mft record on an ntfs volume
1484  * @vol:	volume on which to free the mft record
1485  * @ni:		open ntfs inode of the mft record to free
1486  *
1487  * Free the mft record of the open inode @ni on the mounted ntfs volume @vol.
1488  * Note that this function calls ntfs_inode_close() internally and hence you
1489  * cannot use the pointer @ni any more after this function returns success.
1490  *
1491  * On success return 0 and on error return -1 with errno set to the error code.
1492  */
1493 int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni)
1494 {
1495 	u64 mft_no;
1496 	int err;
1497 	u16 seq_no, old_seq_no;
1498 
1499 	ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no);
1500 
1501 	if (!vol || !vol->mftbmp_na || !ni) {
1502 		errno = EINVAL;
1503 		return -1;
1504 	}
1505 
1506 	/* Cache the mft reference for later. */
1507 	mft_no = ni->mft_no;
1508 
1509 	/* Mark the mft record as not in use. */
1510 	ni->mrec->flags &= ~MFT_RECORD_IN_USE;
1511 
1512 	/* Increment the sequence number, skipping zero, if it is not zero. */
1513 	old_seq_no = ni->mrec->sequence_number;
1514 	seq_no = le16_to_cpu(old_seq_no);
1515 	if (seq_no == 0xffff)
1516 		seq_no = 1;
1517 	else if (seq_no)
1518 		seq_no++;
1519 	ni->mrec->sequence_number = cpu_to_le16(seq_no);
1520 
1521 	/* Set the inode dirty and write it out. */
1522 	ntfs_inode_mark_dirty(ni);
1523 	if (ntfs_inode_sync(ni)) {
1524 		err = errno;
1525 		goto sync_rollback;
1526 	}
1527 
1528 	/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
1529 	if (ntfs_bitmap_clear_bit(vol->mftbmp_na, mft_no)) {
1530 		err = errno;
1531 		// FIXME: If ntfs_bitmap_clear_run() guarantees rollback on
1532 		//	  error, this could be changed to goto sync_rollback;
1533 		goto bitmap_rollback;
1534 	}
1535 
1536 	/* Throw away the now freed inode. */
1537 	if (!ntfs_inode_close(ni))
1538 		return 0;
1539 	err = errno;
1540 
1541 	/* Rollback what we did... */
1542 bitmap_rollback:
1543 	if (ntfs_bitmap_set_bit(vol->mftbmp_na, mft_no))
1544 		ntfs_log_debug("Eeek! Rollback failed in ntfs_mft_record_free().  "
1545 				"Leaving inconsistent metadata!\n");
1546 sync_rollback:
1547 	ni->mrec->flags |= MFT_RECORD_IN_USE;
1548 	ni->mrec->sequence_number = old_seq_no;
1549 	ntfs_inode_mark_dirty(ni);
1550 	errno = err;
1551 	return -1;
1552 }
1553 
1554 /**
1555  * ntfs_mft_usn_dec - Decrement USN by one
1556  * @mrec:	pointer to an mft record
1557  *
1558  * On success return 0 and on error return -1 with errno set.
1559  */
1560 int ntfs_mft_usn_dec(MFT_RECORD *mrec)
1561 {
1562 	u16 usn, *usnp;
1563 
1564 	if (!mrec) {
1565 		errno = EINVAL;
1566 		return -1;
1567 	}
1568 	usnp = (u16 *)((char *)mrec + le16_to_cpu(mrec->usa_ofs));
1569 	usn = le16_to_cpup(usnp);
1570 	if (usn-- <= 1)
1571 		usn = 0xfffe;
1572 	*usnp = cpu_to_le16(usn);
1573 
1574 	return 0;
1575 }
1576 
1577