xref: /haiku/src/add-ons/kernel/file_systems/ntfs/utils/mkntfs.c (revision 25a7b01d15612846f332751841da3579db313082)
1 /**
2  * mkntfs - Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2011 Anton Altaparmakov
5  * Copyright (c) 2001-2005 Richard Russon
6  * Copyright (c) 2002-2006 Szabolcs Szakacsits
7  * Copyright (c) 2005      Erik Sornes
8  * Copyright (c) 2007      Yura Pakhuchiy
9  * Copyright (c) 2010      Jean-Pierre Andre
10  *
11  * This utility will create an NTFS 1.2 or 3.1 volume on a user
12  * specified (block) device.
13  *
14  * Some things (option handling and determination of mount status) have been
15  * adapted from e2fsprogs-1.19 and lib/ext2fs/ismounted.c and misc/mke2fs.c in
16  * particular.
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program (in the main directory of the Linux-NTFS source
30  * in the file COPYING); if not, write to the Free Software Foundation,
31  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
32  */
33 
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37 
38 #ifdef  HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #ifdef HAVE_STDIO_H
45 #include <stdio.h>
46 #endif
47 #ifdef HAVE_STDARG_H
48 #include <stdarg.h>
49 #endif
50 #ifdef HAVE_STRING_H
51 #include <string.h>
52 #endif
53 #ifdef HAVE_ERRNO_H
54 #include <errno.h>
55 #endif
56 #ifdef HAVE_TIME_H
57 #include <time.h>
58 #endif
59 #ifdef HAVE_SYS_STAT_H
60 #include <sys/stat.h>
61 #endif
62 #ifdef HAVE_FCNTL_H
63 #include <fcntl.h>
64 #endif
65 #ifdef HAVE_LIMITS_H
66 #include <limits.h>
67 #endif
68 #ifdef HAVE_LIBGEN_H
69 #include <libgen.h>
70 #endif
71 #ifdef ENABLE_UUID
72 #include <uuid/uuid.h>
73 #endif
74 
75 
76 #ifdef HAVE_GETOPT_H
77 #include <getopt.h>
78 #else
79 	extern char *optarg;
80 	extern int optind;
81 #endif
82 
83 #ifdef HAVE_LINUX_MAJOR_H
84 #	include <linux/major.h>
85 #	ifndef MAJOR
86 #		define MAJOR(dev)	((dev) >> 8)
87 #		define MINOR(dev)	((dev) & 0xff)
88 #	endif
89 #	ifndef IDE_DISK_MAJOR
90 #		ifndef IDE0_MAJOR
91 #			define IDE0_MAJOR	3
92 #			define IDE1_MAJOR	22
93 #			define IDE2_MAJOR	33
94 #			define IDE3_MAJOR	34
95 #			define IDE4_MAJOR	56
96 #			define IDE5_MAJOR	57
97 #			define IDE6_MAJOR	88
98 #			define IDE7_MAJOR	89
99 #			define IDE8_MAJOR	90
100 #			define IDE9_MAJOR	91
101 #		endif
102 #		define IDE_DISK_MAJOR(M) \
103 				((M) == IDE0_MAJOR || (M) == IDE1_MAJOR || \
104 				(M) == IDE2_MAJOR || (M) == IDE3_MAJOR || \
105 				(M) == IDE4_MAJOR || (M) == IDE5_MAJOR || \
106 				(M) == IDE6_MAJOR || (M) == IDE7_MAJOR || \
107 				(M) == IDE8_MAJOR || (M) == IDE9_MAJOR)
108 #	endif
109 #	ifndef SCSI_DISK_MAJOR
110 #		ifndef SCSI_DISK0_MAJOR
111 #			define SCSI_DISK0_MAJOR	8
112 #			define SCSI_DISK1_MAJOR	65
113 #			define SCSI_DISK7_MAJOR	71
114 #		endif
115 #		define SCSI_DISK_MAJOR(M) \
116 				((M) == SCSI_DISK0_MAJOR || \
117 				((M) >= SCSI_DISK1_MAJOR && \
118 				(M) <= SCSI_DISK7_MAJOR))
119 #	endif
120 #endif
121 
122 #include "security.h"
123 #include "types.h"
124 #include "attrib.h"
125 #include "bitmap.h"
126 #include "bootsect.h"
127 #include "device.h"
128 #include "dir.h"
129 #include "mft.h"
130 #include "mst.h"
131 #include "runlist.h"
132 #include "utils.h"
133 #include "ntfstime.h"
134 #include "sd.h"
135 #include "boot.h"
136 #include "attrdef.h"
137 /* #include "version.h" */
138 #include "logging.h"
139 #include "support.h"
140 #include "unistr.h"
141 #include "misc.h"
142 
143 int	mkntfs_main(const char *devpath, const char *label);
144 
145 typedef enum { WRITE_STANDARD, WRITE_BITMAP, WRITE_LOGFILE } WRITE_TYPE;
146 
147 #ifdef NO_NTFS_DEVICE_DEFAULT_IO_OPS
148 #error "No default device io operations!  Cannot build mkntfs.  \
149 You need to run ./configure without the --disable-default-device-io-ops \
150 switch if you want to be able to build the NTFS utilities."
151 #endif
152 
153 /* Page size on ia32. Can change to 8192 on Alpha. */
154 #define NTFS_PAGE_SIZE	4096
155 
156 //static char EXEC_NAME[] = "mkntfs";
157 
158 struct BITMAP_ALLOCATION {
159 	struct BITMAP_ALLOCATION *next;
160 	LCN	lcn;		/* first allocated cluster */
161 	s64	length;		/* count of consecutive clusters */
162 } ;
163 
164 /**
165  * global variables
166  */
167 static u8		  *g_buf		  = NULL;
168 static int		   g_mft_bitmap_byte_size = 0;
169 static u8		  *g_mft_bitmap		  = NULL;
170 static int		   g_lcn_bitmap_byte_size = 0;
171 static int		   g_dynamic_buf_size	  = 0;
172 static u8		  *g_dynamic_buf	  = NULL;
173 static runlist		  *g_rl_mft		  = NULL;
174 static runlist		  *g_rl_mft_bmp		  = NULL;
175 static runlist		  *g_rl_mftmirr		  = NULL;
176 static runlist		  *g_rl_logfile		  = NULL;
177 static runlist		  *g_rl_boot		  = NULL;
178 static runlist		  *g_rl_bad		  = NULL;
179 static INDEX_ALLOCATION  *g_index_block	  = NULL;
180 static ntfs_volume	  *g_vol		  = NULL;
181 static int		   g_mft_size		  = 0;
182 static long long	   g_mft_lcn		  = 0;		/* lcn of $MFT, $DATA attribute */
183 static long long	   g_mftmirr_lcn	  = 0;		/* lcn of $MFTMirr, $DATA */
184 static long long	   g_logfile_lcn	  = 0;		/* lcn of $LogFile, $DATA */
185 static int		   g_logfile_size	  = 0;		/* in bytes, determined from volume_size */
186 static long long	   g_mft_zone_end	  = 0;		/* Determined from volume_size and mft_zone_multiplier, in clusters */
187 static long long	   g_num_bad_blocks	  = 0;		/* Number of bad clusters */
188 static long long	  *g_bad_blocks		  = NULL;	/* Array of bad clusters */
189 
190 static struct BITMAP_ALLOCATION *g_allocation	  = NULL;	/* Head of cluster allocations */
191 
192 /**
193  * struct mkntfs_options
194  */
195 static struct mkntfs_options {
196 	char *dev_name;			/* Name of the device, or file, to use */
197 	BOOL enable_compression;	/* -C, enables compression of all files on the volume by default. */
198 	BOOL quick_format;		/* -f or -Q, fast format, don't zero the volume first. */
199 	BOOL force;			/* -F, force fs creation. */
200 	long heads;			/* -H, number of heads on device */
201 	BOOL disable_indexing;		/* -I, disables indexing of file contents on the volume by default. */
202 	BOOL no_action;			/* -n, do not write to device, only display what would be done. */
203 	long long part_start_sect;	/* -p, start sector of partition on parent device */
204 	long sector_size;		/* -s, in bytes, power of 2, default is 512 bytes. */
205 	long sectors_per_track;		/* -S, number of sectors per track on device */
206 	BOOL use_epoch_time;		/* -T, fake the time to be 00:00:00 UTC, Jan 1, 1970. */
207 	long mft_zone_multiplier;	/* -z, value from 1 to 4. Default is 1. */
208 	long long num_sectors;		/* size of device in sectors */
209 	long cluster_size;		/* -c, format with this cluster-size */
210 	BOOL with_uuid;			/* -U, request setting an uuid */
211 	char *label;			/* -L, volume label */
212 } opts;
213 
214 /*
215  *		Mark a run of clusters as allocated
216  *
217  *	Returns FALSE if unsuccessful
218  */
219 
220 static BOOL bitmap_allocate(LCN lcn, s64 length)
221 {
222 	BOOL done;
223 	struct BITMAP_ALLOCATION *p;
224 	struct BITMAP_ALLOCATION *q;
225 	struct BITMAP_ALLOCATION *newall;
226 
227 	done = TRUE;
228 	if (length) {
229 		p = g_allocation;
230 		q = (struct BITMAP_ALLOCATION*)NULL;
231 		/* locate the first run which starts beyond the requested lcn */
232 		while (p && (p->lcn <= lcn)) {
233 			q = p;
234 			p = p->next;
235 		}
236 		/* make sure the requested lcns were not allocated */
237 		if ((q && ((q->lcn + q->length) > lcn))
238 		   || (p && ((lcn + length) > p->lcn))) {
239 			ntfs_log_error("Bitmap allocation error\n");
240 			done = FALSE;
241 		}
242 		if (q && ((q->lcn + q->length) == lcn)) {
243 			/* extend current run, no overlapping possible */
244 			q->length += length;
245 		} else {
246 			newall = (struct BITMAP_ALLOCATION*)
247 				    ntfs_malloc(sizeof(struct BITMAP_ALLOCATION));
248 			if (newall) {
249 				newall->lcn = lcn;
250 				newall->length = length;
251 				newall->next = p;
252 				if (q) q->next = newall;
253 				else g_allocation = newall;
254 			} else {
255 				done = FALSE;
256 				ntfs_log_perror("Not enough memory");
257 			}
258 		}
259 	}
260 	return (done);
261 }
262 
263 /*
264  *		Mark a run of cluster as not allocated
265  *
266  *	Returns FALSE if unsuccessful
267  *		(freeing free clusters is not considered as an error)
268  */
269 
270 static BOOL bitmap_deallocate(LCN lcn, s64 length)
271 {
272 	BOOL done;
273 	struct BITMAP_ALLOCATION *p;
274 	struct BITMAP_ALLOCATION *q;
275 	LCN first, last;
276 	s64 begin_length, end_length;
277 
278 	done = TRUE;
279 	if (length) {
280 		p = g_allocation;
281 		q = (struct BITMAP_ALLOCATION*)NULL;
282 			/* locate a run which has a common portion */
283 		while (p) {
284 			first = (p->lcn > lcn ? p->lcn : lcn);
285 			last = ((p->lcn + p->length) < (lcn + length)
286 				? p->lcn + p->length : lcn + length);
287 			if (first < last) {
288 					/* get the parts which must be kept */
289 				begin_length = first - p->lcn;
290 				end_length = p->lcn + p->length - last;
291 					/* delete the entry */
292 				if (q)
293 					q->next = p->next;
294 				else
295 					g_allocation = p->next;
296 				free(p);
297 				/* reallocate the beginning and the end */
298 				if (begin_length
299 				    && !bitmap_allocate(first - begin_length,
300 							begin_length))
301 					done = FALSE;
302 				if (end_length
303 				    && !bitmap_allocate(last, end_length))
304 					done = FALSE;
305 					/* restart a full search */
306 				p = g_allocation;
307 				q = (struct BITMAP_ALLOCATION*)NULL;
308 			} else {
309 				q = p;
310 				p = p->next;
311 			}
312 		}
313 	}
314 	return (done);
315 }
316 
317 /*
318  *		Get the allocation status of a single cluster
319  *	and mark as allocated
320  *
321  *	Returns 1 if the cluster was previously allocated
322  */
323 
324 static int bitmap_get_and_set(LCN lcn, unsigned long length)
325 {
326 	struct BITMAP_ALLOCATION *p;
327 	struct BITMAP_ALLOCATION *q;
328 	int bit;
329 
330 	if (length == 1) {
331 		p = g_allocation;
332 		q = (struct BITMAP_ALLOCATION*)NULL;
333 		/* locate the first run which starts beyond the requested lcn */
334 		while (p && (p->lcn <= lcn)) {
335 			q = p;
336 			p = p->next;
337 		}
338 		if (q && (q->lcn <= lcn) && ((q->lcn + q->length) > lcn))
339 			bit = 1; /* was allocated */
340 		else {
341 			bitmap_allocate(lcn, length);
342 			bit = 0;
343 		}
344 	} else {
345 		ntfs_log_error("Can only allocate a single cluster at a time\n");
346 		bit = 0;
347 	}
348 	return (bit);
349 }
350 
351 /*
352  *		Build a section of the bitmap according to allocation
353  */
354 
355 static void bitmap_build(u8 *buf, LCN lcn, s64 length)
356 {
357 	struct BITMAP_ALLOCATION *p;
358 	LCN first, last;
359 	int j; /* byte number */
360 	int bn; /* bit number */
361 
362 	for (j=0; (8*j)<length; j++)
363 		buf[j] = 0;
364 	for (p=g_allocation; p; p=p->next) {
365 		first = (p->lcn > lcn ? p->lcn : lcn);
366 		last = ((p->lcn + p->length) < (lcn + length)
367 			? p->lcn + p->length : lcn + length);
368 		if (first < last) {
369 			bn = first - lcn;
370 				/* initial partial byte, if any */
371 			while ((bn < (last - lcn)) && (bn & 7)) {
372 				buf[bn >> 3] |= 1 << (bn & 7);
373 				bn++;
374 			}
375 				/* full bytes */
376 			while (bn < (last - lcn - 7)) {
377 				buf[bn >> 3] = 255;
378 				bn += 8;
379 			}
380 				/* final partial byte, if any */
381 			while (bn < (last - lcn)) {
382 				buf[bn >> 3] |= 1 << (bn & 7);
383 				bn++;
384 			}
385 		}
386 	}
387 }
388 
389 /**
390  * mkntfs_init_options
391  */
392 static void mkntfs_init_options(struct mkntfs_options *opts2)
393 {
394 	if (!opts2)
395 		return;
396 
397 	memset(opts2, 0, sizeof(*opts2));
398 
399 	/* Mark all the numeric options as "unset". */
400 	opts2->cluster_size		= -1;
401 	opts2->heads			= -1;
402 	opts2->mft_zone_multiplier	= -1;
403 	opts2->num_sectors		= -1;
404 	opts2->part_start_sect		= -1;
405 	opts2->sector_size		= -1;
406 	opts2->sectors_per_track	= -1;
407 }
408 
409 /**
410  * mkntfs_time
411  */
412 static ntfs_time mkntfs_time(void)
413 {
414 	struct timespec ts;
415 
416 	ts.tv_sec = 0;
417 	ts.tv_nsec = 0;
418 	if (!opts.use_epoch_time)
419 		ts.tv_sec = time(NULL);
420 	return timespec2ntfs(ts);
421 }
422 
423 /**
424  * append_to_bad_blocks
425  */
426 static BOOL append_to_bad_blocks(unsigned long long block)
427 {
428 	long long *new_buf;
429 
430 	if (!(g_num_bad_blocks & 15)) {
431 		new_buf = realloc(g_bad_blocks, (g_num_bad_blocks + 16) *
432 							sizeof(long long));
433 		if (!new_buf) {
434 			ntfs_log_perror("Reallocating memory for bad blocks "
435 				"list failed");
436 			return FALSE;
437 		}
438 		g_bad_blocks = new_buf;
439 	}
440 	g_bad_blocks[g_num_bad_blocks++] = block;
441 	return TRUE;
442 }
443 
444 /**
445  * mkntfs_write
446  */
447 static long long mkntfs_write(struct ntfs_device *dev,
448 		const void *b, long long count)
449 {
450 	long long bytes_written, total;
451 	int retry;
452 
453 	if (opts.no_action)
454 		return count;
455 	total = 0LL;
456 	retry = 0;
457 	do {
458 		bytes_written = dev->d_ops->write(dev, b, count);
459 		if (bytes_written == -1LL) {
460 			retry = errno;
461 			ntfs_log_perror("Error writing to %s", dev->d_name);
462 			errno = retry;
463 			return bytes_written;
464 		} else if (!bytes_written) {
465 			retry++;
466 		} else {
467 			count -= bytes_written;
468 			total += bytes_written;
469 		}
470 	} while (count && retry < 3);
471 	if (count)
472 		ntfs_log_error("Failed to complete writing to %s after three retries."
473 			"\n", dev->d_name);
474 	return total;
475 }
476 
477 /**
478  *		Build and write a part of the global bitmap
479  *	without overflowing from the allocated buffer
480  *
481  * mkntfs_bitmap_write
482  */
483 static s64 mkntfs_bitmap_write(struct ntfs_device *dev,
484 			s64 offset, s64 length)
485 {
486 	s64 partial_length;
487 	s64 written;
488 
489 	partial_length = length;
490 	if (partial_length > g_dynamic_buf_size)
491 		partial_length = g_dynamic_buf_size;
492 		/* create a partial bitmap section, and write it */
493 	bitmap_build(g_dynamic_buf,offset << 3,partial_length << 3);
494 	written = dev->d_ops->write(dev, g_dynamic_buf, partial_length);
495 	return (written);
496 }
497 
498 /**
499  *		Build and write a part of the log file
500  *	without overflowing from the allocated buffer
501  *
502  * mkntfs_logfile_write
503  */
504 static s64 mkntfs_logfile_write(struct ntfs_device *dev,
505 			s64 offset __attribute__((unused)), s64 length)
506 {
507 	s64 partial_length;
508 	s64 written;
509 
510 	partial_length = length;
511 	if (partial_length > g_dynamic_buf_size)
512 		partial_length = g_dynamic_buf_size;
513 		/* create a partial bad cluster section, and write it */
514 	memset(g_dynamic_buf, -1, partial_length);
515 	written = dev->d_ops->write(dev, g_dynamic_buf, partial_length);
516 	return (written);
517 }
518 
519 /**
520  * ntfs_rlwrite - Write to disk the clusters contained in the runlist @rl
521  * taking the data from @val.  Take @val_len bytes from @val and pad the
522  * rest with zeroes.
523  *
524  * If the @rl specifies a completely sparse file, @val is allowed to be NULL.
525  *
526  * @inited_size if not NULL points to an output variable which will contain
527  * the actual number of bytes written to disk. I.e. this will not include
528  * sparse bytes for example.
529  *
530  * Return the number of bytes written (minus padding) or -1 on error. Errno
531  * will be set to the error code.
532  */
533 static s64 ntfs_rlwrite(struct ntfs_device *dev, const runlist *rl,
534 		const u8 *val, const s64 val_len, s64 *inited_size,
535 		WRITE_TYPE write_type)
536 {
537 	s64 bytes_written, total, length, delta;
538 	int retry, i;
539 
540 	if (inited_size)
541 		*inited_size = 0LL;
542 	if (opts.no_action)
543 		return val_len;
544 	total = 0LL;
545 	delta = 0LL;
546 	for (i = 0; rl[i].length; i++) {
547 		length = rl[i].length * g_vol->cluster_size;
548 		/* Don't write sparse runs. */
549 		if (rl[i].lcn == -1) {
550 			total += length;
551 			if (!val)
552 				continue;
553 			/* TODO: Check that *val is really zero at pos and len. */
554 			continue;
555 		}
556 		/*
557 		 * Break up the write into the real data write and then a write
558 		 * of zeroes between the end of the real data and the end of
559 		 * the (last) run.
560 		 */
561 		if (total + length > val_len) {
562 			delta = length;
563 			length = val_len - total;
564 			delta -= length;
565 		}
566 		if (dev->d_ops->seek(dev, rl[i].lcn * g_vol->cluster_size,
567 				SEEK_SET) == (off_t)-1)
568 			return -1LL;
569 		retry = 0;
570 		do {
571 			/* use specific functions if buffer is not prefilled */
572 			switch (write_type) {
573 			case WRITE_BITMAP :
574 				bytes_written = mkntfs_bitmap_write(dev,
575 					total, length);
576 				break;
577 			case WRITE_LOGFILE :
578 				bytes_written = mkntfs_logfile_write(dev,
579 					total, length);
580 				break;
581 			default :
582 				bytes_written = dev->d_ops->write(dev,
583 					val + total, length);
584 				break;
585 			}
586 			if (bytes_written == -1LL) {
587 				retry = errno;
588 				ntfs_log_perror("Error writing to %s",
589 					dev->d_name);
590 				errno = retry;
591 				return bytes_written;
592 			}
593 			if (bytes_written) {
594 				length -= bytes_written;
595 				total += bytes_written;
596 				if (inited_size)
597 					*inited_size += bytes_written;
598 			} else {
599 				retry++;
600 			}
601 		} while (length && retry < 3);
602 		if (length) {
603 			ntfs_log_error("Failed to complete writing to %s after three "
604 					"retries.\n", dev->d_name);
605 			return total;
606 		}
607 	}
608 	if (delta) {
609 		int eo;
610 		char *b = ntfs_calloc(delta);
611 		if (!b)
612 			return -1;
613 		bytes_written = mkntfs_write(dev, b, delta);
614 		eo = errno;
615 		free(b);
616 		errno = eo;
617 		if (bytes_written == -1LL)
618 			return bytes_written;
619 	}
620 	return total;
621 }
622 
623 /**
624  * make_room_for_attribute - make room for an attribute inside an mft record
625  * @m:		mft record
626  * @pos:	position at which to make space
627  * @size:	byte size to make available at this position
628  *
629  * @pos points to the attribute in front of which we want to make space.
630  *
631  * Return 0 on success or -errno on error. Possible error codes are:
632  *
633  *	-ENOSPC		There is not enough space available to complete
634  *			operation. The caller has to make space before calling
635  *			this.
636  *	-EINVAL		Can only occur if mkntfs was compiled with -DDEBUG. Means
637  *			the input parameters were faulty.
638  */
639 static int make_room_for_attribute(MFT_RECORD *m, char *pos, const u32 size)
640 {
641 	u32 biu;
642 
643 	if (!size)
644 		return 0;
645 #ifdef DEBUG
646 	/*
647 	 * Rigorous consistency checks. Always return -EINVAL even if more
648 	 * appropriate codes exist for simplicity of parsing the return value.
649 	 */
650 	if (size != ((size + 7) & ~7)) {
651 		ntfs_log_error("make_room_for_attribute() received non 8-byte aligned "
652 				"size.\n");
653 		return -EINVAL;
654 	}
655 	if (!m || !pos)
656 		return -EINVAL;
657 	if (pos < (char*)m || pos + size < (char*)m ||
658 			pos > (char*)m + le32_to_cpu(m->bytes_allocated) ||
659 			pos + size > (char*)m + le32_to_cpu(m->bytes_allocated))
660 		return -EINVAL;
661 	/* The -8 is for the attribute terminator. */
662 	if (pos - (char*)m > (int)le32_to_cpu(m->bytes_in_use) - 8)
663 		return -EINVAL;
664 #endif
665 	biu = le32_to_cpu(m->bytes_in_use);
666 	/* Do we have enough space? */
667 	if (biu + size > le32_to_cpu(m->bytes_allocated))
668 		return -ENOSPC;
669 	/* Move everything after pos to pos + size. */
670 	memmove(pos + size, pos, biu - (pos - (char*)m));
671 	/* Update mft record. */
672 	m->bytes_in_use = cpu_to_le32(biu + size);
673 	return 0;
674 }
675 
676 /**
677  * deallocate_scattered_clusters
678  */
679 static void deallocate_scattered_clusters(const runlist *rl)
680 {
681 	int i;
682 
683 	if (!rl)
684 		return;
685 	/* Iterate over all runs in the runlist @rl. */
686 	for (i = 0; rl[i].length; i++) {
687 		/* Skip sparse runs. */
688 		if (rl[i].lcn == -1LL)
689 			continue;
690 		/* Deallocate the current run. */
691 		bitmap_deallocate(rl[i].lcn, rl[i].length);
692 	}
693 }
694 
695 /**
696  * allocate_scattered_clusters
697  * @clusters: Amount of clusters to allocate.
698  *
699  * Allocate @clusters and create a runlist of the allocated clusters.
700  *
701  * Return the allocated runlist. Caller has to free the runlist when finished
702  * with it.
703  *
704  * On error return NULL and errno is set to the error code.
705  *
706  * TODO: We should be returning the size as well, but for mkntfs this is not
707  * necessary.
708  */
709 static runlist * allocate_scattered_clusters(s64 clusters)
710 {
711 	runlist *rl = NULL, *rlt;
712 	VCN vcn = 0LL;
713 	LCN lcn, end, prev_lcn = 0LL;
714 	int rlpos = 0;
715 	int rlsize = 0;
716 	s64 prev_run_len = 0LL;
717 	char bit;
718 
719 	end = g_vol->nr_clusters;
720 	/* Loop until all clusters are allocated. */
721 	while (clusters) {
722 		/* Loop in current zone until we run out of free clusters. */
723 		for (lcn = g_mft_zone_end; lcn < end; lcn++) {
724 			bit = bitmap_get_and_set(lcn,1);
725 			if (bit)
726 				continue;
727 			/*
728 			 * Reallocate memory if necessary. Make sure we have
729 			 * enough for the terminator entry as well.
730 			 */
731 			if ((rlpos + 2) * (int)sizeof(runlist) >= rlsize) {
732 				rlsize += 4096; /* PAGE_SIZE */
733 				rlt = realloc(rl, rlsize);
734 				if (!rlt)
735 					goto err_end;
736 				rl = rlt;
737 			}
738 			/* Coalesce with previous run if adjacent LCNs. */
739 			if (prev_lcn == lcn - prev_run_len) {
740 				rl[rlpos - 1].length = ++prev_run_len;
741 				vcn++;
742 			} else {
743 				rl[rlpos].vcn = vcn++;
744 				rl[rlpos].lcn = lcn;
745 				prev_lcn = lcn;
746 				rl[rlpos].length = 1LL;
747 				prev_run_len = 1LL;
748 				rlpos++;
749 			}
750 			/* Done? */
751 			if (!--clusters) {
752 				/* Add terminator element and return. */
753 				rl[rlpos].vcn = vcn;
754 				rl[rlpos].lcn = 0LL;
755 				rl[rlpos].length = 0LL;
756 				return rl;
757 			}
758 
759 		}
760 		/* Switch to next zone, decreasing mft zone by factor 2. */
761 		end = g_mft_zone_end;
762 		g_mft_zone_end >>= 1;
763 		/* Have we run out of space on the volume? */
764 		if (g_mft_zone_end <= 0)
765 			goto err_end;
766 	}
767 	return rl;
768 err_end:
769 	if (rl) {
770 		/* Add terminator element. */
771 		rl[rlpos].vcn = vcn;
772 		rl[rlpos].lcn = -1LL;
773 		rl[rlpos].length = 0LL;
774 		/* Deallocate all allocated clusters. */
775 		deallocate_scattered_clusters(rl);
776 		/* Free the runlist. */
777 		free(rl);
778 	}
779 	return NULL;
780 }
781 
782 /**
783  * ntfs_attr_find - find (next) attribute in mft record
784  * @type:	attribute type to find
785  * @name:	attribute name to find (optional, i.e. NULL means don't care)
786  * @name_len:	attribute name length (only needed if @name present)
787  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
788  * @val:	attribute value to find (optional, resident attributes only)
789  * @val_len:	attribute value length
790  * @ctx:	search context with mft record and attribute to search from
791  *
792  * You shouldn't need to call this function directly. Use lookup_attr() instead.
793  *
794  * ntfs_attr_find() takes a search context @ctx as parameter and searches the
795  * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
796  * attribute of @type, optionally @name and @val. If found, ntfs_attr_find()
797  * returns 0 and @ctx->attr will point to the found attribute.
798  *
799  * If not found, ntfs_attr_find() returns -1, with errno set to ENOENT and
800  * @ctx->attr will point to the attribute before which the attribute being
801  * searched for would need to be inserted if such an action were to be desired.
802  *
803  * On actual error, ntfs_attr_find() returns -1 with errno set to the error
804  * code but not to ENOENT.  In this case @ctx->attr is undefined and in
805  * particular do not rely on it not changing.
806  *
807  * If @ctx->is_first is TRUE, the search begins with @ctx->attr itself. If it
808  * is FALSE, the search begins after @ctx->attr.
809  *
810  * If @type is AT_UNUSED, return the first found attribute, i.e. one can
811  * enumerate all attributes by setting @type to AT_UNUSED and then calling
812  * ntfs_attr_find() repeatedly until it returns -1 with errno set to ENOENT to
813  * indicate that there are no more entries. During the enumeration, each
814  * successful call of ntfs_attr_find() will return the next attribute in the
815  * mft record @ctx->mrec.
816  *
817  * If @type is AT_END, seek to the end and return -1 with errno set to ENOENT.
818  * AT_END is not a valid attribute, its length is zero for example, thus it is
819  * safer to return error instead of success in this case. This also allows us
820  * to interoperate cleanly with ntfs_external_attr_find().
821  *
822  * If @name is AT_UNNAMED search for an unnamed attribute. If @name is present
823  * but not AT_UNNAMED search for a named attribute matching @name. Otherwise,
824  * match both named and unnamed attributes.
825  *
826  * If @ic is IGNORE_CASE, the @name comparison is not case sensitive and
827  * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
828  * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
829  * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
830  * sensitive. When @name is present, @name_len is the @name length in Unicode
831  * characters.
832  *
833  * If @name is not present (NULL), we assume that the unnamed attribute is
834  * being searched for.
835  *
836  * Finally, the resident attribute value @val is looked for, if present.
837  * If @val is not present (NULL), @val_len is ignored.
838  *
839  * ntfs_attr_find() only searches the specified mft record and it ignores the
840  * presence of an attribute list attribute (unless it is the one being searched
841  * for, obviously). If you need to take attribute lists into consideration, use
842  * ntfs_attr_lookup() instead (see below). This also means that you cannot use
843  * ntfs_attr_find() to search for extent records of non-resident attributes, as
844  * extents with lowest_vcn != 0 are usually described by the attribute list
845  * attribute only. - Note that it is possible that the first extent is only in
846  * the attribute list while the last extent is in the base mft record, so don't
847  * rely on being able to find the first extent in the base mft record.
848  *
849  * Warning: Never use @val when looking for attribute types which can be
850  *	    non-resident as this most likely will result in a crash!
851  */
852 static int mkntfs_attr_find(const ATTR_TYPES type, const ntfschar *name,
853 		const u32 name_len, const IGNORE_CASE_BOOL ic,
854 		const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
855 {
856 	ATTR_RECORD *a;
857 	ntfschar *upcase = g_vol->upcase;
858 	u32 upcase_len = g_vol->upcase_len;
859 
860 	/*
861 	 * Iterate over attributes in mft record starting at @ctx->attr, or the
862 	 * attribute following that, if @ctx->is_first is TRUE.
863 	 */
864 	if (ctx->is_first) {
865 		a = ctx->attr;
866 		ctx->is_first = FALSE;
867 	} else {
868 		a = (ATTR_RECORD*)((char*)ctx->attr +
869 				le32_to_cpu(ctx->attr->length));
870 	}
871 	for (;;	a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) {
872 		if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec +
873 				le32_to_cpu(ctx->mrec->bytes_allocated))
874 			break;
875 		ctx->attr = a;
876 		if (((type != AT_UNUSED) && (le32_to_cpu(a->type) >
877 				le32_to_cpu(type))) ||
878 				(a->type == AT_END)) {
879 			errno = ENOENT;
880 			return -1;
881 		}
882 		if (!a->length)
883 			break;
884 		/* If this is an enumeration return this attribute. */
885 		if (type == AT_UNUSED)
886 			return 0;
887 		if (a->type != type)
888 			continue;
889 		/*
890 		 * If @name is AT_UNNAMED we want an unnamed attribute.
891 		 * If @name is present, compare the two names.
892 		 * Otherwise, match any attribute.
893 		 */
894 		if (name == AT_UNNAMED) {
895 			/* The search failed if the found attribute is named. */
896 			if (a->name_length) {
897 				errno = ENOENT;
898 				return -1;
899 			}
900 		} else if (name && !ntfs_names_are_equal(name, name_len,
901 				(ntfschar*)((char*)a + le16_to_cpu(a->name_offset)),
902 				a->name_length, ic, upcase, upcase_len)) {
903 			int rc;
904 
905 			rc = ntfs_names_full_collate(name, name_len,
906 					(ntfschar*)((char*)a +
907 					le16_to_cpu(a->name_offset)),
908 					a->name_length, IGNORE_CASE,
909 					upcase, upcase_len);
910 			/*
911 			 * If @name collates before a->name, there is no
912 			 * matching attribute.
913 			 */
914 			if (rc == -1) {
915 				errno = ENOENT;
916 				return -1;
917 			}
918 			/* If the strings are not equal, continue search. */
919 			if (rc)
920 				continue;
921 			rc = ntfs_names_full_collate(name, name_len,
922 					(ntfschar*)((char*)a +
923 					le16_to_cpu(a->name_offset)),
924 					a->name_length, CASE_SENSITIVE,
925 					upcase, upcase_len);
926 			if (rc == -1) {
927 				errno = ENOENT;
928 				return -1;
929 			}
930 			if (rc)
931 				continue;
932 		}
933 		/*
934 		 * The names match or @name not present and attribute is
935 		 * unnamed. If no @val specified, we have found the attribute
936 		 * and are done.
937 		 */
938 		if (!val) {
939 			return 0;
940 		/* @val is present; compare values. */
941 		} else {
942 			int rc;
943 
944 			rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset),
945 					min(val_len,
946 					le32_to_cpu(a->value_length)));
947 			/*
948 			 * If @val collates before the current attribute's
949 			 * value, there is no matching attribute.
950 			 */
951 			if (!rc) {
952 				u32 avl;
953 				avl = le32_to_cpu(a->value_length);
954 				if (val_len == avl)
955 					return 0;
956 				if (val_len < avl) {
957 					errno = ENOENT;
958 					return -1;
959 				}
960 			} else if (rc < 0) {
961 				errno = ENOENT;
962 				return -1;
963 			}
964 		}
965 	}
966 	ntfs_log_trace("File is corrupt. Run chkdsk.\n");
967 	errno = EIO;
968 	return -1;
969 }
970 
971 /**
972  * ntfs_attr_lookup - find an attribute in an ntfs inode
973  * @type:	attribute type to find
974  * @name:	attribute name to find (optional, i.e. NULL means don't care)
975  * @name_len:	attribute name length (only needed if @name present)
976  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
977  * @lowest_vcn:	lowest vcn to find (optional, non-resident attributes only)
978  * @val:	attribute value to find (optional, resident attributes only)
979  * @val_len:	attribute value length
980  * @ctx:	search context with mft record and attribute to search from
981  *
982  * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
983  * be the base mft record and @ctx must have been obtained from a call to
984  * ntfs_attr_get_search_ctx().
985  *
986  * This function transparently handles attribute lists and @ctx is used to
987  * continue searches where they were left off at.
988  *
989  * If @type is AT_UNUSED, return the first found attribute, i.e. one can
990  * enumerate all attributes by setting @type to AT_UNUSED and then calling
991  * ntfs_attr_lookup() repeatedly until it returns -1 with errno set to ENOENT
992  * to indicate that there are no more entries. During the enumeration, each
993  * successful call of ntfs_attr_lookup() will return the next attribute, with
994  * the current attribute being described by the search context @ctx.
995  *
996  * If @type is AT_END, seek to the end of the base mft record ignoring the
997  * attribute list completely and return -1 with errno set to ENOENT.  AT_END is
998  * not a valid attribute, its length is zero for example, thus it is safer to
999  * return error instead of success in this case.  It should never be needed to
1000  * do this, but we implement the functionality because it allows for simpler
1001  * code inside ntfs_external_attr_find().
1002  *
1003  * If @name is AT_UNNAMED search for an unnamed attribute. If @name is present
1004  * but not AT_UNNAMED search for a named attribute matching @name. Otherwise,
1005  * match both named and unnamed attributes.
1006  *
1007  * After finishing with the attribute/mft record you need to call
1008  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1009  * mapped extent inodes, etc).
1010  *
1011  * Return 0 if the search was successful and -1 if not, with errno set to the
1012  * error code.
1013  *
1014  * On success, @ctx->attr is the found attribute, it is in mft record
1015  * @ctx->mrec, and @ctx->al_entry is the attribute list entry for this
1016  * attribute with @ctx->base_* being the base mft record to which @ctx->attr
1017  * belongs.  If no attribute list attribute is present @ctx->al_entry and
1018  * @ctx->base_* are NULL.
1019  *
1020  * On error ENOENT, i.e. attribute not found, @ctx->attr is set to the
1021  * attribute which collates just after the attribute being searched for in the
1022  * base ntfs inode, i.e. if one wants to add the attribute to the mft record
1023  * this is the correct place to insert it into, and if there is not enough
1024  * space, the attribute should be placed in an extent mft record.
1025  * @ctx->al_entry points to the position within @ctx->base_ntfs_ino->attr_list
1026  * at which the new attribute's attribute list entry should be inserted.  The
1027  * other @ctx fields, base_ntfs_ino, base_mrec, and base_attr are set to NULL.
1028  * The only exception to this is when @type is AT_END, in which case
1029  * @ctx->al_entry is set to NULL also (see above).
1030  *
1031  * The following error codes are defined:
1032  *	ENOENT	Attribute not found, not an error as such.
1033  *	EINVAL	Invalid arguments.
1034  *	EIO	I/O error or corrupt data structures found.
1035  *	ENOMEM	Not enough memory to allocate necessary buffers.
1036  */
1037 static int mkntfs_attr_lookup(const ATTR_TYPES type, const ntfschar *name,
1038 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1039 		const VCN lowest_vcn __attribute__((unused)), const u8 *val,
1040 		const u32 val_len, ntfs_attr_search_ctx *ctx)
1041 {
1042 	ntfs_inode *base_ni;
1043 
1044 	if (!ctx || !ctx->mrec || !ctx->attr) {
1045 		errno = EINVAL;
1046 		return -1;
1047 	}
1048 	if (ctx->base_ntfs_ino)
1049 		base_ni = ctx->base_ntfs_ino;
1050 	else
1051 		base_ni = ctx->ntfs_ino;
1052 	if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
1053 		return mkntfs_attr_find(type, name, name_len, ic, val, val_len,
1054 				ctx);
1055 	errno = EOPNOTSUPP;
1056 	return -1;
1057 }
1058 
1059 /**
1060  * insert_positioned_attr_in_mft_record
1061  *
1062  * Create a non-resident attribute with a predefined on disk location
1063  * specified by the runlist @rl. The clusters specified by @rl are assumed to
1064  * be allocated already.
1065  *
1066  * Return 0 on success and -errno on error.
1067  */
1068 static int insert_positioned_attr_in_mft_record(MFT_RECORD *m,
1069 		const ATTR_TYPES type, const char *name, u32 name_len,
1070 		const IGNORE_CASE_BOOL ic, const ATTR_FLAGS flags,
1071 		const runlist *rl, const u8 *val, const s64 val_len)
1072 {
1073 	ntfs_attr_search_ctx *ctx;
1074 	ATTR_RECORD *a;
1075 	u16 hdr_size;
1076 	int asize, mpa_size, err, i;
1077 	s64 bw = 0, inited_size;
1078 	VCN highest_vcn;
1079 	ntfschar *uname = NULL;
1080 	int uname_len = 0;
1081 	/*
1082 	if (base record)
1083 		attr_lookup();
1084 	else
1085 	*/
1086 
1087 	uname = ntfs_str2ucs(name, &uname_len);
1088 	if (!uname)
1089 		return -errno;
1090 
1091 	/* Check if the attribute is already there. */
1092 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1093 	if (!ctx) {
1094 		ntfs_log_error("Failed to allocate attribute search context.\n");
1095 		err = -ENOMEM;
1096 		goto err_out;
1097 	}
1098 	if (ic == IGNORE_CASE) {
1099 		ntfs_log_error("FIXME: Hit unimplemented code path #1.\n");
1100 		err = -EOPNOTSUPP;
1101 		goto err_out;
1102 	}
1103 	if (!mkntfs_attr_lookup(type, uname, uname_len, ic, 0, NULL, 0, ctx)) {
1104 		err = -EEXIST;
1105 		goto err_out;
1106 	}
1107 	if (errno != ENOENT) {
1108 		ntfs_log_error("Corrupt inode.\n");
1109 		err = -errno;
1110 		goto err_out;
1111 	}
1112 	a = ctx->attr;
1113 	if (flags & ATTR_COMPRESSION_MASK) {
1114 		ntfs_log_error("Compressed attributes not supported yet.\n");
1115 		/* FIXME: Compress attribute into a temporary buffer, set */
1116 		/* val accordingly and save the compressed size. */
1117 		err = -EOPNOTSUPP;
1118 		goto err_out;
1119 	}
1120 	if (flags & (ATTR_IS_ENCRYPTED | ATTR_IS_SPARSE)) {
1121 		ntfs_log_error("Encrypted/sparse attributes not supported.\n");
1122 		err = -EOPNOTSUPP;
1123 		goto err_out;
1124 	}
1125 	if (flags & ATTR_COMPRESSION_MASK) {
1126 		hdr_size = 72;
1127 		/* FIXME: This compression stuff is all wrong. Never mind for */
1128 		/* now. (AIA) */
1129 		if (val_len)
1130 			mpa_size = 0; /* get_size_for_compressed_mapping_pairs(rl); */
1131 		else
1132 			mpa_size = 0;
1133 	} else {
1134 		hdr_size = 64;
1135 		if (val_len) {
1136 			mpa_size = ntfs_get_size_for_mapping_pairs(g_vol, rl, 0, INT_MAX);
1137 			if (mpa_size < 0) {
1138 				err = -errno;
1139 				ntfs_log_error("Failed to get size for mapping "
1140 						"pairs.\n");
1141 				goto err_out;
1142 			}
1143 		} else {
1144 			mpa_size = 0;
1145 		}
1146 	}
1147 	/* Mapping pairs array and next attribute must be 8-byte aligned. */
1148 	asize = (((int)hdr_size + ((name_len + 7) & ~7) + mpa_size) + 7) & ~7;
1149 	/* Get the highest vcn. */
1150 	for (i = 0, highest_vcn = 0LL; rl[i].length; i++)
1151 		highest_vcn += rl[i].length;
1152 	/* Does the value fit inside the allocated size? */
1153 	if (highest_vcn * g_vol->cluster_size < val_len) {
1154 		ntfs_log_error("BUG: Allocated size is smaller than data size!\n");
1155 		err = -EINVAL;
1156 		goto err_out;
1157 	}
1158 	err = make_room_for_attribute(m, (char*)a, asize);
1159 	if (err == -ENOSPC) {
1160 		/*
1161 		 * FIXME: Make space! (AIA)
1162 		 * can we make it non-resident? if yes, do that.
1163 		 *	does it fit now? yes -> do it.
1164 		 * m's $DATA or $BITMAP+$INDEX_ALLOCATION resident?
1165 		 * yes -> make non-resident
1166 		 *	does it fit now? yes -> do it.
1167 		 * make all attributes non-resident
1168 		 *	does it fit now? yes -> do it.
1169 		 * m is a base record? yes -> allocate extension record
1170 		 *	does the new attribute fit in there? yes -> do it.
1171 		 * split up runlist into extents and place each in an extension
1172 		 * record.
1173 		 * FIXME: the check for needing extension records should be
1174 		 * earlier on as it is very quick: asize > m->bytes_allocated?
1175 		 */
1176 		err = -EOPNOTSUPP;
1177 		goto err_out;
1178 #ifdef DEBUG
1179 	} else if (err == -EINVAL) {
1180 		ntfs_log_error("BUG(): in insert_positioned_attribute_in_mft_"
1181 				"record(): make_room_for_attribute() returned "
1182 				"error: EINVAL!\n");
1183 		goto err_out;
1184 #endif
1185 	}
1186 	a->type = type;
1187 	a->length = cpu_to_le32(asize);
1188 	a->non_resident = 1;
1189 	a->name_length = name_len;
1190 	a->name_offset = cpu_to_le16(hdr_size);
1191 	a->flags = flags;
1192 	a->instance = m->next_attr_instance;
1193 	m->next_attr_instance = cpu_to_le16((le16_to_cpu(m->next_attr_instance)
1194 			+ 1) & 0xffff);
1195 	a->lowest_vcn = cpu_to_le64(0);
1196 	a->highest_vcn = cpu_to_sle64(highest_vcn - 1LL);
1197 	a->mapping_pairs_offset = cpu_to_le16(hdr_size + ((name_len + 7) & ~7));
1198 	memset(a->reserved1, 0, sizeof(a->reserved1));
1199 	/* FIXME: Allocated size depends on compression. */
1200 	a->allocated_size = cpu_to_sle64(highest_vcn * g_vol->cluster_size);
1201 	a->data_size = cpu_to_sle64(val_len);
1202 	if (name_len)
1203 		memcpy((char*)a + hdr_size, uname, name_len << 1);
1204 	if (flags & ATTR_COMPRESSION_MASK) {
1205 		if (flags & ATTR_COMPRESSION_MASK & ~ATTR_IS_COMPRESSED) {
1206 			ntfs_log_error("Unknown compression format. Reverting "
1207 					"to standard compression.\n");
1208 			a->flags &= ~ATTR_COMPRESSION_MASK;
1209 			a->flags |= ATTR_IS_COMPRESSED;
1210 		}
1211 		a->compression_unit = 4;
1212 		inited_size = val_len;
1213 		/* FIXME: Set the compressed size. */
1214 		a->compressed_size = cpu_to_le64(0);
1215 		/* FIXME: Write out the compressed data. */
1216 		/* FIXME: err = build_mapping_pairs_compressed(); */
1217 		err = -EOPNOTSUPP;
1218 	} else {
1219 		a->compression_unit = 0;
1220 		if ((type == AT_DATA)
1221 		    && (m->mft_record_number
1222 				 == const_cpu_to_le32(FILE_LogFile)))
1223 			bw = ntfs_rlwrite(g_vol->dev, rl, val, val_len,
1224 					&inited_size, WRITE_LOGFILE);
1225 		else
1226 			bw = ntfs_rlwrite(g_vol->dev, rl, val, val_len,
1227 					&inited_size, WRITE_STANDARD);
1228 		if (bw != val_len) {
1229 			ntfs_log_error("Error writing non-resident attribute "
1230 					"value.\n");
1231 			return -errno;
1232 		}
1233 		err = ntfs_mapping_pairs_build(g_vol, (u8*)a + hdr_size +
1234 				((name_len + 7) & ~7), mpa_size, rl, 0, NULL);
1235 	}
1236 	a->initialized_size = cpu_to_sle64(inited_size);
1237 	if (err < 0 || bw != val_len) {
1238 		/* FIXME: Handle error. */
1239 		/* deallocate clusters */
1240 		/* remove attribute */
1241 		if (err >= 0)
1242 			err = -EIO;
1243 		ntfs_log_error("insert_positioned_attr_in_mft_record failed "
1244 				"with error %i.\n", err < 0 ? err : (int)bw);
1245 	}
1246 err_out:
1247 	if (ctx)
1248 		ntfs_attr_put_search_ctx(ctx);
1249 	ntfs_ucsfree(uname);
1250 	return err;
1251 }
1252 
1253 /**
1254  * insert_non_resident_attr_in_mft_record
1255  *
1256  * Return 0 on success and -errno on error.
1257  */
1258 static int insert_non_resident_attr_in_mft_record(MFT_RECORD *m,
1259 		const ATTR_TYPES type, const char *name, u32 name_len,
1260 		const IGNORE_CASE_BOOL ic, const ATTR_FLAGS flags,
1261 		const u8 *val, const s64 val_len,
1262 		WRITE_TYPE write_type)
1263 {
1264 	ntfs_attr_search_ctx *ctx;
1265 	ATTR_RECORD *a;
1266 	u16 hdr_size;
1267 	int asize, mpa_size, err, i;
1268 	runlist *rl = NULL;
1269 	s64 bw = 0;
1270 	ntfschar *uname = NULL;
1271 	int uname_len = 0;
1272 	/*
1273 	if (base record)
1274 		attr_lookup();
1275 	else
1276 	*/
1277 
1278 	uname = ntfs_str2ucs(name, &uname_len);
1279 	if (!uname)
1280 		return -errno;
1281 
1282 	/* Check if the attribute is already there. */
1283 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1284 	if (!ctx) {
1285 		ntfs_log_error("Failed to allocate attribute search context.\n");
1286 		err = -ENOMEM;
1287 		goto err_out;
1288 	}
1289 	if (ic == IGNORE_CASE) {
1290 		ntfs_log_error("FIXME: Hit unimplemented code path #2.\n");
1291 		err = -EOPNOTSUPP;
1292 		goto err_out;
1293 	}
1294 	if (!mkntfs_attr_lookup(type, uname, uname_len, ic, 0, NULL, 0, ctx)) {
1295 		err = -EEXIST;
1296 		goto err_out;
1297 	}
1298 	if (errno != ENOENT) {
1299 		ntfs_log_error("Corrupt inode.\n");
1300 		err = -errno;
1301 		goto err_out;
1302 	}
1303 	a = ctx->attr;
1304 	if (flags & ATTR_COMPRESSION_MASK) {
1305 		ntfs_log_error("Compressed attributes not supported yet.\n");
1306 		/* FIXME: Compress attribute into a temporary buffer, set */
1307 		/* val accordingly and save the compressed size. */
1308 		err = -EOPNOTSUPP;
1309 		goto err_out;
1310 	}
1311 	if (flags & (ATTR_IS_ENCRYPTED | ATTR_IS_SPARSE)) {
1312 		ntfs_log_error("Encrypted/sparse attributes not supported.\n");
1313 		err = -EOPNOTSUPP;
1314 		goto err_out;
1315 	}
1316 	if (val_len) {
1317 		rl = allocate_scattered_clusters((val_len +
1318 				g_vol->cluster_size - 1) / g_vol->cluster_size);
1319 		if (!rl) {
1320 			err = -errno;
1321 			ntfs_log_perror("Failed to allocate scattered clusters");
1322 			goto err_out;
1323 		}
1324 	} else {
1325 		rl = NULL;
1326 	}
1327 	if (flags & ATTR_COMPRESSION_MASK) {
1328 		hdr_size = 72;
1329 		/* FIXME: This compression stuff is all wrong. Never mind for */
1330 		/* now. (AIA) */
1331 		if (val_len)
1332 			mpa_size = 0; /* get_size_for_compressed_mapping_pairs(rl); */
1333 		else
1334 			mpa_size = 0;
1335 	} else {
1336 		hdr_size = 64;
1337 		if (val_len) {
1338 			mpa_size = ntfs_get_size_for_mapping_pairs(g_vol, rl, 0, INT_MAX);
1339 			if (mpa_size < 0) {
1340 				err = -errno;
1341 				ntfs_log_error("Failed to get size for mapping "
1342 						"pairs.\n");
1343 				goto err_out;
1344 			}
1345 		} else {
1346 			mpa_size = 0;
1347 		}
1348 	}
1349 	/* Mapping pairs array and next attribute must be 8-byte aligned. */
1350 	asize = (((int)hdr_size + ((name_len + 7) & ~7) + mpa_size) + 7) & ~7;
1351 	err = make_room_for_attribute(m, (char*)a, asize);
1352 	if (err == -ENOSPC) {
1353 		/*
1354 		 * FIXME: Make space! (AIA)
1355 		 * can we make it non-resident? if yes, do that.
1356 		 *	does it fit now? yes -> do it.
1357 		 * m's $DATA or $BITMAP+$INDEX_ALLOCATION resident?
1358 		 * yes -> make non-resident
1359 		 *	does it fit now? yes -> do it.
1360 		 * make all attributes non-resident
1361 		 *	does it fit now? yes -> do it.
1362 		 * m is a base record? yes -> allocate extension record
1363 		 *	does the new attribute fit in there? yes -> do it.
1364 		 * split up runlist into extents and place each in an extension
1365 		 * record.
1366 		 * FIXME: the check for needing extension records should be
1367 		 * earlier on as it is very quick: asize > m->bytes_allocated?
1368 		 */
1369 		err = -EOPNOTSUPP;
1370 		goto err_out;
1371 #ifdef DEBUG
1372 	} else if (err == -EINVAL) {
1373 		ntfs_log_error("BUG(): in insert_non_resident_attribute_in_"
1374 				"mft_record(): make_room_for_attribute() "
1375 				"returned error: EINVAL!\n");
1376 		goto err_out;
1377 #endif
1378 	}
1379 	a->type = type;
1380 	a->length = cpu_to_le32(asize);
1381 	a->non_resident = 1;
1382 	a->name_length = name_len;
1383 	a->name_offset = cpu_to_le16(hdr_size);
1384 	a->flags = flags;
1385 	a->instance = m->next_attr_instance;
1386 	m->next_attr_instance = cpu_to_le16((le16_to_cpu(m->next_attr_instance)
1387 			+ 1) & 0xffff);
1388 	a->lowest_vcn = cpu_to_le64(0);
1389 	for (i = 0; rl[i].length; i++)
1390 		;
1391 	a->highest_vcn = cpu_to_sle64(rl[i].vcn - 1);
1392 	a->mapping_pairs_offset = cpu_to_le16(hdr_size + ((name_len + 7) & ~7));
1393 	memset(a->reserved1, 0, sizeof(a->reserved1));
1394 	/* FIXME: Allocated size depends on compression. */
1395 	a->allocated_size = cpu_to_sle64((val_len + (g_vol->cluster_size - 1)) &
1396 			~(g_vol->cluster_size - 1));
1397 	a->data_size = cpu_to_sle64(val_len);
1398 	a->initialized_size = cpu_to_sle64(val_len);
1399 	if (name_len)
1400 		memcpy((char*)a + hdr_size, uname, name_len << 1);
1401 	if (flags & ATTR_COMPRESSION_MASK) {
1402 		if (flags & ATTR_COMPRESSION_MASK & ~ATTR_IS_COMPRESSED) {
1403 			ntfs_log_error("Unknown compression format. Reverting "
1404 					"to standard compression.\n");
1405 			a->flags &= ~ATTR_COMPRESSION_MASK;
1406 			a->flags |= ATTR_IS_COMPRESSED;
1407 		}
1408 		a->compression_unit = 4;
1409 		/* FIXME: Set the compressed size. */
1410 		a->compressed_size = cpu_to_le64(0);
1411 		/* FIXME: Write out the compressed data. */
1412 		/* FIXME: err = build_mapping_pairs_compressed(); */
1413 		err = -EOPNOTSUPP;
1414 	} else {
1415 		a->compression_unit = 0;
1416 		bw = ntfs_rlwrite(g_vol->dev, rl, val, val_len, NULL,
1417 					write_type);
1418 		if (bw != val_len) {
1419 			ntfs_log_error("Error writing non-resident attribute "
1420 					"value.\n");
1421 			return -errno;
1422 		}
1423 		err = ntfs_mapping_pairs_build(g_vol, (u8*)a + hdr_size +
1424 				((name_len + 7) & ~7), mpa_size, rl, 0, NULL);
1425 	}
1426 	if (err < 0 || bw != val_len) {
1427 		/* FIXME: Handle error. */
1428 		/* deallocate clusters */
1429 		/* remove attribute */
1430 		if (err >= 0)
1431 			err = -EIO;
1432 		ntfs_log_error("insert_non_resident_attr_in_mft_record failed with "
1433 			"error %lld.\n", (long long) (err < 0 ? err : bw));
1434 	}
1435 err_out:
1436 	if (ctx)
1437 		ntfs_attr_put_search_ctx(ctx);
1438 	ntfs_ucsfree(uname);
1439 	free(rl);
1440 	return err;
1441 }
1442 
1443 /**
1444  * insert_resident_attr_in_mft_record
1445  *
1446  * Return 0 on success and -errno on error.
1447  */
1448 static int insert_resident_attr_in_mft_record(MFT_RECORD *m,
1449 		const ATTR_TYPES type, const char *name, u32 name_len,
1450 		const IGNORE_CASE_BOOL ic, const ATTR_FLAGS flags,
1451 		const RESIDENT_ATTR_FLAGS res_flags,
1452 		const u8 *val, const u32 val_len)
1453 {
1454 	ntfs_attr_search_ctx *ctx;
1455 	ATTR_RECORD *a;
1456 	int asize, err;
1457 	ntfschar *uname = NULL;
1458 	int uname_len = 0;
1459 	/*
1460 	if (base record)
1461 		mkntfs_attr_lookup();
1462 	else
1463 	*/
1464 
1465 	uname = ntfs_str2ucs(name, &uname_len);
1466 	if (!uname)
1467 		return -errno;
1468 
1469 	/* Check if the attribute is already there. */
1470 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1471 	if (!ctx) {
1472 		ntfs_log_error("Failed to allocate attribute search context.\n");
1473 		err = -ENOMEM;
1474 		goto err_out;
1475 	}
1476 	if (ic == IGNORE_CASE) {
1477 		ntfs_log_error("FIXME: Hit unimplemented code path #3.\n");
1478 		err = -EOPNOTSUPP;
1479 		goto err_out;
1480 	}
1481 	if (!mkntfs_attr_lookup(type, uname, uname_len, ic, 0, val, val_len,
1482 			ctx)) {
1483 		err = -EEXIST;
1484 		goto err_out;
1485 	}
1486 	if (errno != ENOENT) {
1487 		ntfs_log_error("Corrupt inode.\n");
1488 		err = -errno;
1489 		goto err_out;
1490 	}
1491 	a = ctx->attr;
1492 	/* sizeof(resident attribute record header) == 24 */
1493 	asize = ((24 + ((name_len + 7) & ~7) + val_len) + 7) & ~7;
1494 	err = make_room_for_attribute(m, (char*)a, asize);
1495 	if (err == -ENOSPC) {
1496 		/*
1497 		 * FIXME: Make space! (AIA)
1498 		 * can we make it non-resident? if yes, do that.
1499 		 *	does it fit now? yes -> do it.
1500 		 * m's $DATA or $BITMAP+$INDEX_ALLOCATION resident?
1501 		 * yes -> make non-resident
1502 		 *	does it fit now? yes -> do it.
1503 		 * make all attributes non-resident
1504 		 *	does it fit now? yes -> do it.
1505 		 * m is a base record? yes -> allocate extension record
1506 		 *	does the new attribute fit in there? yes -> do it.
1507 		 * split up runlist into extents and place each in an extension
1508 		 * record.
1509 		 * FIXME: the check for needing extension records should be
1510 		 * earlier on as it is very quick: asize > m->bytes_allocated?
1511 		 */
1512 		err = -EOPNOTSUPP;
1513 		goto err_out;
1514 	}
1515 #ifdef DEBUG
1516 	if (err == -EINVAL) {
1517 		ntfs_log_error("BUG(): in insert_resident_attribute_in_mft_"
1518 				"record(): make_room_for_attribute() returned "
1519 				"error: EINVAL!\n");
1520 		goto err_out;
1521 	}
1522 #endif
1523 	a->type = type;
1524 	a->length = cpu_to_le32(asize);
1525 	a->non_resident = 0;
1526 	a->name_length = name_len;
1527 	if (type == AT_OBJECT_ID)
1528 		a->name_offset = const_cpu_to_le16(0);
1529 	else
1530 		a->name_offset = const_cpu_to_le16(24);
1531 	a->flags = flags;
1532 	a->instance = m->next_attr_instance;
1533 	m->next_attr_instance = cpu_to_le16((le16_to_cpu(m->next_attr_instance)
1534 			+ 1) & 0xffff);
1535 	a->value_length = cpu_to_le32(val_len);
1536 	a->value_offset = cpu_to_le16(24 + ((name_len + 7) & ~7));
1537 	a->resident_flags = res_flags;
1538 	a->reservedR = 0;
1539 	if (name_len)
1540 		memcpy((char*)a + 24, uname, name_len << 1);
1541 	if (val_len)
1542 		memcpy((char*)a + le16_to_cpu(a->value_offset), val, val_len);
1543 err_out:
1544 	if (ctx)
1545 		ntfs_attr_put_search_ctx(ctx);
1546 	ntfs_ucsfree(uname);
1547 	return err;
1548 }
1549 
1550 
1551 /**
1552  * add_attr_std_info
1553  *
1554  * Return 0 on success or -errno on error.
1555  */
1556 static int add_attr_std_info(MFT_RECORD *m, const FILE_ATTR_FLAGS flags,
1557 		le32 security_id)
1558 {
1559 	STANDARD_INFORMATION si;
1560 	int err, sd_size;
1561 
1562 	sd_size = 48;
1563 
1564 	si.creation_time = mkntfs_time();
1565 	si.last_data_change_time = si.creation_time;
1566 	si.last_mft_change_time = si.creation_time;
1567 	si.last_access_time = si.creation_time;
1568 	si.file_attributes = flags; /* already LE */
1569 	si.maximum_versions = cpu_to_le32(0);
1570 	si.version_number = cpu_to_le32(0);
1571 	si.class_id = cpu_to_le32(0);
1572 	si.security_id = security_id;
1573 	if (si.security_id != const_cpu_to_le32(0))
1574 		sd_size = 72;
1575 	/* FIXME: $Quota support... */
1576 	si.owner_id = cpu_to_le32(0);
1577 	si.quota_charged = cpu_to_le64(0ULL);
1578 	/* FIXME: $UsnJrnl support... Not needed on fresh w2k3-volume */
1579 	si.usn = cpu_to_le64(0ULL);
1580 	/* NTFS 1.2: size of si = 48, NTFS 3.[01]: size of si = 72 */
1581 	err = insert_resident_attr_in_mft_record(m, AT_STANDARD_INFORMATION,
1582 			NULL, 0, CASE_SENSITIVE, const_cpu_to_le16(0),
1583 			0, (u8*)&si, sd_size);
1584 	if (err < 0)
1585 		ntfs_log_perror("add_attr_std_info failed");
1586 	return err;
1587 }
1588 
1589 /*
1590  *		Tell whether the unnamed data is non resident
1591  */
1592 
1593 static BOOL non_resident_unnamed_data(MFT_RECORD *m)
1594 {
1595 	ATTR_RECORD *a;
1596 	ntfs_attr_search_ctx *ctx;
1597 	BOOL nonres;
1598 
1599 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1600 	if (ctx && !mkntfs_attr_find(AT_DATA,
1601 				(const ntfschar*)NULL, 0, CASE_SENSITIVE,
1602 				(u8*)NULL, 0, ctx)) {
1603 		a = ctx->attr;
1604 		nonres = a->non_resident != 0;
1605 	} else {
1606 		ntfs_log_error("BUG: Unnamed data not found\n");
1607 		nonres = TRUE;
1608 	}
1609 	if (ctx)
1610 		ntfs_attr_put_search_ctx(ctx);
1611 	return (nonres);
1612 }
1613 
1614 /*
1615  *		Get the time stored in the standard information attribute
1616  */
1617 
1618 static ntfs_time stdinfo_time(MFT_RECORD *m)
1619 {
1620 	STANDARD_INFORMATION *si;
1621 	ntfs_attr_search_ctx *ctx;
1622 	ntfs_time info_time;
1623 
1624 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1625 	if (ctx && !mkntfs_attr_find(AT_STANDARD_INFORMATION,
1626 				(const ntfschar*)NULL, 0, CASE_SENSITIVE,
1627 				(u8*)NULL, 0, ctx)) {
1628 		si = (STANDARD_INFORMATION*)((char*)ctx->attr +
1629 				le16_to_cpu(ctx->attr->value_offset));
1630 		info_time = si->creation_time;
1631 	} else {
1632 		ntfs_log_error("BUG: Standard information not found\n");
1633 		info_time = mkntfs_time();
1634 	}
1635 	if (ctx)
1636 		ntfs_attr_put_search_ctx(ctx);
1637 	return (info_time);
1638 }
1639 
1640 /**
1641  * add_attr_file_name
1642  *
1643  * Return 0 on success or -errno on error.
1644  */
1645 static int add_attr_file_name(MFT_RECORD *m, const leMFT_REF parent_dir,
1646 		const s64 allocated_size, const s64 data_size,
1647 		const FILE_ATTR_FLAGS flags, const u16 packed_ea_size,
1648 		const u32 reparse_point_tag, const char *file_name,
1649 		const FILE_NAME_TYPE_FLAGS file_name_type)
1650 {
1651 	ntfs_attr_search_ctx *ctx;
1652 	STANDARD_INFORMATION *si;
1653 	FILE_NAME_ATTR *fn;
1654 	int i, fn_size;
1655 	ntfschar *uname;
1656 
1657 	/* Check if the attribute is already there. */
1658 	ctx = ntfs_attr_get_search_ctx(NULL, m);
1659 	if (!ctx) {
1660 		ntfs_log_error("Failed to get attribute search context.\n");
1661 		return -ENOMEM;
1662 	}
1663 	if (mkntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, 0,
1664 				CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1665 		int eo = errno;
1666 		ntfs_log_error("BUG: Standard information attribute not "
1667 				"present in file record.\n");
1668 		ntfs_attr_put_search_ctx(ctx);
1669 		return -eo;
1670 	}
1671 	si = (STANDARD_INFORMATION*)((char*)ctx->attr +
1672 			le16_to_cpu(ctx->attr->value_offset));
1673 	i = (strlen(file_name) + 1) * sizeof(ntfschar);
1674 	fn_size = sizeof(FILE_NAME_ATTR) + i;
1675 	fn = ntfs_malloc(fn_size);
1676 	if (!fn) {
1677 		ntfs_attr_put_search_ctx(ctx);
1678 		return -errno;
1679 	}
1680 	fn->parent_directory = parent_dir;
1681 
1682 	fn->creation_time = si->creation_time;
1683 	fn->last_data_change_time = si->last_data_change_time;
1684 	fn->last_mft_change_time = si->last_mft_change_time;
1685 	fn->last_access_time = si->last_access_time;
1686 	ntfs_attr_put_search_ctx(ctx);
1687 
1688 	fn->allocated_size = cpu_to_sle64(allocated_size);
1689 	fn->data_size = cpu_to_sle64(data_size);
1690 	fn->file_attributes = flags;
1691 	/* These are in a union so can't have both. */
1692 	if (packed_ea_size && reparse_point_tag) {
1693 		free(fn);
1694 		return -EINVAL;
1695 	}
1696 	if (packed_ea_size) {
1697 		fn->packed_ea_size = cpu_to_le16(packed_ea_size);
1698 		fn->reserved = cpu_to_le16(0);
1699 	} else {
1700 		fn->reparse_point_tag = cpu_to_le32(reparse_point_tag);
1701 	}
1702 	fn->file_name_type = file_name_type;
1703 	uname = fn->file_name;
1704 	i = ntfs_mbstoucs_libntfscompat(file_name, &uname, i);
1705 	if (i < 1) {
1706 		free(fn);
1707 		return -EINVAL;
1708 	}
1709 	if (i > 0xff) {
1710 		free(fn);
1711 		return -ENAMETOOLONG;
1712 	}
1713 	/* No terminating null in file names. */
1714 	fn->file_name_length = i;
1715 	fn_size = sizeof(FILE_NAME_ATTR) + i * sizeof(ntfschar);
1716 	i = insert_resident_attr_in_mft_record(m, AT_FILE_NAME, NULL, 0,
1717 			CASE_SENSITIVE, const_cpu_to_le16(0),
1718 			RESIDENT_ATTR_IS_INDEXED, (u8*)fn, fn_size);
1719 	free(fn);
1720 	if (i < 0)
1721 		ntfs_log_error("add_attr_file_name failed: %s\n", strerror(-i));
1722 	return i;
1723 }
1724 
1725 /**
1726  * add_attr_object_id -
1727  *
1728  * Note we insert only a basic object id which only has the GUID and none of
1729  * the extended fields.  This is because we currently only use this function
1730  * when creating the object id for the volume.
1731  *
1732  * Return 0 on success or -errno on error.
1733  */
1734 static int add_attr_object_id(MFT_RECORD *m, const GUID *object_id)
1735 {
1736 	OBJECT_ID_ATTR oi;
1737 	int err;
1738 
1739 	oi = (OBJECT_ID_ATTR) {
1740 		.object_id = *object_id,
1741 	};
1742 	err = insert_resident_attr_in_mft_record(m, AT_OBJECT_ID, NULL,
1743 			0, CASE_SENSITIVE, const_cpu_to_le16(0),
1744 			0, (u8*)&oi, sizeof(oi.object_id));
1745 	if (err < 0)
1746 		ntfs_log_error("add_attr_vol_info failed: %s\n", strerror(-err));
1747 	return err;
1748 }
1749 
1750 /**
1751  * add_attr_sd
1752  *
1753  * Create the security descriptor attribute adding the security descriptor @sd
1754  * of length @sd_len to the mft record @m.
1755  *
1756  * Return 0 on success or -errno on error.
1757  */
1758 static int add_attr_sd(MFT_RECORD *m, const u8 *sd, const s64 sd_len)
1759 {
1760 	int err;
1761 
1762 	/* Does it fit? NO: create non-resident. YES: create resident. */
1763 	if (le32_to_cpu(m->bytes_in_use) + 24 + sd_len >
1764 						le32_to_cpu(m->bytes_allocated))
1765 		err = insert_non_resident_attr_in_mft_record(m,
1766 				AT_SECURITY_DESCRIPTOR, NULL, 0,
1767 				CASE_SENSITIVE, const_cpu_to_le16(0), sd,
1768 				sd_len, WRITE_STANDARD);
1769 	else
1770 		err = insert_resident_attr_in_mft_record(m,
1771 				AT_SECURITY_DESCRIPTOR, NULL, 0,
1772 				CASE_SENSITIVE, const_cpu_to_le16(0), 0, sd,
1773 				sd_len);
1774 	if (err < 0)
1775 		ntfs_log_error("add_attr_sd failed: %s\n", strerror(-err));
1776 	return err;
1777 }
1778 
1779 /**
1780  * add_attr_data
1781  *
1782  * Return 0 on success or -errno on error.
1783  */
1784 static int add_attr_data(MFT_RECORD *m, const char *name, const u32 name_len,
1785 		const IGNORE_CASE_BOOL ic, const ATTR_FLAGS flags,
1786 		const u8 *val, const s64 val_len)
1787 {
1788 	int err;
1789 
1790 	/*
1791 	 * Does it fit? NO: create non-resident. YES: create resident.
1792 	 *
1793 	 * FIXME: Introduced arbitrary limit of mft record allocated size - 512.
1794 	 * This is to get around the problem that if $Bitmap/$DATA becomes too
1795 	 * big, but is just small enough to be resident, we would make it
1796 	 * resident, and later run out of space when creating the other
1797 	 * attributes and this would cause us to abort as making resident
1798 	 * attributes non-resident is not supported yet.
1799 	 * The proper fix is to support making resident attribute non-resident.
1800 	 */
1801 	if (le32_to_cpu(m->bytes_in_use) + 24 + val_len >
1802 			min(le32_to_cpu(m->bytes_allocated),
1803 			le32_to_cpu(m->bytes_allocated) - 512))
1804 		err = insert_non_resident_attr_in_mft_record(m, AT_DATA, name,
1805 				name_len, ic, flags, val, val_len,
1806 				WRITE_STANDARD);
1807 	else
1808 		err = insert_resident_attr_in_mft_record(m, AT_DATA, name,
1809 				name_len, ic, flags, 0, val, val_len);
1810 
1811 	if (err < 0)
1812 		ntfs_log_error("add_attr_data failed: %s\n", strerror(-err));
1813 	return err;
1814 }
1815 
1816 /**
1817  * add_attr_data_positioned
1818  *
1819  * Create a non-resident data attribute with a predefined on disk location
1820  * specified by the runlist @rl. The clusters specified by @rl are assumed to
1821  * be allocated already.
1822  *
1823  * Return 0 on success or -errno on error.
1824  */
1825 static int add_attr_data_positioned(MFT_RECORD *m, const char *name,
1826 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1827 		const ATTR_FLAGS flags, const runlist *rl,
1828 		const u8 *val, const s64 val_len)
1829 {
1830 	int err;
1831 
1832 	err = insert_positioned_attr_in_mft_record(m, AT_DATA, name, name_len,
1833 			ic, flags, rl, val, val_len);
1834 	if (err < 0)
1835 		ntfs_log_error("add_attr_data_positioned failed: %s\n",
1836 				strerror(-err));
1837 	return err;
1838 }
1839 
1840 /**
1841  * add_attr_vol_name
1842  *
1843  * Create volume name attribute specifying the volume name @vol_name as a null
1844  * terminated char string of length @vol_name_len (number of characters not
1845  * including the terminating null), which is converted internally to a little
1846  * endian ntfschar string. The name is at least 1 character long (though
1847  * Windows accepts zero characters), and at most 128 characters long (not
1848  * counting the terminating null).
1849  *
1850  * Return 0 on success or -errno on error.
1851  */
1852 static int add_attr_vol_name(MFT_RECORD *m, const char *vol_name,
1853 		const int vol_name_len __attribute__((unused)))
1854 {
1855 	ntfschar *uname = NULL;
1856 	int uname_len = 0;
1857 	int i;
1858 
1859 	if (vol_name) {
1860 		uname_len = ntfs_mbstoucs(vol_name, &uname);
1861 		if (uname_len < 0)
1862 			return -errno;
1863 		if (uname_len > 128) {
1864 			free(uname);
1865 			return -ENAMETOOLONG;
1866 		}
1867 	}
1868 	i = insert_resident_attr_in_mft_record(m, AT_VOLUME_NAME, NULL, 0,
1869 			CASE_SENSITIVE, const_cpu_to_le16(0),
1870 			0, (u8*)uname, uname_len*sizeof(ntfschar));
1871 	free(uname);
1872 	if (i < 0)
1873 		ntfs_log_error("add_attr_vol_name failed: %s\n", strerror(-i));
1874 	return i;
1875 }
1876 
1877 /**
1878  * add_attr_vol_info
1879  *
1880  * Return 0 on success or -errno on error.
1881  */
1882 static int add_attr_vol_info(MFT_RECORD *m, const VOLUME_FLAGS flags,
1883 		const u8 major_ver, const u8 minor_ver)
1884 {
1885 	VOLUME_INFORMATION vi;
1886 	int err;
1887 
1888 	memset(&vi, 0, sizeof(vi));
1889 	vi.major_ver = major_ver;
1890 	vi.minor_ver = minor_ver;
1891 	vi.flags = flags & VOLUME_FLAGS_MASK;
1892 	err = insert_resident_attr_in_mft_record(m, AT_VOLUME_INFORMATION, NULL,
1893 			0, CASE_SENSITIVE, const_cpu_to_le16(0),
1894 			0, (u8*)&vi, sizeof(vi));
1895 	if (err < 0)
1896 		ntfs_log_error("add_attr_vol_info failed: %s\n", strerror(-err));
1897 	return err;
1898 }
1899 
1900 /**
1901  * add_attr_index_root
1902  *
1903  * Return 0 on success or -errno on error.
1904  */
1905 static int add_attr_index_root(MFT_RECORD *m, const char *name,
1906 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1907 		const ATTR_TYPES indexed_attr_type,
1908 		const COLLATION_RULES collation_rule,
1909 		const u32 index_block_size)
1910 {
1911 	INDEX_ROOT *r;
1912 	INDEX_ENTRY_HEADER *e;
1913 	int err, val_len;
1914 
1915 	val_len = sizeof(INDEX_ROOT) + sizeof(INDEX_ENTRY_HEADER);
1916 	r = ntfs_malloc(val_len);
1917 	if (!r)
1918 		return -errno;
1919 	r->type = (indexed_attr_type == AT_FILE_NAME)
1920 				? AT_FILE_NAME : const_cpu_to_le32(0);
1921 	if (indexed_attr_type == AT_FILE_NAME &&
1922 			collation_rule != COLLATION_FILE_NAME) {
1923 		free(r);
1924 		ntfs_log_error("add_attr_index_root: indexed attribute is $FILE_NAME "
1925 			"but collation rule is not COLLATION_FILE_NAME.\n");
1926 		return -EINVAL;
1927 	}
1928 	r->collation_rule = collation_rule;
1929 	r->index_block_size = cpu_to_le32(index_block_size);
1930 	if (index_block_size >= g_vol->cluster_size) {
1931 		if (index_block_size % g_vol->cluster_size) {
1932 			ntfs_log_error("add_attr_index_root: index block size is not "
1933 					"a multiple of the cluster size.\n");
1934 			free(r);
1935 			return -EINVAL;
1936 		}
1937 		r->clusters_per_index_block = index_block_size /
1938 				g_vol->cluster_size;
1939 	} else { /* if (g_vol->cluster_size > index_block_size) */
1940 		if (index_block_size & (index_block_size - 1)) {
1941 			ntfs_log_error("add_attr_index_root: index block size is not "
1942 					"a power of 2.\n");
1943 			free(r);
1944 			return -EINVAL;
1945 		}
1946 		if (index_block_size < (u32)opts.sector_size) {
1947 			 ntfs_log_error("add_attr_index_root: index block size "
1948 					 "is smaller than the sector size.\n");
1949 			 free(r);
1950 			 return -EINVAL;
1951 		}
1952 		r->clusters_per_index_block = index_block_size
1953 				>> NTFS_BLOCK_SIZE_BITS;
1954 	}
1955 	memset(&r->reserved, 0, sizeof(r->reserved));
1956 	r->index.entries_offset = const_cpu_to_le32(sizeof(INDEX_HEADER));
1957 	r->index.index_length = const_cpu_to_le32(sizeof(INDEX_HEADER) +
1958 			sizeof(INDEX_ENTRY_HEADER));
1959 	r->index.allocated_size = r->index.index_length;
1960 	r->index.ih_flags = SMALL_INDEX;
1961 	memset(&r->index.reserved, 0, sizeof(r->index.reserved));
1962 	e = (INDEX_ENTRY_HEADER*)((u8*)&r->index +
1963 			le32_to_cpu(r->index.entries_offset));
1964 	/*
1965 	 * No matter whether this is a file index or a view as this is a
1966 	 * termination entry, hence no key value / data is associated with it
1967 	 * at all. Thus, we just need the union to be all zero.
1968 	 */
1969 	e->indexed_file = const_cpu_to_le64(0LL);
1970 	e->length = const_cpu_to_le16(sizeof(INDEX_ENTRY_HEADER));
1971 	e->key_length = const_cpu_to_le16(0);
1972 	e->flags = INDEX_ENTRY_END;
1973 	e->reserved = const_cpu_to_le16(0);
1974 	err = insert_resident_attr_in_mft_record(m, AT_INDEX_ROOT, name,
1975 				name_len, ic, const_cpu_to_le16(0), 0,
1976 				(u8*)r, val_len);
1977 	free(r);
1978 	if (err < 0)
1979 		ntfs_log_error("add_attr_index_root failed: %s\n", strerror(-err));
1980 	return err;
1981 }
1982 
1983 /**
1984  * add_attr_index_alloc
1985  *
1986  * Return 0 on success or -errno on error.
1987  */
1988 static int add_attr_index_alloc(MFT_RECORD *m, const char *name,
1989 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1990 		const u8 *index_alloc_val, const u32 index_alloc_val_len)
1991 {
1992 	int err;
1993 
1994 	err = insert_non_resident_attr_in_mft_record(m, AT_INDEX_ALLOCATION,
1995 			name, name_len, ic, const_cpu_to_le16(0),
1996 			index_alloc_val, index_alloc_val_len, WRITE_STANDARD);
1997 	if (err < 0)
1998 		ntfs_log_error("add_attr_index_alloc failed: %s\n", strerror(-err));
1999 	return err;
2000 }
2001 
2002 /**
2003  * add_attr_bitmap
2004  *
2005  * Return 0 on success or -errno on error.
2006  */
2007 static int add_attr_bitmap(MFT_RECORD *m, const char *name, const u32 name_len,
2008 		const IGNORE_CASE_BOOL ic, const u8 *bitmap,
2009 		const u32 bitmap_len)
2010 {
2011 	int err;
2012 
2013 	/* Does it fit? NO: create non-resident. YES: create resident. */
2014 	if (le32_to_cpu(m->bytes_in_use) + 24 + bitmap_len >
2015 						le32_to_cpu(m->bytes_allocated))
2016 		err = insert_non_resident_attr_in_mft_record(m, AT_BITMAP, name,
2017 				name_len, ic, const_cpu_to_le16(0), bitmap,
2018 				bitmap_len, WRITE_STANDARD);
2019 	else
2020 		err = insert_resident_attr_in_mft_record(m, AT_BITMAP, name,
2021 				name_len, ic, const_cpu_to_le16(0), 0,
2022 				bitmap, bitmap_len);
2023 
2024 	if (err < 0)
2025 		ntfs_log_error("add_attr_bitmap failed: %s\n", strerror(-err));
2026 	return err;
2027 }
2028 
2029 /**
2030  * add_attr_bitmap_positioned
2031  *
2032  * Create a non-resident bitmap attribute with a predefined on disk location
2033  * specified by the runlist @rl. The clusters specified by @rl are assumed to
2034  * be allocated already.
2035  *
2036  * Return 0 on success or -errno on error.
2037  */
2038 static int add_attr_bitmap_positioned(MFT_RECORD *m, const char *name,
2039 		const u32 name_len, const IGNORE_CASE_BOOL ic,
2040 		const runlist *rl, const u8 *bitmap, const u32 bitmap_len)
2041 {
2042 	int err;
2043 
2044 	err = insert_positioned_attr_in_mft_record(m, AT_BITMAP, name, name_len,
2045 			ic, const_cpu_to_le16(0), rl, bitmap, bitmap_len);
2046 	if (err < 0)
2047 		ntfs_log_error("add_attr_bitmap_positioned failed: %s\n",
2048 				strerror(-err));
2049 	return err;
2050 }
2051 
2052 
2053 /**
2054  * upgrade_to_large_index
2055  *
2056  * Create bitmap and index allocation attributes, modify index root
2057  * attribute accordingly and move all of the index entries from the index root
2058  * into the index allocation.
2059  *
2060  * Return 0 on success or -errno on error.
2061  */
2062 static int upgrade_to_large_index(MFT_RECORD *m, const char *name,
2063 		u32 name_len, const IGNORE_CASE_BOOL ic,
2064 		INDEX_ALLOCATION **idx)
2065 {
2066 	ntfs_attr_search_ctx *ctx;
2067 	ATTR_RECORD *a;
2068 	INDEX_ROOT *r;
2069 	INDEX_ENTRY *re;
2070 	INDEX_ALLOCATION *ia_val = NULL;
2071 	ntfschar *uname = NULL;
2072 	int uname_len = 0;
2073 	u8 bmp[8];
2074 	char *re_start, *re_end;
2075 	int i, err, index_block_size;
2076 
2077 	uname = ntfs_str2ucs(name, &uname_len);
2078 	if (!uname)
2079 		return -errno;
2080 
2081 	/* Find the index root attribute. */
2082 	ctx = ntfs_attr_get_search_ctx(NULL, m);
2083 	if (!ctx) {
2084 		ntfs_log_error("Failed to allocate attribute search context.\n");
2085 		ntfs_ucsfree(uname);
2086 		return -ENOMEM;
2087 	}
2088 	if (ic == IGNORE_CASE) {
2089 		ntfs_log_error("FIXME: Hit unimplemented code path #4.\n");
2090 		err = -EOPNOTSUPP;
2091 		ntfs_ucsfree(uname);
2092 		goto err_out;
2093 	}
2094 	err = mkntfs_attr_lookup(AT_INDEX_ROOT, uname, uname_len, ic, 0, NULL, 0,
2095 			ctx);
2096 	ntfs_ucsfree(uname);
2097 	if (err) {
2098 		err = -ENOTDIR;
2099 		goto err_out;
2100 	}
2101 	a = ctx->attr;
2102 	if (a->non_resident || a->flags) {
2103 		err = -EINVAL;
2104 		goto err_out;
2105 	}
2106 	r = (INDEX_ROOT*)((char*)a + le16_to_cpu(a->value_offset));
2107 	re_end = (char*)r + le32_to_cpu(a->value_length);
2108 	re_start = (char*)&r->index + le32_to_cpu(r->index.entries_offset);
2109 	re = (INDEX_ENTRY*)re_start;
2110 	index_block_size = le32_to_cpu(r->index_block_size);
2111 	memset(bmp, 0, sizeof(bmp));
2112 	ntfs_bit_set(bmp, 0ULL, 1);
2113 	/* Bitmap has to be at least 8 bytes in size. */
2114 	err = add_attr_bitmap(m, name, name_len, ic, bmp, sizeof(bmp));
2115 	if (err)
2116 		goto err_out;
2117 	ia_val = ntfs_calloc(index_block_size);
2118 	if (!ia_val) {
2119 		err = -errno;
2120 		goto err_out;
2121 	}
2122 	/* Setup header. */
2123 	ia_val->magic = magic_INDX;
2124 	ia_val->usa_ofs = cpu_to_le16(sizeof(INDEX_ALLOCATION));
2125 	if (index_block_size >= NTFS_BLOCK_SIZE) {
2126 		ia_val->usa_count = cpu_to_le16(index_block_size /
2127 				NTFS_BLOCK_SIZE + 1);
2128 	} else {
2129 		ia_val->usa_count = cpu_to_le16(1);
2130 		ntfs_log_error("Sector size is bigger than index block size. "
2131 				"Setting usa_count to 1. If Windows chkdsk "
2132 				"reports this as corruption, please email %s "
2133 				"stating that you saw this message and that "
2134 				"the filesystem created was corrupt.  "
2135 				"Thank you.", NTFS_DEV_LIST);
2136 	}
2137 	/* Set USN to 1. */
2138 	*(le16*)((char*)ia_val + le16_to_cpu(ia_val->usa_ofs)) =
2139 			cpu_to_le16(1);
2140 	ia_val->lsn = cpu_to_le64(0);
2141 	ia_val->index_block_vcn = cpu_to_le64(0);
2142 	ia_val->index.ih_flags = LEAF_NODE;
2143 	/* Align to 8-byte boundary. */
2144 	ia_val->index.entries_offset = cpu_to_le32((sizeof(INDEX_HEADER) +
2145 			le16_to_cpu(ia_val->usa_count) * 2 + 7) & ~7);
2146 	ia_val->index.allocated_size = cpu_to_le32(index_block_size -
2147 			(sizeof(INDEX_ALLOCATION) - sizeof(INDEX_HEADER)));
2148 	/* Find the last entry in the index root and save it in re. */
2149 	while ((char*)re < re_end && !(re->ie_flags & INDEX_ENTRY_END)) {
2150 		/* Next entry in index root. */
2151 		re = (INDEX_ENTRY*)((char*)re + le16_to_cpu(re->length));
2152 	}
2153 	/* Copy all the entries including the termination entry. */
2154 	i = (char*)re - re_start + le16_to_cpu(re->length);
2155 	memcpy((char*)&ia_val->index +
2156 			le32_to_cpu(ia_val->index.entries_offset), re_start, i);
2157 	/* Finish setting up index allocation. */
2158 	ia_val->index.index_length = cpu_to_le32(i +
2159 			le32_to_cpu(ia_val->index.entries_offset));
2160 	/* Move the termination entry forward to the beginning if necessary. */
2161 	if ((char*)re > re_start) {
2162 		memmove(re_start, (char*)re, le16_to_cpu(re->length));
2163 		re = (INDEX_ENTRY*)re_start;
2164 	}
2165 	/* Now fixup empty index root with pointer to index allocation VCN 0. */
2166 	r->index.ih_flags = LARGE_INDEX;
2167 	re->ie_flags |= INDEX_ENTRY_NODE;
2168 	if (le16_to_cpu(re->length) < sizeof(INDEX_ENTRY_HEADER) + sizeof(VCN))
2169 		re->length = cpu_to_le16(le16_to_cpu(re->length) + sizeof(VCN));
2170 	r->index.index_length = cpu_to_le32(le32_to_cpu(r->index.entries_offset)
2171 			+ le16_to_cpu(re->length));
2172 	r->index.allocated_size = r->index.index_length;
2173 	/* Resize index root attribute. */
2174 	if (ntfs_resident_attr_value_resize(m, a, sizeof(INDEX_ROOT) -
2175 			sizeof(INDEX_HEADER) +
2176 			le32_to_cpu(r->index.allocated_size))) {
2177 		/* TODO: Remove the added bitmap! */
2178 		/* Revert index root from index allocation. */
2179 		err = -errno;
2180 		goto err_out;
2181 	}
2182 	/* Set VCN pointer to 0LL. */
2183 	*(leVCN*)((char*)re + cpu_to_le16(re->length) - sizeof(VCN)) =
2184 			cpu_to_le64(0);
2185 	err = ntfs_mst_pre_write_fixup((NTFS_RECORD*)ia_val, index_block_size);
2186 	if (err) {
2187 		err = -errno;
2188 		ntfs_log_error("ntfs_mst_pre_write_fixup() failed in "
2189 				"upgrade_to_large_index.\n");
2190 		goto err_out;
2191 	}
2192 	err = add_attr_index_alloc(m, name, name_len, ic, (u8*)ia_val,
2193 			index_block_size);
2194 	ntfs_mst_post_write_fixup((NTFS_RECORD*)ia_val);
2195 	if (err) {
2196 		/* TODO: Remove the added bitmap! */
2197 		/* Revert index root from index allocation. */
2198 		goto err_out;
2199 	}
2200 	*idx = ia_val;
2201 	ntfs_attr_put_search_ctx(ctx);
2202 	return 0;
2203 err_out:
2204 	ntfs_attr_put_search_ctx(ctx);
2205 	free(ia_val);
2206 	return err;
2207 }
2208 
2209 /**
2210  * make_room_for_index_entry_in_index_block
2211  *
2212  * Create space of @size bytes at position @pos inside the index block @idx.
2213  *
2214  * Return 0 on success or -errno on error.
2215  */
2216 static int make_room_for_index_entry_in_index_block(INDEX_BLOCK *idx,
2217 		INDEX_ENTRY *pos, u32 size)
2218 {
2219 	u32 biu;
2220 
2221 	if (!size)
2222 		return 0;
2223 #ifdef DEBUG
2224 	/*
2225 	 * Rigorous consistency checks. Always return -EINVAL even if more
2226 	 * appropriate codes exist for simplicity of parsing the return value.
2227 	 */
2228 	if (size != ((size + 7) & ~7)) {
2229 		ntfs_log_error("make_room_for_index_entry_in_index_block() received "
2230 				"non 8-byte aligned size.\n");
2231 		return -EINVAL;
2232 	}
2233 	if (!idx || !pos)
2234 		return -EINVAL;
2235 	if ((char*)pos < (char*)idx || (char*)pos + size < (char*)idx ||
2236 			(char*)pos > (char*)idx + sizeof(INDEX_BLOCK) -
2237 				sizeof(INDEX_HEADER) +
2238 				le32_to_cpu(idx->index.allocated_size) ||
2239 			(char*)pos + size > (char*)idx + sizeof(INDEX_BLOCK) -
2240 				sizeof(INDEX_HEADER) +
2241 				le32_to_cpu(idx->index.allocated_size))
2242 		return -EINVAL;
2243 	/* The - sizeof(INDEX_ENTRY_HEADER) is for the index terminator. */
2244 	if ((char*)pos - (char*)&idx->index >
2245 			(int)le32_to_cpu(idx->index.index_length)
2246 			- (int)sizeof(INDEX_ENTRY_HEADER))
2247 		return -EINVAL;
2248 #endif
2249 	biu = le32_to_cpu(idx->index.index_length);
2250 	/* Do we have enough space? */
2251 	if (biu + size > le32_to_cpu(idx->index.allocated_size))
2252 		return -ENOSPC;
2253 	/* Move everything after pos to pos + size. */
2254 	memmove((char*)pos + size, (char*)pos, biu - ((char*)pos -
2255 			(char*)&idx->index));
2256 	/* Update index block. */
2257 	idx->index.index_length = cpu_to_le32(biu + size);
2258 	return 0;
2259 }
2260 
2261 /**
2262  * ntfs_index_keys_compare
2263  *
2264  * not all types of COLLATION_RULES supported yet...
2265  * added as needed.. (remove this comment when all are added)
2266  */
2267 static int ntfs_index_keys_compare(u8 *key1, u8 *key2, int key1_length,
2268 		int key2_length, COLLATION_RULES collation_rule)
2269 {
2270 	u32 u1, u2;
2271 	int i;
2272 
2273 	if (collation_rule == COLLATION_NTOFS_ULONG) {
2274 		/* i.e. $SII or $QUOTA-$Q */
2275 		u1 = le32_to_cpup((const le32*)key1);
2276 		u2 = le32_to_cpup((const le32*)key2);
2277 		if (u1 < u2)
2278 			return -1;
2279 		if (u1 > u2)
2280 			return 1;
2281 		/* u1 == u2 */
2282 		return 0;
2283 	}
2284 	if (collation_rule == COLLATION_NTOFS_ULONGS) {
2285 		/* i.e $OBJID-$O */
2286 		i = 0;
2287 		while (i < min(key1_length, key2_length)) {
2288 			u1 = le32_to_cpup((const le32*)(key1 + i));
2289 			u2 = le32_to_cpup((const le32*)(key2 + i));
2290 			if (u1 < u2)
2291 				return -1;
2292 			if (u1 > u2)
2293 				return 1;
2294 			/* u1 == u2 */
2295 			i += sizeof(u32);
2296 		}
2297 		if (key1_length < key2_length)
2298 			return -1;
2299 		if (key1_length > key2_length)
2300 			return 1;
2301 		return 0;
2302 	}
2303 	if (collation_rule == COLLATION_NTOFS_SECURITY_HASH) {
2304 		/* i.e. $SDH */
2305 		u1 = le32_to_cpu(((SDH_INDEX_KEY*)key1)->hash);
2306 		u2 = le32_to_cpu(((SDH_INDEX_KEY*)key2)->hash);
2307 		if (u1 < u2)
2308 			return -1;
2309 		if (u1 > u2)
2310 			return 1;
2311 		/* u1 == u2 */
2312 		u1 = le32_to_cpu(((SDH_INDEX_KEY*)key1)->security_id);
2313 		u2 = le32_to_cpu(((SDH_INDEX_KEY*)key2)->security_id);
2314 		if (u1 < u2)
2315 			return -1;
2316 		if (u1 > u2)
2317 			return 1;
2318 		return 0;
2319 	}
2320 	if (collation_rule == COLLATION_NTOFS_SID) {
2321 		/* i.e. $QUOTA-O */
2322 		i = memcmp(key1, key2, min(key1_length, key2_length));
2323 		if (!i) {
2324 			if (key1_length < key2_length)
2325 				return -1;
2326 			if (key1_length > key2_length)
2327 				return 1;
2328 		}
2329 		return i;
2330 	}
2331 	ntfs_log_critical("ntfs_index_keys_compare called without supported "
2332 			"collation rule.\n");
2333 	return 0;	/* Claim they're equal.  What else can we do? */
2334 }
2335 
2336 /**
2337  * insert_index_entry_in_res_dir_index
2338  *
2339  * i.e. insert an index_entry in some named index_root
2340  * simplified search method, works for mkntfs
2341  */
2342 static int insert_index_entry_in_res_dir_index(INDEX_ENTRY *idx, u32 idx_size,
2343 		MFT_RECORD *m, ntfschar *name, u32 name_size, ATTR_TYPES type)
2344 {
2345 	ntfs_attr_search_ctx *ctx;
2346 	INDEX_HEADER *idx_header;
2347 	INDEX_ENTRY *idx_entry, *idx_end;
2348 	ATTR_RECORD *a;
2349 	COLLATION_RULES collation_rule;
2350 	int err, i;
2351 
2352 	err = 0;
2353 	/* does it fit ?*/
2354 	if (g_vol->mft_record_size > idx_size + le32_to_cpu(m->bytes_allocated))
2355 		return -ENOSPC;
2356 	/* find the INDEX_ROOT attribute:*/
2357 	ctx = ntfs_attr_get_search_ctx(NULL, m);
2358 	if (!ctx) {
2359 		ntfs_log_error("Failed to allocate attribute search "
2360 				"context.\n");
2361 		err = -ENOMEM;
2362 		goto err_out;
2363 	}
2364 	if (mkntfs_attr_lookup(AT_INDEX_ROOT, name, name_size,
2365 			CASE_SENSITIVE, 0, NULL, 0, ctx)) {
2366 		err = -EEXIST;
2367 		goto err_out;
2368 	}
2369 	/* found attribute */
2370 	a = (ATTR_RECORD*)ctx->attr;
2371 	collation_rule = ((INDEX_ROOT*)((u8*)a +
2372 			le16_to_cpu(a->value_offset)))->collation_rule;
2373 	idx_header = (INDEX_HEADER*)((u8*)a + le16_to_cpu(a->value_offset)
2374 			+ 0x10);
2375 	idx_entry = (INDEX_ENTRY*)((u8*)idx_header +
2376 			le32_to_cpu(idx_header->entries_offset));
2377 	idx_end = (INDEX_ENTRY*)((u8*)idx_entry +
2378 			le32_to_cpu(idx_header->index_length));
2379 	/*
2380 	 * Loop until we exceed valid memory (corruption case) or until we
2381 	 * reach the last entry.
2382 	 */
2383 	if (type == AT_FILE_NAME) {
2384 		while (((u8*)idx_entry < (u8*)idx_end) &&
2385 				!(idx_entry->ie_flags & INDEX_ENTRY_END)) {
2386 			/*
2387 			i = ntfs_file_values_compare(&idx->key.file_name,
2388 					&idx_entry->key.file_name, 1,
2389 					IGNORE_CASE, g_vol->upcase,
2390 					g_vol->upcase_len);
2391 			*/
2392 			i = ntfs_names_full_collate(idx->key.file_name.file_name, idx->key.file_name.file_name_length,
2393 					idx_entry->key.file_name.file_name, idx_entry->key.file_name.file_name_length,
2394 					IGNORE_CASE, g_vol->upcase,
2395 					g_vol->upcase_len);
2396 			/*
2397 			 * If @file_name collates before ie->key.file_name,
2398 			 * there is no matching index entry.
2399 			 */
2400 			if (i == -1)
2401 				break;
2402 			/* If file names are not equal, continue search. */
2403 			if (i)
2404 				goto do_next;
2405 			if (idx->key.file_name.file_name_type !=
2406 					FILE_NAME_POSIX ||
2407 					idx_entry->key.file_name.file_name_type
2408 					!= FILE_NAME_POSIX)
2409 				return -EEXIST;
2410 			/*
2411 			i = ntfs_file_values_compare(&idx->key.file_name,
2412 					&idx_entry->key.file_name, 1,
2413 					CASE_SENSITIVE, g_vol->upcase,
2414 					g_vol->upcase_len);
2415 			*/
2416 			i = ntfs_names_full_collate(idx->key.file_name.file_name, idx->key.file_name.file_name_length,
2417 					idx_entry->key.file_name.file_name, idx_entry->key.file_name.file_name_length,
2418 					CASE_SENSITIVE, g_vol->upcase,
2419 					g_vol->upcase_len);
2420 			if (!i)
2421 				return -EEXIST;
2422 			if (i == -1)
2423 				break;
2424 do_next:
2425 			idx_entry = (INDEX_ENTRY*)((u8*)idx_entry +
2426 					le16_to_cpu(idx_entry->length));
2427 		}
2428 	} else if (type == AT_UNUSED) {  /* case view */
2429 		while (((u8*)idx_entry < (u8*)idx_end) &&
2430 				!(idx_entry->ie_flags & INDEX_ENTRY_END)) {
2431 			i = ntfs_index_keys_compare((u8*)idx + 0x10,
2432 					(u8*)idx_entry + 0x10,
2433 					le16_to_cpu(idx->key_length),
2434 					le16_to_cpu(idx_entry->key_length),
2435 					collation_rule);
2436 			if (!i)
2437 				return -EEXIST;
2438 			if (i == -1)
2439 				break;
2440 			idx_entry = (INDEX_ENTRY*)((u8*)idx_entry +
2441 					le16_to_cpu(idx_entry->length));
2442 		}
2443 	} else
2444 		return -EINVAL;
2445 	memmove((u8*)idx_entry + idx_size, (u8*)idx_entry,
2446 			le32_to_cpu(m->bytes_in_use) -
2447 			((u8*)idx_entry - (u8*)m));
2448 	memcpy((u8*)idx_entry, (u8*)idx, idx_size);
2449 	/* Adjust various offsets, etc... */
2450 	m->bytes_in_use = cpu_to_le32(le32_to_cpu(m->bytes_in_use) + idx_size);
2451 	a->length = cpu_to_le32(le32_to_cpu(a->length) + idx_size);
2452 	a->value_length = cpu_to_le32(le32_to_cpu(a->value_length) + idx_size);
2453 	idx_header->index_length = cpu_to_le32(
2454 			le32_to_cpu(idx_header->index_length) + idx_size);
2455 	idx_header->allocated_size = cpu_to_le32(
2456 			le32_to_cpu(idx_header->allocated_size) + idx_size);
2457 err_out:
2458 	if (ctx)
2459 		ntfs_attr_put_search_ctx(ctx);
2460 	return err;
2461 }
2462 
2463 /**
2464  * initialize_secure
2465  *
2466  * initializes $Secure's $SDH and $SII indexes from $SDS datastream
2467  */
2468 static int initialize_secure(char *sds, u32 sds_size, MFT_RECORD *m)
2469 {
2470 	int err, sdh_size, sii_size;
2471 	SECURITY_DESCRIPTOR_HEADER *sds_header;
2472 	INDEX_ENTRY *idx_entry_sdh, *idx_entry_sii;
2473 	SDH_INDEX_DATA *sdh_data;
2474 	SII_INDEX_DATA *sii_data;
2475 
2476 	sds_header = (SECURITY_DESCRIPTOR_HEADER*)sds;
2477 	sdh_size  = sizeof(INDEX_ENTRY_HEADER);
2478 	sdh_size += sizeof(SDH_INDEX_KEY) + sizeof(SDH_INDEX_DATA);
2479 	sii_size  = sizeof(INDEX_ENTRY_HEADER);
2480 	sii_size += sizeof(SII_INDEX_KEY) + sizeof(SII_INDEX_DATA);
2481 	idx_entry_sdh = ntfs_calloc(sizeof(INDEX_ENTRY));
2482 	if (!idx_entry_sdh)
2483 		return -errno;
2484 	idx_entry_sii = ntfs_calloc(sizeof(INDEX_ENTRY));
2485 	if (!idx_entry_sii) {
2486 		free(idx_entry_sdh);
2487 		return -errno;
2488 	}
2489 	err = 0;
2490 
2491 	while ((char*)sds_header < (char*)sds + sds_size) {
2492 		if (!sds_header->length)
2493 			break;
2494 		/* SDH index entry */
2495 		idx_entry_sdh->data_offset = const_cpu_to_le16(0x18);
2496 		idx_entry_sdh->data_length = const_cpu_to_le16(0x14);
2497 		idx_entry_sdh->reservedV = const_cpu_to_le32(0x00);
2498 		idx_entry_sdh->length = const_cpu_to_le16(0x30);
2499 		idx_entry_sdh->key_length = const_cpu_to_le16(0x08);
2500 		idx_entry_sdh->ie_flags = const_cpu_to_le16(0x00);
2501 		idx_entry_sdh->reserved = const_cpu_to_le16(0x00);
2502 		idx_entry_sdh->key.sdh.hash = sds_header->hash;
2503 		idx_entry_sdh->key.sdh.security_id = sds_header->security_id;
2504 		sdh_data = (SDH_INDEX_DATA*)((u8*)idx_entry_sdh +
2505 				le16_to_cpu(idx_entry_sdh->data_offset));
2506 		sdh_data->hash = sds_header->hash;
2507 		sdh_data->security_id = sds_header->security_id;
2508 		sdh_data->offset = sds_header->offset;
2509 		sdh_data->length = sds_header->length;
2510 		sdh_data->reserved_II = const_cpu_to_le32(0x00490049);
2511 
2512 		/* SII index entry */
2513 		idx_entry_sii->data_offset = const_cpu_to_le16(0x14);
2514 		idx_entry_sii->data_length = const_cpu_to_le16(0x14);
2515 		idx_entry_sii->reservedV = const_cpu_to_le32(0x00);
2516 		idx_entry_sii->length = const_cpu_to_le16(0x28);
2517 		idx_entry_sii->key_length = const_cpu_to_le16(0x04);
2518 		idx_entry_sii->ie_flags = const_cpu_to_le16(0x00);
2519 		idx_entry_sii->reserved = const_cpu_to_le16(0x00);
2520 		idx_entry_sii->key.sii.security_id = sds_header->security_id;
2521 		sii_data = (SII_INDEX_DATA*)((u8*)idx_entry_sii +
2522 				le16_to_cpu(idx_entry_sii->data_offset));
2523 		sii_data->hash = sds_header->hash;
2524 		sii_data->security_id = sds_header->security_id;
2525 		sii_data->offset = sds_header->offset;
2526 		sii_data->length = sds_header->length;
2527 		if ((err = insert_index_entry_in_res_dir_index(idx_entry_sdh,
2528 				sdh_size, m, NTFS_INDEX_SDH, 4, AT_UNUSED)))
2529 			break;
2530 		if ((err = insert_index_entry_in_res_dir_index(idx_entry_sii,
2531 				sii_size, m, NTFS_INDEX_SII, 4, AT_UNUSED)))
2532 			break;
2533 		sds_header = (SECURITY_DESCRIPTOR_HEADER*)((u8*)sds_header +
2534 				((le32_to_cpu(sds_header->length) + 15) & ~15));
2535 	}
2536 	free(idx_entry_sdh);
2537 	free(idx_entry_sii);
2538 	return err;
2539 }
2540 
2541 /**
2542  * initialize_quota
2543  *
2544  * initialize $Quota with the default quota index-entries.
2545  */
2546 static int initialize_quota(MFT_RECORD *m)
2547 {
2548 	int o_size, q1_size, q2_size, err, i;
2549 	INDEX_ENTRY *idx_entry_o, *idx_entry_q1, *idx_entry_q2;
2550 	QUOTA_O_INDEX_DATA *idx_entry_o_data;
2551 	QUOTA_CONTROL_ENTRY *idx_entry_q1_data, *idx_entry_q2_data;
2552 
2553 	err = 0;
2554 	/* q index entry num 1 */
2555 	q1_size = 0x48;
2556 	idx_entry_q1 = ntfs_calloc(q1_size);
2557 	if (!idx_entry_q1)
2558 		return errno;
2559 	idx_entry_q1->data_offset = const_cpu_to_le16(0x14);
2560 	idx_entry_q1->data_length = const_cpu_to_le16(0x30);
2561 	idx_entry_q1->reservedV = const_cpu_to_le32(0x00);
2562 	idx_entry_q1->length = const_cpu_to_le16(0x48);
2563 	idx_entry_q1->key_length = const_cpu_to_le16(0x04);
2564 	idx_entry_q1->ie_flags = const_cpu_to_le16(0x00);
2565 	idx_entry_q1->reserved = const_cpu_to_le16(0x00);
2566 	idx_entry_q1->key.owner_id = const_cpu_to_le32(0x01);
2567 	idx_entry_q1_data = (QUOTA_CONTROL_ENTRY*)((char*)idx_entry_q1
2568 			+ le16_to_cpu(idx_entry_q1->data_offset));
2569 	idx_entry_q1_data->version = const_cpu_to_le32(0x02);
2570 	idx_entry_q1_data->flags = QUOTA_FLAG_DEFAULT_LIMITS;
2571 	idx_entry_q1_data->bytes_used = const_cpu_to_le64(0x00);
2572 	idx_entry_q1_data->change_time = mkntfs_time();
2573 	idx_entry_q1_data->threshold = cpu_to_sle64(-1);
2574 	idx_entry_q1_data->limit = cpu_to_sle64(-1);
2575 	idx_entry_q1_data->exceeded_time = const_cpu_to_le64(0);
2576 	err = insert_index_entry_in_res_dir_index(idx_entry_q1, q1_size, m,
2577 			NTFS_INDEX_Q, 2, AT_UNUSED);
2578 	free(idx_entry_q1);
2579 	if (err)
2580 		return err;
2581 	/* q index entry num 2 */
2582 	q2_size = 0x58;
2583 	idx_entry_q2 = ntfs_calloc(q2_size);
2584 	if (!idx_entry_q2)
2585 		return errno;
2586 	idx_entry_q2->data_offset = const_cpu_to_le16(0x14);
2587 	idx_entry_q2->data_length = const_cpu_to_le16(0x40);
2588 	idx_entry_q2->reservedV = const_cpu_to_le32(0x00);
2589 	idx_entry_q2->length = const_cpu_to_le16(0x58);
2590 	idx_entry_q2->key_length = const_cpu_to_le16(0x04);
2591 	idx_entry_q2->ie_flags = const_cpu_to_le16(0x00);
2592 	idx_entry_q2->reserved = const_cpu_to_le16(0x00);
2593 	idx_entry_q2->key.owner_id = QUOTA_FIRST_USER_ID;
2594 	idx_entry_q2_data = (QUOTA_CONTROL_ENTRY*)((char*)idx_entry_q2
2595 			+ le16_to_cpu(idx_entry_q2->data_offset));
2596 	idx_entry_q2_data->version = const_cpu_to_le32(0x02);
2597 	idx_entry_q2_data->flags = QUOTA_FLAG_DEFAULT_LIMITS;
2598 	idx_entry_q2_data->bytes_used = const_cpu_to_le64(0x00);
2599 	idx_entry_q2_data->change_time = mkntfs_time();
2600 	idx_entry_q2_data->threshold = cpu_to_sle64(-1);
2601 	idx_entry_q2_data->limit = cpu_to_sle64(-1);
2602 	idx_entry_q2_data->exceeded_time = const_cpu_to_le64(0);
2603 	idx_entry_q2_data->sid.revision = 1;
2604 	idx_entry_q2_data->sid.sub_authority_count = 2;
2605 	for (i = 0; i < 5; i++)
2606 		idx_entry_q2_data->sid.identifier_authority.value[i] = 0;
2607 	idx_entry_q2_data->sid.identifier_authority.value[5] = 0x05;
2608 	idx_entry_q2_data->sid.sub_authority[0] =
2609 			const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID);
2610 	idx_entry_q2_data->sid.sub_authority[1] =
2611 			const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS);
2612 	err = insert_index_entry_in_res_dir_index(idx_entry_q2, q2_size, m,
2613 			NTFS_INDEX_Q, 2, AT_UNUSED);
2614 	free(idx_entry_q2);
2615 	if (err)
2616 		return err;
2617 	o_size = 0x28;
2618 	idx_entry_o = ntfs_calloc(o_size);
2619 	if (!idx_entry_o)
2620 		return errno;
2621 	idx_entry_o->data_offset = const_cpu_to_le16(0x20);
2622 	idx_entry_o->data_length = const_cpu_to_le16(0x04);
2623 	idx_entry_o->reservedV = const_cpu_to_le32(0x00);
2624 	idx_entry_o->length = const_cpu_to_le16(0x28);
2625 	idx_entry_o->key_length = const_cpu_to_le16(0x10);
2626 	idx_entry_o->ie_flags = const_cpu_to_le16(0x00);
2627 	idx_entry_o->reserved = const_cpu_to_le16(0x00);
2628 	idx_entry_o->key.sid.revision = 0x01;
2629 	idx_entry_o->key.sid.sub_authority_count = 0x02;
2630 	for (i = 0; i < 5; i++)
2631 		idx_entry_o->key.sid.identifier_authority.value[i] = 0;
2632 	idx_entry_o->key.sid.identifier_authority.value[5] = 0x05;
2633 	idx_entry_o->key.sid.sub_authority[0] =
2634 			const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID);
2635 	idx_entry_o->key.sid.sub_authority[1] =
2636 			const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS);
2637 	idx_entry_o_data = (QUOTA_O_INDEX_DATA*)((char*)idx_entry_o
2638 			+ le16_to_cpu(idx_entry_o->data_offset));
2639 	idx_entry_o_data->owner_id  = QUOTA_FIRST_USER_ID;
2640 	/* 20 00 00 00 padding after here on ntfs 3.1. 3.0 is unchecked. */
2641 	idx_entry_o_data->unknown = const_cpu_to_le32(32);
2642 	err = insert_index_entry_in_res_dir_index(idx_entry_o, o_size, m,
2643 			NTFS_INDEX_O, 2, AT_UNUSED);
2644 	free(idx_entry_o);
2645 
2646 	return err;
2647 }
2648 
2649 /**
2650  * insert_file_link_in_dir_index
2651  *
2652  * Insert the fully completed FILE_NAME_ATTR @file_name which is inside
2653  * the file with mft reference @file_ref into the index (allocation) block
2654  * @idx (which belongs to @file_ref's parent directory).
2655  *
2656  * Return 0 on success or -errno on error.
2657  */
2658 static int insert_file_link_in_dir_index(INDEX_BLOCK *idx, leMFT_REF file_ref,
2659 		FILE_NAME_ATTR *file_name, u32 file_name_size)
2660 {
2661 	int err, i;
2662 	INDEX_ENTRY *ie;
2663 	char *index_end;
2664 
2665 	/*
2666 	 * Lookup dir entry @file_name in dir @idx to determine correct
2667 	 * insertion location. FIXME: Using a very oversimplified lookup
2668 	 * method which is sufficient for mkntfs but no good whatsoever in
2669 	 * real world scenario. (AIA)
2670 	 */
2671 
2672 	index_end = (char*)&idx->index + le32_to_cpu(idx->index.index_length);
2673 	ie = (INDEX_ENTRY*)((char*)&idx->index +
2674 			le32_to_cpu(idx->index.entries_offset));
2675 	/*
2676 	 * Loop until we exceed valid memory (corruption case) or until we
2677 	 * reach the last entry.
2678 	 */
2679 	while ((char*)ie < index_end && !(ie->ie_flags & INDEX_ENTRY_END)) {
2680 #if 0
2681 #ifdef DEBUG
2682 		ntfs_log_debug("file_name_attr1->file_name_length = %i\n",
2683 				file_name->file_name_length);
2684 		if (file_name->file_name_length) {
2685 			char *__buf = NULL;
2686 			i = ntfs_ucstombs((ntfschar*)&file_name->file_name,
2687 				file_name->file_name_length, &__buf, 0);
2688 			if (i < 0)
2689 				ntfs_log_debug("Name contains non-displayable "
2690 						"Unicode characters.\n");
2691 			ntfs_log_debug("file_name_attr1->file_name = %s\n",
2692 					__buf);
2693 			free(__buf);
2694 		}
2695 		ntfs_log_debug("file_name_attr2->file_name_length = %i\n",
2696 				ie->key.file_name.file_name_length);
2697 		if (ie->key.file_name.file_name_length) {
2698 			char *__buf = NULL;
2699 			i = ntfs_ucstombs(ie->key.file_name.file_name,
2700 				ie->key.file_name.file_name_length + 1, &__buf,
2701 				0);
2702 			if (i < 0)
2703 				ntfs_log_debug("Name contains non-displayable "
2704 						"Unicode characters.\n");
2705 			ntfs_log_debug("file_name_attr2->file_name = %s\n",
2706 					__buf);
2707 			free(__buf);
2708 		}
2709 #endif
2710 #endif
2711 		/*
2712 		i = ntfs_file_values_compare(file_name,
2713 				(FILE_NAME_ATTR*)&ie->key.file_name, 1,
2714 				IGNORE_CASE, g_vol->upcase, g_vol->upcase_len);
2715 		*/
2716 		i = ntfs_names_full_collate(file_name->file_name, file_name->file_name_length,
2717 				((FILE_NAME_ATTR*)&ie->key.file_name)->file_name, ((FILE_NAME_ATTR*)&ie->key.file_name)->file_name_length,
2718 				IGNORE_CASE, g_vol->upcase, g_vol->upcase_len);
2719 		/*
2720 		 * If @file_name collates before ie->key.file_name, there is no
2721 		 * matching index entry.
2722 		 */
2723 		if (i == -1)
2724 			break;
2725 		/* If file names are not equal, continue search. */
2726 		if (i)
2727 			goto do_next;
2728 		/* File names are equal when compared ignoring case. */
2729 		/*
2730 		 * If BOTH file names are in the POSIX namespace, do a case
2731 		 * sensitive comparison as well. Otherwise the names match so
2732 		 * we return -EEXIST. FIXME: There are problems with this in a
2733 		 * real world scenario, when one is POSIX and one isn't, but
2734 		 * fine for mkntfs where we don't use POSIX namespace at all
2735 		 * and hence this following code is luxury. (AIA)
2736 		 */
2737 		if (file_name->file_name_type != FILE_NAME_POSIX ||
2738 		    ie->key.file_name.file_name_type != FILE_NAME_POSIX)
2739 			return -EEXIST;
2740 		/*
2741 		i = ntfs_file_values_compare(file_name,
2742 				(FILE_NAME_ATTR*)&ie->key.file_name, 1,
2743 				CASE_SENSITIVE, g_vol->upcase,
2744 				g_vol->upcase_len);
2745 		*/
2746 		i = ntfs_names_full_collate(file_name->file_name, file_name->file_name_length,
2747 				((FILE_NAME_ATTR*)&ie->key.file_name)->file_name, ((FILE_NAME_ATTR*)&ie->key.file_name)->file_name_length,
2748 				CASE_SENSITIVE, g_vol->upcase, g_vol->upcase_len);
2749 		if (i == -1)
2750 			break;
2751 		/* Complete match. Bugger. Can't insert. */
2752 		if (!i)
2753 			return -EEXIST;
2754 do_next:
2755 #ifdef DEBUG
2756 		/* Next entry. */
2757 		if (!ie->length) {
2758 			ntfs_log_debug("BUG: ie->length is zero, breaking out "
2759 					"of loop.\n");
2760 			break;
2761 		}
2762 #endif
2763 		ie = (INDEX_ENTRY*)((char*)ie + le16_to_cpu(ie->length));
2764 	};
2765 	i = (sizeof(INDEX_ENTRY_HEADER) + file_name_size + 7) & ~7;
2766 	err = make_room_for_index_entry_in_index_block(idx, ie, i);
2767 	if (err) {
2768 		ntfs_log_error("make_room_for_index_entry_in_index_block "
2769 				"failed: %s\n", strerror(-err));
2770 		return err;
2771 	}
2772 	/* Create entry in place and copy file name attribute value. */
2773 	ie->indexed_file = file_ref;
2774 	ie->length = cpu_to_le16(i);
2775 	ie->key_length = cpu_to_le16(file_name_size);
2776 	ie->ie_flags = cpu_to_le16(0);
2777 	ie->reserved = cpu_to_le16(0);
2778 	memcpy((char*)&ie->key.file_name, (char*)file_name, file_name_size);
2779 	return 0;
2780 }
2781 
2782 /**
2783  * create_hardlink_res
2784  *
2785  * Create a file_name_attribute in the mft record @m_file which points to the
2786  * parent directory with mft reference @ref_parent.
2787  *
2788  * Then, insert an index entry with this file_name_attribute in the index
2789  * root @idx of the index_root attribute of the parent directory.
2790  *
2791  * @ref_file is the mft reference of @m_file.
2792  *
2793  * Return 0 on success or -errno on error.
2794  */
2795 static int create_hardlink_res(MFT_RECORD *m_parent, const leMFT_REF ref_parent,
2796 		MFT_RECORD *m_file, const leMFT_REF ref_file,
2797 		const s64 allocated_size, const s64 data_size,
2798 		const FILE_ATTR_FLAGS flags, const u16 packed_ea_size,
2799 		const u32 reparse_point_tag, const char *file_name,
2800 		const FILE_NAME_TYPE_FLAGS file_name_type)
2801 {
2802 	FILE_NAME_ATTR *fn;
2803 	int i, fn_size, idx_size;
2804 	INDEX_ENTRY *idx_entry_new;
2805 	ntfschar *uname;
2806 
2807 	/* Create the file_name attribute. */
2808 	i = (strlen(file_name) + 1) * sizeof(ntfschar);
2809 	fn_size = sizeof(FILE_NAME_ATTR) + i;
2810 	fn = ntfs_malloc(fn_size);
2811 	if (!fn)
2812 		return -errno;
2813 	fn->parent_directory = ref_parent;
2814 	fn->creation_time = stdinfo_time(m_file);
2815 	fn->last_data_change_time = fn->creation_time;
2816 	fn->last_mft_change_time = fn->creation_time;
2817 	fn->last_access_time = fn->creation_time;
2818 	fn->allocated_size = cpu_to_sle64(allocated_size);
2819 	fn->data_size = cpu_to_sle64(data_size);
2820 	fn->file_attributes = flags;
2821 	/* These are in a union so can't have both. */
2822 	if (packed_ea_size && reparse_point_tag) {
2823 		free(fn);
2824 		return -EINVAL;
2825 	}
2826 	if (packed_ea_size) {
2827 		free(fn);
2828 		return -EINVAL;
2829 	}
2830 	if (packed_ea_size) {
2831 		fn->packed_ea_size = cpu_to_le16(packed_ea_size);
2832 		fn->reserved = cpu_to_le16(0);
2833 	} else {
2834 		fn->reparse_point_tag = cpu_to_le32(reparse_point_tag);
2835 	}
2836 	fn->file_name_type = file_name_type;
2837 	uname = fn->file_name;
2838 	i = ntfs_mbstoucs_libntfscompat(file_name, &uname, i);
2839 	if (i < 1) {
2840 		free(fn);
2841 		return -EINVAL;
2842 	}
2843 	if (i > 0xff) {
2844 		free(fn);
2845 		return -ENAMETOOLONG;
2846 	}
2847 	/* No terminating null in file names. */
2848 	fn->file_name_length = i;
2849 	fn_size = sizeof(FILE_NAME_ATTR) + i * sizeof(ntfschar);
2850 	/* Increment the link count of @m_file. */
2851 	i = le16_to_cpu(m_file->link_count);
2852 	if (i == 0xffff) {
2853 		ntfs_log_error("Too many hardlinks present already.\n");
2854 		free(fn);
2855 		return -EINVAL;
2856 	}
2857 	m_file->link_count = cpu_to_le16(i + 1);
2858 	/* Add the file_name to @m_file. */
2859 	i = insert_resident_attr_in_mft_record(m_file, AT_FILE_NAME, NULL, 0,
2860 			CASE_SENSITIVE, const_cpu_to_le16(0),
2861 			RESIDENT_ATTR_IS_INDEXED, (u8*)fn, fn_size);
2862 	if (i < 0) {
2863 		ntfs_log_error("create_hardlink failed adding file name "
2864 				"attribute: %s\n", strerror(-i));
2865 		free(fn);
2866 		/* Undo link count increment. */
2867 		m_file->link_count = cpu_to_le16(
2868 				le16_to_cpu(m_file->link_count) - 1);
2869 		return i;
2870 	}
2871 	/* Insert the index entry for file_name in @idx. */
2872 	idx_size = (fn_size + 7)  & ~7;
2873 	idx_entry_new = ntfs_calloc(idx_size + 0x10);
2874 	if (!idx_entry_new)
2875 		return -errno;
2876 	idx_entry_new->indexed_file = ref_file;
2877 	idx_entry_new->length = cpu_to_le16(idx_size + 0x10);
2878 	idx_entry_new->key_length = cpu_to_le16(fn_size);
2879 	memcpy((u8*)idx_entry_new + 0x10, (u8*)fn, fn_size);
2880 	i = insert_index_entry_in_res_dir_index(idx_entry_new, idx_size + 0x10,
2881 			m_parent, NTFS_INDEX_I30, 4, AT_FILE_NAME);
2882 	if (i < 0) {
2883 		ntfs_log_error("create_hardlink failed inserting index entry: "
2884 				"%s\n", strerror(-i));
2885 		/* FIXME: Remove the file name attribute from @m_file. */
2886 		free(idx_entry_new);
2887 		free(fn);
2888 		/* Undo link count increment. */
2889 		m_file->link_count = cpu_to_le16(
2890 				le16_to_cpu(m_file->link_count) - 1);
2891 		return i;
2892 	}
2893 	free(idx_entry_new);
2894 	free(fn);
2895 	return 0;
2896 }
2897 
2898 /**
2899  * create_hardlink
2900  *
2901  * Create a file_name_attribute in the mft record @m_file which points to the
2902  * parent directory with mft reference @ref_parent.
2903  *
2904  * Then, insert an index entry with this file_name_attribute in the index
2905  * block @idx of the index allocation attribute of the parent directory.
2906  *
2907  * @ref_file is the mft reference of @m_file.
2908  *
2909  * Return 0 on success or -errno on error.
2910  */
2911 static int create_hardlink(INDEX_BLOCK *idx, const leMFT_REF ref_parent,
2912 		MFT_RECORD *m_file, const leMFT_REF ref_file,
2913 		const s64 allocated_size, const s64 data_size,
2914 		const FILE_ATTR_FLAGS flags, const u16 packed_ea_size,
2915 		const u32 reparse_point_tag, const char *file_name,
2916 		const FILE_NAME_TYPE_FLAGS file_name_type)
2917 {
2918 	FILE_NAME_ATTR *fn;
2919 	int i, fn_size;
2920 	ntfschar *uname;
2921 
2922 	/* Create the file_name attribute. */
2923 	i = (strlen(file_name) + 1) * sizeof(ntfschar);
2924 	fn_size = sizeof(FILE_NAME_ATTR) + i;
2925 	fn = ntfs_malloc(fn_size);
2926 	if (!fn)
2927 		return -errno;
2928 	fn->parent_directory = ref_parent;
2929 	fn->creation_time = stdinfo_time(m_file);
2930 	fn->last_data_change_time = fn->creation_time;
2931 	fn->last_mft_change_time = fn->creation_time;
2932 	fn->last_access_time = fn->creation_time;
2933 		/* allocated size depends on unnamed data being resident */
2934 	if (allocated_size && non_resident_unnamed_data(m_file))
2935 		fn->allocated_size = cpu_to_sle64(allocated_size);
2936 	else
2937 		fn->allocated_size = cpu_to_sle64((data_size + 7) & -8);
2938 	fn->data_size = cpu_to_sle64(data_size);
2939 	fn->file_attributes = flags;
2940 	/* These are in a union so can't have both. */
2941 	if (packed_ea_size && reparse_point_tag) {
2942 		free(fn);
2943 		return -EINVAL;
2944 	}
2945 	if (packed_ea_size) {
2946 		fn->packed_ea_size = cpu_to_le16(packed_ea_size);
2947 		fn->reserved = cpu_to_le16(0);
2948 	} else {
2949 		fn->reparse_point_tag = cpu_to_le32(reparse_point_tag);
2950 	}
2951 	fn->file_name_type = file_name_type;
2952 	uname = fn->file_name;
2953 	i = ntfs_mbstoucs_libntfscompat(file_name, &uname, i);
2954 	if (i < 1) {
2955 		free(fn);
2956 		return -EINVAL;
2957 	}
2958 	if (i > 0xff) {
2959 		free(fn);
2960 		return -ENAMETOOLONG;
2961 	}
2962 	/* No terminating null in file names. */
2963 	fn->file_name_length = i;
2964 	fn_size = sizeof(FILE_NAME_ATTR) + i * sizeof(ntfschar);
2965 	/* Increment the link count of @m_file. */
2966 	i = le16_to_cpu(m_file->link_count);
2967 	if (i == 0xffff) {
2968 		ntfs_log_error("Too many hardlinks present already.\n");
2969 		free(fn);
2970 		return -EINVAL;
2971 	}
2972 	m_file->link_count = cpu_to_le16(i + 1);
2973 	/* Add the file_name to @m_file. */
2974 	i = insert_resident_attr_in_mft_record(m_file, AT_FILE_NAME, NULL, 0,
2975 			CASE_SENSITIVE, cpu_to_le16(0),
2976 			RESIDENT_ATTR_IS_INDEXED, (u8*)fn, fn_size);
2977 	if (i < 0) {
2978 		ntfs_log_error("create_hardlink failed adding file name attribute: "
2979 				"%s\n", strerror(-i));
2980 		free(fn);
2981 		/* Undo link count increment. */
2982 		m_file->link_count = cpu_to_le16(
2983 				le16_to_cpu(m_file->link_count) - 1);
2984 		return i;
2985 	}
2986 	/* Insert the index entry for file_name in @idx. */
2987 	i = insert_file_link_in_dir_index(idx, ref_file, fn, fn_size);
2988 	if (i < 0) {
2989 		ntfs_log_error("create_hardlink failed inserting index entry: %s\n",
2990 				strerror(-i));
2991 		/* FIXME: Remove the file name attribute from @m_file. */
2992 		free(fn);
2993 		/* Undo link count increment. */
2994 		m_file->link_count = cpu_to_le16(
2995 				le16_to_cpu(m_file->link_count) - 1);
2996 		return i;
2997 	}
2998 	free(fn);
2999 	return 0;
3000 }
3001 
3002 /**
3003  * index_obj_id_insert
3004  *
3005  * Insert an index entry with the key @guid and data pointing to the mft record
3006  * @ref in the $O index root of the mft record @m (which must be the mft record
3007  * for $ObjId).
3008  *
3009  * Return 0 on success or -errno on error.
3010  */
3011 static int index_obj_id_insert(MFT_RECORD *m, const GUID *guid,
3012 		const leMFT_REF ref)
3013 {
3014 	INDEX_ENTRY *idx_entry_new;
3015 	int data_ofs, idx_size, err;
3016 	OBJ_ID_INDEX_DATA *oi;
3017 
3018 	/*
3019 	 * Insert the index entry for the object id in the index.
3020 	 *
3021 	 * First determine the size of the index entry to be inserted.  This
3022 	 * consists of the index entry header, followed by the index key, i.e.
3023 	 * the GUID, followed by the index data, i.e. OBJ_ID_INDEX_DATA.
3024 	 */
3025 	data_ofs = (sizeof(INDEX_ENTRY_HEADER) + sizeof(GUID) + 7) & ~7;
3026 	idx_size = (data_ofs + sizeof(OBJ_ID_INDEX_DATA) + 7) & ~7;
3027 	idx_entry_new = ntfs_calloc(idx_size);
3028 	if (!idx_entry_new)
3029 		return -errno;
3030 	idx_entry_new->data_offset = cpu_to_le16(data_ofs);
3031 	idx_entry_new->data_length = cpu_to_le16(sizeof(OBJ_ID_INDEX_DATA));
3032 	idx_entry_new->length = cpu_to_le16(idx_size);
3033 	idx_entry_new->key_length = cpu_to_le16(sizeof(GUID));
3034 	idx_entry_new->key.object_id = *guid;
3035 	oi = (OBJ_ID_INDEX_DATA*)((u8*)idx_entry_new + data_ofs);
3036 	oi->mft_reference = ref;
3037 	err = insert_index_entry_in_res_dir_index(idx_entry_new, idx_size, m,
3038 			NTFS_INDEX_O, 2, AT_UNUSED);
3039 	free(idx_entry_new);
3040 	if (err < 0) {
3041 		ntfs_log_error("index_obj_id_insert failed inserting index "
3042 				"entry: %s\n", strerror(-err));
3043 		return err;
3044 	}
3045 	return 0;
3046 }
3047 
3048 /**
3049  * mkntfs_cleanup
3050  */
3051 static void mkntfs_cleanup(void)
3052 {
3053 	struct BITMAP_ALLOCATION *p, *q;
3054 
3055 	/* Close the volume */
3056 	if (g_vol) {
3057 		if (g_vol->dev) {
3058 			if (NDevOpen(g_vol->dev) && g_vol->dev->d_ops->close(g_vol->dev))
3059 				ntfs_log_perror("Warning: Could not close %s", g_vol->dev->d_name);
3060 			ntfs_device_free(g_vol->dev);
3061 		}
3062 		free(g_vol->vol_name);
3063 		free(g_vol->attrdef);
3064 		free(g_vol->upcase);
3065 		free(g_vol);
3066 		g_vol = NULL;
3067 	}
3068 
3069 	/* Free any memory we've used */
3070 	free(g_bad_blocks);	g_bad_blocks	= NULL;
3071 	free(g_buf);		g_buf		= NULL;
3072 	free(g_index_block);	g_index_block	= NULL;
3073 	free(g_dynamic_buf);	g_dynamic_buf	= NULL;
3074 	free(g_mft_bitmap);	g_mft_bitmap	= NULL;
3075 	free(g_rl_bad);		g_rl_bad	= NULL;
3076 	free(g_rl_boot);	g_rl_boot	= NULL;
3077 	free(g_rl_logfile);	g_rl_logfile	= NULL;
3078 	free(g_rl_mft);		g_rl_mft	= NULL;
3079 	free(g_rl_mft_bmp);	g_rl_mft_bmp	= NULL;
3080 	free(g_rl_mftmirr);	g_rl_mftmirr	= NULL;
3081 
3082 	p = g_allocation;
3083 	while (p) {
3084 		q = p->next;
3085 		free(p);
3086 		p = q;
3087 	}
3088 }
3089 
3090 
3091 /**
3092  * mkntfs_open_partition -
3093  */
3094 static BOOL mkntfs_open_partition(ntfs_volume *vol)
3095 {
3096 	BOOL result = FALSE;
3097 	int i;
3098 	struct stat sbuf;
3099 	unsigned long mnt_flags;
3100 
3101 	/*
3102 	 * Allocate and initialize an ntfs device structure and attach it to
3103 	 * the volume.
3104 	 */
3105 	vol->dev = ntfs_device_alloc(opts.dev_name, 0, &ntfs_device_default_io_ops, NULL);
3106 	if (!vol->dev) {
3107 		ntfs_log_perror("Could not create device");
3108 		goto done;
3109 	}
3110 
3111 	/* Open the device for reading or reading and writing. */
3112 	if (opts.no_action) {
3113 		ntfs_log_quiet("Running in READ-ONLY mode!\n");
3114 		i = O_RDONLY;
3115 	} else {
3116 		i = O_RDWR;
3117 	}
3118 	if (vol->dev->d_ops->open(vol->dev, i)) {
3119 		if (errno == ENOENT)
3120 			ntfs_log_error("The device doesn't exist; did you specify it correctly?\n");
3121 		else
3122 			ntfs_log_perror("Could not open %s", vol->dev->d_name);
3123 		goto done;
3124 	}
3125 	/* Verify we are dealing with a block device. */
3126 	if (vol->dev->d_ops->stat(vol->dev, &sbuf)) {
3127 		ntfs_log_perror("Error getting information about %s", vol->dev->d_name);
3128 		goto done;
3129 	}
3130 
3131 	if (!S_ISBLK(sbuf.st_mode)) {
3132 		ntfs_log_error("%s is not a block device.\n", vol->dev->d_name);
3133 		if (!opts.force) {
3134 			ntfs_log_error("Refusing to make a filesystem here!\n");
3135 			goto done;
3136 		}
3137 		if (!opts.num_sectors) {
3138 			if (!sbuf.st_size && !sbuf.st_blocks) {
3139 				ntfs_log_error("You must specify the number of sectors.\n");
3140 				goto done;
3141 			}
3142 			if (opts.sector_size) {
3143 				if (sbuf.st_size)
3144 					opts.num_sectors = sbuf.st_size / opts.sector_size;
3145 				else
3146 					opts.num_sectors = ((s64)sbuf.st_blocks << 9) / opts.sector_size;
3147 			} else {
3148 				if (sbuf.st_size)
3149 					opts.num_sectors = sbuf.st_size / 512;
3150 				else
3151 					opts.num_sectors = sbuf.st_blocks;
3152 				opts.sector_size = 512;
3153 			}
3154 		}
3155 		ntfs_log_warning("mkntfs forced anyway.\n");
3156 #ifdef HAVE_LINUX_MAJOR_H
3157 	} else if ((IDE_DISK_MAJOR(MAJOR(sbuf.st_rdev)) &&
3158 			MINOR(sbuf.st_rdev) % 64 == 0) ||
3159 			(SCSI_DISK_MAJOR(MAJOR(sbuf.st_rdev)) &&
3160 			MINOR(sbuf.st_rdev) % 16 == 0)) {
3161 		ntfs_log_error("%s is entire device, not just one partition.\n", vol->dev->d_name);
3162 		if (!opts.force) {
3163 			ntfs_log_error("Refusing to make a filesystem here!\n");
3164 			goto done;
3165 		}
3166 		ntfs_log_warning("mkntfs forced anyway.\n");
3167 #endif
3168 	}
3169 	/* Make sure the file system is not mounted. */
3170 	if (ntfs_check_if_mounted(vol->dev->d_name, &mnt_flags)) {
3171 		ntfs_log_perror("Failed to determine whether %s is mounted", vol->dev->d_name);
3172 	} else if (mnt_flags & NTFS_MF_MOUNTED) {
3173 		ntfs_log_error("%s is mounted.\n", vol->dev->d_name);
3174 		if (!opts.force) {
3175 			ntfs_log_error("Refusing to make a filesystem here!\n");
3176 			goto done;
3177 		}
3178 		ntfs_log_warning("mkntfs forced anyway. Hope /etc/mtab is incorrect.\n");
3179 	}
3180 	result = TRUE;
3181 done:
3182 	return result;
3183 }
3184 
3185 /**
3186  * mkntfs_get_page_size - detect the system's memory page size.
3187  */
3188 static long mkntfs_get_page_size(void)
3189 {
3190 	return NTFS_PAGE_SIZE;
3191 }
3192 
3193 /**
3194  * mkntfs_override_vol_params -
3195  */
3196 static BOOL mkntfs_override_vol_params(ntfs_volume *vol)
3197 {
3198 	s64 volume_size;
3199 	long page_size;
3200 	int i;
3201 	BOOL winboot = TRUE;
3202 
3203 	/* If user didn't specify the sector size, determine it now. */
3204 	if (opts.sector_size < 0) {
3205 		opts.sector_size = ntfs_device_sector_size_get(vol->dev);
3206 		if (opts.sector_size < 0) {
3207 			ntfs_log_warning("The sector size was not specified "
3208 				"for %s and it could not be obtained "
3209 				"automatically.  It has been set to 512 "
3210 				"bytes.\n", vol->dev->d_name);
3211 			opts.sector_size = 512;
3212 		}
3213 	}
3214 	/* Validate sector size. */
3215 	if ((opts.sector_size - 1) & opts.sector_size) {
3216 		ntfs_log_error("The sector size is invalid.  It must be a "
3217 			"power of two, e.g. 512, 1024.\n");
3218 		return FALSE;
3219 	}
3220 	if (opts.sector_size < 256 || opts.sector_size > 4096) {
3221 		ntfs_log_error("The sector size is invalid.  The minimum size "
3222 			"is 256 bytes and the maximum is 4096 bytes.\n");
3223 		return FALSE;
3224 	}
3225 	ntfs_log_debug("sector size = %ld bytes\n", opts.sector_size);
3226 	/* Now set the device block size to the sector size. */
3227 	if (ntfs_device_block_size_set(vol->dev, opts.sector_size))
3228 		ntfs_log_debug("Failed to set the device block size to the "
3229 				"sector size.  This may cause problems when "
3230 				"creating the backup boot sector and also may "
3231 				"affect performance but should be harmless "
3232 				"otherwise.  Error: %s\n", strerror(errno));
3233 	/* If user didn't specify the number of sectors, determine it now. */
3234 	if (opts.num_sectors < 0) {
3235 		opts.num_sectors = ntfs_device_size_get(vol->dev,
3236 				opts.sector_size);
3237 		if (opts.num_sectors <= 0) {
3238 			ntfs_log_error("Couldn't determine the size of %s.  "
3239 				"Please specify the number of sectors "
3240 				"manually.\n", vol->dev->d_name);
3241 			return FALSE;
3242 		}
3243 	}
3244 	ntfs_log_debug("number of sectors = %lld (0x%llx)\n", opts.num_sectors,
3245 			opts.num_sectors);
3246 	/*
3247 	 * Reserve the last sector for the backup boot sector unless the
3248 	 * sector size is less than 512 bytes in which case reserve 512 bytes
3249 	 * worth of sectors.
3250 	 */
3251 	i = 1;
3252 	if (opts.sector_size < 512)
3253 		i = 512 / opts.sector_size;
3254 	opts.num_sectors -= i;
3255 	/* If user didn't specify the partition start sector, determine it. */
3256 	if (opts.part_start_sect < 0) {
3257 		opts.part_start_sect = ntfs_device_partition_start_sector_get(
3258 				vol->dev);
3259 		if (opts.part_start_sect < 0) {
3260 			ntfs_log_warning("The partition start sector was not "
3261 				"specified for %s and it could not be obtained "
3262 				"automatically.  It has been set to 0.\n",
3263 				vol->dev->d_name);
3264 			opts.part_start_sect = 0;
3265 			winboot = FALSE;
3266 		} else if (opts.part_start_sect >> 32) {
3267 			ntfs_log_warning("The partition start sector specified "
3268 				"for %s and the automatically determined value "
3269 				"is too large.  It has been set to 0.\n",
3270 				vol->dev->d_name);
3271 			opts.part_start_sect = 0;
3272 			winboot = FALSE;
3273 		}
3274 	} else if (opts.part_start_sect >> 32) {
3275 		ntfs_log_error("Invalid partition start sector.  Maximum is "
3276 			"4294967295 (2^32-1).\n");
3277 		return FALSE;
3278 	}
3279 	/* If user didn't specify the sectors per track, determine it now. */
3280 	if (opts.sectors_per_track < 0) {
3281 		opts.sectors_per_track = ntfs_device_sectors_per_track_get(
3282 				vol->dev);
3283 		if (opts.sectors_per_track < 0) {
3284 			ntfs_log_warning("The number of sectors per track was "
3285 				"not specified for %s and it could not be "
3286 				"obtained automatically.  It has been set to "
3287 				"0.\n", vol->dev->d_name);
3288 			opts.sectors_per_track = 0;
3289 			winboot = FALSE;
3290 		} else if (opts.sectors_per_track > 65535) {
3291 			ntfs_log_warning("The number of sectors per track was "
3292 				"not specified for %s and the automatically "
3293 				"determined value is too large.  It has been "
3294 				"set to 0.\n", vol->dev->d_name);
3295 			opts.sectors_per_track = 0;
3296 			winboot = FALSE;
3297 		}
3298 	} else if (opts.sectors_per_track > 65535) {
3299 		ntfs_log_error("Invalid number of sectors per track.  Maximum "
3300 			"is 65535.\n");
3301 		return FALSE;
3302 	}
3303 	/* If user didn't specify the number of heads, determine it now. */
3304 	if (opts.heads < 0) {
3305 		opts.heads = ntfs_device_heads_get(vol->dev);
3306 		if (opts.heads < 0) {
3307 			ntfs_log_warning("The number of heads was not "
3308 				"specified for %s and it could not be obtained "
3309 				"automatically.  It has been set to 0.\n",
3310 				vol->dev->d_name);
3311 			opts.heads = 0;
3312 			winboot = FALSE;
3313 		} else if (opts.heads > 65535) {
3314 			ntfs_log_warning("The number of heads was not "
3315 				"specified for %s and the automatically "
3316 				"determined value is too large.  It has been "
3317 				"set to 0.\n", vol->dev->d_name);
3318 			opts.heads = 0;
3319 			winboot = FALSE;
3320 		}
3321 	} else if (opts.heads > 65535) {
3322 		ntfs_log_error("Invalid number of heads.  Maximum is 65535.\n");
3323 		return FALSE;
3324 	}
3325 	volume_size = opts.num_sectors * opts.sector_size;
3326 	/* Validate volume size. */
3327 	if (volume_size < (1 << 20)) {			/* 1MiB */
3328 		ntfs_log_error("Device is too small (%llikiB).  Minimum NTFS "
3329 				"volume size is 1MiB.\n",
3330 				(long long)(volume_size / 1024));
3331 		return FALSE;
3332 	}
3333 	ntfs_log_debug("volume size = %llikiB\n", volume_size / 1024);
3334 	/* If user didn't specify the cluster size, determine it now. */
3335 	if (!vol->cluster_size) {
3336 		/*
3337 		 * Windows Vista always uses 4096 bytes as the default cluster
3338 		 * size regardless of the volume size so we do it, too.
3339 		 */
3340 		vol->cluster_size = 4096;
3341 		/* For small volumes on devices with large sector sizes. */
3342 		if (vol->cluster_size < (u32)opts.sector_size)
3343 			vol->cluster_size = opts.sector_size;
3344 		/*
3345 		 * For huge volumes, grow the cluster size until the number of
3346 		 * clusters fits into 32 bits or the cluster size exceeds the
3347 		 * maximum limit of 64kiB.
3348 		 */
3349 		while (volume_size >> (ffs(vol->cluster_size) - 1 + 32)) {
3350 			vol->cluster_size <<= 1;
3351 			if (vol->cluster_size > 65535) {
3352 				ntfs_log_error("Device is too large to hold an "
3353 						"NTFS volume (maximum size is "
3354 						"256TiB).\n");
3355 				return FALSE;
3356 			}
3357 		}
3358 		ntfs_log_quiet("Cluster size has been automatically set to %u "
3359 				"bytes.\n", (unsigned)vol->cluster_size);
3360 	}
3361 	/* Validate cluster size. */
3362 	if (vol->cluster_size & (vol->cluster_size - 1)) {
3363 		ntfs_log_error("The cluster size is invalid.  It must be a "
3364 				"power of two, e.g. 1024, 4096.\n");
3365 		return FALSE;
3366 	}
3367 	if (vol->cluster_size < (u32)opts.sector_size) {
3368 		ntfs_log_error("The cluster size is invalid.  It must be equal "
3369 				"to, or larger than, the sector size.\n");
3370 		return FALSE;
3371 	}
3372 	if (vol->cluster_size > 128 * (u32)opts.sector_size) {
3373 		ntfs_log_error("The cluster size is invalid.  It cannot be "
3374 				"more that 128 times the size of the sector "
3375 				"size.\n");
3376 		return FALSE;
3377 	}
3378 	if (vol->cluster_size > 65536) {
3379 		ntfs_log_error("The cluster size is invalid.  The maximum "
3380 			"cluster size is 65536 bytes (64kiB).\n");
3381 		return FALSE;
3382 	}
3383 	vol->cluster_size_bits = ffs(vol->cluster_size) - 1;
3384 	ntfs_log_debug("cluster size = %u bytes\n",
3385 			(unsigned int)vol->cluster_size);
3386 	if (vol->cluster_size > 4096) {
3387 		if (opts.enable_compression) {
3388 			if (!opts.force) {
3389 				ntfs_log_error("Windows cannot use compression "
3390 						"when the cluster size is "
3391 						"larger than 4096 bytes.\n");
3392 				return FALSE;
3393 			}
3394 			opts.enable_compression = 0;
3395 		}
3396 		ntfs_log_warning("Windows cannot use compression when the "
3397 				"cluster size is larger than 4096 bytes.  "
3398 				"Compression has been disabled for this "
3399 				"volume.\n");
3400 	}
3401 	vol->nr_clusters = volume_size / vol->cluster_size;
3402 	/*
3403 	 * Check the cluster_size and num_sectors for consistency with
3404 	 * sector_size and num_sectors. And check both of these for consistency
3405 	 * with volume_size.
3406 	 */
3407 	if ((vol->nr_clusters != ((opts.num_sectors * opts.sector_size) /
3408 			vol->cluster_size) ||
3409 			(volume_size / opts.sector_size) != opts.num_sectors ||
3410 			(volume_size / vol->cluster_size) !=
3411 			vol->nr_clusters)) {
3412 		/* XXX is this code reachable? */
3413 		ntfs_log_error("Illegal combination of volume/cluster/sector "
3414 				"size and/or cluster/sector number.\n");
3415 		return FALSE;
3416 	}
3417 	ntfs_log_debug("number of clusters = %llu (0x%llx)\n",
3418 			vol->nr_clusters, vol->nr_clusters);
3419 	/* Number of clusters must fit within 32 bits (Win2k limitation). */
3420 	if (vol->nr_clusters >> 32) {
3421 		if (vol->cluster_size >= 65536) {
3422 			ntfs_log_error("Device is too large to hold an NTFS "
3423 					"volume (maximum size is 256TiB).\n");
3424 			return FALSE;
3425 		}
3426 		ntfs_log_error("Number of clusters exceeds 32 bits.  Please "
3427 				"try again with a larger\ncluster size or "
3428 				"leave the cluster size unspecified and the "
3429 				"smallest possible cluster size for the size "
3430 				"of the device will be used.\n");
3431 		return FALSE;
3432 	}
3433 	page_size = mkntfs_get_page_size();
3434 	/*
3435 	 * Set the mft record size.  By default this is 1024 but it has to be
3436 	 * at least as big as a sector and not bigger than a page on the system
3437 	 * or the NTFS kernel driver will not be able to mount the volume.
3438 	 * TODO: The mft record size should be user specifiable just like the
3439 	 * "inode size" can be specified on other Linux/Unix file systems.
3440 	 */
3441 	vol->mft_record_size = 1024;
3442 	if (vol->mft_record_size < (u32)opts.sector_size)
3443 		vol->mft_record_size = opts.sector_size;
3444 	if (vol->mft_record_size > (unsigned long)page_size)
3445 		ntfs_log_warning("Mft record size (%u bytes) exceeds system "
3446 				"page size (%li bytes).  You will not be able "
3447 				"to mount this volume using the NTFS kernel "
3448 				"driver.\n", (unsigned)vol->mft_record_size,
3449 				page_size);
3450 	vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1;
3451 	ntfs_log_debug("mft record size = %u bytes\n",
3452 			(unsigned)vol->mft_record_size);
3453 	/*
3454 	 * Set the index record size.  By default this is 4096 but it has to be
3455 	 * at least as big as a sector and not bigger than a page on the system
3456 	 * or the NTFS kernel driver will not be able to mount the volume.
3457 	 * FIXME: Should we make the index record size to be user specifiable?
3458 	 */
3459 	vol->indx_record_size = 4096;
3460 	if (vol->indx_record_size < (u32)opts.sector_size)
3461 		vol->indx_record_size = opts.sector_size;
3462 	if (vol->indx_record_size > (unsigned long)page_size)
3463 		ntfs_log_warning("Index record size (%u bytes) exceeds system "
3464 				"page size (%li bytes).  You will not be able "
3465 				"to mount this volume using the NTFS kernel "
3466 				"driver.\n", (unsigned)vol->indx_record_size,
3467 				page_size);
3468 	vol->indx_record_size_bits = ffs(vol->indx_record_size) - 1;
3469 	ntfs_log_debug("index record size = %u bytes\n",
3470 			(unsigned)vol->indx_record_size);
3471 	if (!winboot) {
3472 		ntfs_log_warning("To boot from a device, Windows needs the "
3473 				"'partition start sector', the 'sectors per "
3474 				"track' and the 'number of heads' to be "
3475 				"set.\n");
3476 		ntfs_log_warning("Windows will not be able to boot from this "
3477 				"device.\n");
3478 	}
3479 	return TRUE;
3480 }
3481 
3482 /**
3483  * mkntfs_initialize_bitmaps -
3484  */
3485 static BOOL mkntfs_initialize_bitmaps(void)
3486 {
3487 	u64 i;
3488 	int mft_bitmap_size;
3489 
3490 	/* Determine lcn bitmap byte size and allocate it. */
3491 	g_lcn_bitmap_byte_size = (g_vol->nr_clusters + 7) >> 3;
3492 	/* Needs to be multiple of 8 bytes. */
3493 	g_lcn_bitmap_byte_size = (g_lcn_bitmap_byte_size + 7) & ~7;
3494 	i = (g_lcn_bitmap_byte_size + g_vol->cluster_size - 1) &
3495 			~(g_vol->cluster_size - 1);
3496 	ntfs_log_debug("g_lcn_bitmap_byte_size = %i, allocated = %llu\n",
3497 			g_lcn_bitmap_byte_size, i);
3498 	g_dynamic_buf_size = mkntfs_get_page_size();
3499 	g_dynamic_buf = (u8*)ntfs_calloc(g_dynamic_buf_size);
3500 	if (!g_dynamic_buf)
3501 		return FALSE;
3502 	/*
3503 	 * $Bitmap can overlap the end of the volume. Any bits in this region
3504 	 * must be set. This region also encompasses the backup boot sector.
3505 	 */
3506 	if (!bitmap_allocate(g_vol->nr_clusters,
3507 		    ((s64)g_lcn_bitmap_byte_size << 3) - g_vol->nr_clusters))
3508 		return (FALSE);
3509 	/*
3510 	 * Mft size is 27 (NTFS 3.0+) mft records or one cluster, whichever is
3511 	 * bigger.
3512 	 */
3513 	g_mft_size = 27;
3514 	g_mft_size *= g_vol->mft_record_size;
3515 	if (g_mft_size < (s32)g_vol->cluster_size)
3516 		g_mft_size = g_vol->cluster_size;
3517 	ntfs_log_debug("MFT size = %i (0x%x) bytes\n", g_mft_size, g_mft_size);
3518 	/* Determine mft bitmap size and allocate it. */
3519 	mft_bitmap_size = g_mft_size / g_vol->mft_record_size;
3520 	/* Convert to bytes, at least one. */
3521 	g_mft_bitmap_byte_size = (mft_bitmap_size + 7) >> 3;
3522 	/* Mft bitmap is allocated in multiples of 8 bytes. */
3523 	g_mft_bitmap_byte_size = (g_mft_bitmap_byte_size + 7) & ~7;
3524 	ntfs_log_debug("mft_bitmap_size = %i, g_mft_bitmap_byte_size = %i\n",
3525 			mft_bitmap_size, g_mft_bitmap_byte_size);
3526 	g_mft_bitmap = ntfs_calloc(g_mft_bitmap_byte_size);
3527 	if (!g_mft_bitmap)
3528 		return FALSE;
3529 	/* Create runlist for mft bitmap. */
3530 	g_rl_mft_bmp = ntfs_malloc(2 * sizeof(runlist));
3531 	if (!g_rl_mft_bmp)
3532 		return FALSE;
3533 
3534 	g_rl_mft_bmp[0].vcn = 0LL;
3535 	/* Mft bitmap is right after $Boot's data. */
3536 	i = (8192 + g_vol->cluster_size - 1) / g_vol->cluster_size;
3537 	g_rl_mft_bmp[0].lcn = i;
3538 	/*
3539 	 * Size is always one cluster, even though valid data size and
3540 	 * initialized data size are only 8 bytes.
3541 	 */
3542 	g_rl_mft_bmp[1].vcn = 1LL;
3543 	g_rl_mft_bmp[0].length = 1LL;
3544 	g_rl_mft_bmp[1].lcn = -1LL;
3545 	g_rl_mft_bmp[1].length = 0LL;
3546 	/* Allocate cluster for mft bitmap. */
3547 	return (bitmap_allocate(i,1));
3548 }
3549 
3550 /**
3551  * mkntfs_initialize_rl_mft -
3552  */
3553 static BOOL mkntfs_initialize_rl_mft(void)
3554 {
3555 	int j;
3556 	BOOL done;
3557 
3558 	/* If user didn't specify the mft lcn, determine it now. */
3559 	if (!g_mft_lcn) {
3560 		/*
3561 		 * We start at the higher value out of 16kiB and just after the
3562 		 * mft bitmap.
3563 		 */
3564 		g_mft_lcn = g_rl_mft_bmp[0].lcn + g_rl_mft_bmp[0].length;
3565 		if (g_mft_lcn * g_vol->cluster_size < 16 * 1024)
3566 			g_mft_lcn = (16 * 1024 + g_vol->cluster_size - 1) /
3567 					g_vol->cluster_size;
3568 	}
3569 	ntfs_log_debug("$MFT logical cluster number = 0x%llx\n", g_mft_lcn);
3570 	/* Determine MFT zone size. */
3571 	g_mft_zone_end = g_vol->nr_clusters;
3572 	switch (opts.mft_zone_multiplier) {  /* % of volume size in clusters */
3573 	case 4:
3574 		g_mft_zone_end = g_mft_zone_end >> 1;	/* 50%   */
3575 		break;
3576 	case 3:
3577 		g_mft_zone_end = g_mft_zone_end * 3 >> 3;/* 37.5% */
3578 		break;
3579 	case 2:
3580 		g_mft_zone_end = g_mft_zone_end >> 2;	/* 25%   */
3581 		break;
3582 	case 1:
3583 	default:
3584 		g_mft_zone_end = g_mft_zone_end >> 3;	/* 12.5% */
3585 		break;
3586 	}
3587 	ntfs_log_debug("MFT zone size = %lldkiB\n", g_mft_zone_end <<
3588 			g_vol->cluster_size_bits >> 10 /* >> 10 == / 1024 */);
3589 	/*
3590 	 * The mft zone begins with the mft data attribute, not at the beginning
3591 	 * of the device.
3592 	 */
3593 	g_mft_zone_end += g_mft_lcn;
3594 	/* Create runlist for mft. */
3595 	g_rl_mft = ntfs_malloc(2 * sizeof(runlist));
3596 	if (!g_rl_mft)
3597 		return FALSE;
3598 
3599 	g_rl_mft[0].vcn = 0LL;
3600 	g_rl_mft[0].lcn = g_mft_lcn;
3601 	/* rounded up division by cluster size */
3602 	j = (g_mft_size + g_vol->cluster_size - 1) / g_vol->cluster_size;
3603 	g_rl_mft[1].vcn = j;
3604 	g_rl_mft[0].length = j;
3605 	g_rl_mft[1].lcn = -1LL;
3606 	g_rl_mft[1].length = 0LL;
3607 	/* Allocate clusters for mft. */
3608 	bitmap_allocate(g_mft_lcn,j);
3609 	/* Determine mftmirr_lcn (middle of volume). */
3610 	g_mftmirr_lcn = (opts.num_sectors * opts.sector_size >> 1)
3611 			/ g_vol->cluster_size;
3612 	ntfs_log_debug("$MFTMirr logical cluster number = 0x%llx\n",
3613 			g_mftmirr_lcn);
3614 	/* Create runlist for mft mirror. */
3615 	g_rl_mftmirr = ntfs_malloc(2 * sizeof(runlist));
3616 	if (!g_rl_mftmirr)
3617 		return FALSE;
3618 
3619 	g_rl_mftmirr[0].vcn = 0LL;
3620 	g_rl_mftmirr[0].lcn = g_mftmirr_lcn;
3621 	/*
3622 	 * The mft mirror is either 4kb (the first four records) or one cluster
3623 	 * in size, which ever is bigger. In either case, it contains a
3624 	 * byte-for-byte identical copy of the beginning of the mft (i.e. either
3625 	 * the first four records (4kb) or the first cluster worth of records,
3626 	 * whichever is bigger).
3627 	 */
3628 	j = (4 * g_vol->mft_record_size + g_vol->cluster_size - 1) / g_vol->cluster_size;
3629 	g_rl_mftmirr[1].vcn = j;
3630 	g_rl_mftmirr[0].length = j;
3631 	g_rl_mftmirr[1].lcn = -1LL;
3632 	g_rl_mftmirr[1].length = 0LL;
3633 	/* Allocate clusters for mft mirror. */
3634 	done = bitmap_allocate(g_mftmirr_lcn,j);
3635 	g_logfile_lcn = g_mftmirr_lcn + j;
3636 	ntfs_log_debug("$LogFile logical cluster number = 0x%llx\n",
3637 			g_logfile_lcn);
3638 	return (done);
3639 }
3640 
3641 /**
3642  * mkntfs_initialize_rl_logfile -
3643  */
3644 static BOOL mkntfs_initialize_rl_logfile(void)
3645 {
3646 	int j;
3647 	u64 volume_size;
3648 
3649 	/* Create runlist for log file. */
3650 	g_rl_logfile = ntfs_malloc(2 * sizeof(runlist));
3651 	if (!g_rl_logfile)
3652 		return FALSE;
3653 
3654 
3655 	volume_size = g_vol->nr_clusters << g_vol->cluster_size_bits;
3656 
3657 	g_rl_logfile[0].vcn = 0LL;
3658 	g_rl_logfile[0].lcn = g_logfile_lcn;
3659 	/*
3660 	 * Determine logfile_size from volume_size (rounded up to a cluster),
3661 	 * making sure it does not overflow the end of the volume.
3662 	 */
3663 	if (volume_size < 2048LL * 1024)		/* < 2MiB	*/
3664 		g_logfile_size = 256LL * 1024;		/*   -> 256kiB	*/
3665 	else if (volume_size < 4000000LL)		/* < 4MB	*/
3666 		g_logfile_size = 512LL * 1024;		/*   -> 512kiB	*/
3667 	else if (volume_size <= 200LL * 1024 * 1024)	/* < 200MiB	*/
3668 		g_logfile_size = 2048LL * 1024;		/*   -> 2MiB	*/
3669 	else	{
3670 		/*
3671 		 * FIXME: The $LogFile size is 64 MiB upwards from 12GiB but
3672 		 * the "200" divider below apparently approximates "100" or
3673 		 * some other value as the volume size decreases. For example:
3674 		 *      Volume size   LogFile size    Ratio
3675 		 *	  8799808        46048       191.100
3676 		 *	  8603248        45072       190.877
3677 		 *	  7341704        38768       189.375
3678 		 *	  6144828        32784       187.433
3679 		 *	  4192932        23024       182.111
3680 		 */
3681 		if (volume_size >= 12LL << 30)		/* > 12GiB	*/
3682 			g_logfile_size = 64 << 20;	/*   -> 64MiB	*/
3683 		else
3684 			g_logfile_size = (volume_size / 200) &
3685 					~(g_vol->cluster_size - 1);
3686 	}
3687 	j = g_logfile_size / g_vol->cluster_size;
3688 	while (g_rl_logfile[0].lcn + j >= g_vol->nr_clusters) {
3689 		/*
3690 		 * $Logfile would overflow volume. Need to make it smaller than
3691 		 * the standard size. It's ok as we are creating a non-standard
3692 		 * volume anyway if it is that small.
3693 		 */
3694 		g_logfile_size >>= 1;
3695 		j = g_logfile_size / g_vol->cluster_size;
3696 	}
3697 	g_logfile_size = (g_logfile_size + g_vol->cluster_size - 1) &
3698 			~(g_vol->cluster_size - 1);
3699 	ntfs_log_debug("$LogFile (journal) size = %ikiB\n",
3700 			g_logfile_size / 1024);
3701 	/*
3702 	 * FIXME: The 256kiB limit is arbitrary. Should find out what the real
3703 	 * minimum requirement for Windows is so it doesn't blue screen.
3704 	 */
3705 	if (g_logfile_size < 256 << 10) {
3706 		ntfs_log_error("$LogFile would be created with invalid size. "
3707 				"This is not allowed as it would cause Windows "
3708 				"to blue screen and during boot.\n");
3709 		return FALSE;
3710 	}
3711 	g_rl_logfile[1].vcn = j;
3712 	g_rl_logfile[0].length = j;
3713 	g_rl_logfile[1].lcn = -1LL;
3714 	g_rl_logfile[1].length = 0LL;
3715 	/* Allocate clusters for log file. */
3716 	return (bitmap_allocate(g_logfile_lcn,j));
3717 }
3718 
3719 /**
3720  * mkntfs_initialize_rl_boot -
3721  */
3722 static BOOL mkntfs_initialize_rl_boot(void)
3723 {
3724 	int j;
3725 	/* Create runlist for $Boot. */
3726 	g_rl_boot = ntfs_malloc(2 * sizeof(runlist));
3727 	if (!g_rl_boot)
3728 		return FALSE;
3729 
3730 	g_rl_boot[0].vcn = 0LL;
3731 	g_rl_boot[0].lcn = 0LL;
3732 	/*
3733 	 * $Boot is always 8192 (0x2000) bytes or 1 cluster, whichever is
3734 	 * bigger.
3735 	 */
3736 	j = (8192 + g_vol->cluster_size - 1) / g_vol->cluster_size;
3737 	g_rl_boot[1].vcn = j;
3738 	g_rl_boot[0].length = j;
3739 	g_rl_boot[1].lcn = -1LL;
3740 	g_rl_boot[1].length = 0LL;
3741 	/* Allocate clusters for $Boot. */
3742 	return (bitmap_allocate(0,j));
3743 }
3744 
3745 /**
3746  * mkntfs_initialize_rl_bad -
3747  */
3748 static BOOL mkntfs_initialize_rl_bad(void)
3749 {
3750 	/* Create runlist for $BadClus, $DATA named stream $Bad. */
3751 	g_rl_bad = ntfs_malloc(2 * sizeof(runlist));
3752 	if (!g_rl_bad)
3753 		return FALSE;
3754 
3755 	g_rl_bad[0].vcn = 0LL;
3756 	g_rl_bad[0].lcn = -1LL;
3757 	/*
3758 	 * $BadClus named stream $Bad contains the whole volume as a single
3759 	 * sparse runlist entry.
3760 	 */
3761 	g_rl_bad[1].vcn = g_vol->nr_clusters;
3762 	g_rl_bad[0].length = g_vol->nr_clusters;
3763 	g_rl_bad[1].lcn = -1LL;
3764 	g_rl_bad[1].length = 0LL;
3765 
3766 	/* TODO: Mark bad blocks as such. */
3767 	return TRUE;
3768 }
3769 
3770 /**
3771  * mkntfs_fill_device_with_zeroes -
3772  */
3773 static BOOL mkntfs_fill_device_with_zeroes(void)
3774 {
3775 	/*
3776 	 * If not quick format, fill the device with 0s.
3777 	 * FIXME: Except bad blocks! (AIA)
3778 	 */
3779 	int i;
3780 	ssize_t bw;
3781 	unsigned long long position;
3782 	float progress_inc = (float)g_vol->nr_clusters / 100;
3783 	u64 volume_size;
3784 
3785 	volume_size = g_vol->nr_clusters << g_vol->cluster_size_bits;
3786 
3787 	ntfs_log_progress("Initializing device with zeroes:   0%%");
3788 	for (position = 0; position < (unsigned long long)g_vol->nr_clusters;
3789 			position++) {
3790 		if (!(position % (int)(progress_inc+1))) {
3791 			ntfs_log_progress("\b\b\b\b%3.0f%%", position /
3792 					progress_inc);
3793 		}
3794 		bw = mkntfs_write(g_vol->dev, g_buf, g_vol->cluster_size);
3795 		if (bw != (ssize_t)g_vol->cluster_size) {
3796 			if (bw != -1 || errno != EIO) {
3797 				ntfs_log_error("This should not happen.\n");
3798 				return FALSE;
3799 			}
3800 			if (!position) {
3801 				ntfs_log_error("Error: Cluster zero is bad. "
3802 					"Cannot create NTFS file "
3803 					"system.\n");
3804 				return FALSE;
3805 			}
3806 			/* Add the baddie to our bad blocks list. */
3807 			if (!append_to_bad_blocks(position))
3808 				return FALSE;
3809 			ntfs_log_quiet("\nFound bad cluster (%lld). Adding to "
3810 				"list of bad blocks.\nInitializing "
3811 				"device with zeroes: %3.0f%%", position,
3812 				position / progress_inc);
3813 			/* Seek to next cluster. */
3814 			g_vol->dev->d_ops->seek(g_vol->dev,
3815 					((off_t)position + 1) *
3816 					g_vol->cluster_size, SEEK_SET);
3817 		}
3818 	}
3819 	ntfs_log_progress("\b\b\b\b100%%");
3820 	position = (volume_size & (g_vol->cluster_size - 1)) /
3821 			opts.sector_size;
3822 	for (i = 0; (unsigned long)i < position; i++) {
3823 		bw = mkntfs_write(g_vol->dev, g_buf, opts.sector_size);
3824 		if (bw != opts.sector_size) {
3825 			if (bw != -1 || errno != EIO) {
3826 				ntfs_log_error("This should not happen.\n");
3827 				return FALSE;
3828 			} else if (i + 1ull == position) {
3829 				ntfs_log_error("Error: Bad cluster found in "
3830 					"location reserved for system "
3831 					"file $Boot.\n");
3832 				return FALSE;
3833 			}
3834 			/* Seek to next sector. */
3835 			g_vol->dev->d_ops->seek(g_vol->dev,
3836 					opts.sector_size, SEEK_CUR);
3837 		}
3838 	}
3839 	ntfs_log_progress(" - Done.\n");
3840 	return TRUE;
3841 }
3842 
3843 /**
3844  * mkntfs_sync_index_record
3845  *
3846  * (ERSO) made a function out of this, but the reason for doing that
3847  * disappeared during coding....
3848  */
3849 static BOOL mkntfs_sync_index_record(INDEX_ALLOCATION* idx, MFT_RECORD* m,
3850 		ntfschar* name, u32 name_len)
3851 {
3852 	int i, err;
3853 	ntfs_attr_search_ctx *ctx;
3854 	ATTR_RECORD *a;
3855 	long long lw;
3856 	runlist	*rl_index = NULL;
3857 
3858 	i = 5 * sizeof(ntfschar);
3859 	ctx = ntfs_attr_get_search_ctx(NULL, m);
3860 	if (!ctx) {
3861 		ntfs_log_perror("Failed to allocate attribute search context");
3862 		return FALSE;
3863 	}
3864 	/* FIXME: This should be IGNORE_CASE! */
3865 	if (mkntfs_attr_lookup(AT_INDEX_ALLOCATION, name, name_len,
3866 			CASE_SENSITIVE, 0, NULL, 0, ctx)) {
3867 		ntfs_attr_put_search_ctx(ctx);
3868 		ntfs_log_error("BUG: $INDEX_ALLOCATION attribute not found.\n");
3869 		return FALSE;
3870 	}
3871 	a = ctx->attr;
3872 	rl_index = ntfs_mapping_pairs_decompress(g_vol, a, NULL);
3873 	if (!rl_index) {
3874 		ntfs_attr_put_search_ctx(ctx);
3875 		ntfs_log_error("Failed to decompress runlist of $INDEX_ALLOCATION "
3876 				"attribute.\n");
3877 		return FALSE;
3878 	}
3879 	if (sle64_to_cpu(a->initialized_size) < i) {
3880 		ntfs_attr_put_search_ctx(ctx);
3881 		free(rl_index);
3882 		ntfs_log_error("BUG: $INDEX_ALLOCATION attribute too short.\n");
3883 		return FALSE;
3884 	}
3885 	ntfs_attr_put_search_ctx(ctx);
3886 	i = sizeof(INDEX_BLOCK) - sizeof(INDEX_HEADER) +
3887 			le32_to_cpu(idx->index.allocated_size);
3888 	err = ntfs_mst_pre_write_fixup((NTFS_RECORD*)idx, i);
3889 	if (err) {
3890 		free(rl_index);
3891 		ntfs_log_error("ntfs_mst_pre_write_fixup() failed while "
3892 			"syncing index block.\n");
3893 		return FALSE;
3894 	}
3895 	lw = ntfs_rlwrite(g_vol->dev, rl_index, (u8*)idx, i, NULL,
3896 				WRITE_STANDARD);
3897 	free(rl_index);
3898 	if (lw != i) {
3899 		ntfs_log_error("Error writing $INDEX_ALLOCATION.\n");
3900 		return FALSE;
3901 	}
3902 	/* No more changes to @idx below here so no need for fixup: */
3903 	/* ntfs_mst_post_write_fixup((NTFS_RECORD*)idx); */
3904 	return TRUE;
3905 }
3906 
3907 /**
3908  * create_file_volume -
3909  */
3910 static BOOL create_file_volume(MFT_RECORD *m, leMFT_REF root_ref,
3911 		VOLUME_FLAGS fl, const GUID *volume_guid)
3912 {
3913 	int i, err;
3914 	u8 *sd;
3915 
3916 	ntfs_log_verbose("Creating $Volume (mft record 3)\n");
3917 	m = (MFT_RECORD*)(g_buf + 3 * g_vol->mft_record_size);
3918 	err = create_hardlink(g_index_block, root_ref, m,
3919 			MK_LE_MREF(FILE_Volume, FILE_Volume), 0LL, 0LL,
3920 			FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
3921 			"$Volume", FILE_NAME_WIN32_AND_DOS);
3922 	if (!err) {
3923 		init_system_file_sd(FILE_Volume, &sd, &i);
3924 		err = add_attr_sd(m, sd, i);
3925 	}
3926 	if (!err)
3927 		err = add_attr_data(m, NULL, 0, CASE_SENSITIVE,
3928 				const_cpu_to_le16(0), NULL, 0);
3929 	if (!err)
3930 		err = add_attr_vol_name(m, g_vol->vol_name, g_vol->vol_name ?
3931 				strlen(g_vol->vol_name) : 0);
3932 	if (!err) {
3933 		if (fl & VOLUME_IS_DIRTY)
3934 			ntfs_log_quiet("Setting the volume dirty so check "
3935 					"disk runs on next reboot into "
3936 					"Windows.\n");
3937 		err = add_attr_vol_info(m, fl, g_vol->major_ver,
3938 				g_vol->minor_ver);
3939 	}
3940 	if (!err && opts.with_uuid)
3941 		err = add_attr_object_id(m, volume_guid);
3942 	if (err < 0) {
3943 		ntfs_log_error("Couldn't create $Volume: %s\n",
3944 				strerror(-err));
3945 		return FALSE;
3946 	}
3947 	return TRUE;
3948 }
3949 
3950 /**
3951  * create_backup_boot_sector
3952  *
3953  * Return 0 on success or -1 if it couldn't be created.
3954  */
3955 static int create_backup_boot_sector(u8 *buff)
3956 {
3957 	const char *s;
3958 	ssize_t bw;
3959 	int size, e;
3960 
3961 	ntfs_log_verbose("Creating backup boot sector.\n");
3962 	/*
3963 	 * Write the first max(512, opts.sector_size) bytes from buf to the
3964 	 * last sector, but limit that to 8192 bytes of written data since that
3965 	 * is how big $Boot is (and how big our buffer is)..
3966 	 */
3967 	size = 512;
3968 	if (size < opts.sector_size)
3969 		size = opts.sector_size;
3970 	if (g_vol->dev->d_ops->seek(g_vol->dev, (opts.num_sectors + 1) *
3971 			opts.sector_size - size, SEEK_SET) == (off_t)-1) {
3972 		ntfs_log_perror("Seek failed");
3973 		goto bb_err;
3974 	}
3975 	if (size > 8192)
3976 		size = 8192;
3977 	bw = mkntfs_write(g_vol->dev, buff, size);
3978 	if (bw == size)
3979 		return 0;
3980 	e = errno;
3981 	if (bw == -1LL)
3982 		s = strerror(e);
3983 	else
3984 		s = "unknown error";
3985 	/* At least some 2.4 kernels return EIO instead of ENOSPC. */
3986 	if (bw != -1LL || (bw == -1LL && e != ENOSPC && e != EIO)) {
3987 		ntfs_log_critical("Couldn't write backup boot sector: %s\n", s);
3988 		return -1;
3989 	}
3990 bb_err:
3991 	ntfs_log_error("Couldn't write backup boot sector. This is due to a "
3992 			"limitation in the\nLinux kernel. This is not a major "
3993 			"problem as Windows check disk will create the\n"
3994 			"backup boot sector when it is run on your next boot "
3995 			"into Windows.\n");
3996 	return -1;
3997 }
3998 
3999 /**
4000  * mkntfs_create_root_structures -
4001  */
4002 static BOOL mkntfs_create_root_structures(void)
4003 {
4004 	NTFS_BOOT_SECTOR *bs;
4005 	MFT_RECORD *m;
4006 	leMFT_REF root_ref;
4007 	leMFT_REF extend_ref;
4008 	int i;
4009 	int j;
4010 	int err;
4011 	u8 *sd;
4012 	FILE_ATTR_FLAGS extend_flags;
4013 	VOLUME_FLAGS volume_flags = const_cpu_to_le16(0);
4014 	int nr_sysfiles;
4015 	int buf_sds_first_size;
4016 	char *buf_sds;
4017 	GUID vol_guid;
4018 
4019 	ntfs_log_quiet("Creating NTFS volume structures.\n");
4020 	nr_sysfiles = 27;
4021 	/*
4022 	 * Setup an empty mft record.  Note, we can just give 0 as the mft
4023 	 * reference as we are creating an NTFS 1.2 volume for which the mft
4024 	 * reference is ignored by ntfs_mft_record_layout().
4025 	 *
4026 	 * Copy the mft record onto all 16 records in the buffer and setup the
4027 	 * sequence numbers of each system file to equal the mft record number
4028 	 * of that file (only for $MFT is the sequence number 1 rather than 0).
4029 	 */
4030 	for (i = 0; i < nr_sysfiles; i++) {
4031 		if (ntfs_mft_record_layout(g_vol, 0, m = (MFT_RECORD *)(g_buf +
4032 				i * g_vol->mft_record_size))) {
4033 			ntfs_log_error("Failed to layout system mft records."
4034 					"\n");
4035 			return FALSE;
4036 		}
4037 		if (i == 0 || i > 23)
4038 			m->sequence_number = cpu_to_le16(1);
4039 		else
4040 			m->sequence_number = cpu_to_le16(i);
4041 	}
4042 	/*
4043 	 * If only one cluster contains all system files then
4044 	 * fill the rest of it with empty, formatted records.
4045 	 */
4046 	if (nr_sysfiles * (s32)g_vol->mft_record_size < g_mft_size) {
4047 		for (i = nr_sysfiles;
4048 		      i * (s32)g_vol->mft_record_size < g_mft_size; i++) {
4049 			m = (MFT_RECORD *)(g_buf + i * g_vol->mft_record_size);
4050 			if (ntfs_mft_record_layout(g_vol, 0, m)) {
4051 				ntfs_log_error("Failed to layout mft record."
4052 						"\n");
4053 				return FALSE;
4054 			}
4055 			m->flags = cpu_to_le16(0);
4056 			m->sequence_number = cpu_to_le16(i);
4057 		}
4058 	}
4059 	/*
4060 	 * Create the 16 system files, adding the system information attribute
4061 	 * to each as well as marking them in use in the mft bitmap.
4062 	 */
4063 	for (i = 0; i < nr_sysfiles; i++) {
4064 		le32 file_attrs;
4065 
4066 		m = (MFT_RECORD*)(g_buf + i * g_vol->mft_record_size);
4067 		if (i < 16 || i > 23) {
4068 			m->mft_record_number = cpu_to_le32(i);
4069 			m->flags |= MFT_RECORD_IN_USE;
4070 			ntfs_bit_set(g_mft_bitmap, 0LL + i, 1);
4071 		}
4072 		file_attrs = FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM;
4073 		if (i == FILE_root) {
4074 			file_attrs |= FILE_ATTR_ARCHIVE;
4075 			if (opts.disable_indexing)
4076 				file_attrs |= FILE_ATTR_NOT_CONTENT_INDEXED;
4077 			if (opts.enable_compression)
4078 				file_attrs |= FILE_ATTR_COMPRESSED;
4079 		}
4080 		/* setting specific security_id flag and */
4081 		/* file permissions for ntfs 3.x */
4082 		if (i == 0 || i == 1 || i == 2 || i == 6 || i == 8 ||
4083 				i == 10) {
4084 			add_attr_std_info(m, file_attrs,
4085 				cpu_to_le32(0x0100));
4086 		} else if (i == 9) {
4087 			file_attrs |= FILE_ATTR_VIEW_INDEX_PRESENT;
4088 			add_attr_std_info(m, file_attrs,
4089 				cpu_to_le32(0x0101));
4090 		} else if (i == 11) {
4091 			add_attr_std_info(m, file_attrs,
4092 				cpu_to_le32(0x0101));
4093 		} else if (i == 24 || i == 25 || i == 26) {
4094 			file_attrs |= FILE_ATTR_ARCHIVE;
4095 			file_attrs |= FILE_ATTR_VIEW_INDEX_PRESENT;
4096 			add_attr_std_info(m, file_attrs,
4097 				cpu_to_le32(0x0101));
4098 		} else {
4099 			add_attr_std_info(m, file_attrs,
4100 				cpu_to_le32(0x00));
4101 		}
4102 	}
4103 	/* The root directory mft reference. */
4104 	root_ref = MK_LE_MREF(FILE_root, FILE_root);
4105 	extend_ref = MK_LE_MREF(11,11);
4106 	ntfs_log_verbose("Creating root directory (mft record 5)\n");
4107 	m = (MFT_RECORD*)(g_buf + 5 * g_vol->mft_record_size);
4108 	m->flags |= MFT_RECORD_IS_DIRECTORY;
4109 	m->link_count = cpu_to_le16(le16_to_cpu(m->link_count) + 1);
4110 	err = add_attr_file_name(m, root_ref, 0LL, 0LL,
4111 			FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM |
4112 			FILE_ATTR_I30_INDEX_PRESENT, 0, 0, ".",
4113 			FILE_NAME_WIN32_AND_DOS);
4114 	if (!err) {
4115 		init_root_sd(&sd, &i);
4116 		err = add_attr_sd(m, sd, i);
4117 	}
4118 	/* FIXME: This should be IGNORE_CASE */
4119 	if (!err)
4120 		err = add_attr_index_root(m, "$I30", 4, CASE_SENSITIVE,
4121 				AT_FILE_NAME, COLLATION_FILE_NAME,
4122 				g_vol->indx_record_size);
4123 	/* FIXME: This should be IGNORE_CASE */
4124 	if (!err)
4125 		err = upgrade_to_large_index(m, "$I30", 4, CASE_SENSITIVE,
4126 				&g_index_block);
4127 	if (!err) {
4128 		ntfs_attr_search_ctx *ctx;
4129 		ATTR_RECORD *a;
4130 		ctx = ntfs_attr_get_search_ctx(NULL, m);
4131 		if (!ctx) {
4132 			ntfs_log_perror("Failed to allocate attribute search "
4133 					"context");
4134 			return FALSE;
4135 		}
4136 		/* There is exactly one file name so this is ok. */
4137 		if (mkntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0,
4138 				CASE_SENSITIVE, 0, NULL, 0, ctx)) {
4139 			ntfs_attr_put_search_ctx(ctx);
4140 			ntfs_log_error("BUG: $FILE_NAME attribute not found."
4141 					"\n");
4142 			return FALSE;
4143 		}
4144 		a = ctx->attr;
4145 		err = insert_file_link_in_dir_index(g_index_block, root_ref,
4146 				(FILE_NAME_ATTR*)((char*)a +
4147 				le16_to_cpu(a->value_offset)),
4148 				le32_to_cpu(a->value_length));
4149 		ntfs_attr_put_search_ctx(ctx);
4150 	}
4151 	if (err) {
4152 		ntfs_log_error("Couldn't create root directory: %s\n",
4153 			strerror(-err));
4154 		return FALSE;
4155 	}
4156 	/* Add all other attributes, on a per-file basis for clarity. */
4157 	ntfs_log_verbose("Creating $MFT (mft record 0)\n");
4158 	m = (MFT_RECORD*)g_buf;
4159 	err = add_attr_data_positioned(m, NULL, 0, CASE_SENSITIVE,
4160 			const_cpu_to_le16(0), g_rl_mft, g_buf, g_mft_size);
4161 	if (!err)
4162 		err = create_hardlink(g_index_block, root_ref, m,
4163 				MK_LE_MREF(FILE_MFT, 1),
4164 				((g_mft_size - 1)
4165 					| (g_vol->cluster_size - 1)) + 1,
4166 				g_mft_size, FILE_ATTR_HIDDEN |
4167 				FILE_ATTR_SYSTEM, 0, 0, "$MFT",
4168 				FILE_NAME_WIN32_AND_DOS);
4169 	/* mft_bitmap is not modified in mkntfs; no need to sync it later. */
4170 	if (!err)
4171 		err = add_attr_bitmap_positioned(m, NULL, 0, CASE_SENSITIVE,
4172 				g_rl_mft_bmp,
4173 				g_mft_bitmap, g_mft_bitmap_byte_size);
4174 	if (err < 0) {
4175 		ntfs_log_error("Couldn't create $MFT: %s\n", strerror(-err));
4176 		return FALSE;
4177 	}
4178 	ntfs_log_verbose("Creating $MFTMirr (mft record 1)\n");
4179 	m = (MFT_RECORD*)(g_buf + 1 * g_vol->mft_record_size);
4180 	err = add_attr_data_positioned(m, NULL, 0, CASE_SENSITIVE,
4181 			const_cpu_to_le16(0), g_rl_mftmirr, g_buf,
4182 			g_rl_mftmirr[0].length * g_vol->cluster_size);
4183 	if (!err)
4184 		err = create_hardlink(g_index_block, root_ref, m,
4185 				MK_LE_MREF(FILE_MFTMirr, FILE_MFTMirr),
4186 				g_rl_mftmirr[0].length * g_vol->cluster_size,
4187 				g_rl_mftmirr[0].length * g_vol->cluster_size,
4188 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4189 				"$MFTMirr", FILE_NAME_WIN32_AND_DOS);
4190 	if (err < 0) {
4191 		ntfs_log_error("Couldn't create $MFTMirr: %s\n",
4192 				strerror(-err));
4193 		return FALSE;
4194 	}
4195 	ntfs_log_verbose("Creating $LogFile (mft record 2)\n");
4196 	m = (MFT_RECORD*)(g_buf + 2 * g_vol->mft_record_size);
4197 	err = add_attr_data_positioned(m, NULL, 0, CASE_SENSITIVE,
4198 			const_cpu_to_le16(0), g_rl_logfile,
4199 			(const u8*)NULL, g_logfile_size);
4200 	if (!err)
4201 		err = create_hardlink(g_index_block, root_ref, m,
4202 				MK_LE_MREF(FILE_LogFile, FILE_LogFile),
4203 				g_logfile_size, g_logfile_size,
4204 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4205 				"$LogFile", FILE_NAME_WIN32_AND_DOS);
4206 	if (err < 0) {
4207 		ntfs_log_error("Couldn't create $LogFile: %s\n",
4208 				strerror(-err));
4209 		return FALSE;
4210 	}
4211 	ntfs_log_verbose("Creating $AttrDef (mft record 4)\n");
4212 	m = (MFT_RECORD*)(g_buf + 4 * g_vol->mft_record_size);
4213 	err = add_attr_data(m, NULL, 0, CASE_SENSITIVE, const_cpu_to_le16(0),
4214 			(u8*)g_vol->attrdef, g_vol->attrdef_len);
4215 	if (!err)
4216 		err = create_hardlink(g_index_block, root_ref, m,
4217 				MK_LE_MREF(FILE_AttrDef, FILE_AttrDef),
4218 				(g_vol->attrdef_len + g_vol->cluster_size - 1) &
4219 				~(g_vol->cluster_size - 1), g_vol->attrdef_len,
4220 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4221 				"$AttrDef", FILE_NAME_WIN32_AND_DOS);
4222 	if (!err) {
4223 		init_system_file_sd(FILE_AttrDef, &sd, &i);
4224 		err = add_attr_sd(m, sd, i);
4225 	}
4226 	if (err < 0) {
4227 		ntfs_log_error("Couldn't create $AttrDef: %s\n",
4228 				strerror(-err));
4229 		return FALSE;
4230 	}
4231 	ntfs_log_verbose("Creating $Bitmap (mft record 6)\n");
4232 	m = (MFT_RECORD*)(g_buf + 6 * g_vol->mft_record_size);
4233 	/* the data attribute of $Bitmap must be non-resident or otherwise */
4234 	/* windows 2003 will regard the volume as corrupt (ERSO) */
4235 	if (!err)
4236 		err = insert_non_resident_attr_in_mft_record(m,
4237 			AT_DATA,  NULL, 0, CASE_SENSITIVE,
4238 			const_cpu_to_le16(0), (const u8*)NULL,
4239 			g_lcn_bitmap_byte_size, WRITE_BITMAP);
4240 
4241 
4242 	if (!err)
4243 		err = create_hardlink(g_index_block, root_ref, m,
4244 				MK_LE_MREF(FILE_Bitmap, FILE_Bitmap),
4245 				(g_lcn_bitmap_byte_size + g_vol->cluster_size -
4246 				1) & ~(g_vol->cluster_size - 1),
4247 				g_lcn_bitmap_byte_size,
4248 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4249 				"$Bitmap", FILE_NAME_WIN32_AND_DOS);
4250 	if (err < 0) {
4251 		ntfs_log_error("Couldn't create $Bitmap: %s\n", strerror(-err));
4252 		return FALSE;
4253 	}
4254 	ntfs_log_verbose("Creating $Boot (mft record 7)\n");
4255 	m = (MFT_RECORD*)(g_buf + 7 * g_vol->mft_record_size);
4256 	bs = ntfs_calloc(8192);
4257 	if (!bs)
4258 		return FALSE;
4259 	memcpy(bs, boot_array, sizeof(boot_array));
4260 	/*
4261 	 * Create the boot sector in bs. Note, that bs is already zeroed
4262 	 * in the boot sector section and that it has the NTFS OEM id/magic
4263 	 * already inserted, so no need to worry about these things.
4264 	 */
4265 	bs->bpb.bytes_per_sector = cpu_to_le16(opts.sector_size);
4266 	bs->bpb.sectors_per_cluster = (u8)(g_vol->cluster_size /
4267 			opts.sector_size);
4268 	bs->bpb.media_type = 0xf8; /* hard disk */
4269 	bs->bpb.sectors_per_track = cpu_to_le16(opts.sectors_per_track);
4270 	ntfs_log_debug("sectors per track = %ld (0x%lx)\n",
4271 			opts.sectors_per_track, opts.sectors_per_track);
4272 	bs->bpb.heads = cpu_to_le16(opts.heads);
4273 	ntfs_log_debug("heads = %ld (0x%lx)\n", opts.heads, opts.heads);
4274 	bs->bpb.hidden_sectors = cpu_to_le32(opts.part_start_sect);
4275 	ntfs_log_debug("hidden sectors = %llu (0x%llx)\n", opts.part_start_sect,
4276 			opts.part_start_sect);
4277 	bs->physical_drive = 0x80;  	    /* boot from hard disk */
4278 	bs->extended_boot_signature = 0x80; /* everybody sets this, so we do */
4279 	bs->number_of_sectors = cpu_to_sle64(opts.num_sectors);
4280 	bs->mft_lcn = cpu_to_sle64(g_mft_lcn);
4281 	bs->mftmirr_lcn = cpu_to_sle64(g_mftmirr_lcn);
4282 	if (g_vol->mft_record_size >= g_vol->cluster_size) {
4283 		bs->clusters_per_mft_record = g_vol->mft_record_size /
4284 			g_vol->cluster_size;
4285 	} else {
4286 		bs->clusters_per_mft_record = -(ffs(g_vol->mft_record_size) -
4287 				1);
4288 		if ((u32)(1 << -bs->clusters_per_mft_record) !=
4289 				g_vol->mft_record_size) {
4290 			free(bs);
4291 			ntfs_log_error("BUG: calculated clusters_per_mft_record"
4292 					" is wrong (= 0x%x)\n",
4293 					bs->clusters_per_mft_record);
4294 			return FALSE;
4295 		}
4296 	}
4297 	ntfs_log_debug("clusters per mft record = %i (0x%x)\n",
4298 			bs->clusters_per_mft_record,
4299 			bs->clusters_per_mft_record);
4300 	if (g_vol->indx_record_size >= g_vol->cluster_size) {
4301 		bs->clusters_per_index_record = g_vol->indx_record_size /
4302 			g_vol->cluster_size;
4303 	} else {
4304 		bs->clusters_per_index_record = -g_vol->indx_record_size_bits;
4305 		if ((1 << -bs->clusters_per_index_record) !=
4306 				(s32)g_vol->indx_record_size) {
4307 			free(bs);
4308 			ntfs_log_error("BUG: calculated "
4309 					"clusters_per_index_record is wrong "
4310 					"(= 0x%x)\n",
4311 					bs->clusters_per_index_record);
4312 			return FALSE;
4313 		}
4314 	}
4315 	ntfs_log_debug("clusters per index block = %i (0x%x)\n",
4316 			bs->clusters_per_index_record,
4317 			bs->clusters_per_index_record);
4318 	/* Generate a 64-bit random number for the serial number. */
4319 	bs->volume_serial_number = cpu_to_le64(((u64)random() << 32) |
4320 			((u64)random() & 0xffffffff));
4321 	/*
4322 	 * Leave zero for now as NT4 leaves it zero, too. If want it later, see
4323 	 * ../libntfs/bootsect.c for how to calculate it.
4324 	 */
4325 	bs->checksum = cpu_to_le32(0);
4326 	/* Make sure the bootsector is ok. */
4327 	if (!ntfs_boot_sector_is_ntfs(bs)) {
4328 		free(bs);
4329 		ntfs_log_error("FATAL: Generated boot sector is invalid!\n");
4330 		return FALSE;
4331 	}
4332 	err = add_attr_data_positioned(m, NULL, 0, CASE_SENSITIVE,
4333 			const_cpu_to_le16(0), g_rl_boot, (u8*)bs, 8192);
4334 	if (!err)
4335 		err = create_hardlink(g_index_block, root_ref, m,
4336 				MK_LE_MREF(FILE_Boot, FILE_Boot),
4337 				(8192 + g_vol->cluster_size - 1) &
4338 				~(g_vol->cluster_size - 1), 8192,
4339 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4340 				"$Boot", FILE_NAME_WIN32_AND_DOS);
4341 	if (!err) {
4342 		init_system_file_sd(FILE_Boot, &sd, &i);
4343 		err = add_attr_sd(m, sd, i);
4344 	}
4345 	if (err < 0) {
4346 		free(bs);
4347 		ntfs_log_error("Couldn't create $Boot: %s\n", strerror(-err));
4348 		return FALSE;
4349 	}
4350 	if (create_backup_boot_sector((u8*)bs)) {
4351 		/*
4352 		 * Pre-2.6 kernels couldn't access the last sector if it was
4353 		 * odd and we failed to set the device block size to the sector
4354 		 * size, hence we schedule chkdsk to create it.
4355 		 */
4356 		volume_flags |= VOLUME_IS_DIRTY;
4357 	}
4358 	free(bs);
4359 	/*
4360 	 * We cheat a little here and if the user has requested all times to be
4361 	 * set to zero then we set the GUID to zero as well.  This options is
4362 	 * only used for development purposes so that should be fine.
4363 	 */
4364 	if (!opts.use_epoch_time) {
4365 		/* Generate a GUID for the volume. */
4366 #ifdef ENABLE_UUID
4367 		uuid_generate((void*)&vol_guid);
4368 #else
4369 		ntfs_generate_guid(&vol_guid);
4370 #endif
4371 	} else
4372 		memset(&vol_guid, 0, sizeof(vol_guid));
4373 	if (!create_file_volume(m, root_ref, volume_flags, &vol_guid))
4374 		return FALSE;
4375 	ntfs_log_verbose("Creating $BadClus (mft record 8)\n");
4376 	m = (MFT_RECORD*)(g_buf + 8 * g_vol->mft_record_size);
4377 	/* FIXME: This should be IGNORE_CASE */
4378 	/* Create a sparse named stream of size equal to the volume size. */
4379 	err = add_attr_data_positioned(m, "$Bad", 4, CASE_SENSITIVE,
4380 			const_cpu_to_le16(0), g_rl_bad, NULL,
4381 			g_vol->nr_clusters * g_vol->cluster_size);
4382 	if (!err) {
4383 		err = add_attr_data(m, NULL, 0, CASE_SENSITIVE,
4384 				const_cpu_to_le16(0), NULL, 0);
4385 	}
4386 	if (!err) {
4387 		err = create_hardlink(g_index_block, root_ref, m,
4388 				MK_LE_MREF(FILE_BadClus, FILE_BadClus),
4389 				0LL, 0LL, FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM,
4390 				0, 0, "$BadClus", FILE_NAME_WIN32_AND_DOS);
4391 	}
4392 	if (err < 0) {
4393 		ntfs_log_error("Couldn't create $BadClus: %s\n",
4394 				strerror(-err));
4395 		return FALSE;
4396 	}
4397 	/* create $Secure (NTFS 3.0+) */
4398 	ntfs_log_verbose("Creating $Secure (mft record 9)\n");
4399 	m = (MFT_RECORD*)(g_buf + 9 * g_vol->mft_record_size);
4400 	m->flags |= MFT_RECORD_IS_VIEW_INDEX;
4401 	if (!err)
4402 		err = create_hardlink(g_index_block, root_ref, m,
4403 				MK_LE_MREF(9, 9), 0LL, 0LL,
4404 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM |
4405 				FILE_ATTR_VIEW_INDEX_PRESENT, 0, 0,
4406 				"$Secure", FILE_NAME_WIN32_AND_DOS);
4407 	buf_sds = NULL;
4408 	buf_sds_first_size = 0;
4409 	if (!err) {
4410 		int buf_sds_size;
4411 
4412 		buf_sds_first_size = 0xfc;
4413 		buf_sds_size = 0x40000 + buf_sds_first_size;
4414 		buf_sds = ntfs_calloc(buf_sds_size);
4415 		if (!buf_sds)
4416 			return FALSE;
4417 		init_secure_sds(buf_sds);
4418 		memcpy(buf_sds + 0x40000, buf_sds, buf_sds_first_size);
4419 		err = add_attr_data(m, "$SDS", 4, CASE_SENSITIVE,
4420 				const_cpu_to_le16(0), (u8*)buf_sds,
4421 				buf_sds_size);
4422 	}
4423 	/* FIXME: This should be IGNORE_CASE */
4424 	if (!err)
4425 		err = add_attr_index_root(m, "$SDH", 4, CASE_SENSITIVE,
4426 			AT_UNUSED, COLLATION_NTOFS_SECURITY_HASH,
4427 			g_vol->indx_record_size);
4428 	/* FIXME: This should be IGNORE_CASE */
4429 	if (!err)
4430 		err = add_attr_index_root(m, "$SII", 4, CASE_SENSITIVE,
4431 			AT_UNUSED, COLLATION_NTOFS_ULONG,
4432 			g_vol->indx_record_size);
4433 	if (!err)
4434 		err = initialize_secure(buf_sds, buf_sds_first_size, m);
4435 	free(buf_sds);
4436 	if (err < 0) {
4437 		ntfs_log_error("Couldn't create $Secure: %s\n",
4438 			strerror(-err));
4439 		return FALSE;
4440 	}
4441 	ntfs_log_verbose("Creating $UpCase (mft record 0xa)\n");
4442 	m = (MFT_RECORD*)(g_buf + 0xa * g_vol->mft_record_size);
4443 	err = add_attr_data(m, NULL, 0, CASE_SENSITIVE, const_cpu_to_le16(0),
4444 			(u8*)g_vol->upcase, g_vol->upcase_len << 1);
4445 	if (!err)
4446 		err = create_hardlink(g_index_block, root_ref, m,
4447 				MK_LE_MREF(FILE_UpCase, FILE_UpCase),
4448 				((g_vol->upcase_len << 1) +
4449 				g_vol->cluster_size - 1) &
4450 				~(g_vol->cluster_size - 1),
4451 				g_vol->upcase_len << 1,
4452 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM, 0, 0,
4453 				"$UpCase", FILE_NAME_WIN32_AND_DOS);
4454 	if (err < 0) {
4455 		ntfs_log_error("Couldn't create $UpCase: %s\n", strerror(-err));
4456 		return FALSE;
4457 	}
4458 	ntfs_log_verbose("Creating $Extend (mft record 11)\n");
4459 	/*
4460 	 * $Extend index must be resident.  Otherwise, w2k3 will regard the
4461 	 * volume as corrupt. (ERSO)
4462 	 */
4463 	m = (MFT_RECORD*)(g_buf + 11 * g_vol->mft_record_size);
4464 	m->flags |= MFT_RECORD_IS_DIRECTORY;
4465 	if (!err)
4466 		err = create_hardlink(g_index_block, root_ref, m,
4467 				MK_LE_MREF(11, 11), 0LL, 0LL,
4468 				FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM |
4469 				FILE_ATTR_I30_INDEX_PRESENT, 0, 0,
4470 				"$Extend", FILE_NAME_WIN32_AND_DOS);
4471 	/* FIXME: This should be IGNORE_CASE */
4472 	if (!err)
4473 		err = add_attr_index_root(m, "$I30", 4, CASE_SENSITIVE,
4474 			AT_FILE_NAME, COLLATION_FILE_NAME,
4475 			g_vol->indx_record_size);
4476 	if (err < 0) {
4477 		ntfs_log_error("Couldn't create $Extend: %s\n",
4478 			strerror(-err));
4479 		return FALSE;
4480 	}
4481 	/* NTFS reserved system files (mft records 0xc-0xf) */
4482 	for (i = 0xc; i < 0x10; i++) {
4483 		ntfs_log_verbose("Creating system file (mft record 0x%x)\n", i);
4484 		m = (MFT_RECORD*)(g_buf + i * g_vol->mft_record_size);
4485 		err = add_attr_data(m, NULL, 0, CASE_SENSITIVE,
4486 				const_cpu_to_le16(0), NULL, 0);
4487 		if (!err) {
4488 			init_system_file_sd(i, &sd, &j);
4489 			err = add_attr_sd(m, sd, j);
4490 		}
4491 		if (err < 0) {
4492 			ntfs_log_error("Couldn't create system file %i (0x%x): "
4493 					"%s\n", i, i, strerror(-err));
4494 			return FALSE;
4495 		}
4496 	}
4497 	/* create systemfiles for ntfs volumes (3.1) */
4498 	/* starting with file 24 (ignoring file 16-23) */
4499 	extend_flags = FILE_ATTR_HIDDEN | FILE_ATTR_SYSTEM |
4500 		FILE_ATTR_ARCHIVE | FILE_ATTR_VIEW_INDEX_PRESENT;
4501 	ntfs_log_verbose("Creating $Quota (mft record 24)\n");
4502 	m = (MFT_RECORD*)(g_buf + 24 * g_vol->mft_record_size);
4503 	m->flags |= MFT_RECORD_IS_4;
4504 	m->flags |= MFT_RECORD_IS_VIEW_INDEX;
4505 	if (!err)
4506 		err = create_hardlink_res((MFT_RECORD*)(g_buf +
4507 			11 * g_vol->mft_record_size), extend_ref, m,
4508 			MK_LE_MREF(24, 1), 0LL, 0LL, extend_flags,
4509 			0, 0, "$Quota", FILE_NAME_WIN32_AND_DOS);
4510 	/* FIXME: This should be IGNORE_CASE */
4511 	if (!err)
4512 		err = add_attr_index_root(m, "$Q", 2, CASE_SENSITIVE, AT_UNUSED,
4513 			COLLATION_NTOFS_ULONG, g_vol->indx_record_size);
4514 	/* FIXME: This should be IGNORE_CASE */
4515 	if (!err)
4516 		err = add_attr_index_root(m, "$O", 2, CASE_SENSITIVE, AT_UNUSED,
4517 			COLLATION_NTOFS_SID, g_vol->indx_record_size);
4518 	if (!err)
4519 		err = initialize_quota(m);
4520 	if (err < 0) {
4521 		ntfs_log_error("Couldn't create $Quota: %s\n", strerror(-err));
4522 		return FALSE;
4523 	}
4524 	ntfs_log_verbose("Creating $ObjId (mft record 25)\n");
4525 	m = (MFT_RECORD*)(g_buf + 25 * g_vol->mft_record_size);
4526 	m->flags |= MFT_RECORD_IS_4;
4527 	m->flags |= MFT_RECORD_IS_VIEW_INDEX;
4528 	if (!err)
4529 		err = create_hardlink_res((MFT_RECORD*)(g_buf +
4530 				11 * g_vol->mft_record_size), extend_ref,
4531 				m, MK_LE_MREF(25, 1), 0LL, 0LL,
4532 				extend_flags, 0, 0, "$ObjId",
4533 				FILE_NAME_WIN32_AND_DOS);
4534 
4535 	/* FIXME: This should be IGNORE_CASE */
4536 	if (!err)
4537 		err = add_attr_index_root(m, "$O", 2, CASE_SENSITIVE, AT_UNUSED,
4538 			COLLATION_NTOFS_ULONGS,
4539 			g_vol->indx_record_size);
4540 	if (!err && opts.with_uuid)
4541 		err = index_obj_id_insert(m, &vol_guid,
4542 				MK_LE_MREF(FILE_Volume, FILE_Volume));
4543 	if (err < 0) {
4544 		ntfs_log_error("Couldn't create $ObjId: %s\n",
4545 				strerror(-err));
4546 		return FALSE;
4547 	}
4548 	ntfs_log_verbose("Creating $Reparse (mft record 26)\n");
4549 	m = (MFT_RECORD*)(g_buf + 26 * g_vol->mft_record_size);
4550 	m->flags |= MFT_RECORD_IS_4;
4551 	m->flags |= MFT_RECORD_IS_VIEW_INDEX;
4552 	if (!err)
4553 		err = create_hardlink_res((MFT_RECORD*)(g_buf +
4554 				11 * g_vol->mft_record_size),
4555 				extend_ref, m, MK_LE_MREF(26, 1),
4556 				0LL, 0LL, extend_flags, 0, 0,
4557 				"$Reparse", FILE_NAME_WIN32_AND_DOS);
4558 	/* FIXME: This should be IGNORE_CASE */
4559 	if (!err)
4560 		err = add_attr_index_root(m, "$R", 2, CASE_SENSITIVE, AT_UNUSED,
4561 			COLLATION_NTOFS_ULONGS, g_vol->indx_record_size);
4562 	if (err < 0) {
4563 		ntfs_log_error("Couldn't create $Reparse: %s\n",
4564 			strerror(-err));
4565 		return FALSE;
4566 	}
4567 	return TRUE;
4568 }
4569 
4570 /**
4571  * mkntfs_redirect
4572  */
4573 static int mkntfs_redirect(struct mkntfs_options *opts2)
4574 {
4575 	int result = 1;
4576 	ntfs_attr_search_ctx *ctx = NULL;
4577 	long long lw, pos;
4578 	ATTR_RECORD *a;
4579 	MFT_RECORD *m;
4580 	int i, err;
4581 
4582 	if (!opts2) {
4583 		ntfs_log_error("Internal error: invalid parameters to mkntfs_options.\n");
4584 		goto done;
4585 	}
4586 	/* Initialize the random number generator with the current time. */
4587 	srandom(le64_to_cpu(mkntfs_time())/10000000);
4588 	/* Allocate and initialize ntfs_volume structure g_vol. */
4589 	g_vol = ntfs_volume_alloc();
4590 	if (!g_vol) {
4591 		ntfs_log_perror("Could not create volume");
4592 		goto done;
4593 	}
4594 	/* Create NTFS 3.1 (Windows XP/Vista) volumes. */
4595 	g_vol->major_ver = 3;
4596 	g_vol->minor_ver = 1;
4597 	/* Transfer some options to the volume. */
4598 	if (opts.label) {
4599 		g_vol->vol_name = strdup(opts.label);
4600 		if (!g_vol->vol_name) {
4601 			ntfs_log_perror("Could not copy volume name");
4602 			goto done;
4603 		}
4604 	}
4605 	if (opts.cluster_size >= 0)
4606 		g_vol->cluster_size = opts.cluster_size;
4607 	/* Length is in unicode characters. */
4608 	g_vol->upcase_len = 65536;
4609 	g_vol->upcase = ntfs_malloc(g_vol->upcase_len * sizeof(ntfschar));
4610 	if (!g_vol->upcase)
4611 		goto done;
4612 	ntfs_upcase_table_build(g_vol->upcase,
4613 			g_vol->upcase_len * sizeof(ntfschar));
4614 	g_vol->attrdef = ntfs_malloc(sizeof(attrdef_ntfs3x_array));
4615 	if (!g_vol->attrdef) {
4616 		ntfs_log_perror("Could not create attrdef structure");
4617 		goto done;
4618 	}
4619 	memcpy(g_vol->attrdef, attrdef_ntfs3x_array,
4620 			sizeof(attrdef_ntfs3x_array));
4621 	g_vol->attrdef_len = sizeof(attrdef_ntfs3x_array);
4622 	/* Open the partition. */
4623 	if (!mkntfs_open_partition(g_vol))
4624 		goto done;
4625 	/*
4626 	 * Decide on the sector size, cluster size, mft record and index record
4627 	 * sizes as well as the number of sectors/tracks/heads/size, etc.
4628 	 */
4629 	if (!mkntfs_override_vol_params(g_vol))
4630 		goto done;
4631 	/* Initialize $Bitmap and $MFT/$BITMAP related stuff. */
4632 	if (!mkntfs_initialize_bitmaps())
4633 		goto done;
4634 	/* Initialize MFT & set g_logfile_lcn. */
4635 	if (!mkntfs_initialize_rl_mft())
4636 		goto done;
4637 	/* Initialize $LogFile. */
4638 	if (!mkntfs_initialize_rl_logfile())
4639 		goto done;
4640 	/* Initialize $Boot. */
4641 	if (!mkntfs_initialize_rl_boot())
4642 		goto done;
4643 	/* Allocate a buffer large enough to hold the mft. */
4644 	g_buf = ntfs_calloc(g_mft_size);
4645 	if (!g_buf)
4646 		goto done;
4647 	/* Create runlist for $BadClus, $DATA named stream $Bad. */
4648 	if (!mkntfs_initialize_rl_bad())
4649 		goto done;
4650 	/* If not quick format, fill the device with 0s. */
4651 	if (!opts.quick_format) {
4652 		if (!mkntfs_fill_device_with_zeroes())
4653 			goto done;
4654 	}
4655 	/* Create NTFS volume structures. */
4656 	if (!mkntfs_create_root_structures())
4657 		goto done;
4658 	/*
4659 	 * - Do not step onto bad blocks!!!
4660 	 * - If any bad blocks were specified or found, modify $BadClus,
4661 	 *   allocating the bad clusters in $Bitmap.
4662 	 * - C&w bootsector backup bootsector (backup in last sector of the
4663 	 *   partition).
4664 	 * - If NTFS 3.0+, c&w $Secure file and $Extend directory with the
4665 	 *   corresponding special files in it, i.e. $ObjId, $Quota, $Reparse,
4666 	 *   and $UsnJrnl. And others? Or not all necessary?
4667 	 * - RE: Populate $root with the system files (and $Extend directory if
4668 	 *   applicable). Possibly should move this as far to the top as
4669 	 *   possible and update during each subsequent c&w of each system file.
4670 	 */
4671 	ntfs_log_verbose("Syncing root directory index record.\n");
4672 	if (!mkntfs_sync_index_record(g_index_block, (MFT_RECORD*)(g_buf + 5 *
4673 			g_vol->mft_record_size), NTFS_INDEX_I30, 4))
4674 		goto done;
4675 
4676 	ntfs_log_verbose("Syncing $Bitmap.\n");
4677 	m = (MFT_RECORD*)(g_buf + 6 * g_vol->mft_record_size);
4678 
4679 	ctx = ntfs_attr_get_search_ctx(NULL, m);
4680 	if (!ctx) {
4681 		ntfs_log_perror("Could not create an attribute search context");
4682 		goto done;
4683 	}
4684 
4685 	if (mkntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, CASE_SENSITIVE,
4686 				0, NULL, 0, ctx)) {
4687 		ntfs_log_error("BUG: $DATA attribute not found.\n");
4688 		goto done;
4689 	}
4690 
4691 	a = ctx->attr;
4692 	if (a->non_resident) {
4693 		runlist *rl = ntfs_mapping_pairs_decompress(g_vol, a, NULL);
4694 		if (!rl) {
4695 			ntfs_log_error("ntfs_mapping_pairs_decompress() failed\n");
4696 			goto done;
4697 		}
4698 		lw = ntfs_rlwrite(g_vol->dev, rl, (const u8*)NULL,
4699 			 g_lcn_bitmap_byte_size, NULL, WRITE_BITMAP);
4700 		err = errno;
4701 		free(rl);
4702 		if (lw != g_lcn_bitmap_byte_size) {
4703 			ntfs_log_error("ntfs_rlwrite: %s\n", lw == -1 ?
4704 				       strerror(err) : "unknown error");
4705 			goto done;
4706 		}
4707 	} else {
4708 		/* Error : the bitmap must be created non resident */
4709 		ntfs_log_error("Error : the global bitmap is resident\n");
4710 		goto done;
4711 	}
4712 
4713 	/*
4714 	 * No need to sync $MFT/$BITMAP as that has never been modified since
4715 	 * its creation.
4716 	 */
4717 	ntfs_log_verbose("Syncing $MFT.\n");
4718 	pos = g_mft_lcn * g_vol->cluster_size;
4719 	lw = 1;
4720 	for (i = 0; i < g_mft_size / (s32)g_vol->mft_record_size; i++) {
4721 		if (!opts.no_action)
4722 			lw = ntfs_mst_pwrite(g_vol->dev, pos, 1, g_vol->mft_record_size, g_buf + i * g_vol->mft_record_size);
4723 		if (lw != 1) {
4724 			ntfs_log_error("ntfs_mst_pwrite: %s\n", lw == -1 ?
4725 				       strerror(errno) : "unknown error");
4726 			goto done;
4727 		}
4728 		pos += g_vol->mft_record_size;
4729 	}
4730 	ntfs_log_verbose("Updating $MFTMirr.\n");
4731 	pos = g_mftmirr_lcn * g_vol->cluster_size;
4732 	lw = 1;
4733 	for (i = 0; i < g_rl_mftmirr[0].length * g_vol->cluster_size / g_vol->mft_record_size; i++) {
4734 		m = (MFT_RECORD*)(g_buf + i * g_vol->mft_record_size);
4735 		/*
4736 		 * Decrement the usn by one, so it becomes the same as the one
4737 		 * in $MFT once it is mst protected. - This is as we need the
4738 		 * $MFTMirr to have the exact same byte by byte content as
4739 		 * $MFT, rather than just equivalent meaning content.
4740 		 */
4741 		if (ntfs_mft_usn_dec(m)) {
4742 			ntfs_log_error("ntfs_mft_usn_dec");
4743 			goto done;
4744 		}
4745 		if (!opts.no_action)
4746 			lw = ntfs_mst_pwrite(g_vol->dev, pos, 1, g_vol->mft_record_size, g_buf + i * g_vol->mft_record_size);
4747 		if (lw != 1) {
4748 			ntfs_log_error("ntfs_mst_pwrite: %s\n", lw == -1 ?
4749 				       strerror(errno) : "unknown error");
4750 			goto done;
4751 		}
4752 		pos += g_vol->mft_record_size;
4753 	}
4754 	ntfs_log_verbose("Syncing device.\n");
4755 	if (g_vol->dev->d_ops->sync(g_vol->dev)) {
4756 		ntfs_log_error("Syncing device. FAILED");
4757 		goto done;
4758 	}
4759 	ntfs_log_quiet("mkntfs completed successfully. Have a nice day.\n");
4760 	result = 0;
4761 done:
4762 	ntfs_attr_put_search_ctx(ctx);
4763 	mkntfs_cleanup();	/* Device is unlocked and closed here */
4764 	return result;
4765 }
4766 
4767 /**
4768  * mkntfs_main
4769  */
4770 int	mkntfs_main(const char *devpath, const char *label)
4771 {
4772 	//reset global variables
4773 	g_buf = NULL;
4774 	g_mft_bitmap_byte_size = 0;
4775 	g_mft_bitmap = NULL;
4776 	g_lcn_bitmap_byte_size = 0;
4777 	g_dynamic_buf_size = 0;
4778 	g_dynamic_buf = NULL;
4779 	g_rl_mft = NULL;
4780 	g_rl_mft_bmp = NULL;
4781 	g_rl_mftmirr = NULL;
4782 	g_rl_logfile = NULL;
4783 	g_rl_boot = NULL;
4784 	g_rl_bad = NULL;
4785 	g_index_block = NULL;
4786 	g_vol = NULL;
4787 	g_mft_size = 0;
4788 	g_mft_lcn = 0;
4789 	g_mftmirr_lcn = 0;
4790 	g_logfile_lcn = 0;
4791 	g_logfile_size = 0;
4792 	g_mft_zone_end = 0;
4793 	g_num_bad_blocks = 0;
4794 	g_bad_blocks = NULL;
4795 	g_allocation = NULL;
4796 
4797 	//init default options
4798 	mkntfs_init_options(&opts);
4799 
4800 	opts.dev_name = devpath;
4801 	opts.label = label;
4802 
4803 	opts.force = TRUE;
4804 	opts.quick_format = TRUE;
4805 
4806 	return mkntfs_redirect(&opts);
4807 }
4808 
4809