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