xref: /haiku/src/add-ons/kernel/file_systems/ntfs/libntfs/attrib.c (revision 508f54795f39c3e7552d87c95aae9dd8ec6f505b)
1 /**
2  * attrib.c - Attribute handling code. Originated from the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2005 Anton Altaparmakov
5  * Copyright (c) 2002-2005 Richard Russon
6  * Copyright (c) 2002-2008 Szabolcs Szakacsits
7  * Copyright (c) 2004-2007 Yura Pakhuchiy
8  * Copyright (c) 2007-2008 Jean-Pierre Andre
9  *
10  * This program/include file is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as published
12  * by the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program/include file is distributed in the hope that it will be
16  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program (in the main directory of the NTFS-3G
22  * distribution in the file COPYING); if not, write to the Free Software
23  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29 
30 #ifdef HAVE_STDIO_H
31 #include <stdio.h>
32 #endif
33 #ifdef HAVE_STRING_H
34 #include <string.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 
43 #include "compat.h"
44 #include "attrib.h"
45 #include "attrlist.h"
46 #include "device.h"
47 #include "mft.h"
48 #include "debug.h"
49 #include "mst.h"
50 #include "volume.h"
51 #include "types.h"
52 #include "layout.h"
53 #include "inode.h"
54 #include "runlist.h"
55 #include "lcnalloc.h"
56 #include "dir.h"
57 #include "compress.h"
58 #include "bitmap.h"
59 #include "logging.h"
60 #include "misc.h"
61 
62 ntfschar AT_UNNAMED[] = { const_cpu_to_le16('\0') };
63 
64 static int NAttrFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag)
65 {
66 	if (na->type == AT_DATA && na->name == AT_UNNAMED)
67 		return (na->ni->flags & flag);
68 	return 0;
69 }
70 
71 static void NAttrSetFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag)
72 {
73 	if (na->type == AT_DATA && na->name == AT_UNNAMED)
74 		na->ni->flags |= flag;
75 	else
76 		ntfs_log_trace("Denied setting flag %d for not unnamed data "
77 			       "attribute\n", flag);
78 }
79 
80 static void NAttrClearFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag)
81 {
82 	if (na->type == AT_DATA && na->name == AT_UNNAMED)
83 		na->ni->flags &= ~flag;
84 }
85 
86 #define GenNAttrIno(func_name, flag)					\
87 int NAttr##func_name(ntfs_attr *na) { return NAttrFlag   (na, flag); } 	\
88 void NAttrSet##func_name(ntfs_attr *na)	 { NAttrSetFlag  (na, flag); }	\
89 void NAttrClear##func_name(ntfs_attr *na){ NAttrClearFlag(na, flag); }
90 
91 GenNAttrIno(Compressed, FILE_ATTR_COMPRESSED)
92 GenNAttrIno(Encrypted, 	FILE_ATTR_ENCRYPTED)
93 GenNAttrIno(Sparse, 	FILE_ATTR_SPARSE_FILE)
94 
95 /**
96  * ntfs_get_attribute_value_length - Find the length of an attribute
97  * @a:
98  *
99  * Description...
100  *
101  * Returns:
102  */
103 s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a)
104 {
105 	if (!a) {
106 		errno = EINVAL;
107 		return 0;
108 	}
109 	errno = 0;
110 	if (a->non_resident)
111 		return sle64_to_cpu(a->data_size);
112 
113 	return (s64)le32_to_cpu(a->value_length);
114 }
115 
116 /**
117  * ntfs_get_attribute_value - Get a copy of an attribute
118  * @vol:
119  * @a:
120  * @b:
121  *
122  * Description...
123  *
124  * Returns:
125  */
126 s64 ntfs_get_attribute_value(const ntfs_volume *vol,
127 		const ATTR_RECORD *a, u8 *b)
128 {
129 	runlist *rl;
130 	s64 total, r;
131 	int i;
132 
133 	/* Sanity checks. */
134 	if (!vol || !a || !b) {
135 		errno = EINVAL;
136 		return 0;
137 	}
138 	/* Complex attribute? */
139 	/*
140 	 * Ignore the flags in case they are not zero for an attribute list
141 	 * attribute.  Windows does not complain about invalid flags and chkdsk
142 	 * does not detect or fix them so we need to cope with it, too.
143 	 */
144 	if (a->type != AT_ATTRIBUTE_LIST && a->flags) {
145 		ntfs_log_error("Non-zero (%04x) attribute flags. Cannot handle "
146 			       "this yet.\n", le16_to_cpu(a->flags));
147 		errno = EOPNOTSUPP;
148 		return 0;
149 	}
150 	if (!a->non_resident) {
151 		/* Attribute is resident. */
152 
153 		/* Sanity check. */
154 		if (le32_to_cpu(a->value_length) + le16_to_cpu(a->value_offset)
155 				> le32_to_cpu(a->length)) {
156 			return 0;
157 		}
158 
159 		memcpy(b, (const char*)a + le16_to_cpu(a->value_offset),
160 				le32_to_cpu(a->value_length));
161 		errno = 0;
162 		return (s64)le32_to_cpu(a->value_length);
163 	}
164 
165 	/* Attribute is not resident. */
166 
167 	/* If no data, return 0. */
168 	if (!(a->data_size)) {
169 		errno = 0;
170 		return 0;
171 	}
172 	/*
173 	 * FIXME: What about attribute lists?!? (AIA)
174 	 */
175 	/* Decompress the mapping pairs array into a runlist. */
176 	rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
177 	if (!rl) {
178 		errno = EINVAL;
179 		return 0;
180 	}
181 	/*
182 	 * FIXED: We were overflowing here in a nasty fashion when we
183 	 * reach the last cluster in the runlist as the buffer will
184 	 * only be big enough to hold data_size bytes while we are
185 	 * reading in allocated_size bytes which is usually larger
186 	 * than data_size, since the actual data is unlikely to have a
187 	 * size equal to a multiple of the cluster size!
188 	 * FIXED2:  We were also overflowing here in the same fashion
189 	 * when the data_size was more than one run smaller than the
190 	 * allocated size which happens with Windows XP sometimes.
191 	 */
192 	/* Now load all clusters in the runlist into b. */
193 	for (i = 0, total = 0; rl[i].length; i++) {
194 		if (total + (rl[i].length << vol->cluster_size_bits) >=
195 				sle64_to_cpu(a->data_size)) {
196 			unsigned char *intbuf = NULL;
197 			/*
198 			 * We have reached the last run so we were going to
199 			 * overflow when executing the ntfs_pread() which is
200 			 * BAAAAAAAD!
201 			 * Temporary fix:
202 			 *	Allocate a new buffer with size:
203 			 *	rl[i].length << vol->cluster_size_bits, do the
204 			 *	read into our buffer, then memcpy the correct
205 			 *	amount of data into the caller supplied buffer,
206 			 *	free our buffer, and continue.
207 			 * We have reached the end of data size so we were
208 			 * going to overflow in the same fashion.
209 			 * Temporary fix:  same as above.
210 			 */
211 			intbuf = ntfs_malloc(rl[i].length << vol->cluster_size_bits);
212 			if (!intbuf) {
213 				free(rl);
214 				return 0;
215 			}
216 			/*
217 			 * FIXME: If compressed file: Only read if lcn != -1.
218 			 * Otherwise, we are dealing with a sparse run and we
219 			 * just memset the user buffer to 0 for the length of
220 			 * the run, which should be 16 (= compression unit
221 			 * size).
222 			 * FIXME: Really only when file is compressed, or can
223 			 * we have sparse runs in uncompressed files as well?
224 			 * - Yes we can, in sparse files! But not necessarily
225 			 * size of 16, just run length.
226 			 */
227 			r = ntfs_pread(vol->dev, rl[i].lcn <<
228 					vol->cluster_size_bits, rl[i].length <<
229 					vol->cluster_size_bits, intbuf);
230 			if (r != rl[i].length << vol->cluster_size_bits) {
231 #define ESTR "Error reading attribute value"
232 				if (r == -1)
233 					ntfs_log_perror(ESTR);
234 				else if (r < rl[i].length <<
235 						vol->cluster_size_bits) {
236 					ntfs_log_debug(ESTR ": Ran out of input data.\n");
237 					errno = EIO;
238 				} else {
239 					ntfs_log_debug(ESTR ": unknown error\n");
240 					errno = EIO;
241 				}
242 #undef ESTR
243 				free(rl);
244 				free(intbuf);
245 				return 0;
246 			}
247 			memcpy(b + total, intbuf, sle64_to_cpu(a->data_size) -
248 					total);
249 			free(intbuf);
250 			total = sle64_to_cpu(a->data_size);
251 			break;
252 		}
253 		/*
254 		 * FIXME: If compressed file: Only read if lcn != -1.
255 		 * Otherwise, we are dealing with a sparse run and we just
256 		 * memset the user buffer to 0 for the length of the run, which
257 		 * should be 16 (= compression unit size).
258 		 * FIXME: Really only when file is compressed, or can
259 		 * we have sparse runs in uncompressed files as well?
260 		 * - Yes we can, in sparse files! But not necessarily size of
261 		 * 16, just run length.
262 		 */
263 		r = ntfs_pread(vol->dev, rl[i].lcn << vol->cluster_size_bits,
264 				rl[i].length << vol->cluster_size_bits,
265 				b + total);
266 		if (r != rl[i].length << vol->cluster_size_bits) {
267 #define ESTR "Error reading attribute value"
268 			if (r == -1)
269 				ntfs_log_perror(ESTR);
270 			else if (r < rl[i].length << vol->cluster_size_bits) {
271 				ntfs_log_debug(ESTR ": Ran out of input data.\n");
272 				errno = EIO;
273 			} else {
274 				ntfs_log_debug(ESTR ": unknown error\n");
275 				errno = EIO;
276 			}
277 #undef ESTR
278 			free(rl);
279 			return 0;
280 		}
281 		total += r;
282 	}
283 	free(rl);
284 	return total;
285 }
286 
287 /* Already cleaned up code below, but still look for FIXME:... */
288 
289 /**
290  * __ntfs_attr_init - primary initialization of an ntfs attribute structure
291  * @na:		ntfs attribute to initialize
292  * @ni:		ntfs inode with which to initialize the ntfs attribute
293  * @type:	attribute type
294  * @name:	attribute name in little endian Unicode or NULL
295  * @name_len:	length of attribute @name in Unicode characters (if @name given)
296  *
297  * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len.
298  */
299 static void __ntfs_attr_init(ntfs_attr *na, ntfs_inode *ni,
300 		const ATTR_TYPES type, ntfschar *name, const u32 name_len)
301 {
302 	na->rl = NULL;
303 	na->ni = ni;
304 	na->type = type;
305 	na->name = name;
306 	if (name)
307 		na->name_len = name_len;
308 	else
309 		na->name_len = 0;
310 }
311 
312 /**
313  * ntfs_attr_init - initialize an ntfs_attr with data sizes and status
314  * @na:
315  * @non_resident:
316  * @compressed:
317  * @encrypted:
318  * @sparse:
319  * @allocated_size:
320  * @data_size:
321  * @initialized_size:
322  * @compressed_size:
323  * @compression_unit:
324  *
325  * Final initialization for an ntfs attribute.
326  */
327 void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident,
328 		const BOOL compressed, const BOOL encrypted, const BOOL sparse,
329 		const s64 allocated_size, const s64 data_size,
330 		const s64 initialized_size, const s64 compressed_size,
331 		const u8 compression_unit)
332 {
333 	if (!NAttrInitialized(na)) {
334 		if (non_resident)
335 			NAttrSetNonResident(na);
336 		if (compressed)
337 			NAttrSetCompressed(na);
338 		if (encrypted)
339 			NAttrSetEncrypted(na);
340 		if (sparse)
341 			NAttrSetSparse(na);
342 		na->allocated_size = allocated_size;
343 		na->data_size = data_size;
344 		na->initialized_size = initialized_size;
345 		if (compressed || sparse) {
346 			ntfs_volume *vol = na->ni->vol;
347 
348 			na->compressed_size = compressed_size;
349 			na->compression_block_clusters = 1 << compression_unit;
350 			na->compression_block_size = 1 << (compression_unit +
351 					vol->cluster_size_bits);
352 			na->compression_block_size_bits = ffs(
353 					na->compression_block_size) - 1;
354 		}
355 		NAttrSetInitialized(na);
356 	}
357 }
358 
359 /**
360  * ntfs_attr_open - open an ntfs attribute for access
361  * @ni:		open ntfs inode in which the ntfs attribute resides
362  * @type:	attribute type
363  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
364  * @name_len:	length of attribute @name in Unicode characters (if @name given)
365  *
366  * Allocate a new ntfs attribute structure, initialize it with @ni, @type,
367  * @name, and @name_len, then return it. Return NULL on error with
368  * errno set to the error code.
369  *
370  * If @name is AT_UNNAMED look specifically for an unnamed attribute.  If you
371  * do not care whether the attribute is named or not set @name to NULL.  In
372  * both those cases @name_len is not used at all.
373  */
374 ntfs_attr *ntfs_attr_open(ntfs_inode *ni, const ATTR_TYPES type,
375 		ntfschar *name, u32 name_len)
376 {
377 	ntfs_attr_search_ctx *ctx;
378 	ntfs_attr *na = NULL;
379 	ntfschar *newname = NULL;
380 	ATTR_RECORD *a;
381 	BOOL cs;
382 
383 	ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n",
384 		       (unsigned long long)ni->mft_no, type);
385 
386 	if (!ni || !ni->vol || !ni->mrec) {
387 		errno = EINVAL;
388 		goto out;
389 	}
390 	na = ntfs_calloc(sizeof(ntfs_attr));
391 	if (!na)
392 		goto out;
393 	if (name && name != AT_UNNAMED && name != NTFS_INDEX_I30) {
394 		name = ntfs_ucsndup(name, name_len);
395 		if (!name)
396 			goto err_out;
397 		newname = name;
398 	}
399 
400 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
401 	if (!ctx)
402 		goto err_out;
403 
404 	if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx))
405 		goto put_err_out;
406 
407 	a = ctx->attr;
408 
409 	if (!name) {
410 		if (a->name_length) {
411 			name = ntfs_ucsndup((ntfschar*)((u8*)a + le16_to_cpu(
412 					a->name_offset)), a->name_length);
413 			if (!name)
414 				goto put_err_out;
415 			newname = name;
416 			name_len = a->name_length;
417 		} else {
418 			name = AT_UNNAMED;
419 			name_len = 0;
420 		}
421 	}
422 
423 	__ntfs_attr_init(na, ni, type, name, name_len);
424 
425 	/*
426 	 * Wipe the flags in case they are not zero for an attribute list
427 	 * attribute.  Windows does not complain about invalid flags and chkdsk
428 	 * does not detect or fix them so we need to cope with it, too.
429 	 */
430 	if (type == AT_ATTRIBUTE_LIST)
431 		a->flags = 0;
432 
433 	cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE);
434 
435 	if (na->type == AT_DATA && na->name == AT_UNNAMED &&
436 	    ((!(a->flags & ATTR_IS_COMPRESSED) != !NAttrCompressed(na)) ||
437 	     (!(a->flags & ATTR_IS_SPARSE)     != !NAttrSparse(na)) ||
438 	     (!(a->flags & ATTR_IS_ENCRYPTED)  != !NAttrEncrypted(na)))) {
439 		errno = EIO;
440 		ntfs_log_perror("Inode %lld has corrupt attribute flags "
441 				"(0x%x <> 0x%x)",(unsigned long long)ni->mft_no,
442 				a->flags, na->ni->flags);
443 		goto put_err_out;
444 	}
445 
446 	if (a->non_resident) {
447 		if ((a->flags & ATTR_IS_COMPRESSED) && !a->compression_unit) {
448 			errno = EIO;
449 			ntfs_log_perror("Compressed inode %lld attr 0x%x has "
450 					"no compression unit",
451 					(unsigned long long)ni->mft_no, type);
452 			goto put_err_out;
453 		}
454 		ntfs_attr_init(na, TRUE, a->flags & ATTR_IS_COMPRESSED,
455 				a->flags & ATTR_IS_ENCRYPTED,
456 				a->flags & ATTR_IS_SPARSE,
457 				sle64_to_cpu(a->allocated_size),
458 				sle64_to_cpu(a->data_size),
459 				sle64_to_cpu(a->initialized_size),
460 				cs ? sle64_to_cpu(a->compressed_size) : 0,
461 				cs ? a->compression_unit : 0);
462 	} else {
463 		s64 l = le32_to_cpu(a->value_length);
464 		ntfs_attr_init(na, FALSE, a->flags & ATTR_IS_COMPRESSED,
465 				a->flags & ATTR_IS_ENCRYPTED,
466 				a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l,
467 				cs ? (l + 7) & ~7 : 0, 0);
468 	}
469 	ntfs_attr_put_search_ctx(ctx);
470 out:
471 	ntfs_log_leave("\n");
472 	return na;
473 
474 put_err_out:
475 	ntfs_attr_put_search_ctx(ctx);
476 err_out:
477 	free(newname);
478 	free(na);
479 	na = NULL;
480 	goto out;
481 }
482 
483 /**
484  * ntfs_attr_close - free an ntfs attribute structure
485  * @na:		ntfs attribute structure to free
486  *
487  * Release all memory associated with the ntfs attribute @na and then release
488  * @na itself.
489  */
490 void ntfs_attr_close(ntfs_attr *na)
491 {
492 	if (!na)
493 		return;
494 	if (NAttrNonResident(na) && na->rl)
495 		free(na->rl);
496 	/* Don't release if using an internal constant. */
497 	if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30)
498 		free(na->name);
499 	free(na);
500 }
501 
502 /**
503  * ntfs_attr_map_runlist - map (a part of) a runlist of an ntfs attribute
504  * @na:		ntfs attribute for which to map (part of) a runlist
505  * @vcn:	map runlist part containing this vcn
506  *
507  * Map the part of a runlist containing the @vcn of the ntfs attribute @na.
508  *
509  * Return 0 on success and -1 on error with errno set to the error code.
510  */
511 int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn)
512 {
513 	LCN lcn;
514 	ntfs_attr_search_ctx *ctx;
515 
516 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn 0x%llx.\n",
517 		(unsigned long long)na->ni->mft_no, na->type, (long long)vcn);
518 
519 	lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn);
520 	if (lcn >= 0 || lcn == LCN_HOLE || lcn == LCN_ENOENT)
521 		return 0;
522 
523 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
524 	if (!ctx)
525 		return -1;
526 
527 	/* Find the attribute in the mft record. */
528 	if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE,
529 			vcn, NULL, 0, ctx)) {
530 		runlist_element *rl;
531 
532 		/* Decode the runlist. */
533 		rl = ntfs_mapping_pairs_decompress(na->ni->vol, ctx->attr,
534 				na->rl);
535 		if (rl) {
536 			na->rl = rl;
537 			ntfs_attr_put_search_ctx(ctx);
538 			return 0;
539 		}
540 	}
541 
542 	ntfs_attr_put_search_ctx(ctx);
543 	return -1;
544 }
545 
546 /**
547  * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute
548  * @na:		ntfs attribute for which to map the runlist
549  *
550  * Map the whole runlist of the ntfs attribute @na.  For an attribute made up
551  * of only one attribute extent this is the same as calling
552  * ntfs_attr_map_runlist(na, 0) but for an attribute with multiple extents this
553  * will map the runlist fragments from each of the extents thus giving access
554  * to the entirety of the disk allocation of an attribute.
555  *
556  * Return 0 on success and -1 on error with errno set to the error code.
557  */
558 int ntfs_attr_map_whole_runlist(ntfs_attr *na)
559 {
560 	VCN next_vcn, last_vcn, highest_vcn;
561 	ntfs_attr_search_ctx *ctx;
562 	ntfs_volume *vol = na->ni->vol;
563 	ATTR_RECORD *a;
564 	int ret = -1;
565 
566 	ntfs_log_enter("Entering for inode %llu, attr 0x%x.\n",
567 		       (unsigned long long)na->ni->mft_no, na->type);
568 
569 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
570 	if (!ctx)
571 		goto out;
572 
573 	/* Map all attribute extents one by one. */
574 	next_vcn = last_vcn = highest_vcn = 0;
575 	a = NULL;
576 	while (1) {
577 		runlist_element *rl;
578 
579 		int not_mapped = 0;
580 		if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED)
581 			not_mapped = 1;
582 
583 		if (ntfs_attr_lookup(na->type, na->name, na->name_len,
584 				CASE_SENSITIVE, next_vcn, NULL, 0, ctx))
585 			break;
586 
587 		a = ctx->attr;
588 
589 		if (not_mapped) {
590 			/* Decode the runlist. */
591 			rl = ntfs_mapping_pairs_decompress(na->ni->vol,
592 								a, na->rl);
593 			if (!rl)
594 				goto err_out;
595 			na->rl = rl;
596 		}
597 
598 		/* Are we in the first extent? */
599 		if (!next_vcn) {
600 			 if (a->lowest_vcn) {
601 				 errno = EIO;
602 				 ntfs_log_perror("First extent of inode %llu "
603 					"attribute has non-zero lowest_vcn",
604 					(unsigned long long)na->ni->mft_no);
605 				 goto err_out;
606 			}
607 			/* Get the last vcn in the attribute. */
608 			last_vcn = sle64_to_cpu(a->allocated_size) >>
609 					vol->cluster_size_bits;
610 		}
611 
612 		/* Get the lowest vcn for the next extent. */
613 		highest_vcn = sle64_to_cpu(a->highest_vcn);
614 		next_vcn = highest_vcn + 1;
615 
616 		/* Only one extent or error, which we catch below. */
617 		if (next_vcn <= 0) {
618 			errno = ENOENT;
619 			break;
620 		}
621 
622 		/* Avoid endless loops due to corruption. */
623 		if (next_vcn < sle64_to_cpu(a->lowest_vcn)) {
624 			errno = EIO;
625 			ntfs_log_perror("Inode %llu has corrupt attribute list",
626 					(unsigned long long)na->ni->mft_no);
627 			goto err_out;
628 		}
629 	}
630 	if (!a) {
631 		ntfs_log_perror("Couldn't find attribute for runlist mapping");
632 		goto err_out;
633 	}
634 	if (highest_vcn && highest_vcn != last_vcn - 1) {
635 		errno = EIO;
636 		ntfs_log_perror("Failed to load full runlist: inode: %llu "
637 				"highest_vcn: 0x%llx last_vcn: 0x%llx",
638 				(unsigned long long)na->ni->mft_no,
639 				(long long)highest_vcn, (long long)last_vcn);
640 		goto err_out;
641 	}
642 	if (errno == ENOENT)
643 		ret = 0;
644 err_out:
645 	ntfs_attr_put_search_ctx(ctx);
646 out:
647 	ntfs_log_leave("\n");
648 	return ret;
649 }
650 
651 /**
652  * ntfs_attr_vcn_to_lcn - convert a vcn into a lcn given an ntfs attribute
653  * @na:		ntfs attribute whose runlist to use for conversion
654  * @vcn:	vcn to convert
655  *
656  * Convert the virtual cluster number @vcn of an attribute into a logical
657  * cluster number (lcn) of a device using the runlist @na->rl to map vcns to
658  * their corresponding lcns.
659  *
660  * If the @vcn is not mapped yet, attempt to map the attribute extent
661  * containing the @vcn and retry the vcn to lcn conversion.
662  *
663  * Since lcns must be >= 0, we use negative return values with special meaning:
664  *
665  * Return value		Meaning / Description
666  * ==========================================
667  *  -1 = LCN_HOLE	Hole / not allocated on disk.
668  *  -3 = LCN_ENOENT	There is no such vcn in the attribute.
669  *  -4 = LCN_EINVAL	Input parameter error.
670  *  -5 = LCN_EIO	Corrupt fs, disk i/o error, or not enough memory.
671  */
672 LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn)
673 {
674 	LCN lcn;
675 	BOOL is_retry = FALSE;
676 
677 	if (!na || !NAttrNonResident(na) || vcn < 0)
678 		return (LCN)LCN_EINVAL;
679 
680 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long
681 			long)na->ni->mft_no, na->type);
682 retry:
683 	/* Convert vcn to lcn. If that fails map the runlist and retry once. */
684 	lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn);
685 	if (lcn >= 0)
686 		return lcn;
687 	if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) {
688 		is_retry = TRUE;
689 		goto retry;
690 	}
691 	/*
692 	 * If the attempt to map the runlist failed, or we are getting
693 	 * LCN_RL_NOT_MAPPED despite having mapped the attribute extent
694 	 * successfully, something is really badly wrong...
695 	 */
696 	if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED)
697 		return (LCN)LCN_EIO;
698 	/* lcn contains the appropriate error code. */
699 	return lcn;
700 }
701 
702 /**
703  * ntfs_attr_find_vcn - find a vcn in the runlist of an ntfs attribute
704  * @na:		ntfs attribute whose runlist to search
705  * @vcn:	vcn to find
706  *
707  * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
708  * @na and return the the address of the runlist element containing the @vcn.
709  *
710  * Note you need to distinguish between the lcn of the returned runlist
711  * element being >= 0 and LCN_HOLE. In the later case you have to return zeroes
712  * on read and allocate clusters on write. You need to update the runlist, the
713  * attribute itself as well as write the modified mft record to disk.
714  *
715  * If there is an error return NULL with errno set to the error code. The
716  * following error codes are defined:
717  *	EINVAL		Input parameter error.
718  *	ENOENT		There is no such vcn in the runlist.
719  *	ENOMEM		Not enough memory.
720  *	EIO		I/O error or corrupt metadata.
721  */
722 runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn)
723 {
724 	runlist_element *rl;
725 	BOOL is_retry = FALSE;
726 
727 	if (!na || !NAttrNonResident(na) || vcn < 0) {
728 		errno = EINVAL;
729 		return NULL;
730 	}
731 
732 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn %llx\n",
733 		       (unsigned long long)na->ni->mft_no, na->type,
734 		       (long long)vcn);
735 retry:
736 	rl = na->rl;
737 	if (!rl)
738 		goto map_rl;
739 	if (vcn < rl[0].vcn)
740 		goto map_rl;
741 	while (rl->length) {
742 		if (vcn < rl[1].vcn) {
743 			if (rl->lcn >= (LCN)LCN_HOLE)
744 				return rl;
745 			break;
746 		}
747 		rl++;
748 	}
749 	switch (rl->lcn) {
750 	case (LCN)LCN_RL_NOT_MAPPED:
751 		goto map_rl;
752 	case (LCN)LCN_ENOENT:
753 		errno = ENOENT;
754 		break;
755 	case (LCN)LCN_EINVAL:
756 		errno = EINVAL;
757 		break;
758 	default:
759 		errno = EIO;
760 		break;
761 	}
762 	return NULL;
763 map_rl:
764 	/* The @vcn is in an unmapped region, map the runlist and retry. */
765 	if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) {
766 		is_retry = TRUE;
767 		goto retry;
768 	}
769 	/*
770 	 * If we already retried or the mapping attempt failed something has
771 	 * gone badly wrong. EINVAL and ENOENT coming from a failed mapping
772 	 * attempt are equivalent to errors for us as they should not happen
773 	 * in our code paths.
774 	 */
775 	if (is_retry || errno == EINVAL || errno == ENOENT)
776 		errno = EIO;
777 	return NULL;
778 }
779 
780 /**
781  * ntfs_attr_pread_i - see description at ntfs_attr_pread()
782  */
783 static s64 ntfs_attr_pread_i(ntfs_attr *na, const s64 pos, s64 count, void *b)
784 {
785 	s64 br, to_read, ofs, total, total2;
786 	ntfs_volume *vol;
787 	runlist_element *rl;
788 
789 	/* Sanity checking arguments is done in ntfs_attr_pread(). */
790 
791 	if (NAttrCompressed(na) && NAttrNonResident(na))
792 		return ntfs_compressed_attr_pread(na, pos, count, b);
793 	/*
794 	 * Encrypted non-resident attributes are not supported.  We return
795 	 * access denied, which is what Windows NT4 does, too.
796 	 */
797 	if (NAttrEncrypted(na) && NAttrNonResident(na)) {
798 		errno = EACCES;
799 		return -1;
800 	}
801 	vol = na->ni->vol;
802 
803 	if (!count)
804 		return 0;
805 	/* Truncate reads beyond end of attribute. */
806 	if (pos + count > na->data_size) {
807 		if (pos >= na->data_size)
808 			return 0;
809 		count = na->data_size - pos;
810 	}
811 	/* If it is a resident attribute, get the value from the mft record. */
812 	if (!NAttrNonResident(na)) {
813 		ntfs_attr_search_ctx *ctx;
814 		char *val;
815 
816 		ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
817 		if (!ctx)
818 			return -1;
819 		if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0,
820 				0, NULL, 0, ctx)) {
821 res_err_out:
822 			ntfs_attr_put_search_ctx(ctx);
823 			return -1;
824 		}
825 		val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset);
826 		if (val < (char*)ctx->attr || val +
827 				le32_to_cpu(ctx->attr->value_length) >
828 				(char*)ctx->mrec + vol->mft_record_size) {
829 			errno = EIO;
830 			ntfs_log_perror("%s: Sanity check failed", __FUNCTION__);
831 			goto res_err_out;
832 		}
833 		memcpy(b, val + pos, count);
834 		ntfs_attr_put_search_ctx(ctx);
835 		return count;
836 	}
837 	total = total2 = 0;
838 	/* Zero out reads beyond initialized size. */
839 	if (pos + count > na->initialized_size) {
840 		if (pos >= na->initialized_size) {
841 			memset(b, 0, count);
842 			return count;
843 		}
844 		total2 = pos + count - na->initialized_size;
845 		count -= total2;
846 		memset((u8*)b + count, 0, total2);
847 	}
848 	/* Find the runlist element containing the vcn. */
849 	rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits);
850 	if (!rl) {
851 		/*
852 		 * If the vcn is not present it is an out of bounds read.
853 		 * However, we already truncated the read to the data_size,
854 		 * so getting this here is an error.
855 		 */
856 		if (errno == ENOENT) {
857 			errno = EIO;
858 			ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__);
859 		}
860 		return -1;
861 	}
862 	/*
863 	 * Gather the requested data into the linear destination buffer. Note,
864 	 * a partial final vcn is taken care of by the @count capping of read
865 	 * length.
866 	 */
867 	ofs = pos - (rl->vcn << vol->cluster_size_bits);
868 	for (; count; rl++, ofs = 0) {
869 		if (rl->lcn == LCN_RL_NOT_MAPPED) {
870 			rl = ntfs_attr_find_vcn(na, rl->vcn);
871 			if (!rl) {
872 				if (errno == ENOENT) {
873 					errno = EIO;
874 					ntfs_log_perror("%s: Failed to find VCN #2",
875 							__FUNCTION__);
876 				}
877 				goto rl_err_out;
878 			}
879 			/* Needed for case when runs merged. */
880 			ofs = pos + total - (rl->vcn << vol->cluster_size_bits);
881 		}
882 		if (!rl->length) {
883 			errno = EIO;
884 			ntfs_log_perror("%s: Zero run length", __FUNCTION__);
885 			goto rl_err_out;
886 		}
887 		if (rl->lcn < (LCN)0) {
888 			if (rl->lcn != (LCN)LCN_HOLE) {
889 				ntfs_log_perror("%s: Bad run (%lld)",
890 						__FUNCTION__,
891 						(long long)rl->lcn);
892 				goto rl_err_out;
893 			}
894 			/* It is a hole, just zero the matching @b range. */
895 			to_read = min(count, (rl->length <<
896 					vol->cluster_size_bits) - ofs);
897 			memset(b, 0, to_read);
898 			/* Update progress counters. */
899 			total += to_read;
900 			count -= to_read;
901 			b = (u8*)b + to_read;
902 			continue;
903 		}
904 		/* It is a real lcn, read it into @dst. */
905 		to_read = min(count, (rl->length << vol->cluster_size_bits) -
906 				ofs);
907 retry:
908 		ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs"
909 				" %lld.\n", (long long)to_read, (long long)rl->vcn,
910 			       (long long )rl->lcn, (long long)ofs);
911 		br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) +
912 				ofs, to_read, b);
913 		/* If everything ok, update progress counters and continue. */
914 		if (br > 0) {
915 			total += br;
916 			count -= br;
917 			b = (u8*)b + br;
918 		}
919 		if (br == to_read)
920 			continue;
921 		/* If the syscall was interrupted, try again. */
922 		if (br == (s64)-1 && errno == EINTR)
923 			goto retry;
924 		if (total)
925 			return total;
926 		if (!br)
927 			errno = EIO;
928 		ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__);
929 		return -1;
930 	}
931 	/* Finally, return the number of bytes read. */
932 	return total + total2;
933 rl_err_out:
934 	if (total)
935 		return total;
936 	errno = EIO;
937 	return -1;
938 }
939 
940 /**
941  * ntfs_attr_pread - read from an attribute specified by an ntfs_attr structure
942  * @na:		ntfs attribute to read from
943  * @pos:	byte position in the attribute to begin reading from
944  * @count:	number of bytes to read
945  * @b:		output data buffer
946  *
947  * This function will read @count bytes starting at offset @pos from the ntfs
948  * attribute @na into the data buffer @b.
949  *
950  * On success, return the number of successfully read bytes. If this number is
951  * lower than @count this means that the read reached end of file or that an
952  * error was encountered during the read so that the read is partial. 0 means
953  * end of file or nothing was read (also return 0 when @count is 0).
954  *
955  * On error and nothing has been read, return -1 with errno set appropriately
956  * to the return code of ntfs_pread(), or to EINVAL in case of invalid
957  * arguments.
958  */
959 s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, void *b)
960 {
961 	s64 ret;
962 
963 	if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) {
964 		errno = EINVAL;
965 		ntfs_log_perror("%s: na=%p  b=%p  pos=%lld  count=%lld",
966 				__FUNCTION__, na, b, (long long)pos,
967 				(long long)count);
968 		return -1;
969 	}
970 
971 	ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count "
972 		       "%lld\n", (unsigned long long)na->ni->mft_no,
973 		       na->type, (long long)pos, (long long)count);
974 
975 	ret = ntfs_attr_pread_i(na, pos, count, b);
976 
977 	ntfs_log_leave("\n");
978 	return ret;
979 }
980 
981 static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count)
982 {
983 	char *buf;
984 	s64 written, size, end = pos + count;
985 	int ret = -1;
986 
987 	ntfs_log_trace("pos %lld, count %lld\n", (long long)pos,
988 		       (long long)count);
989 
990 	if (!na || pos < 0 || count < 0) {
991 		errno = EINVAL;
992 		goto err_out;
993 	}
994 
995 	buf = ntfs_calloc(NTFS_BUF_SIZE);
996 	if (!buf)
997 		goto err_out;
998 
999 	while (pos < end) {
1000 		size = min(end - pos, NTFS_BUF_SIZE);
1001 		written = ntfs_rl_pwrite(na->ni->vol, na->rl, pos, size, buf);
1002 		if (written <= 0) {
1003 			ntfs_log_perror("Failed to zero space");
1004 			goto err_free;
1005 		}
1006 		pos += written;
1007 	}
1008 
1009 	ret = 0;
1010 err_free:
1011 	free(buf);
1012 err_out:
1013 	return ret;
1014 }
1015 
1016 static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs,
1017 			       runlist_element **rl, VCN *update_from)
1018 {
1019 	s64 to_write;
1020 	ntfs_volume *vol = na->ni->vol;
1021 	int eo, ret = -1;
1022 	runlist *rlc;
1023 	LCN lcn_seek_from = -1;
1024 	VCN cur_vcn, from_vcn;
1025 
1026 	to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs);
1027 
1028 	cur_vcn = (*rl)->vcn;
1029 	from_vcn = (*rl)->vcn + (*ofs >> vol->cluster_size_bits);
1030 
1031 	ntfs_log_trace("count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: "
1032 		       "%lld\n", (long long)count, (long long)cur_vcn,
1033 		       (long long)from_vcn, (long long)to_write, (long long)*ofs);
1034 
1035 	/* Map whole runlist to be able update mapping pairs later. */
1036 	if (ntfs_attr_map_whole_runlist(na))
1037 		goto err_out;
1038 
1039 	/* Restore @*rl, it probably get lost during runlist mapping. */
1040 	*rl = ntfs_attr_find_vcn(na, cur_vcn);
1041 	if (!*rl) {
1042 		ntfs_log_error("Failed to find run after mapping runlist. "
1043 			       "Please report to %s.\n", NTFS_DEV_LIST);
1044 		errno = EIO;
1045 		goto err_out;
1046 	}
1047 
1048 	/* Search backwards to find the best lcn to start seek from. */
1049 	rlc = *rl;
1050 	while (rlc->vcn) {
1051 		rlc--;
1052 		if (rlc->lcn >= 0) {
1053 			lcn_seek_from = rlc->lcn + (from_vcn - rlc->vcn);
1054 			break;
1055 		}
1056 	}
1057 	if (lcn_seek_from == -1) {
1058 		/* Backwards search failed, search forwards. */
1059 		rlc = *rl;
1060 		while (rlc->length) {
1061 			rlc++;
1062 			if (rlc->lcn >= 0) {
1063 				lcn_seek_from = rlc->lcn - (rlc->vcn - from_vcn);
1064 				if (lcn_seek_from < -1)
1065 					lcn_seek_from = -1;
1066 				break;
1067 			}
1068 		}
1069 	}
1070 
1071 	rlc = ntfs_cluster_alloc(vol, from_vcn,
1072 				((*ofs + to_write - 1) >> vol->cluster_size_bits)
1073 				 + 1 + (*rl)->vcn - from_vcn,
1074 				 lcn_seek_from, DATA_ZONE);
1075 	if (!rlc)
1076 		goto err_out;
1077 
1078 	*rl = ntfs_runlists_merge(na->rl, rlc);
1079 	if (!*rl) {
1080 		eo = errno;
1081 		ntfs_log_perror("Failed to merge runlists");
1082 		if (ntfs_cluster_free_from_rl(vol, rlc)) {
1083 			ntfs_log_perror("Failed to free hot clusters. "
1084 					"Please run chkdsk /f");
1085 		}
1086 		errno = eo;
1087 		goto err_out;
1088 	}
1089 	na->rl = *rl;
1090 	if (*update_from == -1)
1091 		*update_from = from_vcn;
1092 	*rl = ntfs_attr_find_vcn(na, cur_vcn);
1093 	if (!*rl) {
1094 		/*
1095 		 * It's definitely a BUG, if we failed to find @cur_vcn, because
1096 		 * we missed it during instantiating of the hole.
1097 		 */
1098 		ntfs_log_error("Failed to find run after hole instantiation. "
1099 			       "Please report to %s.\n", NTFS_DEV_LIST);
1100 		errno = EIO;
1101 		goto err_out;
1102 	}
1103 	/* If leaved part of the hole go to the next run. */
1104 	if ((*rl)->lcn < 0)
1105 		(*rl)++;
1106 	/* Now LCN shoudn't be less than 0. */
1107 	if ((*rl)->lcn < 0) {
1108 		ntfs_log_error("BUG! LCN is lesser than 0. "
1109 			       "Please report to the %s.\n", NTFS_DEV_LIST);
1110 		errno = EIO;
1111 		goto err_out;
1112 	}
1113 	if (*ofs) {
1114 		/* Clear non-sparse region from @cur_vcn to @*ofs. */
1115 		if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits,
1116 					*ofs))
1117 			goto err_out;
1118 	}
1119 	if ((*rl)->vcn < cur_vcn) {
1120 		/*
1121 		 * Clusters that replaced hole are merged with
1122 		 * previous run, so we need to update offset.
1123 		 */
1124 		*ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits;
1125 	}
1126 	if ((*rl)->vcn > cur_vcn) {
1127 		/*
1128 		 * We left part of the hole, so we need to update offset
1129 		 */
1130 		*ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits;
1131 	}
1132 
1133 	ret = 0;
1134 err_out:
1135 	return ret;
1136 }
1137 
1138 /**
1139  * ntfs_attr_pwrite - positioned write to an ntfs attribute
1140  * @na:		ntfs attribute to write to
1141  * @pos:	position in the attribute to write to
1142  * @count:	number of bytes to write
1143  * @b:		data buffer to write to disk
1144  *
1145  * This function will write @count bytes from data buffer @b to ntfs attribute
1146  * @na at position @pos.
1147  *
1148  * On success, return the number of successfully written bytes. If this number
1149  * is lower than @count this means that an error was encountered during the
1150  * write so that the write is partial. 0 means nothing was written (also return
1151  * 0 when @count is 0).
1152  *
1153  * On error and nothing has been written, return -1 with errno set
1154  * appropriately to the return code of ntfs_pwrite(), or to EINVAL in case of
1155  * invalid arguments.
1156  */
1157 s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b)
1158 {
1159 	s64 written, to_write, ofs, old_initialized_size, old_data_size;
1160 	s64 total = 0;
1161 	VCN update_from = -1;
1162 	ntfs_volume *vol;
1163 	ntfs_attr_search_ctx *ctx = NULL;
1164 	runlist_element *rl;
1165 	s64 hole_end;
1166 	int eo;
1167 	struct {
1168 		unsigned int undo_initialized_size	: 1;
1169 		unsigned int undo_data_size		: 1;
1170 	} need_to = { 0, 0 };
1171 
1172 	ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count "
1173 		       "0x%llx.\n", (long long)na->ni->mft_no, na->type,
1174 		       (long long)pos, (long long)count);
1175 
1176 	if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) {
1177 		errno = EINVAL;
1178 		ntfs_log_perror("%s", __FUNCTION__);
1179 		goto errno_set;
1180 	}
1181 	vol = na->ni->vol;
1182 	/*
1183 	 * Encrypted non-resident attributes are not supported.  We return
1184 	 * access denied, which is what Windows NT4 does, too.
1185 	 */
1186 	if (NAttrEncrypted(na) && NAttrNonResident(na)) {
1187 		errno = EACCES;
1188 		goto errno_set;
1189 	}
1190 	/* If this is a compressed attribute it needs special treatment. */
1191 	if (NAttrCompressed(na)) {
1192 		// TODO: Implement writing compressed attributes! (AIA)
1193 		// return ntfs_attr_pwrite_compressed(ntfs_attr *na,
1194 		//		const s64 pos, s64 count, void *b);
1195 		errno = EOPNOTSUPP;
1196 		goto errno_set;
1197 	}
1198 
1199 	if (!count)
1200 		goto out;
1201 	/* If the write reaches beyond the end, extend the attribute. */
1202 	old_data_size = na->data_size;
1203 	if (pos + count > na->data_size) {
1204 		if (ntfs_attr_truncate(na, pos + count)) {
1205 			ntfs_log_perror("Failed to enlarge attribute");
1206 			goto errno_set;
1207 		}
1208 		need_to.undo_data_size = 1;
1209 	}
1210 	old_initialized_size = na->initialized_size;
1211 	/* If it is a resident attribute, write the data to the mft record. */
1212 	if (!NAttrNonResident(na)) {
1213 		char *val;
1214 
1215 		ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
1216 		if (!ctx)
1217 			goto err_out;
1218 		if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0,
1219 				0, NULL, 0, ctx)) {
1220 			ntfs_log_perror("%s: lookup failed", __FUNCTION__);
1221 			goto err_out;
1222 		}
1223 		val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset);
1224 		if (val < (char*)ctx->attr || val +
1225 				le32_to_cpu(ctx->attr->value_length) >
1226 				(char*)ctx->mrec + vol->mft_record_size) {
1227 			errno = EIO;
1228 			ntfs_log_perror("%s: Sanity check failed", __FUNCTION__);
1229 			goto err_out;
1230 		}
1231 		memcpy(val + pos, b, count);
1232 		if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no,
1233 				ctx->mrec)) {
1234 			/*
1235 			 * NOTE: We are in a bad state at this moment. We have
1236 			 * dirtied the mft record but we failed to commit it to
1237 			 * disk. Since we have read the mft record ok before,
1238 			 * it is unlikely to fail writing it, so is ok to just
1239 			 * return error here... (AIA)
1240 			 */
1241 			ntfs_log_perror("%s: failed to write mft record", __FUNCTION__);
1242 			goto err_out;
1243 		}
1244 		ntfs_attr_put_search_ctx(ctx);
1245 		total = count;
1246 		goto out;
1247 	}
1248 
1249 	/* Handle writes beyond initialized_size. */
1250 	if (pos + count > na->initialized_size) {
1251 		if (ntfs_attr_map_whole_runlist(na))
1252 			goto err_out;
1253 		/* Set initialized_size to @pos + @count. */
1254 		ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
1255 		if (!ctx)
1256 			goto err_out;
1257 		if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0,
1258 				0, NULL, 0, ctx))
1259 			goto err_out;
1260 
1261 		/* If write starts beyond initialized_size, zero the gap. */
1262 		if (pos > na->initialized_size)
1263 			if (ntfs_attr_fill_zero(na, na->initialized_size,
1264 						pos - na->initialized_size))
1265 				goto err_out;
1266 
1267 		ctx->attr->initialized_size = cpu_to_sle64(pos + count);
1268 		if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no,
1269 				ctx->mrec)) {
1270 			/*
1271 			 * Undo the change in the in-memory copy and send it
1272 			 * back for writing.
1273 			 */
1274 			ctx->attr->initialized_size =
1275 					cpu_to_sle64(old_initialized_size);
1276 			ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no,
1277 					ctx->mrec);
1278 			goto err_out;
1279 		}
1280 		na->initialized_size = pos + count;
1281 		ntfs_attr_put_search_ctx(ctx);
1282 		ctx = NULL;
1283 		/*
1284 		 * NOTE: At this point the initialized_size in the mft record
1285 		 * has been updated BUT there is random data on disk thus if
1286 		 * we decide to abort, we MUST change the initialized_size
1287 		 * again.
1288 		 */
1289 		need_to.undo_initialized_size = 1;
1290 	}
1291 	/* Find the runlist element containing the vcn. */
1292 	rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits);
1293 	if (!rl) {
1294 		/*
1295 		 * If the vcn is not present it is an out of bounds write.
1296 		 * However, we already extended the size of the attribute,
1297 		 * so getting this here must be an error of some kind.
1298 		 */
1299 		if (errno == ENOENT) {
1300 			errno = EIO;
1301 			ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__);
1302 		}
1303 		goto err_out;
1304 	}
1305 	/*
1306 	 * Scatter the data from the linear data buffer to the volume. Note, a
1307 	 * partial final vcn is taken care of by the @count capping of write
1308 	 * length.
1309 	 */
1310 	ofs = pos - (rl->vcn << vol->cluster_size_bits);
1311 	for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) {
1312 		if (rl->lcn == LCN_RL_NOT_MAPPED) {
1313 			rl = ntfs_attr_find_vcn(na, rl->vcn);
1314 			if (!rl) {
1315 				if (errno == ENOENT) {
1316 					errno = EIO;
1317 					ntfs_log_perror("%s: Failed to find VCN"
1318 							" #2", __FUNCTION__);
1319 				}
1320 				goto rl_err_out;
1321 			}
1322 			/* Needed for case when runs merged. */
1323 			ofs = pos + total - (rl->vcn << vol->cluster_size_bits);
1324 		}
1325 		if (!rl->length) {
1326 			errno = EIO;
1327 			ntfs_log_perror("%s: Zero run length", __FUNCTION__);
1328 			goto rl_err_out;
1329 		}
1330 		if (rl->lcn < (LCN)0) {
1331 
1332 			hole_end = rl->vcn + rl->length;
1333 
1334 			if (rl->lcn != (LCN)LCN_HOLE) {
1335 				errno = EIO;
1336 				ntfs_log_perror("%s: Unexpected LCN (%lld)",
1337 						__FUNCTION__,
1338 						(long long)rl->lcn);
1339 				goto rl_err_out;
1340 			}
1341 
1342 			if (ntfs_attr_fill_hole(na, count, &ofs, &rl, &update_from))
1343 				goto err_out;
1344 		}
1345 		/* It is a real lcn, write it to the volume. */
1346 		to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs);
1347 retry:
1348 		ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs "
1349 			       "%lld.\n", (long long)to_write, (long long)rl->vcn,
1350 			       (long long)rl->lcn, (long long)ofs);
1351 		if (!NVolReadOnly(vol)) {
1352 
1353 			s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs;
1354 			s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write;
1355 			u32 bsize = vol->cluster_size;
1356 			/* Byte size needed to zero fill a cluster */
1357 			s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend;
1358 			/**
1359 			 * Zero fill to cluster boundary if we're writing at the
1360 			 * end of the attribute or into an ex-sparse cluster.
1361 			 * This will cause the kernel not to seek and read disk
1362 			 * blocks during write(2) to fill the end of the buffer
1363 			 * which increases write speed by 2-10 fold typically.
1364 			 */
1365 			if (rounding && ((wend == na->initialized_size) ||
1366 				(wend < (hole_end << vol->cluster_size_bits)))){
1367 
1368 				char *cb;
1369 
1370 				rounding += to_write;
1371 
1372 				cb = ntfs_malloc(rounding);
1373 				if (!cb)
1374 					goto err_out;
1375 
1376 				memcpy(cb, b, to_write);
1377 				memset(cb + to_write, 0, rounding - to_write);
1378 
1379 				written = ntfs_pwrite(vol->dev, wpos, rounding, cb);
1380 				if (written == rounding)
1381 					written = to_write;
1382 
1383 				free(cb);
1384 			} else
1385 				written = ntfs_pwrite(vol->dev, wpos, to_write, b);
1386 		} else
1387 			written = to_write;
1388 		/* If everything ok, update progress counters and continue. */
1389 		if (written > 0) {
1390 			total += written;
1391 			count -= written;
1392 			b = (const u8*)b + written;
1393 		}
1394 		if (written == to_write)
1395 			continue;
1396 		/* If the syscall was interrupted, try again. */
1397 		if (written == (s64)-1 && errno == EINTR)
1398 			goto retry;
1399 		if (!written)
1400 			errno = EIO;
1401 		goto rl_err_out;
1402 	}
1403 done:
1404 	if (ctx)
1405 		ntfs_attr_put_search_ctx(ctx);
1406 	/* Update mapping pairs if needed. */
1407 	if (update_from != -1)
1408 		if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) {
1409 			/*
1410 			 * FIXME: trying to recover by goto rl_err_out;
1411 			 * could cause driver hang by infinite looping.
1412 			 */
1413 			total = -1;
1414 			goto out;
1415 		}
1416 out:
1417 	ntfs_log_leave("\n");
1418 	return total;
1419 rl_err_out:
1420 	eo = errno;
1421 	if (total) {
1422 		if (need_to.undo_initialized_size) {
1423 			if (pos + total > na->initialized_size)
1424 				goto done;
1425 			/*
1426 			 * TODO: Need to try to change initialized_size. If it
1427 			 * succeeds goto done, otherwise goto err_out. (AIA)
1428 			 */
1429 			goto err_out;
1430 		}
1431 		goto done;
1432 	}
1433 	errno = eo;
1434 err_out:
1435 	eo = errno;
1436 	if (need_to.undo_initialized_size) {
1437 		int err;
1438 
1439 		err = 0;
1440 		if (!ctx) {
1441 			ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
1442 			if (!ctx)
1443 				err = 1;
1444 		} else
1445 			ntfs_attr_reinit_search_ctx(ctx);
1446 		if (!err) {
1447 			err = ntfs_attr_lookup(na->type, na->name,
1448 					na->name_len, 0, 0, NULL, 0, ctx);
1449 			if (!err) {
1450 				na->initialized_size = old_initialized_size;
1451 				ctx->attr->initialized_size = cpu_to_sle64(
1452 						old_initialized_size);
1453 				err = ntfs_mft_record_write(vol,
1454 						ctx->ntfs_ino->mft_no,
1455 						ctx->mrec);
1456 			}
1457 		}
1458 		if (err) {
1459 			/*
1460 			 * FIXME: At this stage could try to recover by filling
1461 			 * old_initialized_size -> new_initialized_size with
1462 			 * data or at least zeroes. (AIA)
1463 			 */
1464 			ntfs_log_error("Eeek! Failed to recover from error. "
1465 					"Leaving metadata in inconsistent "
1466 					"state! Run chkdsk!\n");
1467 		}
1468 	}
1469 	if (ctx)
1470 		ntfs_attr_put_search_ctx(ctx);
1471 	/* Update mapping pairs if needed. */
1472 	if (update_from != -1)
1473 		ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/);
1474 	/* Restore original data_size if needed. */
1475 	if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size))
1476 		ntfs_log_perror("Failed to restore data_size");
1477 	errno = eo;
1478 errno_set:
1479 	total = -1;
1480 	goto out;
1481 }
1482 
1483 /**
1484  * ntfs_attr_mst_pread - multi sector transfer protected ntfs attribute read
1485  * @na:		multi sector transfer protected ntfs attribute to read from
1486  * @pos:	byte position in the attribute to begin reading from
1487  * @bk_cnt:	number of mst protected blocks to read
1488  * @bk_size:	size of each mst protected block in bytes
1489  * @dst:	output data buffer
1490  *
1491  * This function will read @bk_cnt blocks of size @bk_size bytes each starting
1492  * at offset @pos from the ntfs attribute @na into the data buffer @b.
1493  *
1494  * On success, the multi sector transfer fixups are applied and the number of
1495  * read blocks is returned. If this number is lower than @bk_cnt this means
1496  * that the read has either reached end of attribute or that an error was
1497  * encountered during the read so that the read is partial. 0 means end of
1498  * attribute or nothing to read (also return 0 when @bk_cnt or @bk_size are 0).
1499  *
1500  * On error and nothing has been read, return -1 with errno set appropriately
1501  * to the return code of ntfs_attr_pread() or to EINVAL in case of invalid
1502  * arguments.
1503  *
1504  * NOTE: If an incomplete multi sector transfer is detected the magic is
1505  * changed to BAAD but no error is returned, i.e. it is possible that any of
1506  * the returned blocks have multi sector transfer errors. This should be
1507  * detected by the caller by checking each block with is_baad_recordp(&block).
1508  * The reasoning is that we want to fixup as many blocks as possible and we
1509  * want to return even bad ones to the caller so, e.g. in case of ntfsck, the
1510  * errors can be repaired.
1511  */
1512 s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt,
1513 		const u32 bk_size, void *dst)
1514 {
1515 	s64 br;
1516 	u8 *end;
1517 
1518 	ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n",
1519 			(unsigned long long)na->ni->mft_no, na->type,
1520 			(long long)pos);
1521 	if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) {
1522 		errno = EINVAL;
1523 		ntfs_log_perror("%s", __FUNCTION__);
1524 		return -1;
1525 	}
1526 	br = ntfs_attr_pread(na, pos, bk_cnt * bk_size, dst);
1527 	if (br <= 0)
1528 		return br;
1529 	br /= bk_size;
1530 	for (end = (u8*)dst + br * bk_size; (u8*)dst < end; dst = (u8*)dst +
1531 			bk_size)
1532 		ntfs_mst_post_read_fixup((NTFS_RECORD*)dst, bk_size);
1533 	/* Finally, return the number of blocks read. */
1534 	return br;
1535 }
1536 
1537 /**
1538  * ntfs_attr_mst_pwrite - multi sector transfer protected ntfs attribute write
1539  * @na:		multi sector transfer protected ntfs attribute to write to
1540  * @pos:	position in the attribute to write to
1541  * @bk_cnt:	number of mst protected blocks to write
1542  * @bk_size:	size of each mst protected block in bytes
1543  * @src:	data buffer to write to disk
1544  *
1545  * This function will write @bk_cnt blocks of size @bk_size bytes each from
1546  * data buffer @b to multi sector transfer (mst) protected ntfs attribute @na
1547  * at position @pos.
1548  *
1549  * On success, return the number of successfully written blocks. If this number
1550  * is lower than @bk_cnt this means that an error was encountered during the
1551  * write so that the write is partial. 0 means nothing was written (also
1552  * return 0 when @bk_cnt or @bk_size are 0).
1553  *
1554  * On error and nothing has been written, return -1 with errno set
1555  * appropriately to the return code of ntfs_attr_pwrite(), or to EINVAL in case
1556  * of invalid arguments.
1557  *
1558  * NOTE: We mst protect the data, write it, then mst deprotect it using a quick
1559  * deprotect algorithm (no checking). This saves us from making a copy before
1560  * the write and at the same time causes the usn to be incremented in the
1561  * buffer. This conceptually fits in better with the idea that cached data is
1562  * always deprotected and protection is performed when the data is actually
1563  * going to hit the disk and the cache is immediately deprotected again
1564  * simulating an mst read on the written data. This way cache coherency is
1565  * achieved.
1566  */
1567 s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt,
1568 		const u32 bk_size, void *src)
1569 {
1570 	s64 written, i;
1571 
1572 	ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n",
1573 			(unsigned long long)na->ni->mft_no, na->type,
1574 			(long long)pos);
1575 	if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) {
1576 		errno = EINVAL;
1577 		return -1;
1578 	}
1579 	if (!bk_cnt)
1580 		return 0;
1581 	/* Prepare data for writing. */
1582 	for (i = 0; i < bk_cnt; ++i) {
1583 		int err;
1584 
1585 		err = ntfs_mst_pre_write_fixup((NTFS_RECORD*)
1586 				((u8*)src + i * bk_size), bk_size);
1587 		if (err < 0) {
1588 			/* Abort write at this position. */
1589 			ntfs_log_perror("%s #1", __FUNCTION__);
1590 			if (!i)
1591 				return err;
1592 			bk_cnt = i;
1593 			break;
1594 		}
1595 	}
1596 	/* Write the prepared data. */
1597 	written = ntfs_attr_pwrite(na, pos, bk_cnt * bk_size, src);
1598 	if (written <= 0) {
1599 		ntfs_log_perror("%s: written=%lld", __FUNCTION__,
1600 				(long long)written);
1601 	}
1602 	/* Quickly deprotect the data again. */
1603 	for (i = 0; i < bk_cnt; ++i)
1604 		ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)src + i *
1605 				bk_size));
1606 	if (written <= 0)
1607 		return written;
1608 	/* Finally, return the number of complete blocks written. */
1609 	return written / bk_size;
1610 }
1611 
1612 /**
1613  * ntfs_attr_find - find (next) attribute in mft record
1614  * @type:	attribute type to find
1615  * @name:	attribute name to find (optional, i.e. NULL means don't care)
1616  * @name_len:	attribute name length (only needed if @name present)
1617  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1618  * @val:	attribute value to find (optional, resident attributes only)
1619  * @val_len:	attribute value length
1620  * @ctx:	search context with mft record and attribute to search from
1621  *
1622  * You shouldn't need to call this function directly. Use lookup_attr() instead.
1623  *
1624  * ntfs_attr_find() takes a search context @ctx as parameter and searches the
1625  * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
1626  * attribute of @type, optionally @name and @val. If found, ntfs_attr_find()
1627  * returns 0 and @ctx->attr will point to the found attribute.
1628  *
1629  * If not found, ntfs_attr_find() returns -1, with errno set to ENOENT and
1630  * @ctx->attr will point to the attribute before which the attribute being
1631  * searched for would need to be inserted if such an action were to be desired.
1632  *
1633  * On actual error, ntfs_attr_find() returns -1 with errno set to the error
1634  * code but not to ENOENT.  In this case @ctx->attr is undefined and in
1635  * particular do not rely on it not changing.
1636  *
1637  * If @ctx->is_first is TRUE, the search begins with @ctx->attr itself. If it
1638  * is FALSE, the search begins after @ctx->attr.
1639  *
1640  * If @type is AT_UNUSED, return the first found attribute, i.e. one can
1641  * enumerate all attributes by setting @type to AT_UNUSED and then calling
1642  * ntfs_attr_find() repeatedly until it returns -1 with errno set to ENOENT to
1643  * indicate that there are no more entries. During the enumeration, each
1644  * successful call of ntfs_attr_find() will return the next attribute in the
1645  * mft record @ctx->mrec.
1646  *
1647  * If @type is AT_END, seek to the end and return -1 with errno set to ENOENT.
1648  * AT_END is not a valid attribute, its length is zero for example, thus it is
1649  * safer to return error instead of success in this case. This also allows us
1650  * to interoperate cleanly with ntfs_external_attr_find().
1651  *
1652  * If @name is AT_UNNAMED search for an unnamed attribute. If @name is present
1653  * but not AT_UNNAMED search for a named attribute matching @name. Otherwise,
1654  * match both named and unnamed attributes.
1655  *
1656  * If @ic is IGNORE_CASE, the @name comparison is not case sensitive and
1657  * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
1658  * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
1659  * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
1660  * sensitive. When @name is present, @name_len is the @name length in Unicode
1661  * characters.
1662  *
1663  * If @name is not present (NULL), we assume that the unnamed attribute is
1664  * being searched for.
1665  *
1666  * Finally, the resident attribute value @val is looked for, if present.
1667  * If @val is not present (NULL), @val_len is ignored.
1668  *
1669  * ntfs_attr_find() only searches the specified mft record and it ignores the
1670  * presence of an attribute list attribute (unless it is the one being searched
1671  * for, obviously). If you need to take attribute lists into consideration, use
1672  * ntfs_attr_lookup() instead (see below). This also means that you cannot use
1673  * ntfs_attr_find() to search for extent records of non-resident attributes, as
1674  * extents with lowest_vcn != 0 are usually described by the attribute list
1675  * attribute only. - Note that it is possible that the first extent is only in
1676  * the attribute list while the last extent is in the base mft record, so don't
1677  * rely on being able to find the first extent in the base mft record.
1678  *
1679  * Warning: Never use @val when looking for attribute types which can be
1680  *	    non-resident as this most likely will result in a crash!
1681  */
1682 static int ntfs_attr_find(const ATTR_TYPES type, const ntfschar *name,
1683 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1684 		const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
1685 {
1686 	ATTR_RECORD *a;
1687 	ntfs_volume *vol;
1688 	ntfschar *upcase;
1689 	u32 upcase_len;
1690 
1691 	ntfs_log_trace("attribute type 0x%x.\n", type);
1692 
1693 	if (ctx->ntfs_ino) {
1694 		vol = ctx->ntfs_ino->vol;
1695 		upcase = vol->upcase;
1696 		upcase_len = vol->upcase_len;
1697 	} else {
1698 		if (name && name != AT_UNNAMED) {
1699 			errno = EINVAL;
1700 			ntfs_log_perror("%s", __FUNCTION__);
1701 			return -1;
1702 		}
1703 		vol = NULL;
1704 		upcase = NULL;
1705 		upcase_len = 0;
1706 	}
1707 	/*
1708 	 * Iterate over attributes in mft record starting at @ctx->attr, or the
1709 	 * attribute following that, if @ctx->is_first is TRUE.
1710 	 */
1711 	if (ctx->is_first) {
1712 		a = ctx->attr;
1713 		ctx->is_first = FALSE;
1714 	} else
1715 		a = (ATTR_RECORD*)((char*)ctx->attr +
1716 				le32_to_cpu(ctx->attr->length));
1717 	for (;;	a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) {
1718 		if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec +
1719 				le32_to_cpu(ctx->mrec->bytes_allocated))
1720 			break;
1721 		ctx->attr = a;
1722 		if (((type != AT_UNUSED) && (le32_to_cpu(a->type) >
1723 				le32_to_cpu(type))) ||
1724 				(a->type == AT_END)) {
1725 			errno = ENOENT;
1726 			return -1;
1727 		}
1728 		if (!a->length)
1729 			break;
1730 		/* If this is an enumeration return this attribute. */
1731 		if (type == AT_UNUSED)
1732 			return 0;
1733 		if (a->type != type)
1734 			continue;
1735 		/*
1736 		 * If @name is AT_UNNAMED we want an unnamed attribute.
1737 		 * If @name is present, compare the two names.
1738 		 * Otherwise, match any attribute.
1739 		 */
1740 		if (name == AT_UNNAMED) {
1741 			/* The search failed if the found attribute is named. */
1742 			if (a->name_length) {
1743 				errno = ENOENT;
1744 				return -1;
1745 			}
1746 		} else if (name && !ntfs_names_are_equal(name, name_len,
1747 			    (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)),
1748 			    a->name_length, ic, upcase, upcase_len)) {
1749 			register int rc;
1750 
1751 			rc = ntfs_names_collate(name, name_len,
1752 					(ntfschar*)((char*)a +
1753 					le16_to_cpu(a->name_offset)),
1754 					a->name_length, 1, IGNORE_CASE,
1755 					upcase, upcase_len);
1756 			/*
1757 			 * If @name collates before a->name, there is no
1758 			 * matching attribute.
1759 			 */
1760 			if (rc == -1) {
1761 				errno = ENOENT;
1762 				return -1;
1763 			}
1764 			/* If the strings are not equal, continue search. */
1765 			if (rc)
1766 				continue;
1767 			rc = ntfs_names_collate(name, name_len,
1768 					(ntfschar*)((char*)a +
1769 					le16_to_cpu(a->name_offset)),
1770 					a->name_length, 1, CASE_SENSITIVE,
1771 					upcase, upcase_len);
1772 			if (rc == -1) {
1773 				errno = ENOENT;
1774 				return -1;
1775 			}
1776 			if (rc)
1777 				continue;
1778 		}
1779 		/*
1780 		 * The names match or @name not present and attribute is
1781 		 * unnamed. If no @val specified, we have found the attribute
1782 		 * and are done.
1783 		 */
1784 		if (!val)
1785 			return 0;
1786 		/* @val is present; compare values. */
1787 		else {
1788 			register int rc;
1789 
1790 			rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset),
1791 					min(val_len,
1792 					le32_to_cpu(a->value_length)));
1793 			/*
1794 			 * If @val collates before the current attribute's
1795 			 * value, there is no matching attribute.
1796 			 */
1797 			if (!rc) {
1798 				register u32 avl;
1799 				avl = le32_to_cpu(a->value_length);
1800 				if (val_len == avl)
1801 					return 0;
1802 				if (val_len < avl) {
1803 					errno = ENOENT;
1804 					return -1;
1805 				}
1806 			} else if (rc < 0) {
1807 				errno = ENOENT;
1808 				return -1;
1809 			}
1810 		}
1811 	}
1812 	errno = EIO;
1813 	ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__,
1814 			ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1);
1815 	return -1;
1816 }
1817 
1818 void ntfs_attr_name_free(char **name)
1819 {
1820 	if (*name) {
1821 		free(*name);
1822 		*name = NULL;
1823 	}
1824 }
1825 
1826 char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len)
1827 {
1828 	char *name = NULL;
1829 	int name_len;
1830 
1831 	name_len = ntfs_ucstombs(uname, uname_len, &name, 0);
1832 	if (name_len < 0) {
1833 		ntfs_log_perror("ntfs_ucstombs");
1834 		return NULL;
1835 
1836 	} else if (name_len > 0)
1837 		return name;
1838 
1839 	ntfs_attr_name_free(&name);
1840 	return NULL;
1841 }
1842 
1843 /**
1844  * ntfs_external_attr_find - find an attribute in the attribute list of an inode
1845  * @type:	attribute type to find
1846  * @name:	attribute name to find (optional, i.e. NULL means don't care)
1847  * @name_len:	attribute name length (only needed if @name present)
1848  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1849  * @lowest_vcn:	lowest vcn to find (optional, non-resident attributes only)
1850  * @val:	attribute value to find (optional, resident attributes only)
1851  * @val_len:	attribute value length
1852  * @ctx:	search context with mft record and attribute to search from
1853  *
1854  * You shouldn't need to call this function directly. Use ntfs_attr_lookup()
1855  * instead.
1856  *
1857  * Find an attribute by searching the attribute list for the corresponding
1858  * attribute list entry. Having found the entry, map the mft record for read
1859  * if the attribute is in a different mft record/inode, find the attribute in
1860  * there and return it.
1861  *
1862  * If @type is AT_UNUSED, return the first found attribute, i.e. one can
1863  * enumerate all attributes by setting @type to AT_UNUSED and then calling
1864  * ntfs_external_attr_find() repeatedly until it returns -1 with errno set to
1865  * ENOENT to indicate that there are no more entries. During the enumeration,
1866  * each successful call of ntfs_external_attr_find() will return the next
1867  * attribute described by the attribute list of the base mft record described
1868  * by the search context @ctx.
1869  *
1870  * If @type is AT_END, seek to the end of the base mft record ignoring the
1871  * attribute list completely and return -1 with errno set to ENOENT.  AT_END is
1872  * not a valid attribute, its length is zero for example, thus it is safer to
1873  * return error instead of success in this case.
1874  *
1875  * If @name is AT_UNNAMED search for an unnamed attribute. If @name is present
1876  * but not AT_UNNAMED search for a named attribute matching @name. Otherwise,
1877  * match both named and unnamed attributes.
1878  *
1879  * On first search @ctx->ntfs_ino must be the inode of the base mft record and
1880  * @ctx must have been obtained from a call to ntfs_attr_get_search_ctx().
1881  * On subsequent calls, @ctx->ntfs_ino can be any extent inode, too
1882  * (@ctx->base_ntfs_ino is then the base inode).
1883  *
1884  * After finishing with the attribute/mft record you need to call
1885  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1886  * mapped extent inodes, etc).
1887  *
1888  * Return 0 if the search was successful and -1 if not, with errno set to the
1889  * error code.
1890  *
1891  * On success, @ctx->attr is the found attribute, it is in mft record
1892  * @ctx->mrec, and @ctx->al_entry is the attribute list entry for this
1893  * attribute with @ctx->base_* being the base mft record to which @ctx->attr
1894  * belongs.
1895  *
1896  * On error ENOENT, i.e. attribute not found, @ctx->attr is set to the
1897  * attribute which collates just after the attribute being searched for in the
1898  * base ntfs inode, i.e. if one wants to add the attribute to the mft record
1899  * this is the correct place to insert it into, and if there is not enough
1900  * space, the attribute should be placed in an extent mft record.
1901  * @ctx->al_entry points to the position within @ctx->base_ntfs_ino->attr_list
1902  * at which the new attribute's attribute list entry should be inserted.  The
1903  * other @ctx fields, base_ntfs_ino, base_mrec, and base_attr are set to NULL.
1904  * The only exception to this is when @type is AT_END, in which case
1905  * @ctx->al_entry is set to NULL also (see above).
1906  *
1907  * The following error codes are defined:
1908  *	ENOENT	Attribute not found, not an error as such.
1909  *	EINVAL	Invalid arguments.
1910  *	EIO	I/O error or corrupt data structures found.
1911  *	ENOMEM	Not enough memory to allocate necessary buffers.
1912  */
1913 static int ntfs_external_attr_find(ATTR_TYPES type, const ntfschar *name,
1914 		const u32 name_len, const IGNORE_CASE_BOOL ic,
1915 		const VCN lowest_vcn, const u8 *val, const u32 val_len,
1916 		ntfs_attr_search_ctx *ctx)
1917 {
1918 	ntfs_inode *base_ni, *ni;
1919 	ntfs_volume *vol;
1920 	ATTR_LIST_ENTRY *al_entry, *next_al_entry;
1921 	u8 *al_start, *al_end;
1922 	ATTR_RECORD *a;
1923 	ntfschar *al_name;
1924 	u32 al_name_len;
1925 	BOOL is_first_search = FALSE;
1926 
1927 	ni = ctx->ntfs_ino;
1928 	base_ni = ctx->base_ntfs_ino;
1929 	ntfs_log_trace("Entering for inode %lld, attribute type 0x%x.\n",
1930 			(unsigned long long)ni->mft_no, type);
1931 	if (!base_ni) {
1932 		/* First call happens with the base mft record. */
1933 		base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
1934 		ctx->base_mrec = ctx->mrec;
1935 	}
1936 	if (ni == base_ni)
1937 		ctx->base_attr = ctx->attr;
1938 	if (type == AT_END)
1939 		goto not_found;
1940 	vol = base_ni->vol;
1941 	al_start = base_ni->attr_list;
1942 	al_end = al_start + base_ni->attr_list_size;
1943 	if (!ctx->al_entry) {
1944 		ctx->al_entry = (ATTR_LIST_ENTRY*)al_start;
1945 		is_first_search = TRUE;
1946 	}
1947 	/*
1948 	 * Iterate over entries in attribute list starting at @ctx->al_entry,
1949 	 * or the entry following that, if @ctx->is_first is TRUE.
1950 	 */
1951 	if (ctx->is_first) {
1952 		al_entry = ctx->al_entry;
1953 		ctx->is_first = FALSE;
1954 		/*
1955 		 * If an enumeration and the first attribute is higher than
1956 		 * the attribute list itself, need to return the attribute list
1957 		 * attribute.
1958 		 */
1959 		if ((type == AT_UNUSED) && is_first_search &&
1960 				le32_to_cpu(al_entry->type) >
1961 				le32_to_cpu(AT_ATTRIBUTE_LIST))
1962 			goto find_attr_list_attr;
1963 	} else {
1964 		al_entry = (ATTR_LIST_ENTRY*)((char*)ctx->al_entry +
1965 				le16_to_cpu(ctx->al_entry->length));
1966 		/*
1967 		 * If this is an enumeration and the attribute list attribute
1968 		 * is the next one in the enumeration sequence, just return the
1969 		 * attribute list attribute from the base mft record as it is
1970 		 * not listed in the attribute list itself.
1971 		 */
1972 		if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) <
1973 				le32_to_cpu(AT_ATTRIBUTE_LIST) &&
1974 				le32_to_cpu(al_entry->type) >
1975 				le32_to_cpu(AT_ATTRIBUTE_LIST)) {
1976 			int rc;
1977 find_attr_list_attr:
1978 
1979 			/* Check for bogus calls. */
1980 			if (name || name_len || val || val_len || lowest_vcn) {
1981 				errno = EINVAL;
1982 				ntfs_log_perror("%s", __FUNCTION__);
1983 				return -1;
1984 			}
1985 
1986 			/* We want the base record. */
1987 			ctx->ntfs_ino = base_ni;
1988 			ctx->mrec = ctx->base_mrec;
1989 			ctx->is_first = TRUE;
1990 			/* Sanity checks are performed elsewhere. */
1991 			ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1992 					le16_to_cpu(ctx->mrec->attrs_offset));
1993 
1994 			/* Find the attribute list attribute. */
1995 			rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0,
1996 					IGNORE_CASE, NULL, 0, ctx);
1997 
1998 			/*
1999 			 * Setup the search context so the correct
2000 			 * attribute is returned next time round.
2001 			 */
2002 			ctx->al_entry = al_entry;
2003 			ctx->is_first = TRUE;
2004 
2005 			/* Got it. Done. */
2006 			if (!rc)
2007 				return 0;
2008 
2009 			/* Error! If other than not found return it. */
2010 			if (errno != ENOENT)
2011 				return rc;
2012 
2013 			/* Not found?!? Absurd! */
2014 			errno = EIO;
2015 			ntfs_log_error("Attribute list wasn't found");
2016 			return -1;
2017 		}
2018 	}
2019 	for (;; al_entry = next_al_entry) {
2020 		/* Out of bounds check. */
2021 		if ((u8*)al_entry < base_ni->attr_list ||
2022 				(u8*)al_entry > al_end)
2023 			break;	/* Inode is corrupt. */
2024 		ctx->al_entry = al_entry;
2025 		/* Catch the end of the attribute list. */
2026 		if ((u8*)al_entry == al_end)
2027 			goto not_found;
2028 		if (!al_entry->length)
2029 			break;
2030 		if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
2031 				le16_to_cpu(al_entry->length) > al_end)
2032 			break;
2033 		next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
2034 				le16_to_cpu(al_entry->length));
2035 		if (type != AT_UNUSED) {
2036 			if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
2037 				goto not_found;
2038 			if (type != al_entry->type)
2039 				continue;
2040 		}
2041 		al_name_len = al_entry->name_length;
2042 		al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset);
2043 		/*
2044 		 * If !@type we want the attribute represented by this
2045 		 * attribute list entry.
2046 		 */
2047 		if (type == AT_UNUSED)
2048 			goto is_enumeration;
2049 		/*
2050 		 * If @name is AT_UNNAMED we want an unnamed attribute.
2051 		 * If @name is present, compare the two names.
2052 		 * Otherwise, match any attribute.
2053 		 */
2054 		if (name == AT_UNNAMED) {
2055 			if (al_name_len)
2056 				goto not_found;
2057 		} else if (name && !ntfs_names_are_equal(al_name, al_name_len,
2058 				name, name_len, ic, vol->upcase,
2059 				vol->upcase_len)) {
2060 			register int rc;
2061 
2062 			rc = ntfs_names_collate(name, name_len, al_name,
2063 					al_name_len, 1, IGNORE_CASE,
2064 					vol->upcase, vol->upcase_len);
2065 			/*
2066 			 * If @name collates before al_name, there is no
2067 			 * matching attribute.
2068 			 */
2069 			if (rc == -1)
2070 				goto not_found;
2071 			/* If the strings are not equal, continue search. */
2072 			if (rc)
2073 				continue;
2074 			/*
2075 			 * FIXME: Reverse engineering showed 0, IGNORE_CASE but
2076 			 * that is inconsistent with ntfs_attr_find(). The
2077 			 * subsequent rc checks were also different. Perhaps I
2078 			 * made a mistake in one of the two. Need to recheck
2079 			 * which is correct or at least see what is going
2080 			 * on... (AIA)
2081 			 */
2082 			rc = ntfs_names_collate(name, name_len, al_name,
2083 					al_name_len, 1, CASE_SENSITIVE,
2084 					vol->upcase, vol->upcase_len);
2085 			if (rc == -1)
2086 				goto not_found;
2087 			if (rc)
2088 				continue;
2089 		}
2090 		/*
2091 		 * The names match or @name not present and attribute is
2092 		 * unnamed. Now check @lowest_vcn. Continue search if the
2093 		 * next attribute list entry still fits @lowest_vcn. Otherwise
2094 		 * we have reached the right one or the search has failed.
2095 		 */
2096 		if (lowest_vcn && (u8*)next_al_entry >= al_start	    &&
2097 				(u8*)next_al_entry + 6 < al_end	    &&
2098 				(u8*)next_al_entry + le16_to_cpu(
2099 					next_al_entry->length) <= al_end    &&
2100 				sle64_to_cpu(next_al_entry->lowest_vcn) <=
2101 					lowest_vcn			    &&
2102 				next_al_entry->type == al_entry->type	    &&
2103 				next_al_entry->name_length == al_name_len   &&
2104 				ntfs_names_are_equal((ntfschar*)((char*)
2105 					next_al_entry +
2106 					next_al_entry->name_offset),
2107 					next_al_entry->name_length,
2108 					al_name, al_name_len, CASE_SENSITIVE,
2109 					vol->upcase, vol->upcase_len))
2110 			continue;
2111 is_enumeration:
2112 		if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
2113 			if (MSEQNO_LE(al_entry->mft_reference) !=
2114 					le16_to_cpu(
2115 					ni->mrec->sequence_number)) {
2116 				ntfs_log_error("Found stale mft reference in "
2117 						"attribute list!\n");
2118 				break;
2119 			}
2120 		} else { /* Mft references do not match. */
2121 			/* Do we want the base record back? */
2122 			if (MREF_LE(al_entry->mft_reference) ==
2123 					base_ni->mft_no) {
2124 				ni = ctx->ntfs_ino = base_ni;
2125 				ctx->mrec = ctx->base_mrec;
2126 			} else {
2127 				/* We want an extent record. */
2128 				ni = ntfs_extent_inode_open(base_ni,
2129 						al_entry->mft_reference);
2130 				if (!ni)
2131 					break;
2132 				ctx->ntfs_ino = ni;
2133 				ctx->mrec = ni->mrec;
2134 			}
2135 		}
2136 		a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec +
2137 				le16_to_cpu(ctx->mrec->attrs_offset));
2138 		/*
2139 		 * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the
2140 		 * mft record containing the attribute represented by the
2141 		 * current al_entry.
2142 		 *
2143 		 * We could call into ntfs_attr_find() to find the right
2144 		 * attribute in this mft record but this would be less
2145 		 * efficient and not quite accurate as ntfs_attr_find() ignores
2146 		 * the attribute instance numbers for example which become
2147 		 * important when one plays with attribute lists. Also, because
2148 		 * a proper match has been found in the attribute list entry
2149 		 * above, the comparison can now be optimized. So it is worth
2150 		 * re-implementing a simplified ntfs_attr_find() here.
2151 		 *
2152 		 * Use a manual loop so we can still use break and continue
2153 		 * with the same meanings as above.
2154 		 */
2155 do_next_attr_loop:
2156 		if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec +
2157 				le32_to_cpu(ctx->mrec->bytes_allocated))
2158 			break;
2159 		if (a->type == AT_END)
2160 			continue;
2161 		if (!a->length)
2162 			break;
2163 		if (al_entry->instance != a->instance)
2164 			goto do_next_attr;
2165 		/*
2166 		 * If the type and/or the name are/is mismatched between the
2167 		 * attribute list entry and the attribute record, there is
2168 		 * corruption so we break and return error EIO.
2169 		 */
2170 		if (al_entry->type != a->type)
2171 			break;
2172 		if (!ntfs_names_are_equal((ntfschar*)((char*)a +
2173 				le16_to_cpu(a->name_offset)),
2174 				a->name_length, al_name,
2175 				al_name_len, CASE_SENSITIVE,
2176 				vol->upcase, vol->upcase_len))
2177 			break;
2178 		ctx->attr = a;
2179 		/*
2180 		 * If no @val specified or @val specified and it matches, we
2181 		 * have found it! Also, if !@type, it is an enumeration, so we
2182 		 * want the current attribute.
2183 		 */
2184 		if ((type == AT_UNUSED) || !val || (!a->non_resident &&
2185 				le32_to_cpu(a->value_length) == val_len &&
2186 				!memcmp((char*)a + le16_to_cpu(a->value_offset),
2187 				val, val_len))) {
2188 			return 0;
2189 		}
2190 do_next_attr:
2191 		/* Proceed to the next attribute in the current mft record. */
2192 		a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length));
2193 		goto do_next_attr_loop;
2194 	}
2195 	if (ni != base_ni) {
2196 		ctx->ntfs_ino = base_ni;
2197 		ctx->mrec = ctx->base_mrec;
2198 		ctx->attr = ctx->base_attr;
2199 	}
2200 	errno = EIO;
2201 	ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no);
2202 	return -1;
2203 not_found:
2204 	/*
2205 	 * If we were looking for AT_END or we were enumerating and reached the
2206 	 * end, we reset the search context @ctx and use ntfs_attr_find() to
2207 	 * seek to the end of the base mft record.
2208 	 */
2209 	if (type == AT_UNUSED || type == AT_END) {
2210 		ntfs_attr_reinit_search_ctx(ctx);
2211 		return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
2212 				ctx);
2213 	}
2214 	/*
2215 	 * The attribute wasn't found.  Before we return, we want to ensure
2216 	 * @ctx->mrec and @ctx->attr indicate the position at which the
2217 	 * attribute should be inserted in the base mft record.  Since we also
2218 	 * want to preserve @ctx->al_entry we cannot reinitialize the search
2219 	 * context using ntfs_attr_reinit_search_ctx() as this would set
2220 	 * @ctx->al_entry to NULL.  Thus we do the necessary bits manually (see
2221 	 * ntfs_attr_init_search_ctx() below).  Note, we _only_ preserve
2222 	 * @ctx->al_entry as the remaining fields (base_*) are identical to
2223 	 * their non base_ counterparts and we cannot set @ctx->base_attr
2224 	 * correctly yet as we do not know what @ctx->attr will be set to by
2225 	 * the call to ntfs_attr_find() below.
2226 	 */
2227 	ctx->mrec = ctx->base_mrec;
2228 	ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
2229 			le16_to_cpu(ctx->mrec->attrs_offset));
2230 	ctx->is_first = TRUE;
2231 	ctx->ntfs_ino = ctx->base_ntfs_ino;
2232 	ctx->base_ntfs_ino = NULL;
2233 	ctx->base_mrec = NULL;
2234 	ctx->base_attr = NULL;
2235 	/*
2236 	 * In case there are multiple matches in the base mft record, need to
2237 	 * keep enumerating until we get an attribute not found response (or
2238 	 * another error), otherwise we would keep returning the same attribute
2239 	 * over and over again and all programs using us for enumeration would
2240 	 * lock up in a tight loop.
2241 	 */
2242 	{
2243 		int ret;
2244 
2245 		do {
2246 			ret = ntfs_attr_find(type, name, name_len, ic, val,
2247 					val_len, ctx);
2248 		} while (!ret);
2249 		return ret;
2250 	}
2251 }
2252 
2253 /**
2254  * ntfs_attr_lookup - find an attribute in an ntfs inode
2255  * @type:	attribute type to find
2256  * @name:	attribute name to find (optional, i.e. NULL means don't care)
2257  * @name_len:	attribute name length (only needed if @name present)
2258  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
2259  * @lowest_vcn:	lowest vcn to find (optional, non-resident attributes only)
2260  * @val:	attribute value to find (optional, resident attributes only)
2261  * @val_len:	attribute value length
2262  * @ctx:	search context with mft record and attribute to search from
2263  *
2264  * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
2265  * be the base mft record and @ctx must have been obtained from a call to
2266  * ntfs_attr_get_search_ctx().
2267  *
2268  * This function transparently handles attribute lists and @ctx is used to
2269  * continue searches where they were left off at.
2270  *
2271  * If @type is AT_UNUSED, return the first found attribute, i.e. one can
2272  * enumerate all attributes by setting @type to AT_UNUSED and then calling
2273  * ntfs_attr_lookup() repeatedly until it returns -1 with errno set to ENOENT
2274  * to indicate that there are no more entries. During the enumeration, each
2275  * successful call of ntfs_attr_lookup() will return the next attribute, with
2276  * the current attribute being described by the search context @ctx.
2277  *
2278  * If @type is AT_END, seek to the end of the base mft record ignoring the
2279  * attribute list completely and return -1 with errno set to ENOENT.  AT_END is
2280  * not a valid attribute, its length is zero for example, thus it is safer to
2281  * return error instead of success in this case.  It should never be needed to
2282  * do this, but we implement the functionality because it allows for simpler
2283  * code inside ntfs_external_attr_find().
2284  *
2285  * If @name is AT_UNNAMED search for an unnamed attribute. If @name is present
2286  * but not AT_UNNAMED search for a named attribute matching @name. Otherwise,
2287  * match both named and unnamed attributes.
2288  *
2289  * After finishing with the attribute/mft record you need to call
2290  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
2291  * mapped extent inodes, etc).
2292  *
2293  * Return 0 if the search was successful and -1 if not, with errno set to the
2294  * error code.
2295  *
2296  * On success, @ctx->attr is the found attribute, it is in mft record
2297  * @ctx->mrec, and @ctx->al_entry is the attribute list entry for this
2298  * attribute with @ctx->base_* being the base mft record to which @ctx->attr
2299  * belongs.  If no attribute list attribute is present @ctx->al_entry and
2300  * @ctx->base_* are NULL.
2301  *
2302  * On error ENOENT, i.e. attribute not found, @ctx->attr is set to the
2303  * attribute which collates just after the attribute being searched for in the
2304  * base ntfs inode, i.e. if one wants to add the attribute to the mft record
2305  * this is the correct place to insert it into, and if there is not enough
2306  * space, the attribute should be placed in an extent mft record.
2307  * @ctx->al_entry points to the position within @ctx->base_ntfs_ino->attr_list
2308  * at which the new attribute's attribute list entry should be inserted.  The
2309  * other @ctx fields, base_ntfs_ino, base_mrec, and base_attr are set to NULL.
2310  * The only exception to this is when @type is AT_END, in which case
2311  * @ctx->al_entry is set to NULL also (see above).
2312  *
2313  *
2314  * The following error codes are defined:
2315  *	ENOENT	Attribute not found, not an error as such.
2316  *	EINVAL	Invalid arguments.
2317  *	EIO	I/O error or corrupt data structures found.
2318  *	ENOMEM	Not enough memory to allocate necessary buffers.
2319  */
2320 int ntfs_attr_lookup(const ATTR_TYPES type, const ntfschar *name,
2321 		const u32 name_len, const IGNORE_CASE_BOOL ic,
2322 		const VCN lowest_vcn, const u8 *val, const u32 val_len,
2323 		ntfs_attr_search_ctx *ctx)
2324 {
2325 	ntfs_volume *vol;
2326 	ntfs_inode *base_ni;
2327 	int ret = -1;
2328 
2329 	ntfs_log_enter("Entering for attribute type 0x%x\n", type);
2330 
2331 	if (!ctx || !ctx->mrec || !ctx->attr || (name && name != AT_UNNAMED &&
2332 			(!ctx->ntfs_ino || !(vol = ctx->ntfs_ino->vol) ||
2333 			!vol->upcase || !vol->upcase_len))) {
2334 		errno = EINVAL;
2335 		ntfs_log_perror("%s", __FUNCTION__);
2336 		goto out;
2337 	}
2338 
2339 	if (ctx->base_ntfs_ino)
2340 		base_ni = ctx->base_ntfs_ino;
2341 	else
2342 		base_ni = ctx->ntfs_ino;
2343 	if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
2344 		ret = ntfs_attr_find(type, name, name_len, ic, val, val_len, ctx);
2345 	else
2346 		ret = ntfs_external_attr_find(type, name, name_len, ic,
2347 					      lowest_vcn, val, val_len, ctx);
2348 out:
2349 	ntfs_log_leave("\n");
2350 	return ret;
2351 }
2352 
2353 /**
2354  * ntfs_attr_position - find given or next attribute type in an ntfs inode
2355  * @type:	attribute type to start lookup
2356  * @ctx:	search context with mft record and attribute to search from
2357  *
2358  * Find an attribute type in an ntfs inode or the next attribute which is not
2359  * the AT_END attribute. Please see more details at ntfs_attr_lookup.
2360  *
2361  * Return 0 if the search was successful and -1 if not, with errno set to the
2362  * error code.
2363  *
2364  * The following error codes are defined:
2365  *	EINVAL	Invalid arguments.
2366  *	EIO	I/O error or corrupt data structures found.
2367  *	ENOMEM	Not enough memory to allocate necessary buffers.
2368  * 	ENOSPC  No attribute was found after 'type', only AT_END.
2369  */
2370 int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx)
2371 {
2372 	if (ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
2373 		if (errno != ENOENT)
2374 			return -1;
2375 		if (ctx->attr->type == AT_END) {
2376 			errno = ENOSPC;
2377 			return -1;
2378 		}
2379 	}
2380 	return 0;
2381 }
2382 
2383 /**
2384  * ntfs_attr_init_search_ctx - initialize an attribute search context
2385  * @ctx:	attribute search context to initialize
2386  * @ni:		ntfs inode with which to initialize the search context
2387  * @mrec:	mft record with which to initialize the search context
2388  *
2389  * Initialize the attribute search context @ctx with @ni and @mrec.
2390  */
2391 static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx,
2392 		ntfs_inode *ni, MFT_RECORD *mrec)
2393 {
2394 	if (!mrec)
2395 		mrec = ni->mrec;
2396 	ctx->mrec = mrec;
2397 	/* Sanity checks are performed elsewhere. */
2398 	ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset));
2399 	ctx->is_first = TRUE;
2400 	ctx->ntfs_ino = ni;
2401 	ctx->al_entry = NULL;
2402 	ctx->base_ntfs_ino = NULL;
2403 	ctx->base_mrec = NULL;
2404 	ctx->base_attr = NULL;
2405 }
2406 
2407 /**
2408  * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
2409  * @ctx:	attribute search context to reinitialize
2410  *
2411  * Reinitialize the attribute search context @ctx.
2412  *
2413  * This is used when a search for a new attribute is being started to reset
2414  * the search context to the beginning.
2415  */
2416 void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx)
2417 {
2418 	if (!ctx->base_ntfs_ino) {
2419 		/* No attribute list. */
2420 		ctx->is_first = TRUE;
2421 		/* Sanity checks are performed elsewhere. */
2422 		ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
2423 				le16_to_cpu(ctx->mrec->attrs_offset));
2424 		/*
2425 		 * This needs resetting due to ntfs_external_attr_find() which
2426 		 * can leave it set despite having zeroed ctx->base_ntfs_ino.
2427 		 */
2428 		ctx->al_entry = NULL;
2429 		return;
2430 	} /* Attribute list. */
2431 	ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
2432 	return;
2433 }
2434 
2435 /**
2436  * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
2437  * @ni:		ntfs inode with which to initialize the search context
2438  * @mrec:	mft record with which to initialize the search context
2439  *
2440  * Allocate a new attribute search context, initialize it with @ni and @mrec,
2441  * and return it. Return NULL on error with errno set.
2442  *
2443  * @mrec can be NULL, in which case the mft record is taken from @ni.
2444  *
2445  * Note: For low level utilities which know what they are doing we allow @ni to
2446  * be NULL and @mrec to be set.  Do NOT do this unless you understand the
2447  * implications!!!  For example it is no longer safe to call ntfs_attr_lookup().
2448  */
2449 ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)
2450 {
2451 	ntfs_attr_search_ctx *ctx;
2452 
2453 	if (!ni && !mrec) {
2454 		errno = EINVAL;
2455 		ntfs_log_perror("NULL arguments");
2456 		return NULL;
2457 	}
2458 	ctx = ntfs_malloc(sizeof(ntfs_attr_search_ctx));
2459 	if (ctx)
2460 		ntfs_attr_init_search_ctx(ctx, ni, mrec);
2461 	return ctx;
2462 }
2463 
2464 /**
2465  * ntfs_attr_put_search_ctx - release an attribute search context
2466  * @ctx:	attribute search context to free
2467  *
2468  * Release the attribute search context @ctx.
2469  */
2470 void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx)
2471 {
2472 	// NOTE: save errno if it could change and function stays void!
2473 	free(ctx);
2474 }
2475 
2476 /**
2477  * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
2478  * @vol:	ntfs volume to which the attribute belongs
2479  * @type:	attribute type which to find
2480  *
2481  * Search for the attribute definition record corresponding to the attribute
2482  * @type in the $AttrDef system file.
2483  *
2484  * Return the attribute type definition record if found and NULL if not found
2485  * or an error occurred. On error the error code is stored in errno. The
2486  * following error codes are defined:
2487  *	ENOENT	- The attribute @type is not specified in $AttrDef.
2488  *	EINVAL	- Invalid parameters (e.g. @vol is not valid).
2489  */
2490 ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol,
2491 		const ATTR_TYPES type)
2492 {
2493 	ATTR_DEF *ad;
2494 
2495 	if (!vol || !vol->attrdef || !type) {
2496 		errno = EINVAL;
2497 		ntfs_log_perror("%s: type=%d", __FUNCTION__, type);
2498 		return NULL;
2499 	}
2500 	for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef <
2501 			vol->attrdef_len && ad->type; ++ad) {
2502 		/* We haven't found it yet, carry on searching. */
2503 		if (le32_to_cpu(ad->type) < le32_to_cpu(type))
2504 			continue;
2505 		/* We found the attribute; return it. */
2506 		if (ad->type == type)
2507 			return ad;
2508 		/* We have gone too far already. No point in continuing. */
2509 		break;
2510 	}
2511 	errno = ENOENT;
2512 	ntfs_log_perror("%s: type=%d", __FUNCTION__, type);
2513 	return NULL;
2514 }
2515 
2516 /**
2517  * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
2518  * @vol:	ntfs volume to which the attribute belongs
2519  * @type:	attribute type which to check
2520  * @size:	size which to check
2521  *
2522  * Check whether the @size in bytes is valid for an attribute of @type on the
2523  * ntfs volume @vol. This information is obtained from $AttrDef system file.
2524  *
2525  * Return 0 if valid and -1 if not valid or an error occurred. On error the
2526  * error code is stored in errno. The following error codes are defined:
2527  *	ERANGE	- @size is not valid for the attribute @type.
2528  *	ENOENT	- The attribute @type is not specified in $AttrDef.
2529  *	EINVAL	- Invalid parameters (e.g. @size is < 0 or @vol is not valid).
2530  */
2531 int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type,
2532 		const s64 size)
2533 {
2534 	ATTR_DEF *ad;
2535 	s64 min_size, max_size;
2536 
2537 	if (size < 0) {
2538 		errno = EINVAL;
2539 		ntfs_log_perror("%s: size=%lld", __FUNCTION__,
2540 				(long long)size);
2541 		return -1;
2542 	}
2543 
2544 	/*
2545 	 * $ATTRIBUTE_LIST shouldn't be greater than 0x40000, otherwise
2546 	 * Windows would crash. This is not listed in the AttrDef.
2547 	 */
2548 	if (type == AT_ATTRIBUTE_LIST && size > 0x40000) {
2549 		errno = ERANGE;
2550 		ntfs_log_perror("Too large attrlist (%lld)", (long long)size);
2551 		return -1;
2552 	}
2553 
2554 	ad = ntfs_attr_find_in_attrdef(vol, type);
2555 	if (!ad)
2556 		return -1;
2557 
2558 	min_size = sle64_to_cpu(ad->min_size);
2559 	max_size = sle64_to_cpu(ad->max_size);
2560 
2561 	if ((min_size && (size < min_size)) ||
2562 	    ((max_size > 0) && (size > max_size))) {
2563 		errno = ERANGE;
2564 		ntfs_log_perror("Attr type %d size check failed (min,size,max="
2565 			"%lld,%lld,%lld)", type, (long long)min_size,
2566 			(long long)size, (long long)max_size);
2567 		return -1;
2568 	}
2569 	return 0;
2570 }
2571 
2572 /**
2573  * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
2574  * @vol:	ntfs volume to which the attribute belongs
2575  * @type:	attribute type which to check
2576  *
2577  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
2578  * be non-resident. This information is obtained from $AttrDef system file.
2579  *
2580  * Return 0 if the attribute is allowed to be non-resident and -1 if not or an
2581  * error occurred. On error the error code is stored in errno. The following
2582  * error codes are defined:
2583  *	EPERM	- The attribute is not allowed to be non-resident.
2584  *	ENOENT	- The attribute @type is not specified in $AttrDef.
2585  *	EINVAL	- Invalid parameters (e.g. @vol is not valid).
2586  */
2587 int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type)
2588 {
2589 	ATTR_DEF *ad;
2590 
2591 	/* Find the attribute definition record in $AttrDef. */
2592 	ad = ntfs_attr_find_in_attrdef(vol, type);
2593 	if (!ad)
2594 		return -1;
2595 	/* Check the flags and return the result. */
2596 	if (ad->flags & ATTR_DEF_RESIDENT) {
2597 		errno = EPERM;
2598 		ntfs_log_trace("Attribute can't be non-resident\n");
2599 		return -1;
2600 	}
2601 	return 0;
2602 }
2603 
2604 /**
2605  * ntfs_attr_can_be_resident - check if an attribute can be resident
2606  * @vol:	ntfs volume to which the attribute belongs
2607  * @type:	attribute type which to check
2608  *
2609  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
2610  * be resident. This information is derived from our ntfs knowledge and may
2611  * not be completely accurate, especially when user defined attributes are
2612  * present. Basically we allow everything to be resident except for index
2613  * allocation and extended attribute attributes.
2614  *
2615  * Return 0 if the attribute is allowed to be resident and -1 if not or an
2616  * error occurred. On error the error code is stored in errno. The following
2617  * error codes are defined:
2618  *	EPERM	- The attribute is not allowed to be resident.
2619  *	EINVAL	- Invalid parameters (e.g. @vol is not valid).
2620  *
2621  * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
2622  *	    otherwise windows will not boot (blue screen of death)!  We cannot
2623  *	    check for this here as we don't know which inode's $Bitmap is being
2624  *	    asked about so the caller needs to special case this.
2625  */
2626 int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type)
2627 {
2628 	if (!vol || !vol->attrdef || !type) {
2629 		errno = EINVAL;
2630 		return -1;
2631 	}
2632 	if (type != AT_INDEX_ALLOCATION)
2633 		return 0;
2634 
2635 	ntfs_log_trace("Attribute can't be resident\n");
2636 	errno = EPERM;
2637 	return -1;
2638 }
2639 
2640 /**
2641  * ntfs_make_room_for_attr - make room for an attribute inside an mft record
2642  * @m:		mft record
2643  * @pos:	position at which to make space
2644  * @size:	byte size to make available at this position
2645  *
2646  * @pos points to the attribute in front of which we want to make space.
2647  *
2648  * Return 0 on success or -1 on error. On error the error code is stored in
2649  * errno. Possible error codes are:
2650  *	ENOSPC	- There is not enough space available to complete operation. The
2651  *		  caller has to make space before calling this.
2652  *	EINVAL	- Input parameters were faulty.
2653  */
2654 int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size)
2655 {
2656 	u32 biu;
2657 
2658 	ntfs_log_trace("Entering for pos 0x%d, size %u.\n",
2659 		(int)(pos - (u8*)m), (unsigned) size);
2660 
2661 	/* Make size 8-byte alignment. */
2662 	size = (size + 7) & ~7;
2663 
2664 	/* Rigorous consistency checks. */
2665 	if (!m || !pos || pos < (u8*)m) {
2666 		errno = EINVAL;
2667 		ntfs_log_perror("%s: pos=%p  m=%p", __FUNCTION__, pos, m);
2668 		return -1;
2669 	}
2670 	/* The -8 is for the attribute terminator. */
2671 	if (pos - (u8*)m > (int)le32_to_cpu(m->bytes_in_use) - 8) {
2672 		errno = EINVAL;
2673 		return -1;
2674 	}
2675 	/* Nothing to do. */
2676 	if (!size)
2677 		return 0;
2678 
2679 	biu = le32_to_cpu(m->bytes_in_use);
2680 	/* Do we have enough space? */
2681 	if (biu + size > le32_to_cpu(m->bytes_allocated) ||
2682 	    pos + size > (u8*)m + le32_to_cpu(m->bytes_allocated)) {
2683 		errno = ENOSPC;
2684 		ntfs_log_trace("No enough space in the MFT record\n");
2685 		return -1;
2686 	}
2687 	/* Move everything after pos to pos + size. */
2688 	memmove(pos + size, pos, biu - (pos - (u8*)m));
2689 	/* Update mft record. */
2690 	m->bytes_in_use = cpu_to_le32(biu + size);
2691 	return 0;
2692 }
2693 
2694 /**
2695  * ntfs_resident_attr_record_add - add resident attribute to inode
2696  * @ni:		opened ntfs inode to which MFT record add attribute
2697  * @type:	type of the new attribute
2698  * @name:	name of the new attribute
2699  * @name_len:	name length of the new attribute
2700  * @val:	value of the new attribute
2701  * @size:	size of new attribute (length of @val, if @val != NULL)
2702  * @flags:	flags of the new attribute
2703  *
2704  * Return offset to attribute from the beginning of the mft record on success
2705  * and -1 on error. On error the error code is stored in errno.
2706  * Possible error codes are:
2707  *	EINVAL	- Invalid arguments passed to function.
2708  *	EEXIST	- Attribute of such type and with same name already exists.
2709  *	EIO	- I/O error occurred or damaged filesystem.
2710  */
2711 int ntfs_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type,
2712 			ntfschar *name, u8 name_len, u8 *val, u32 size,
2713 			ATTR_FLAGS flags)
2714 {
2715 	ntfs_attr_search_ctx *ctx;
2716 	u32 length;
2717 	ATTR_RECORD *a;
2718 	MFT_RECORD *m;
2719 	int err, offset;
2720 	ntfs_inode *base_ni;
2721 
2722 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n",
2723 		(long long) ni->mft_no, (unsigned) type, (unsigned) flags);
2724 
2725 	if (!ni || (!name && name_len)) {
2726 		errno = EINVAL;
2727 		return -1;
2728 	}
2729 
2730 	if (ntfs_attr_can_be_resident(ni->vol, type)) {
2731 		if (errno == EPERM)
2732 			ntfs_log_trace("Attribute can't be resident.\n");
2733 		else
2734 			ntfs_log_trace("ntfs_attr_can_be_resident failed.\n");
2735 		return -1;
2736 	}
2737 
2738 	/* Locate place where record should be. */
2739 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2740 	if (!ctx)
2741 		return -1;
2742 	/*
2743 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2744 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2745 	 * file record.
2746 	 */
2747 	if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size,
2748 			ctx)) {
2749 		err = EEXIST;
2750 		ntfs_log_trace("Attribute already present.\n");
2751 		goto put_err_out;
2752 	}
2753 	if (errno != ENOENT) {
2754 		err = EIO;
2755 		goto put_err_out;
2756 	}
2757 	a = ctx->attr;
2758 	m = ctx->mrec;
2759 
2760 	/* Make room for attribute. */
2761 	length = offsetof(ATTR_RECORD, resident_end) +
2762 				((name_len * sizeof(ntfschar) + 7) & ~7) +
2763 				((size + 7) & ~7);
2764 	if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) {
2765 		err = errno;
2766 		ntfs_log_trace("Failed to make room for attribute.\n");
2767 		goto put_err_out;
2768 	}
2769 
2770 	/* Setup record fields. */
2771 	offset = ((u8*)a - (u8*)m);
2772 	a->type = type;
2773 	a->length = cpu_to_le32(length);
2774 	a->non_resident = 0;
2775 	a->name_length = name_len;
2776 	a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, resident_end));
2777 	a->flags = flags;
2778 	a->instance = m->next_attr_instance;
2779 	a->value_length = cpu_to_le32(size);
2780 	a->value_offset = cpu_to_le16(length - ((size + 7) & ~7));
2781 	if (val)
2782 		memcpy((u8*)a + le16_to_cpu(a->value_offset), val, size);
2783 	else
2784 		memset((u8*)a + le16_to_cpu(a->value_offset), 0, size);
2785 	if (type == AT_FILE_NAME)
2786 		a->resident_flags = RESIDENT_ATTR_IS_INDEXED;
2787 	else
2788 		a->resident_flags = 0;
2789 	if (name_len)
2790 		memcpy((u8*)a + le16_to_cpu(a->name_offset),
2791 			name, sizeof(ntfschar) * name_len);
2792 	m->next_attr_instance =
2793 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2794 	if (ni->nr_extents == -1)
2795 		base_ni = ni->base_ni;
2796 	else
2797 		base_ni = ni;
2798 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2799 		if (ntfs_attrlist_entry_add(ni, a)) {
2800 			err = errno;
2801 			ntfs_attr_record_resize(m, a, 0);
2802 			ntfs_log_trace("Failed add attribute entry to "
2803 					"ATTRIBUTE_LIST.\n");
2804 			goto put_err_out;
2805 		}
2806 	}
2807 	if (type == AT_DATA && name == AT_UNNAMED) {
2808 		ni->data_size = size;
2809 		ni->allocated_size = (size + 7) & ~7;
2810 	}
2811 	ntfs_inode_mark_dirty(ni);
2812 	ntfs_attr_put_search_ctx(ctx);
2813 	return offset;
2814 put_err_out:
2815 	ntfs_attr_put_search_ctx(ctx);
2816 	errno = err;
2817 	return -1;
2818 }
2819 
2820 /**
2821  * ntfs_non_resident_attr_record_add - add extent of non-resident attribute
2822  * @ni:			opened ntfs inode to which MFT record add attribute
2823  * @type:		type of the new attribute extent
2824  * @name:		name of the new attribute extent
2825  * @name_len:		name length of the new attribute extent
2826  * @lowest_vcn:		lowest vcn of the new attribute extent
2827  * @dataruns_size:	dataruns size of the new attribute extent
2828  * @flags:		flags of the new attribute extent
2829  *
2830  * Return offset to attribute from the beginning of the mft record on success
2831  * and -1 on error. On error the error code is stored in errno.
2832  * Possible error codes are:
2833  *	EINVAL	- Invalid arguments passed to function.
2834  *	EEXIST	- Attribute of such type, with same lowest vcn and with same
2835  *		  name already exists.
2836  *	EIO	- I/O error occurred or damaged filesystem.
2837  */
2838 int ntfs_non_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type,
2839 		ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size,
2840 		ATTR_FLAGS flags)
2841 {
2842 	ntfs_attr_search_ctx *ctx;
2843 	u32 length;
2844 	ATTR_RECORD *a;
2845 	MFT_RECORD *m;
2846 	ntfs_inode *base_ni;
2847 	int err, offset;
2848 
2849 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, "
2850 			"dataruns_size %d, flags 0x%x.\n",
2851 			(long long) ni->mft_no, (unsigned) type,
2852 			(long long) lowest_vcn, dataruns_size, (unsigned) flags);
2853 
2854 	if (!ni || dataruns_size <= 0 || (!name && name_len)) {
2855 		errno = EINVAL;
2856 		return -1;
2857 	}
2858 
2859 	if (ntfs_attr_can_be_non_resident(ni->vol, type)) {
2860 		if (errno == EPERM)
2861 			ntfs_log_perror("Attribute can't be non resident");
2862 		else
2863 			ntfs_log_perror("ntfs_attr_can_be_non_resident failed");
2864 		return -1;
2865 	}
2866 
2867 	/* Locate place where record should be. */
2868 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2869 	if (!ctx)
2870 		return -1;
2871 	/*
2872 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2873 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2874 	 * file record.
2875 	 */
2876 	if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0,
2877 			ctx)) {
2878 		err = EEXIST;
2879 		ntfs_log_perror("Attribute 0x%x already present", type);
2880 		goto put_err_out;
2881 	}
2882 	if (errno != ENOENT) {
2883 		ntfs_log_perror("ntfs_attr_find failed");
2884 		err = EIO;
2885 		goto put_err_out;
2886 	}
2887 	a = ctx->attr;
2888 	m = ctx->mrec;
2889 
2890 	/* Make room for attribute. */
2891 	dataruns_size = (dataruns_size + 7) & ~7;
2892 	length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) *
2893 			name_len + 7) & ~7) + dataruns_size +
2894 			((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2895 			sizeof(a->compressed_size) : 0);
2896 	if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) {
2897 		err = errno;
2898 		ntfs_log_perror("Failed to make room for attribute");
2899 		goto put_err_out;
2900 	}
2901 
2902 	/* Setup record fields. */
2903 	a->type = type;
2904 	a->length = cpu_to_le32(length);
2905 	a->non_resident = 1;
2906 	a->name_length = name_len;
2907 	a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) +
2908 			((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2909 			sizeof(a->compressed_size) : 0));
2910 	a->flags = flags;
2911 	a->instance = m->next_attr_instance;
2912 	a->lowest_vcn = cpu_to_sle64(lowest_vcn);
2913 	a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size);
2914 	a->compression_unit = (flags & ATTR_IS_COMPRESSED) ? 4 : 0;
2915 	/* If @lowest_vcn == 0, than setup empty attribute. */
2916 	if (!lowest_vcn) {
2917 		a->highest_vcn = cpu_to_sle64(-1);
2918 		a->allocated_size = 0;
2919 		a->data_size = 0;
2920 		a->initialized_size = 0;
2921 		/* Set empty mapping pairs. */
2922 		*((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0;
2923 	}
2924 	if (name_len)
2925 		memcpy((u8*)a + le16_to_cpu(a->name_offset),
2926 			name, sizeof(ntfschar) * name_len);
2927 	m->next_attr_instance =
2928 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2929 	if (ni->nr_extents == -1)
2930 		base_ni = ni->base_ni;
2931 	else
2932 		base_ni = ni;
2933 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2934 		if (ntfs_attrlist_entry_add(ni, a)) {
2935 			err = errno;
2936 			ntfs_log_perror("Failed add attr entry to attrlist");
2937 			ntfs_attr_record_resize(m, a, 0);
2938 			goto put_err_out;
2939 		}
2940 	}
2941 	ntfs_inode_mark_dirty(ni);
2942 	/*
2943 	 * Locate offset from start of the MFT record where new attribute is
2944 	 * placed. We need relookup it, because record maybe moved during
2945 	 * update of attribute list.
2946 	 */
2947 	ntfs_attr_reinit_search_ctx(ctx);
2948 	if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
2949 					lowest_vcn, NULL, 0, ctx)) {
2950 		ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__);
2951 		ntfs_attr_put_search_ctx(ctx);
2952 		return -1;
2953 
2954 	}
2955 	offset = (u8*)ctx->attr - (u8*)ctx->mrec;
2956 	ntfs_attr_put_search_ctx(ctx);
2957 	return offset;
2958 put_err_out:
2959 	ntfs_attr_put_search_ctx(ctx);
2960 	errno = err;
2961 	return -1;
2962 }
2963 
2964 /**
2965  * ntfs_attr_record_rm - remove attribute extent
2966  * @ctx:	search context describing the attribute which should be removed
2967  *
2968  * If this function succeed, user should reinit search context if he/she wants
2969  * use it anymore.
2970  *
2971  * Return 0 on success and -1 on error. On error the error code is stored in
2972  * errno. Possible error codes are:
2973  *	EINVAL	- Invalid arguments passed to function.
2974  *	EIO	- I/O error occurred or damaged filesystem.
2975  */
2976 int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx)
2977 {
2978 	ntfs_inode *base_ni, *ni;
2979 	ATTR_TYPES type;
2980 	int err;
2981 
2982 	if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) {
2983 		errno = EINVAL;
2984 		return -1;
2985 	}
2986 
2987 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n",
2988 			(long long) ctx->ntfs_ino->mft_no,
2989 			(unsigned) le32_to_cpu(ctx->attr->type));
2990 	type = ctx->attr->type;
2991 	ni = ctx->ntfs_ino;
2992 	if (ctx->base_ntfs_ino)
2993 		base_ni = ctx->base_ntfs_ino;
2994 	else
2995 		base_ni = ctx->ntfs_ino;
2996 
2997 	/* Remove attribute itself. */
2998 	if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) {
2999 		ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT "
3000 				"record.\n");
3001 		if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST)
3002 			if (ntfs_attrlist_entry_add(ni, ctx->attr))
3003 				ntfs_log_trace("Rollback failed. Leaving inconstant "
3004 						"metadata.\n");
3005 		err = EIO;
3006 		return -1;
3007 	}
3008 	ntfs_inode_mark_dirty(ni);
3009 
3010 	/*
3011 	 * Remove record from $ATTRIBUTE_LIST if present and we don't want
3012 	 * delete $ATTRIBUTE_LIST itself.
3013 	 */
3014 	if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) {
3015 		if (ntfs_attrlist_entry_rm(ctx)) {
3016 			ntfs_log_trace("Couldn't delete record from "
3017 					"$ATTRIBUTE_LIST.\n");
3018 			return -1;
3019 		}
3020 	}
3021 
3022 	/* Post $ATTRIBUTE_LIST delete setup. */
3023 	if (type == AT_ATTRIBUTE_LIST) {
3024 		if (NInoAttrList(base_ni) && base_ni->attr_list)
3025 			free(base_ni->attr_list);
3026 		base_ni->attr_list = NULL;
3027 		NInoClearAttrList(base_ni);
3028 		NInoAttrListClearDirty(base_ni);
3029 	}
3030 
3031 	/* Free MFT record, if it doesn't contain attributes. */
3032 	if (le32_to_cpu(ctx->mrec->bytes_in_use) -
3033 			le16_to_cpu(ctx->mrec->attrs_offset) == 8) {
3034 		if (ntfs_mft_record_free(ni->vol, ni)) {
3035 			// FIXME: We need rollback here.
3036 			ntfs_log_trace("Couldn't free MFT record.\n");
3037 			errno = EIO;
3038 			return -1;
3039 		}
3040 		/* Remove done if we freed base inode. */
3041 		if (ni == base_ni)
3042 			return 0;
3043 	}
3044 
3045 	if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni))
3046 		return 0;
3047 
3048 	/* Remove attribute list if we don't need it any more. */
3049 	if (!ntfs_attrlist_need(base_ni)) {
3050 		ntfs_attr_reinit_search_ctx(ctx);
3051 		if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE,
3052 				0, NULL, 0, ctx)) {
3053 			/*
3054 			 * FIXME: Should we succeed here? Definitely something
3055 			 * goes wrong because NInoAttrList(base_ni) returned
3056 			 * that we have got attribute list.
3057 			 */
3058 			ntfs_log_trace("Couldn't find attribute list. Succeed "
3059 					"anyway.\n");
3060 			return 0;
3061 		}
3062 		/* Deallocate clusters. */
3063 		if (ctx->attr->non_resident) {
3064 			runlist *al_rl;
3065 
3066 			al_rl = ntfs_mapping_pairs_decompress(base_ni->vol,
3067 					ctx->attr, NULL);
3068 			if (!al_rl) {
3069 				ntfs_log_trace("Couldn't decompress attribute list "
3070 						"runlist. Succeed anyway.\n");
3071 				return 0;
3072 			}
3073 			if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) {
3074 				ntfs_log_trace("Leaking clusters! Run chkdsk. "
3075 						"Couldn't free clusters from "
3076 						"attribute list runlist.\n");
3077 			}
3078 			free(al_rl);
3079 		}
3080 		/* Remove attribute record itself. */
3081 		if (ntfs_attr_record_rm(ctx)) {
3082 			/*
3083 			 * FIXME: Should we succeed here? BTW, chkdsk doesn't
3084 			 * complain if it find MFT record with attribute list,
3085 			 * but without extents.
3086 			 */
3087 			ntfs_log_trace("Couldn't remove attribute list. Succeed "
3088 					"anyway.\n");
3089 			return 0;
3090 		}
3091 	}
3092 	return 0;
3093 }
3094 
3095 /**
3096  * ntfs_attr_add - add attribute to inode
3097  * @ni:		opened ntfs inode to which add attribute
3098  * @type:	type of the new attribute
3099  * @name:	name in unicode of the new attribute
3100  * @name_len:	name length in unicode characters of the new attribute
3101  * @val:	value of new attribute
3102  * @size:	size of the new attribute / length of @val (if specified)
3103  *
3104  * @val should always be specified for always resident attributes (eg. FILE_NAME
3105  * attribute), for attributes that can become non-resident @val can be NULL
3106  * (eg. DATA attribute). @size can be specified even if @val is NULL, in this
3107  * case data size will be equal to @size and initialized size will be equal
3108  * to 0.
3109  *
3110  * If inode haven't got enough space to add attribute, add attribute to one of
3111  * it extents, if no extents present or no one of them have enough space, than
3112  * allocate new extent and add attribute to it.
3113  *
3114  * If on one of this steps attribute list is needed but not present, than it is
3115  * added transparently to caller. So, this function should not be called with
3116  * @type == AT_ATTRIBUTE_LIST, if you really need to add attribute list call
3117  * ntfs_inode_add_attrlist instead.
3118  *
3119  * On success return 0. On error return -1 with errno set to the error code.
3120  */
3121 int ntfs_attr_add(ntfs_inode *ni, ATTR_TYPES type,
3122 		ntfschar *name, u8 name_len, u8 *val, s64 size)
3123 {
3124 	u32 attr_rec_size;
3125 	int err, i, offset;
3126 	BOOL is_resident;
3127 	BOOL can_be_non_resident = FALSE;
3128 	ntfs_inode *attr_ni;
3129 	ntfs_attr *na;
3130 
3131 	if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST) {
3132 		errno = EINVAL;
3133 		ntfs_log_perror("%s: ni=%p  size=%lld", __FUNCTION__, ni,
3134 				(long long)size);
3135 		return -1;
3136 	}
3137 
3138 	ntfs_log_trace("Entering for inode %lld, attr %x, size %lld.\n",
3139 			(long long)ni->mft_no, type, (long long)size);
3140 
3141 	if (ni->nr_extents == -1)
3142 		ni = ni->base_ni;
3143 
3144 	/* Check the attribute type and the size. */
3145 	if (ntfs_attr_size_bounds_check(ni->vol, type, size)) {
3146 		if (errno == ENOENT)
3147 			errno = EIO;
3148 		return -1;
3149 	}
3150 
3151 	/* Sanity checks for always resident attributes. */
3152 	if (ntfs_attr_can_be_non_resident(ni->vol, type)) {
3153 		if (errno != EPERM) {
3154 			err = errno;
3155 			ntfs_log_perror("ntfs_attr_can_be_non_resident failed");
3156 			goto err_out;
3157 		}
3158 		/* @val is mandatory. */
3159 		if (!val) {
3160 			errno = EINVAL;
3161 			ntfs_log_perror("val is mandatory for always resident "
3162 					"attributes");
3163 			return -1;
3164 		}
3165 		if (size > ni->vol->mft_record_size) {
3166 			errno = ERANGE;
3167 			ntfs_log_perror("Attribute is too big");
3168 			return -1;
3169 		}
3170 	} else
3171 		can_be_non_resident = TRUE;
3172 
3173 	/*
3174 	 * Determine resident or not will be new attribute. We add 8 to size in
3175 	 * non resident case for mapping pairs.
3176 	 */
3177 	if (!ntfs_attr_can_be_resident(ni->vol, type)) {
3178 		is_resident = TRUE;
3179 	} else {
3180 		if (errno != EPERM) {
3181 			err = errno;
3182 			ntfs_log_perror("ntfs_attr_can_be_resident failed");
3183 			goto err_out;
3184 		}
3185 		is_resident = FALSE;
3186 	}
3187 	/* Calculate attribute record size. */
3188 	if (is_resident)
3189 		attr_rec_size = offsetof(ATTR_RECORD, resident_end) +
3190 				((name_len * sizeof(ntfschar) + 7) & ~7) +
3191 				((size + 7) & ~7);
3192 	else
3193 		attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) +
3194 				((name_len * sizeof(ntfschar) + 7) & ~7) + 8;
3195 
3196 	/*
3197 	 * If we have enough free space for the new attribute in the base MFT
3198 	 * record, then add attribute to it.
3199 	 */
3200 	if (le32_to_cpu(ni->mrec->bytes_allocated) -
3201 			le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) {
3202 		attr_ni = ni;
3203 		goto add_attr_record;
3204 	}
3205 
3206 	/* Try to add to extent inodes. */
3207 	if (ntfs_inode_attach_all_extents(ni)) {
3208 		err = errno;
3209 		ntfs_log_perror("Failed to attach all extents to inode");
3210 		goto err_out;
3211 	}
3212 	for (i = 0; i < ni->nr_extents; i++) {
3213 		attr_ni = ni->extent_nis[i];
3214 		if (le32_to_cpu(attr_ni->mrec->bytes_allocated) -
3215 				le32_to_cpu(attr_ni->mrec->bytes_in_use) >=
3216 				attr_rec_size)
3217 			goto add_attr_record;
3218 	}
3219 
3220 	/* There is no extent that contain enough space for new attribute. */
3221 	if (!NInoAttrList(ni)) {
3222 		/* Add attribute list not present, add it and retry. */
3223 		if (ntfs_inode_add_attrlist(ni)) {
3224 			err = errno;
3225 			ntfs_log_perror("Failed to add attribute list");
3226 			goto err_out;
3227 		}
3228 		return ntfs_attr_add(ni, type, name, name_len, val, size);
3229 	}
3230 	/* Allocate new extent. */
3231 	attr_ni = ntfs_mft_record_alloc(ni->vol, ni);
3232 	if (!attr_ni) {
3233 		err = errno;
3234 		ntfs_log_perror("Failed to allocate extent record");
3235 		goto err_out;
3236 	}
3237 
3238 add_attr_record:
3239 	if (is_resident) {
3240 		/* Add resident attribute. */
3241 		offset = ntfs_resident_attr_record_add(attr_ni, type, name,
3242 				name_len, val, size, 0);
3243 		if (offset < 0) {
3244 			if (errno == ENOSPC && can_be_non_resident)
3245 				goto add_non_resident;
3246 			err = errno;
3247 			ntfs_log_perror("Failed to add resident attribute");
3248 			goto free_err_out;
3249 		}
3250 		return 0;
3251 	}
3252 
3253 add_non_resident:
3254 	/* Add non resident attribute. */
3255 	offset = ntfs_non_resident_attr_record_add(attr_ni, type, name,
3256 				name_len, 0, 8, 0);
3257 	if (offset < 0) {
3258 		err = errno;
3259 		ntfs_log_perror("Failed to add non resident attribute");
3260 		goto free_err_out;
3261 	}
3262 
3263 	/* If @size == 0, we are done. */
3264 	if (!size)
3265 		return 0;
3266 
3267 	/* Open new attribute and resize it. */
3268 	na = ntfs_attr_open(ni, type, name, name_len);
3269 	if (!na) {
3270 		err = errno;
3271 		ntfs_log_perror("Failed to open just added attribute");
3272 		goto rm_attr_err_out;
3273 	}
3274 	/* Resize and set attribute value. */
3275 	if (ntfs_attr_truncate(na, size) ||
3276 			(val && (ntfs_attr_pwrite(na, 0, size, val) != size))) {
3277 		err = errno;
3278 		ntfs_log_perror("Failed to initialize just added attribute");
3279 		if (ntfs_attr_rm(na))
3280 			ntfs_log_perror("Failed to remove just added attribute");
3281 		ntfs_attr_close(na);
3282 		goto err_out;
3283 	}
3284 	ntfs_attr_close(na);
3285 	return 0;
3286 
3287 rm_attr_err_out:
3288 	/* Remove just added attribute. */
3289 	if (ntfs_attr_record_resize(attr_ni->mrec,
3290 			(ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0))
3291 		ntfs_log_perror("Failed to remove just added attribute #2");
3292 free_err_out:
3293 	/* Free MFT record, if it doesn't contain attributes. */
3294 	if (le32_to_cpu(attr_ni->mrec->bytes_in_use) -
3295 			le16_to_cpu(attr_ni->mrec->attrs_offset) == 8)
3296 		if (ntfs_mft_record_free(attr_ni->vol, attr_ni))
3297 			ntfs_log_perror("Failed to free MFT record");
3298 err_out:
3299 	errno = err;
3300 	return -1;
3301 }
3302 
3303 /**
3304  * ntfs_attr_rm - remove attribute from ntfs inode
3305  * @na:		opened ntfs attribute to delete
3306  *
3307  * Remove attribute and all it's extents from ntfs inode. If attribute was non
3308  * resident also free all clusters allocated by attribute.
3309  *
3310  * Return 0 on success or -1 on error with errno set to the error code.
3311  */
3312 int ntfs_attr_rm(ntfs_attr *na)
3313 {
3314 	ntfs_attr_search_ctx *ctx;
3315 	int ret = 0;
3316 
3317 	if (!na) {
3318 		ntfs_log_trace("Invalid arguments passed.\n");
3319 		errno = EINVAL;
3320 		return -1;
3321 	}
3322 
3323 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n",
3324 		(long long) na->ni->mft_no, na->type);
3325 
3326 	/* Free cluster allocation. */
3327 	if (NAttrNonResident(na)) {
3328 		if (ntfs_attr_map_whole_runlist(na))
3329 			return -1;
3330 		if (ntfs_cluster_free(na->ni->vol, na, 0, -1) < 0) {
3331 			ntfs_log_trace("Failed to free cluster allocation. Leaving "
3332 					"inconstant metadata.\n");
3333 			ret = -1;
3334 		}
3335 	}
3336 
3337 	/* Search for attribute extents and remove them all. */
3338 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
3339 	if (!ctx)
3340 		return -1;
3341 	while (!ntfs_attr_lookup(na->type, na->name, na->name_len,
3342 				CASE_SENSITIVE, 0, NULL, 0, ctx)) {
3343 		if (ntfs_attr_record_rm(ctx)) {
3344 			ntfs_log_trace("Failed to remove attribute extent. Leaving "
3345 					"inconstant metadata.\n");
3346 			ret = -1;
3347 		}
3348 		ntfs_attr_reinit_search_ctx(ctx);
3349 	}
3350 	ntfs_attr_put_search_ctx(ctx);
3351 	if (errno != ENOENT) {
3352 		ntfs_log_trace("Attribute lookup failed. Probably leaving inconstant "
3353 				"metadata.\n");
3354 		ret = -1;
3355 	}
3356 
3357 	return ret;
3358 }
3359 
3360 /**
3361  * ntfs_attr_record_resize - resize an attribute record
3362  * @m:		mft record containing attribute record
3363  * @a:		attribute record to resize
3364  * @new_size:	new size in bytes to which to resize the attribute record @a
3365  *
3366  * Resize the attribute record @a, i.e. the resident part of the attribute, in
3367  * the mft record @m to @new_size bytes.
3368  *
3369  * Return 0 on success and -1 on error with errno set to the error code.
3370  * The following error codes are defined:
3371  *	ENOSPC	- Not enough space in the mft record @m to perform the resize.
3372  * Note that on error no modifications have been performed whatsoever.
3373  *
3374  * Warning: If you make a record smaller without having copied all the data you
3375  *	    are interested in the data may be overwritten!
3376  */
3377 int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size)
3378 {
3379 	u32 old_size, alloc_size, attr_size;
3380 
3381 	old_size   = le32_to_cpu(m->bytes_in_use);
3382 	alloc_size = le32_to_cpu(m->bytes_allocated);
3383 	attr_size  = le32_to_cpu(a->length);
3384 
3385 	ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n",
3386 		       (unsigned)old_size, (unsigned)alloc_size,
3387 		       (unsigned)attr_size, (unsigned)new_size);
3388 
3389 	/* Align to 8 bytes, just in case the caller hasn't. */
3390 	new_size = (new_size + 7) & ~7;
3391 
3392 	/* If the actual attribute length has changed, move things around. */
3393 	if (new_size != attr_size) {
3394 
3395 		u32 new_muse = old_size - attr_size + new_size;
3396 
3397 		/* Not enough space in this mft record. */
3398 		if (new_muse > alloc_size) {
3399 			errno = ENOSPC;
3400 			ntfs_log_trace("Not enough space in the MFT record "
3401 				       "(%u > %u)\n", new_muse, alloc_size);
3402 			return -1;
3403 		}
3404 
3405 		if (a->type == AT_INDEX_ROOT && new_size > attr_size &&
3406 		    new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) {
3407 			errno = ENOSPC;
3408 			ntfs_log_trace("Too big INDEX_ROOT (%u > %u)\n",
3409 					new_muse, alloc_size);
3410 			return STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT;
3411 		}
3412 
3413 		/* Move attributes following @a to their new location. */
3414 		memmove((u8 *)a + new_size, (u8 *)a + attr_size,
3415 			old_size - ((u8 *)a - (u8 *)m) - attr_size);
3416 
3417 		/* Adjust @m to reflect the change in used space. */
3418 		m->bytes_in_use = cpu_to_le32(new_muse);
3419 
3420 		/* Adjust @a to reflect the new size. */
3421 		if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length))
3422 			a->length = cpu_to_le32(new_size);
3423 	}
3424 	return 0;
3425 }
3426 
3427 /**
3428  * ntfs_resident_attr_value_resize - resize the value of a resident attribute
3429  * @m:		mft record containing attribute record
3430  * @a:		attribute record whose value to resize
3431  * @new_size:	new size in bytes to which to resize the attribute value of @a
3432  *
3433  * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
3434  * If the value is made bigger, the newly "allocated" space is cleared.
3435  *
3436  * Return 0 on success and -1 on error with errno set to the error code.
3437  * The following error codes are defined:
3438  *	ENOSPC	- Not enough space in the mft record @m to perform the resize.
3439  * Note that on error no modifications have been performed whatsoever.
3440  */
3441 int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a,
3442 		const u32 new_size)
3443 {
3444 	int ret;
3445 
3446 	ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size);
3447 
3448 	/* Resize the resident part of the attribute record. */
3449 	if ((ret = ntfs_attr_record_resize(m, a, (le16_to_cpu(a->value_offset) +
3450 			new_size + 7) & ~7)) < 0)
3451 		return ret;
3452 	/*
3453 	 * If we made the attribute value bigger, clear the area between the
3454 	 * old size and @new_size.
3455 	 */
3456 	if (new_size > le32_to_cpu(a->value_length))
3457 		memset((u8*)a + le16_to_cpu(a->value_offset) +
3458 				le32_to_cpu(a->value_length), 0, new_size -
3459 				le32_to_cpu(a->value_length));
3460 	/* Finally update the length of the attribute value. */
3461 	a->value_length = cpu_to_le32(new_size);
3462 	return 0;
3463 }
3464 
3465 /**
3466  * ntfs_attr_record_move_to - move attribute record to target inode
3467  * @ctx:	attribute search context describing the attribute record
3468  * @ni:		opened ntfs inode to which move attribute record
3469  *
3470  * If this function succeed, user should reinit search context if he/she wants
3471  * use it anymore.
3472  *
3473  * Return 0 on success and -1 on error with errno set to the error code.
3474  */
3475 int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni)
3476 {
3477 	ntfs_attr_search_ctx *nctx;
3478 	ATTR_RECORD *a;
3479 	int err;
3480 
3481 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) {
3482 		ntfs_log_trace("Invalid arguments passed.\n");
3483 		errno = EINVAL;
3484 		return -1;
3485 	}
3486 
3487 	ntfs_log_trace("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no "
3488 			"0x%llx, ni->mft_no 0x%llx.\n",
3489 			(unsigned) le32_to_cpu(ctx->attr->type),
3490 			(long long) ctx->ntfs_ino->mft_no,
3491 			(long long) ni->mft_no);
3492 
3493 	if (ctx->ntfs_ino == ni)
3494 		return 0;
3495 
3496 	if (!ctx->al_entry) {
3497 		ntfs_log_trace("Inode should contain attribute list to use this "
3498 				"function.\n");
3499 		errno = EINVAL;
3500 		return -1;
3501 	}
3502 
3503 	/* Find place in MFT record where attribute will be moved. */
3504 	a = ctx->attr;
3505 	nctx = ntfs_attr_get_search_ctx(ni, NULL);
3506 	if (!nctx)
3507 		return -1;
3508 
3509 	/*
3510 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
3511 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
3512 	 * file record.
3513 	 */
3514 	if (!ntfs_attr_find(a->type, (ntfschar*)((u8*)a + le16_to_cpu(
3515 			a->name_offset)), a->name_length, CASE_SENSITIVE, NULL,
3516 			0, nctx)) {
3517 		ntfs_log_trace("Attribute of such type, with same name already "
3518 				"present in this MFT record.\n");
3519 		err = EEXIST;
3520 		goto put_err_out;
3521 	}
3522 	if (errno != ENOENT) {
3523 		err = errno;
3524 		ntfs_log_debug("Attribute lookup failed.\n");
3525 		goto put_err_out;
3526 	}
3527 
3528 	/* Make space and move attribute. */
3529 	if (ntfs_make_room_for_attr(ni->mrec, (u8*) nctx->attr,
3530 					le32_to_cpu(a->length))) {
3531 		err = errno;
3532 		ntfs_log_trace("Couldn't make space for attribute.\n");
3533 		goto put_err_out;
3534 	}
3535 	memcpy(nctx->attr, a, le32_to_cpu(a->length));
3536 	nctx->attr->instance = nctx->mrec->next_attr_instance;
3537 	nctx->mrec->next_attr_instance = cpu_to_le16(
3538 		(le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff);
3539 	ntfs_attr_record_resize(ctx->mrec, a, 0);
3540 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
3541 	ntfs_inode_mark_dirty(ni);
3542 
3543 	/* Update attribute list. */
3544 	ctx->al_entry->mft_reference =
3545 		MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number));
3546 	ctx->al_entry->instance = nctx->attr->instance;
3547 	ntfs_attrlist_mark_dirty(ni);
3548 
3549 	ntfs_attr_put_search_ctx(nctx);
3550 	return 0;
3551 put_err_out:
3552 	ntfs_attr_put_search_ctx(nctx);
3553 	errno = err;
3554 	return -1;
3555 }
3556 
3557 /**
3558  * ntfs_attr_record_move_away - move away attribute record from it's mft record
3559  * @ctx:	attribute search context describing the attribute record
3560  * @extra:	minimum amount of free space in the new holder of record
3561  *
3562  * New attribute record holder must have free @extra bytes after moving
3563  * attribute record to it.
3564  *
3565  * If this function succeed, user should reinit search context if he/she wants
3566  * use it anymore.
3567  *
3568  * Return 0 on success and -1 on error with errno set to the error code.
3569  */
3570 int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra)
3571 {
3572 	ntfs_inode *base_ni, *ni;
3573 	MFT_RECORD *m;
3574 	int i;
3575 
3576 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0) {
3577 		errno = EINVAL;
3578 		ntfs_log_perror("%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__,
3579 				ctx, ctx ? ctx->attr : NULL, extra);
3580 		return -1;
3581 	}
3582 
3583 	ntfs_log_trace("Entering for attr 0x%x, inode %llu\n",
3584 			(unsigned) le32_to_cpu(ctx->attr->type),
3585 			(unsigned long long)ctx->ntfs_ino->mft_no);
3586 
3587 	if (ctx->ntfs_ino->nr_extents == -1)
3588 		base_ni = ctx->base_ntfs_ino;
3589 	else
3590 		base_ni = ctx->ntfs_ino;
3591 
3592 	if (!NInoAttrList(base_ni)) {
3593 		errno = EINVAL;
3594 		ntfs_log_perror("Inode %llu has no attrlist",
3595 				(unsigned long long)base_ni->mft_no);
3596 		return -1;
3597 	}
3598 
3599 	if (ntfs_inode_attach_all_extents(ctx->ntfs_ino)) {
3600 		ntfs_log_perror("Couldn't attach extents, inode=%llu",
3601 				(unsigned long long)base_ni->mft_no);
3602 		return -1;
3603 	}
3604 
3605 	/* Walk through all extents and try to move attribute to them. */
3606 	for (i = 0; i < base_ni->nr_extents; i++) {
3607 		ni = base_ni->extent_nis[i];
3608 		m = ni->mrec;
3609 
3610 		if (ctx->ntfs_ino->mft_no == ni->mft_no)
3611 			continue;
3612 
3613 		if (le32_to_cpu(m->bytes_allocated) -
3614 				le32_to_cpu(m->bytes_in_use) <
3615 				le32_to_cpu(ctx->attr->length) + extra)
3616 			continue;
3617 
3618 		/*
3619 		 * ntfs_attr_record_move_to can fail if extent with other lowest
3620 		 * VCN already present in inode we trying move record to. So,
3621 		 * do not return error.
3622 		 */
3623 		if (!ntfs_attr_record_move_to(ctx, ni))
3624 			return 0;
3625 	}
3626 
3627 	/*
3628 	 * Failed to move attribute to one of the current extents, so allocate
3629 	 * new extent and move attribute to it.
3630 	 */
3631 	ni = ntfs_mft_record_alloc(base_ni->vol, base_ni);
3632 	if (!ni) {
3633 		ntfs_log_perror("Couldn't allocate MFT record");
3634 		return -1;
3635 	}
3636 	if (ntfs_attr_record_move_to(ctx, ni)) {
3637 		ntfs_log_perror("Couldn't move attribute to MFT record");
3638 		return -1;
3639 	}
3640 	return 0;
3641 }
3642 
3643 /**
3644  * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
3645  * @na:		open ntfs attribute to make non-resident
3646  * @ctx:	ntfs search context describing the attribute
3647  *
3648  * Convert a resident ntfs attribute to a non-resident one.
3649  *
3650  * Return 0 on success and -1 on error with errno set to the error code. The
3651  * following error codes are defined:
3652  *	EPERM	- The attribute is not allowed to be non-resident.
3653  *	TODO: others...
3654  *
3655  * NOTE to self: No changes in the attribute list are required to move from
3656  *		 a resident to a non-resident attribute.
3657  *
3658  * Warning: We do not set the inode dirty and we do not write out anything!
3659  *	    We expect the caller to do this as this is a fairly low level
3660  *	    function and it is likely there will be further changes made.
3661  */
3662 static int ntfs_attr_make_non_resident(ntfs_attr *na,
3663 		ntfs_attr_search_ctx *ctx)
3664 {
3665 	s64 new_allocated_size, bw;
3666 	ntfs_volume *vol = na->ni->vol;
3667 	ATTR_REC *a = ctx->attr;
3668 	runlist *rl;
3669 	int mp_size, mp_ofs, name_ofs, arec_size, err;
3670 
3671 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long
3672 			long)na->ni->mft_no, na->type);
3673 
3674 	/* Some preliminary sanity checking. */
3675 	if (NAttrNonResident(na)) {
3676 		ntfs_log_trace("Eeek!  Trying to make non-resident attribute "
3677 				"non-resident.  Aborting...\n");
3678 		errno = EINVAL;
3679 		return -1;
3680 	}
3681 
3682 	/* Check that the attribute is allowed to be non-resident. */
3683 	if (ntfs_attr_can_be_non_resident(vol, na->type))
3684 		return -1;
3685 
3686 	new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size
3687 			- 1) & ~(vol->cluster_size - 1);
3688 
3689 	if (new_allocated_size > 0) {
3690 		/* Start by allocating clusters to hold the attribute value. */
3691 		rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >>
3692 				vol->cluster_size_bits, -1, DATA_ZONE);
3693 		if (!rl)
3694 			return -1;
3695 	} else
3696 		rl = NULL;
3697 	/*
3698 	 * Setup the in-memory attribute structure to be non-resident so that
3699 	 * we can use ntfs_attr_pwrite().
3700 	 */
3701 	NAttrSetNonResident(na);
3702 	na->rl = rl;
3703 	na->allocated_size = new_allocated_size;
3704 	na->data_size = na->initialized_size = le32_to_cpu(a->value_length);
3705 	/*
3706 	 * FIXME: For now just clear all of these as we don't support them when
3707 	 * writing.
3708 	 */
3709 	NAttrClearCompressed(na);
3710 	NAttrClearSparse(na);
3711 	NAttrClearEncrypted(na);
3712 
3713 	if (rl) {
3714 		/* Now copy the attribute value to the allocated cluster(s). */
3715 		bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length),
3716 				(u8*)a + le16_to_cpu(a->value_offset));
3717 		if (bw != le32_to_cpu(a->value_length)) {
3718 			err = errno;
3719 			ntfs_log_debug("Eeek!  Failed to write out attribute value "
3720 					"(bw = %lli, errno = %i).  "
3721 					"Aborting...\n", (long long)bw, err);
3722 			if (bw >= 0)
3723 				err = EIO;
3724 			goto cluster_free_err_out;
3725 		}
3726 	}
3727 	/* Determine the size of the mapping pairs array. */
3728 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0);
3729 	if (mp_size < 0) {
3730 		err = errno;
3731 		ntfs_log_debug("Eeek!  Failed to get size for mapping pairs array.  "
3732 				"Aborting...\n");
3733 		goto cluster_free_err_out;
3734 	}
3735 	/* Calculate new offsets for the name and the mapping pairs array. */
3736 	name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7;
3737 	mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
3738 	/*
3739 	 * Determine the size of the resident part of the non-resident
3740 	 * attribute record. (Not compressed thus no compressed_size element
3741 	 * present.)
3742 	 */
3743 	arec_size = (mp_ofs + mp_size + 7) & ~7;
3744 
3745 	/* Resize the resident part of the attribute record. */
3746 	if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
3747 		err = errno;
3748 		goto cluster_free_err_out;
3749 	}
3750 
3751 	/*
3752 	 * Convert the resident part of the attribute record to describe a
3753 	 * non-resident attribute.
3754 	 */
3755 	a->non_resident = 1;
3756 
3757 	/* Move the attribute name if it exists and update the offset. */
3758 	if (a->name_length)
3759 		memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
3760 				a->name_length * sizeof(ntfschar));
3761 	a->name_offset = cpu_to_le16(name_ofs);
3762 
3763 	/* Update the flags to match the in-memory ones. */
3764 	a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED |
3765 			ATTR_COMPRESSION_MASK);
3766 
3767 	/* Setup the fields specific to non-resident attributes. */
3768 	a->lowest_vcn = cpu_to_sle64(0);
3769 	a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >>
3770 						vol->cluster_size_bits);
3771 
3772 	a->mapping_pairs_offset = cpu_to_le16(mp_ofs);
3773 
3774 	a->compression_unit = 0;
3775 
3776 	memset(&a->reserved1, 0, sizeof(a->reserved1));
3777 
3778 	a->allocated_size = cpu_to_sle64(new_allocated_size);
3779 	a->data_size = a->initialized_size = cpu_to_sle64(na->data_size);
3780 
3781 	/* Generate the mapping pairs array in the attribute record. */
3782 	if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs,
3783 			rl, 0, NULL) < 0) {
3784 		// FIXME: Eeek! We need rollback! (AIA)
3785 		ntfs_log_trace("Eeek!  Failed to build mapping pairs.  Leaving "
3786 				"corrupt attribute record on disk.  In memory "
3787 				"runlist is still intact!  Error code is %i.  "
3788 				"FIXME:  Need to rollback instead!\n", errno);
3789 		return -1;
3790 	}
3791 
3792 	/* Done! */
3793 	return 0;
3794 
3795 cluster_free_err_out:
3796 	if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0)
3797 		ntfs_log_trace("Eeek!  Failed to release allocated clusters in error "
3798 				"code path.  Leaving inconsistent metadata...\n");
3799 	NAttrClearNonResident(na);
3800 	na->allocated_size = na->data_size;
3801 	na->rl = NULL;
3802 	free(rl);
3803 	errno = err;
3804 	return -1;
3805 }
3806 
3807 
3808 static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize);
3809 
3810 /**
3811  * ntfs_resident_attr_resize - resize a resident, open ntfs attribute
3812  * @na:		resident ntfs attribute to resize
3813  * @newsize:	new size (in bytes) to which to resize the attribute
3814  *
3815  * Change the size of a resident, open ntfs attribute @na to @newsize bytes.
3816  *
3817  * On success return 0
3818  * On error return values are:
3819  * 	STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT
3820  * 	STATUS_ERROR - otherwise
3821  * The following error codes are defined:
3822  *	ENOMEM - Not enough memory to complete operation.
3823  *	ERANGE - @newsize is not valid for the attribute type of @na.
3824  *	ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST.
3825  */
3826 static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize)
3827 {
3828 	ntfs_attr_search_ctx *ctx;
3829 	ntfs_volume *vol;
3830 	ntfs_inode *ni;
3831 	int err, ret = STATUS_ERROR;
3832 
3833 	ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n",
3834 		       (unsigned long long)na->ni->mft_no, na->type,
3835 		       (long long)newsize);
3836 
3837 	/* Get the attribute record that needs modification. */
3838 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
3839 	if (!ctx)
3840 		return -1;
3841 	if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0,
3842 			ctx)) {
3843 		err = errno;
3844 		ntfs_log_perror("ntfs_attr_lookup failed");
3845 		goto put_err_out;
3846 	}
3847 	vol = na->ni->vol;
3848 	/*
3849 	 * Check the attribute type and the corresponding minimum and maximum
3850 	 * sizes against @newsize and fail if @newsize is out of bounds.
3851 	 */
3852 	if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) {
3853 		err = errno;
3854 		if (err == ENOENT)
3855 			err = EIO;
3856 		ntfs_log_perror("%s: bounds check failed", __FUNCTION__);
3857 		goto put_err_out;
3858 	}
3859 	/*
3860 	 * If @newsize is bigger than the mft record we need to make the
3861 	 * attribute non-resident if the attribute type supports it. If it is
3862 	 * smaller we can go ahead and attempt the resize.
3863 	 */
3864 	if (newsize < vol->mft_record_size) {
3865 		/* Perform the resize of the attribute record. */
3866 		if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
3867 				newsize))) {
3868 			/* Update attribute size everywhere. */
3869 			na->data_size = na->initialized_size = newsize;
3870 			na->allocated_size = (newsize + 7) & ~7;
3871 			if (NAttrCompressed(na) || NAttrSparse(na))
3872 				na->compressed_size = na->allocated_size;
3873 			if (na->type == AT_DATA && na->name == AT_UNNAMED) {
3874 				na->ni->data_size = na->data_size;
3875 				na->ni->allocated_size = na->allocated_size;
3876 				NInoFileNameSetDirty(na->ni);
3877 			}
3878 			goto resize_done;
3879 		}
3880 		/* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */
3881 		if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) {
3882 			err = errno;
3883 			goto put_err_out;
3884 		}
3885 	}
3886 	/* There is not enough space in the mft record to perform the resize. */
3887 
3888 	/* Make the attribute non-resident if possible. */
3889 	if (!ntfs_attr_make_non_resident(na, ctx)) {
3890 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
3891 		ntfs_attr_put_search_ctx(ctx);
3892 		/* Resize non-resident attribute */
3893 		return ntfs_attr_truncate(na, newsize);
3894 	} else if (errno != ENOSPC && errno != EPERM) {
3895 		err = errno;
3896 		ntfs_log_perror("Failed to make attribute non-resident");
3897 		goto put_err_out;
3898 	}
3899 
3900 	/* Try to make other attributes non-resident and retry each time. */
3901 	ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec);
3902 	while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) {
3903 		ntfs_attr *tna;
3904 		ATTR_RECORD *a;
3905 
3906 		a = ctx->attr;
3907 		if (a->non_resident)
3908 			continue;
3909 
3910 		/*
3911 		 * Check out whether convert is reasonable. Assume that mapping
3912 		 * pairs will take 8 bytes.
3913 		 */
3914 		if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD,
3915 				compressed_size) + ((a->name_length *
3916 				sizeof(ntfschar) + 7) & ~7) + 8)
3917 			continue;
3918 
3919 		tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a +
3920 				le16_to_cpu(a->name_offset)), a->name_length);
3921 		if (!tna) {
3922 			err = errno;
3923 			ntfs_log_perror("Couldn't open attribute");
3924 			goto put_err_out;
3925 		}
3926 		if (ntfs_attr_make_non_resident(tna, ctx)) {
3927 			ntfs_attr_close(tna);
3928 			continue;
3929 		}
3930 		ntfs_inode_mark_dirty(tna->ni);
3931 		ntfs_attr_close(tna);
3932 		ntfs_attr_put_search_ctx(ctx);
3933 		return ntfs_resident_attr_resize(na, newsize);
3934 	}
3935 	/* Check whether error occurred. */
3936 	if (errno != ENOENT) {
3937 		err = errno;
3938 		ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__);
3939 		goto put_err_out;
3940 	}
3941 
3942 	/*
3943 	 * The standard information and attribute list attributes can't be
3944 	 * moved out from the base MFT record, so try to move out others.
3945 	 */
3946 	if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) {
3947 		ntfs_attr_put_search_ctx(ctx);
3948 		if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD,
3949 				non_resident_end) + 8)) {
3950 			ntfs_log_perror("Could not free space in MFT record");
3951 			return -1;
3952 		}
3953 		return ntfs_resident_attr_resize(na, newsize);
3954 	}
3955 
3956 	/*
3957 	 * Move the attribute to a new mft record, creating an attribute list
3958 	 * attribute or modifying it if it is already present.
3959 	 */
3960 
3961 	/* Point search context back to attribute which we need resize. */
3962 	ntfs_attr_init_search_ctx(ctx, na->ni, NULL);
3963 	if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE,
3964 			0, NULL, 0, ctx)) {
3965 		ntfs_log_perror("%s: Attribute lookup failed 2", __FUNCTION__);
3966 		err = errno;
3967 		goto put_err_out;
3968 	}
3969 
3970 	/*
3971 	 * Check whether attribute is already single in this MFT record.
3972 	 * 8 added for the attribute terminator.
3973 	 */
3974 	if (le32_to_cpu(ctx->mrec->bytes_in_use) ==
3975 			le16_to_cpu(ctx->mrec->attrs_offset) +
3976 			le32_to_cpu(ctx->attr->length) + 8) {
3977 		err = ENOSPC;
3978 		ntfs_log_trace("MFT record is filled with one attribute\n");
3979 		ret = STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT;
3980 		goto put_err_out;
3981 	}
3982 
3983 	/* Add attribute list if not present. */
3984 	if (na->ni->nr_extents == -1)
3985 		ni = na->ni->base_ni;
3986 	else
3987 		ni = na->ni;
3988 	if (!NInoAttrList(ni)) {
3989 		ntfs_attr_put_search_ctx(ctx);
3990 		if (ntfs_inode_add_attrlist(ni))
3991 			return -1;
3992 		return ntfs_resident_attr_resize(na, newsize);
3993 	}
3994 	/* Allocate new mft record. */
3995 	ni = ntfs_mft_record_alloc(vol, ni);
3996 	if (!ni) {
3997 		err = errno;
3998 		ntfs_log_perror("Couldn't allocate new MFT record");
3999 		goto put_err_out;
4000 	}
4001 	/* Move attribute to it. */
4002 	if (ntfs_attr_record_move_to(ctx, ni)) {
4003 		err = errno;
4004 		ntfs_log_perror("Couldn't move attribute to new MFT record");
4005 		goto put_err_out;
4006 	}
4007 	/* Update ntfs attribute. */
4008 	if (na->ni->nr_extents == -1)
4009 		na->ni = ni;
4010 
4011 	ntfs_attr_put_search_ctx(ctx);
4012 	/* Try to perform resize once again. */
4013 	return ntfs_resident_attr_resize(na, newsize);
4014 
4015 resize_done:
4016 	/*
4017 	 * Set the inode (and its base inode if it exists) dirty so it is
4018 	 * written out later.
4019 	 */
4020 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
4021 	ntfs_attr_put_search_ctx(ctx);
4022 	return 0;
4023 put_err_out:
4024 	ntfs_attr_put_search_ctx(ctx);
4025 	errno = err;
4026 	return ret;
4027 }
4028 
4029 static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize)
4030 {
4031 	int ret;
4032 
4033 	ntfs_log_enter("Entering\n");
4034 	ret = ntfs_resident_attr_resize_i(na, newsize);
4035 	ntfs_log_leave("\n");
4036 	return ret;
4037 }
4038 
4039 /**
4040  * ntfs_attr_make_resident - convert a non-resident to a resident attribute
4041  * @na:		open ntfs attribute to make resident
4042  * @ctx:	ntfs search context describing the attribute
4043  *
4044  * Convert a non-resident ntfs attribute to a resident one.
4045  *
4046  * Return 0 on success and -1 on error with errno set to the error code. The
4047  * following error codes are defined:
4048  *	EINVAL	   - Invalid arguments passed.
4049  *	EPERM	   - The attribute is not allowed to be resident.
4050  *	EIO	   - I/O error, damaged inode or bug.
4051  *	ENOSPC	   - There is no enough space to perform conversion.
4052  *	EOPNOTSUPP - Requested conversion is not supported yet.
4053  *
4054  * Warning: We do not set the inode dirty and we do not write out anything!
4055  *	    We expect the caller to do this as this is a fairly low level
4056  *	    function and it is likely there will be further changes made.
4057  */
4058 static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx)
4059 {
4060 	ntfs_volume *vol = na->ni->vol;
4061 	ATTR_REC *a = ctx->attr;
4062 	int name_ofs, val_ofs, err = EIO;
4063 	s64 arec_size, bytes_read;
4064 
4065 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long
4066 			long)na->ni->mft_no, na->type);
4067 
4068 	/* Should be called for the first extent of the attribute. */
4069 	if (sle64_to_cpu(a->lowest_vcn)) {
4070 		ntfs_log_trace("Eeek!  Should be called for the first extent of the "
4071 				"attribute.  Aborting...\n");
4072 		err = EINVAL;
4073 		return -1;
4074 	}
4075 
4076 	/* Some preliminary sanity checking. */
4077 	if (!NAttrNonResident(na)) {
4078 		ntfs_log_trace("Eeek!  Trying to make resident attribute resident.  "
4079 				"Aborting...\n");
4080 		errno = EINVAL;
4081 		return -1;
4082 	}
4083 
4084 	/* Make sure this is not $MFT/$BITMAP or Windows will not boot! */
4085 	if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) {
4086 		errno = EPERM;
4087 		return -1;
4088 	}
4089 
4090 	/* Check that the attribute is allowed to be resident. */
4091 	if (ntfs_attr_can_be_resident(vol, na->type))
4092 		return -1;
4093 
4094 	if (NAttrCompressed(na) || NAttrEncrypted(na)) {
4095 		ntfs_log_trace("Making compressed or encrypted files resident is not "
4096 				"implemented yet.\n");
4097 		errno = EOPNOTSUPP;
4098 		return -1;
4099 	}
4100 
4101 	/* Work out offsets into and size of the resident attribute. */
4102 	name_ofs = 24; /* = sizeof(resident_ATTR_REC); */
4103 	val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
4104 	arec_size = (val_ofs + na->data_size + 7) & ~7;
4105 
4106 	/* Sanity check the size before we start modifying the attribute. */
4107 	if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) +
4108 			arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) {
4109 		errno = ENOSPC;
4110 		ntfs_log_trace("Not enough space to make attribute resident\n");
4111 		return -1;
4112 	}
4113 
4114 	/* Read and cache the whole runlist if not already done. */
4115 	if (ntfs_attr_map_whole_runlist(na))
4116 		return -1;
4117 
4118 	/* Move the attribute name if it exists and update the offset. */
4119 	if (a->name_length) {
4120 		memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
4121 				a->name_length * sizeof(ntfschar));
4122 	}
4123 	a->name_offset = cpu_to_le16(name_ofs);
4124 
4125 	/* Resize the resident part of the attribute record. */
4126 	if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
4127 		/*
4128 		 * Bug, because ntfs_attr_record_resize should not fail (we
4129 		 * already checked that attribute fits MFT record).
4130 		 */
4131 		ntfs_log_error("BUG! Failed to resize attribute record. "
4132 				"Please report to the %s.  Aborting...\n",
4133 				NTFS_DEV_LIST);
4134 		errno = EIO;
4135 		return -1;
4136 	}
4137 
4138 	/* Convert the attribute record to describe a resident attribute. */
4139 	a->non_resident = 0;
4140 	a->flags = 0;
4141 	a->value_length = cpu_to_le32(na->data_size);
4142 	a->value_offset = cpu_to_le16(val_ofs);
4143 	/*
4144 	 * File names cannot be non-resident so we would never see this here
4145 	 * but at least it serves as a reminder that there may be attributes
4146 	 * for which we do need to set this flag. (AIA)
4147 	 */
4148 	if (a->type == AT_FILE_NAME)
4149 		a->resident_flags = RESIDENT_ATTR_IS_INDEXED;
4150 	else
4151 		a->resident_flags = 0;
4152 	a->reservedR = 0;
4153 
4154 	/* Sanity fixup...  Shouldn't really happen. (AIA) */
4155 	if (na->initialized_size > na->data_size)
4156 		na->initialized_size = na->data_size;
4157 
4158 	/* Copy data from run list to resident attribute value. */
4159 	bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size,
4160 			(u8*)a + val_ofs);
4161 	if (bytes_read != na->initialized_size) {
4162 		if (bytes_read < 0)
4163 			err = errno;
4164 		ntfs_log_trace("Eeek! Failed to read attribute data. Leaving "
4165 				"inconstant metadata. Run chkdsk.  "
4166 				"Aborting...\n");
4167 		errno = err;
4168 		return -1;
4169 	}
4170 
4171 	/* Clear memory in gap between initialized_size and data_size. */
4172 	if (na->initialized_size < na->data_size)
4173 		memset((u8*)a + val_ofs + na->initialized_size, 0,
4174 				na->data_size - na->initialized_size);
4175 
4176 	/*
4177 	 * Deallocate clusters from the runlist.
4178 	 *
4179 	 * NOTE: We can use ntfs_cluster_free() because we have already mapped
4180 	 * the whole run list and thus it doesn't matter that the attribute
4181 	 * record is in a transiently corrupted state at this moment in time.
4182 	 */
4183 	if (ntfs_cluster_free(vol, na, 0, -1) < 0) {
4184 		err = errno;
4185 		ntfs_log_perror("Eeek! Failed to release allocated clusters");
4186 		ntfs_log_trace("Ignoring error and leaving behind wasted "
4187 				"clusters.\n");
4188 	}
4189 
4190 	/* Throw away the now unused runlist. */
4191 	free(na->rl);
4192 	na->rl = NULL;
4193 
4194 	/* Update in-memory struct ntfs_attr. */
4195 	NAttrClearNonResident(na);
4196 	NAttrClearCompressed(na);
4197 	NAttrClearSparse(na);
4198 	NAttrClearEncrypted(na);
4199 	na->initialized_size = na->data_size;
4200 	na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7;
4201 	na->compression_block_size = 0;
4202 	na->compression_block_size_bits = na->compression_block_clusters = 0;
4203 	return 0;
4204 }
4205 
4206 /*
4207  * If we are in the first extent, then set/clean sparse bit,
4208  * update allocated and compressed size.
4209  */
4210 static int ntfs_attr_update_meta(ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m,
4211 				 ntfs_attr_search_ctx *ctx)
4212 {
4213 	int sparse, ret = 0;
4214 
4215 	ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n",
4216 		       (unsigned long long)na->ni->mft_no, na->type);
4217 
4218 	if (a->lowest_vcn)
4219 		goto out;
4220 
4221 	a->allocated_size = cpu_to_sle64(na->allocated_size);
4222 
4223 	/* Update sparse bit. */
4224 	sparse = ntfs_rl_sparse(na->rl);
4225 	if (sparse == -1) {
4226 		errno = EIO;
4227 		goto error;
4228 	}
4229 
4230 	/* Attribute become sparse. */
4231 	if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) {
4232 		/*
4233 		 * Move attribute to another mft record, if attribute is too
4234 		 * small to add compressed_size field to it and we have no
4235 		 * free space in the current mft record.
4236 		 */
4237 		if ((le32_to_cpu(a->length) -
4238 				le16_to_cpu(a->mapping_pairs_offset) == 8)
4239 		    && !(le32_to_cpu(m->bytes_allocated) -
4240 				le32_to_cpu(m->bytes_in_use))) {
4241 
4242 			if (!NInoAttrList(na->ni)) {
4243 				ntfs_attr_put_search_ctx(ctx);
4244 				if (ntfs_inode_add_attrlist(na->ni))
4245 					goto leave;
4246 				goto retry;
4247 			}
4248 			if (ntfs_attr_record_move_away(ctx, 8)) {
4249 				ntfs_log_perror("Failed to move attribute");
4250 				goto error;
4251 			}
4252 			ntfs_attr_put_search_ctx(ctx);
4253 			goto retry;
4254 		}
4255 		if (!(le32_to_cpu(a->length) - le16_to_cpu(
4256 						a->mapping_pairs_offset))) {
4257 			errno = EIO;
4258 			ntfs_log_perror("Mapping pairs space is 0");
4259 			goto error;
4260 		}
4261 
4262 		NAttrSetSparse(na);
4263 		a->flags |= ATTR_IS_SPARSE;
4264 		a->compression_unit = 4; /* Windows set it so, even if attribute
4265 					    is not actually compressed. */
4266 
4267 		memmove((u8*)a + le16_to_cpu(a->name_offset) + 8,
4268 			(u8*)a + le16_to_cpu(a->name_offset),
4269 			a->name_length * sizeof(ntfschar));
4270 
4271 		a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8);
4272 
4273 		a->mapping_pairs_offset =
4274 			cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) + 8);
4275 	}
4276 
4277 	/* Attribute no longer sparse. */
4278 	if (!sparse && (a->flags & ATTR_IS_SPARSE) &&
4279 	    !(a->flags & ATTR_IS_COMPRESSED)) {
4280 
4281 		NAttrClearSparse(na);
4282 		a->flags &= ~ATTR_IS_SPARSE;
4283 		a->compression_unit = 0;
4284 
4285 		memmove((u8*)a + le16_to_cpu(a->name_offset) - 8,
4286 			(u8*)a + le16_to_cpu(a->name_offset),
4287 			a->name_length * sizeof(ntfschar));
4288 
4289 		if (le16_to_cpu(a->name_offset) >= 8)
4290 			a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8);
4291 
4292 		a->mapping_pairs_offset =
4293 			cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8);
4294 	}
4295 
4296 	/* Update compressed size if required. */
4297 	if (sparse) {
4298 		s64 new_compr_size;
4299 
4300 		new_compr_size = ntfs_rl_get_compressed_size(na->ni->vol, na->rl);
4301 		if (new_compr_size == -1)
4302 			goto error;
4303 
4304 		na->compressed_size = new_compr_size;
4305 		a->compressed_size = cpu_to_sle64(new_compr_size);
4306 	}
4307 	/*
4308 	 * Set FILE_NAME dirty flag, to update sparse bit and
4309 	 * allocated size in the index.
4310 	 */
4311 	if (na->type == AT_DATA && na->name == AT_UNNAMED) {
4312 		if (sparse)
4313 			na->ni->allocated_size = na->compressed_size;
4314 		else
4315 			na->ni->allocated_size = na->allocated_size;
4316 		NInoFileNameSetDirty(na->ni);
4317 	}
4318 out:
4319 	return ret;
4320 leave:	ret = -1; goto out;  /* return -1 */
4321 retry:	ret = -2; goto out;
4322 error:  ret = -3; goto out;
4323 }
4324 
4325 #define NTFS_VCN_DELETE_MARK -2
4326 /**
4327  * ntfs_attr_update_mapping_pairs_i - see ntfs_attr_update_mapping_pairs
4328  */
4329 static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn)
4330 {
4331 	ntfs_attr_search_ctx *ctx;
4332 	ntfs_inode *ni, *base_ni;
4333 	MFT_RECORD *m;
4334 	ATTR_RECORD *a;
4335 	VCN stop_vcn;
4336 	int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1;
4337 	BOOL finished_build;
4338 retry:
4339 	if (!na || !na->rl || from_vcn) {
4340 		errno = EINVAL;
4341 		ntfs_log_perror("%s: na=%p", __FUNCTION__, na);
4342 		return -1;
4343 	}
4344 
4345 	ntfs_log_trace("Entering for inode %llu, attr 0x%x\n",
4346 		       (unsigned long long)na->ni->mft_no, na->type);
4347 
4348 	if (!NAttrNonResident(na)) {
4349 		errno = EINVAL;
4350 		ntfs_log_perror("%s: resident attribute", __FUNCTION__);
4351 		return -1;
4352 	}
4353 
4354 	if (na->ni->nr_extents == -1)
4355 		base_ni = na->ni->base_ni;
4356 	else
4357 		base_ni = na->ni;
4358 
4359 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4360 	if (!ctx)
4361 		return -1;
4362 
4363 	/* Fill attribute records with new mapping pairs. */
4364 	stop_vcn = 0;
4365 	finished_build = FALSE;
4366 	while (!ntfs_attr_lookup(na->type, na->name, na->name_len,
4367 				CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) {
4368 		a = ctx->attr;
4369 		m = ctx->mrec;
4370 		/*
4371 		 * If runlist is updating not from the beginning, then set
4372 		 * @stop_vcn properly, i.e. to the lowest vcn of record that
4373 		 * contain @from_vcn. Also we do not need @from_vcn anymore,
4374 		 * set it to 0 to make ntfs_attr_lookup enumerate attributes.
4375 		 */
4376 		if (from_vcn) {
4377 			LCN first_lcn;
4378 
4379 			stop_vcn = sle64_to_cpu(a->lowest_vcn);
4380 			from_vcn = 0;
4381 			/*
4382 			 * Check whether the first run we need to update is
4383 			 * the last run in runlist, if so, then deallocate
4384 			 * all attrubute extents starting this one.
4385 			 */
4386 			first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn);
4387 			if (first_lcn == LCN_EINVAL) {
4388 				errno = EIO;
4389 				ntfs_log_perror("Bad runlist");
4390 				goto put_err_out;
4391 			}
4392 			if (first_lcn == LCN_ENOENT ||
4393 					first_lcn == LCN_RL_NOT_MAPPED)
4394 				finished_build = TRUE;
4395 		}
4396 
4397 		/*
4398 		 * Check whether we finished mapping pairs build, if so mark
4399 		 * extent as need to delete (by setting highest vcn to
4400 		 * NTFS_VCN_DELETE_MARK (-2), we shall check it later and
4401 		 * delete extent) and continue search.
4402 		 */
4403 		if (finished_build) {
4404 			ntfs_log_trace("Mark attr 0x%x for delete in inode "
4405 				"%lld.\n", (unsigned)le32_to_cpu(a->type),
4406 				(long long)ctx->ntfs_ino->mft_no);
4407 			a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK);
4408 			ntfs_inode_mark_dirty(ctx->ntfs_ino);
4409 			continue;
4410 		}
4411 
4412 		switch (ntfs_attr_update_meta(a, na, m, ctx)) {
4413 			case -1: return -1;
4414 			case -2: goto retry;
4415 			case -3: goto put_err_out;
4416 		}
4417 
4418 		/* Get the size for the rest of mapping pairs array. */
4419 		mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, na->rl,
4420 								stop_vcn);
4421 		if (mp_size <= 0) {
4422 			ntfs_log_perror("%s: get MP size failed", __FUNCTION__);
4423 			goto put_err_out;
4424 		}
4425 		/*
4426 		 * Determine maximum possible length of mapping pairs,
4427 		 * if we shall *not* expand space for mapping pairs.
4428 		 */
4429 		cur_max_mp_size = le32_to_cpu(a->length) -
4430 				le16_to_cpu(a->mapping_pairs_offset);
4431 		/*
4432 		 * Determine maximum possible length of mapping pairs in the
4433 		 * current mft record, if we shall expand space for mapping
4434 		 * pairs.
4435 		 */
4436 		exp_max_mp_size = le32_to_cpu(m->bytes_allocated) -
4437 				le32_to_cpu(m->bytes_in_use) + cur_max_mp_size;
4438 		/* Test mapping pairs for fitting in the current mft record. */
4439 		if (mp_size > exp_max_mp_size) {
4440 			/*
4441 			 * Mapping pairs of $ATTRIBUTE_LIST attribute must fit
4442 			 * in the base mft record. Try to move out other
4443 			 * attributes and try again.
4444 			 */
4445 			if (na->type == AT_ATTRIBUTE_LIST) {
4446 				ntfs_attr_put_search_ctx(ctx);
4447 				if (ntfs_inode_free_space(na->ni, mp_size -
4448 							cur_max_mp_size)) {
4449 					ntfs_log_perror("Attribute list is too "
4450 							"big. Defragment the "
4451 							"volume\n");
4452 					return -1;
4453 				}
4454 				goto retry;
4455 			}
4456 
4457 			/* Add attribute list if it isn't present, and retry. */
4458 			if (!NInoAttrList(base_ni)) {
4459 				ntfs_attr_put_search_ctx(ctx);
4460 				if (ntfs_inode_add_attrlist(base_ni)) {
4461 					ntfs_log_perror("Can not add attrlist");
4462 					return -1;
4463 				}
4464 				goto retry;
4465 			}
4466 
4467 			/*
4468 			 * Set mapping pairs size to maximum possible for this
4469 			 * mft record. We shall write the rest of mapping pairs
4470 			 * to another MFT records.
4471 			 */
4472 			mp_size = exp_max_mp_size;
4473 		}
4474 
4475 		/* Change space for mapping pairs if we need it. */
4476 		if (((mp_size + 7) & ~7) != cur_max_mp_size) {
4477 			if (ntfs_attr_record_resize(m, a,
4478 					le16_to_cpu(a->mapping_pairs_offset) +
4479 					mp_size)) {
4480 				errno = EIO;
4481 				ntfs_log_perror("Failed to resize attribute");
4482 				goto put_err_out;
4483 			}
4484 		}
4485 
4486 		/* Update lowest vcn. */
4487 		a->lowest_vcn = cpu_to_sle64(stop_vcn);
4488 		ntfs_inode_mark_dirty(ctx->ntfs_ino);
4489 		if ((ctx->ntfs_ino->nr_extents == -1 ||
4490 					NInoAttrList(ctx->ntfs_ino)) &&
4491 					ctx->attr->type != AT_ATTRIBUTE_LIST) {
4492 			ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn);
4493 			ntfs_attrlist_mark_dirty(ctx->ntfs_ino);
4494 		}
4495 
4496 		/*
4497 		 * Generate the new mapping pairs array directly into the
4498 		 * correct destination, i.e. the attribute record itself.
4499 		 */
4500 		if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu(
4501 				a->mapping_pairs_offset), mp_size, na->rl,
4502 				stop_vcn, &stop_vcn))
4503 			finished_build = TRUE;
4504 		if (!finished_build && errno != ENOSPC) {
4505 			ntfs_log_perror("Failed to build mapping pairs");
4506 			goto put_err_out;
4507 		}
4508 		a->highest_vcn = cpu_to_sle64(stop_vcn - 1);
4509 	}
4510 	/* Check whether error occurred. */
4511 	if (errno != ENOENT) {
4512 		ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__);
4513 		goto put_err_out;
4514 	}
4515 
4516 	/* Deallocate not used attribute extents and return with success. */
4517 	if (finished_build) {
4518 		ntfs_attr_reinit_search_ctx(ctx);
4519 		ntfs_log_trace("Deallocate marked extents.\n");
4520 		while (!ntfs_attr_lookup(na->type, na->name, na->name_len,
4521 				CASE_SENSITIVE, 0, NULL, 0, ctx)) {
4522 			if (sle64_to_cpu(ctx->attr->highest_vcn) !=
4523 							NTFS_VCN_DELETE_MARK)
4524 				continue;
4525 			/* Remove unused attribute record. */
4526 			if (ntfs_attr_record_rm(ctx)) {
4527 				ntfs_log_perror("Could not remove unused attr");
4528 				goto put_err_out;
4529 			}
4530 			ntfs_attr_reinit_search_ctx(ctx);
4531 		}
4532 		if (errno != ENOENT) {
4533 			ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__);
4534 			goto put_err_out;
4535 		}
4536 		ntfs_log_trace("Deallocate done.\n");
4537 		ntfs_attr_put_search_ctx(ctx);
4538 		goto ok;
4539 	}
4540 	ntfs_attr_put_search_ctx(ctx);
4541 	ctx = NULL;
4542 
4543 	/* Allocate new MFT records for the rest of mapping pairs. */
4544 	while (1) {
4545 		/* Calculate size of rest mapping pairs. */
4546 		mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol,
4547 						na->rl, stop_vcn);
4548 		if (mp_size <= 0) {
4549 			ntfs_log_perror("%s: get mp size failed", __FUNCTION__);
4550 			goto put_err_out;
4551 		}
4552 		/* Allocate new mft record. */
4553 		ni = ntfs_mft_record_alloc(na->ni->vol, base_ni);
4554 		if (!ni) {
4555 			ntfs_log_perror("Could not allocate new MFT record");
4556 			goto put_err_out;
4557 		}
4558 		m = ni->mrec;
4559 		/*
4560 		 * If mapping size exceed available space, set them to
4561 		 * possible maximum.
4562 		 */
4563 		cur_max_mp_size = le32_to_cpu(m->bytes_allocated) -
4564 				le32_to_cpu(m->bytes_in_use) -
4565 				(offsetof(ATTR_RECORD, compressed_size) +
4566 				((NAttrCompressed(na) || NAttrSparse(na)) ?
4567 				sizeof(a->compressed_size) : 0)) -
4568 				((sizeof(ntfschar) * na->name_len + 7) & ~7);
4569 		if (mp_size > cur_max_mp_size)
4570 			mp_size = cur_max_mp_size;
4571 		/* Add attribute extent to new record. */
4572 		err = ntfs_non_resident_attr_record_add(ni, na->type,
4573 			 na->name, na->name_len, stop_vcn, mp_size, 0);
4574 		if (err == -1) {
4575 			err = errno;
4576 			ntfs_log_perror("Could not add attribute extent");
4577 			if (ntfs_mft_record_free(na->ni->vol, ni))
4578 				ntfs_log_perror("Could not free MFT record");
4579 			errno = err;
4580 			goto put_err_out;
4581 		}
4582 		a = (ATTR_RECORD*)((u8*)m + err);
4583 
4584 		err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a +
4585 			le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl,
4586 			stop_vcn, &stop_vcn);
4587 		if (err < 0 && errno != ENOSPC) {
4588 			err = errno;
4589 			ntfs_log_perror("Failed to build MP");
4590 			if (ntfs_mft_record_free(na->ni->vol, ni))
4591 				ntfs_log_perror("Couldn't free MFT record");
4592 			errno = err;
4593 			goto put_err_out;
4594 		}
4595 		a->highest_vcn = cpu_to_sle64(stop_vcn - 1);
4596 		ntfs_inode_mark_dirty(ni);
4597 		/* All mapping pairs has been written. */
4598 		if (!err)
4599 			break;
4600 	}
4601 ok:
4602 	ret = 0;
4603 out:
4604 	return ret;
4605 put_err_out:
4606 	if (ctx)
4607 		ntfs_attr_put_search_ctx(ctx);
4608 	goto out;
4609 }
4610 #undef NTFS_VCN_DELETE_MARK
4611 
4612 /**
4613  * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute
4614  * @na:		non-resident ntfs open attribute for which we need update
4615  * @from_vcn:	update runlist starting this VCN
4616  *
4617  * Build mapping pairs from @na->rl and write them to the disk. Also, this
4618  * function updates sparse bit, allocated and compressed size (allocates/frees
4619  * space for this field if required).
4620  *
4621  * @na->allocated_size should be set to correct value for the new runlist before
4622  * call to this function. Vice-versa @na->compressed_size will be calculated and
4623  * set to correct value during this function.
4624  *
4625  * FIXME: This function does not update sparse bit and compressed size correctly
4626  * if called with @from_vcn != 0.
4627  *
4628  * FIXME: Rewrite without using NTFS_VCN_DELETE_MARK define.
4629  *
4630  * On success return 0 and on error return -1 with errno set to the error code.
4631  * The following error codes are defined:
4632  *	EINVAL - Invalid arguments passed.
4633  *	ENOMEM - Not enough memory to complete operation.
4634  *	ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST
4635  *		 or there is no free MFT records left to allocate.
4636  */
4637 int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn)
4638 {
4639 	int ret;
4640 
4641 	ntfs_log_enter("Entering\n");
4642 	ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn);
4643 	ntfs_log_leave("\n");
4644 	return ret;
4645 }
4646 
4647 /**
4648  * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute
4649  * @na:		non-resident ntfs attribute to shrink
4650  * @newsize:	new size (in bytes) to which to shrink the attribute
4651  *
4652  * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes.
4653  *
4654  * On success return 0 and on error return -1 with errno set to the error code.
4655  * The following error codes are defined:
4656  *	ENOMEM	- Not enough memory to complete operation.
4657  *	ERANGE	- @newsize is not valid for the attribute type of @na.
4658  */
4659 static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize)
4660 {
4661 	ntfs_volume *vol;
4662 	ntfs_attr_search_ctx *ctx;
4663 	VCN first_free_vcn;
4664 	s64 nr_freed_clusters;
4665 	int err;
4666 
4667 	ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", (unsigned long long)
4668 		       na->ni->mft_no, na->type, (long long)newsize);
4669 
4670 	vol = na->ni->vol;
4671 
4672 	/*
4673 	 * Check the attribute type and the corresponding minimum size
4674 	 * against @newsize and fail if @newsize is too small.
4675 	 */
4676 	if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) {
4677 		if (errno == ERANGE) {
4678 			ntfs_log_trace("Eeek! Size bounds check failed. "
4679 					"Aborting...\n");
4680 		} else if (errno == ENOENT)
4681 			errno = EIO;
4682 		return -1;
4683 	}
4684 
4685 	/* The first cluster outside the new allocation. */
4686 	first_free_vcn = (newsize + vol->cluster_size - 1) >>
4687 			vol->cluster_size_bits;
4688 	/*
4689 	 * Compare the new allocation with the old one and only deallocate
4690 	 * clusters if there is a change.
4691 	 */
4692 	if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) {
4693 		if (ntfs_attr_map_whole_runlist(na)) {
4694 			ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist "
4695 					"failed.\n");
4696 			return -1;
4697 		}
4698 		/* Deallocate all clusters starting with the first free one. */
4699 		nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn,
4700 				-1);
4701 		if (nr_freed_clusters < 0) {
4702 			ntfs_log_trace("Eeek! Freeing of clusters failed. "
4703 					"Aborting...\n");
4704 			return -1;
4705 		}
4706 
4707 		/* Truncate the runlist itself. */
4708 		if (ntfs_rl_truncate(&na->rl, first_free_vcn)) {
4709 			/*
4710 			 * Failed to truncate the runlist, so just throw it
4711 			 * away, it will be mapped afresh on next use.
4712 			 */
4713 			free(na->rl);
4714 			na->rl = NULL;
4715 			ntfs_log_trace("Eeek! Run list truncation failed.\n");
4716 			return -1;
4717 		}
4718 
4719 		/* Prepare to mapping pairs update. */
4720 		na->allocated_size = first_free_vcn << vol->cluster_size_bits;
4721 		/* Write mapping pairs for new runlist. */
4722 		if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) {
4723 			ntfs_log_trace("Eeek! Mapping pairs update failed. "
4724 					"Leaving inconstant metadata. "
4725 					"Run chkdsk.\n");
4726 			return -1;
4727 		}
4728 	}
4729 
4730 	/* Get the first attribute record. */
4731 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
4732 	if (!ctx)
4733 		return -1;
4734 
4735 	if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE,
4736 			0, NULL, 0, ctx)) {
4737 		err = errno;
4738 		if (err == ENOENT)
4739 			err = EIO;
4740 		ntfs_log_trace("Eeek! Lookup of first attribute extent failed. "
4741 				"Leaving inconstant metadata.\n");
4742 		goto put_err_out;
4743 	}
4744 
4745 	/* Update data and initialized size. */
4746 	na->data_size = newsize;
4747 	ctx->attr->data_size = cpu_to_sle64(newsize);
4748 	if (newsize < na->initialized_size) {
4749 		na->initialized_size = newsize;
4750 		ctx->attr->initialized_size = cpu_to_sle64(newsize);
4751 	}
4752 	/* Update data size in the index. */
4753 	if (na->type == AT_DATA && na->name == AT_UNNAMED) {
4754 		na->ni->data_size = na->data_size;
4755 		NInoFileNameSetDirty(na->ni);
4756 	}
4757 
4758 	/* If the attribute now has zero size, make it resident. */
4759 	if (!newsize) {
4760 		if (ntfs_attr_make_resident(na, ctx)) {
4761 			/* If couldn't make resident, just continue. */
4762 			if (errno != EPERM)
4763 				ntfs_log_error("Failed to make attribute "
4764 						"resident. Leaving as is...\n");
4765 		}
4766 	}
4767 
4768 	/* Set the inode dirty so it is written out later. */
4769 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
4770 	/* Done! */
4771 	ntfs_attr_put_search_ctx(ctx);
4772 	return 0;
4773 put_err_out:
4774 	ntfs_attr_put_search_ctx(ctx);
4775 	errno = err;
4776 	return -1;
4777 }
4778 
4779 /**
4780  * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute
4781  * @na:		non-resident ntfs attribute to expand
4782  * @newsize:	new size (in bytes) to which to expand the attribute
4783  *
4784  * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes,
4785  * by allocating new clusters.
4786  *
4787  * On success return 0 and on error return -1 with errno set to the error code.
4788  * The following error codes are defined:
4789  *	ENOMEM - Not enough memory to complete operation.
4790  *	ERANGE - @newsize is not valid for the attribute type of @na.
4791  *	ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST.
4792  */
4793 static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize)
4794 {
4795 	LCN lcn_seek_from;
4796 	VCN first_free_vcn;
4797 	ntfs_volume *vol;
4798 	ntfs_attr_search_ctx *ctx;
4799 	runlist *rl, *rln;
4800 	s64 org_alloc_size;
4801 	int err;
4802 
4803 	ntfs_log_trace("Inode %lld, attr 0x%x, new size %lld old size %lld\n",
4804 			(unsigned long long)na->ni->mft_no, na->type,
4805 			(long long)newsize, (long long)na->data_size);
4806 
4807 	vol = na->ni->vol;
4808 
4809 	/*
4810 	 * Check the attribute type and the corresponding maximum size
4811 	 * against @newsize and fail if @newsize is too big.
4812 	 */
4813 	if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) {
4814 		if (errno == ENOENT)
4815 			errno = EIO;
4816 		ntfs_log_perror("%s: bounds check failed", __FUNCTION__);
4817 		return -1;
4818 	}
4819 
4820 	/* Save for future use. */
4821 	org_alloc_size = na->allocated_size;
4822 	/* The first cluster outside the new allocation. */
4823 	first_free_vcn = (newsize + vol->cluster_size - 1) >>
4824 			vol->cluster_size_bits;
4825 	/*
4826 	 * Compare the new allocation with the old one and only allocate
4827 	 * clusters if there is a change.
4828 	 */
4829 	if ((na->allocated_size >> vol->cluster_size_bits) < first_free_vcn) {
4830 		if (ntfs_attr_map_whole_runlist(na)) {
4831 			ntfs_log_perror("ntfs_attr_map_whole_runlist failed");
4832 			return -1;
4833 		}
4834 
4835 		/*
4836 		 * If we extend $DATA attribute on NTFS 3+ volume, we can add
4837 		 * sparse runs instead of real allocation of clusters.
4838 		 */
4839 		if (na->type == AT_DATA && vol->major_ver >= 3) {
4840 			rl = ntfs_malloc(0x1000);
4841 			if (!rl)
4842 				return -1;
4843 
4844 			rl[0].vcn = (na->allocated_size >>
4845 					vol->cluster_size_bits);
4846 			rl[0].lcn = LCN_HOLE;
4847 			rl[0].length = first_free_vcn -
4848 				(na->allocated_size >> vol->cluster_size_bits);
4849 			rl[1].vcn = first_free_vcn;
4850 			rl[1].lcn = LCN_ENOENT;
4851 			rl[1].length = 0;
4852 		} else {
4853 			/*
4854 			 * Determine first after last LCN of attribute.
4855 			 * We will start seek clusters from this LCN to avoid
4856 			 * fragmentation.  If there are no valid LCNs in the
4857 			 * attribute let the cluster allocator choose the
4858 			 * starting LCN.
4859 			 */
4860 			lcn_seek_from = -1;
4861 			if (na->rl->length) {
4862 				/* Seek to the last run list element. */
4863 				for (rl = na->rl; (rl + 1)->length; rl++)
4864 					;
4865 				/*
4866 				 * If the last LCN is a hole or similar seek
4867 				 * back to last valid LCN.
4868 				 */
4869 				while (rl->lcn < 0 && rl != na->rl)
4870 					rl--;
4871 				/*
4872 				 * Only set lcn_seek_from it the LCN is valid.
4873 				 */
4874 				if (rl->lcn >= 0)
4875 					lcn_seek_from = rl->lcn + rl->length;
4876 			}
4877 
4878 			rl = ntfs_cluster_alloc(vol, na->allocated_size >>
4879 					vol->cluster_size_bits, first_free_vcn -
4880 					(na->allocated_size >>
4881 					vol->cluster_size_bits), lcn_seek_from,
4882 					DATA_ZONE);
4883 			if (!rl) {
4884 				ntfs_log_perror("Cluster allocation failed "
4885 						"(%lld)",
4886 						(long long)first_free_vcn -
4887 						((long long)na->allocated_size >>
4888 						 vol->cluster_size_bits));
4889 				return -1;
4890 			}
4891 		}
4892 
4893 		/* Append new clusters to attribute runlist. */
4894 		rln = ntfs_runlists_merge(na->rl, rl);
4895 		if (!rln) {
4896 			/* Failed, free just allocated clusters. */
4897 			err = errno;
4898 			ntfs_log_perror("Run list merge failed");
4899 			ntfs_cluster_free_from_rl(vol, rl);
4900 			free(rl);
4901 			errno = err;
4902 			return -1;
4903 		}
4904 		na->rl = rln;
4905 
4906 		/* Prepare to mapping pairs update. */
4907 		na->allocated_size = first_free_vcn << vol->cluster_size_bits;
4908 		/* Write mapping pairs for new runlist. */
4909 		if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >>
4910 				vol->cluster_size_bits*/)) {
4911 			err = errno;
4912 			ntfs_log_perror("Mapping pairs update failed");
4913 			goto rollback;
4914 		}
4915 	}
4916 
4917 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
4918 	if (!ctx) {
4919 		err = errno;
4920 		if (na->allocated_size == org_alloc_size) {
4921 			errno = err;
4922 			return -1;
4923 		} else
4924 			goto rollback;
4925 	}
4926 
4927 	if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE,
4928 			0, NULL, 0, ctx)) {
4929 		err = errno;
4930 		ntfs_log_perror("Lookup of first attribute extent failed");
4931 		if (err == ENOENT)
4932 			err = EIO;
4933 		if (na->allocated_size != org_alloc_size) {
4934 			ntfs_attr_put_search_ctx(ctx);
4935 			goto rollback;
4936 		} else
4937 			goto put_err_out;
4938 	}
4939 
4940 	/* Update data size. */
4941 	na->data_size = newsize;
4942 	ctx->attr->data_size = cpu_to_sle64(newsize);
4943 	/* Update data size in the index. */
4944 	if (na->type == AT_DATA && na->name == AT_UNNAMED) {
4945 		na->ni->data_size = na->data_size;
4946 		NInoFileNameSetDirty(na->ni);
4947 	}
4948 	/* Set the inode dirty so it is written out later. */
4949 	ntfs_inode_mark_dirty(ctx->ntfs_ino);
4950 	/* Done! */
4951 	ntfs_attr_put_search_ctx(ctx);
4952 	return 0;
4953 rollback:
4954 	/* Free allocated clusters. */
4955 	if (ntfs_cluster_free(vol, na, org_alloc_size >>
4956 			vol->cluster_size_bits, -1) < 0) {
4957 		err = EIO;
4958 		ntfs_log_perror("Leaking clusters");
4959 	}
4960 	/* Now, truncate the runlist itself. */
4961 	if (ntfs_rl_truncate(&na->rl, org_alloc_size >>
4962 			vol->cluster_size_bits)) {
4963 		/*
4964 		 * Failed to truncate the runlist, so just throw it away, it
4965 		 * will be mapped afresh on next use.
4966 		 */
4967 		free(na->rl);
4968 		na->rl = NULL;
4969 		ntfs_log_perror("Couldn't truncate runlist. Rollback failed");
4970 	} else {
4971 		/* Prepare to mapping pairs update. */
4972 		na->allocated_size = org_alloc_size;
4973 		/* Restore mapping pairs. */
4974 		if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >>
4975 					vol->cluster_size_bits*/)) {
4976 			ntfs_log_perror("Failed to restore old mapping pairs");
4977 		}
4978 	}
4979 	errno = err;
4980 	return -1;
4981 put_err_out:
4982 	ntfs_attr_put_search_ctx(ctx);
4983 	errno = err;
4984 	return -1;
4985 }
4986 
4987 
4988 static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize)
4989 {
4990 	int ret;
4991 
4992 	ntfs_log_enter("Entering\n");
4993 	ret = ntfs_non_resident_attr_expand_i(na, newsize);
4994 	ntfs_log_leave("\n");
4995 	return ret;
4996 }
4997 
4998 /**
4999  * ntfs_attr_truncate - resize an ntfs attribute
5000  * @na:		open ntfs attribute to resize
5001  * @newsize:	new size (in bytes) to which to resize the attribute
5002  *
5003  * Change the size of an open ntfs attribute @na to @newsize bytes. If the
5004  * attribute is made bigger and the attribute is resident the newly
5005  * "allocated" space is cleared and if the attribute is non-resident the
5006  * newly allocated space is marked as not initialised and no real allocation
5007  * on disk is performed.
5008  *
5009  * On success return 0.
5010  * On error return values are:
5011  * 	STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT
5012  * 	STATUS_ERROR - otherwise
5013  * The following error codes are defined:
5014  *	EINVAL	   - Invalid arguments were passed to the function.
5015  *	EOPNOTSUPP - The desired resize is not implemented yet.
5016  * 	EACCES     - Encrypted attribute.
5017  */
5018 int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize)
5019 {
5020 	int ret = STATUS_ERROR;
5021 
5022 	if (!na || newsize < 0 ||
5023 			(na->ni->mft_no == FILE_MFT && na->type == AT_DATA)) {
5024 		ntfs_log_trace("Invalid arguments passed.\n");
5025 		errno = EINVAL;
5026 		return STATUS_ERROR;
5027 	}
5028 
5029 	ntfs_log_enter("Entering for inode %lld, attr 0x%x, size %lld\n",
5030 		       (unsigned long long)na->ni->mft_no, na->type,
5031 		       (long long)newsize);
5032 
5033 	if (na->data_size == newsize) {
5034 		ntfs_log_trace("Size is already ok\n");
5035 		ret = STATUS_OK;
5036 		goto out;
5037 	}
5038 	/*
5039 	 * Encrypted attributes are not supported. We return access denied,
5040 	 * which is what Windows NT4 does, too.
5041 	 */
5042 	if (NAttrEncrypted(na)) {
5043 		errno = EACCES;
5044 		ntfs_log_perror("Failed to truncate encrypted attribute");
5045 		goto out;
5046 	}
5047 	/*
5048 	 * TODO: Implement making handling of compressed attributes.
5049 	 */
5050 	if (NAttrCompressed(na)) {
5051 		errno = EOPNOTSUPP;
5052 		ntfs_log_perror("Failed to truncate compressed attribute");
5053 		goto out;
5054 	}
5055 	if (NAttrNonResident(na)) {
5056 		if (newsize > na->data_size)
5057 			ret = ntfs_non_resident_attr_expand(na, newsize);
5058 		else
5059 			ret = ntfs_non_resident_attr_shrink(na, newsize);
5060 	} else
5061 		ret = ntfs_resident_attr_resize(na, newsize);
5062 out:
5063 	ntfs_log_leave("Return status %d\n", ret);
5064 	return ret;
5065 }
5066 
5067 /**
5068  * ntfs_attr_readall - read the entire data from an ntfs attribute
5069  * @ni:		open ntfs inode in which the ntfs attribute resides
5070  * @type:	attribute type
5071  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
5072  * @name_len:	length of attribute @name in Unicode characters (if @name given)
5073  * @data_size:	if non-NULL then store here the data size
5074  *
5075  * This function will read the entire content of an ntfs attribute.
5076  * If @name is AT_UNNAMED then look specifically for an unnamed attribute.
5077  * If @name is NULL then the attribute could be either named or not.
5078  * In both those cases @name_len is not used at all.
5079  *
5080  * On success a buffer is allocated with the content of the attribute
5081  * and which needs to be freed when it's not needed anymore. If the
5082  * @data_size parameter is non-NULL then the data size is set there.
5083  *
5084  * On error NULL is returned with errno set to the error code.
5085  */
5086 void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type,
5087 			ntfschar *name, u32 name_len, s64 *data_size)
5088 {
5089 	ntfs_attr *na;
5090 	void *data, *ret = NULL;
5091 	s64 size;
5092 
5093 	ntfs_log_enter("Entering\n");
5094 
5095 	na = ntfs_attr_open(ni, type, name, name_len);
5096 	if (!na) {
5097 		ntfs_log_perror("ntfs_attr_open failed");
5098 		goto err_exit;
5099 	}
5100 	data = ntfs_malloc(na->data_size);
5101 	if (!data)
5102 		goto out;
5103 
5104 	size = ntfs_attr_pread(na, 0, na->data_size, data);
5105 	if (size != na->data_size) {
5106 		ntfs_log_perror("ntfs_attr_pread failed");
5107 		free(data);
5108 		goto out;
5109 	}
5110 	ret = data;
5111 	if (data_size)
5112 		*data_size = size;
5113 out:
5114 	ntfs_attr_close(na);
5115 err_exit:
5116 	ntfs_log_leave("\n");
5117 	return ret;
5118 }
5119 
5120 
5121 
5122 int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name,
5123 		    u32 name_len)
5124 {
5125 	ntfs_attr_search_ctx *ctx;
5126 	int ret;
5127 
5128 	ntfs_log_trace("Entering\n");
5129 
5130 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
5131 	if (!ctx)
5132 		return 0;
5133 
5134 	ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, 0, NULL, 0,
5135 			       ctx);
5136 
5137 	ntfs_attr_put_search_ctx(ctx);
5138 
5139 	return !ret;
5140 }
5141 
5142 int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name,
5143 		     u32 name_len)
5144 {
5145 	ntfs_attr *na;
5146 	int ret;
5147 
5148 	ntfs_log_trace("Entering\n");
5149 
5150 	if (!ni) {
5151 		ntfs_log_error("%s: NULL inode pointer", __FUNCTION__);
5152 		errno = EINVAL;
5153 		return -1;
5154 	}
5155 
5156 	na = ntfs_attr_open(ni, type, name, name_len);
5157 	if (!na) {
5158 		ntfs_log_perror("Failed to open attribute 0x%02x of inode "
5159 				"0x%llx", type, (unsigned long long)ni->mft_no);
5160 		return -1;
5161 	}
5162 
5163 	ret = ntfs_attr_rm(na);
5164 	if (ret)
5165 		ntfs_log_perror("Failed to remove attribute 0x%02x of inode "
5166 				"0x%llx", type, (unsigned long long)ni->mft_no);
5167 	ntfs_attr_close(na);
5168 
5169 	return ret;
5170 }
5171 
5172 /* Below macros are 32-bit ready. */
5173 #define BCX(x) ((x) - (((x) >> 1) & 0x77777777) - \
5174 		      (((x) >> 2) & 0x33333333) - \
5175 		      (((x) >> 3) & 0x11111111))
5176 #define BITCOUNT(x) (((BCX(x) + (BCX(x) >> 4)) & 0x0F0F0F0F) % 255)
5177 
5178 static u8 *ntfs_init_lut256(void)
5179 {
5180 	int i;
5181 	u8 *lut;
5182 
5183 	lut = ntfs_malloc(256);
5184 	if (lut)
5185 		for(i = 0; i < 256; i++)
5186 			*(lut + i) = 8 - BITCOUNT(i);
5187 	return lut;
5188 }
5189 
5190 s64 ntfs_attr_get_free_bits(ntfs_attr *na)
5191 {
5192 	u8 *buf, *lut;
5193 	s64 br      = 0;
5194 	s64 total   = 0;
5195 	s64 nr_free = 0;
5196 
5197 	lut = ntfs_init_lut256();
5198 	if (!lut)
5199 		return -1;
5200 
5201 	buf = ntfs_malloc(65536);
5202 	if (!buf)
5203 		goto out;
5204 
5205 	while (1) {
5206 		u32 *p;
5207 		br = ntfs_attr_pread(na, total, 65536, buf);
5208 		if (br <= 0)
5209 			break;
5210 		total += br;
5211 		p = (u32 *)buf + br / 4 - 1;
5212 		for (; (u8 *)p >= buf; p--) {
5213 			nr_free += lut[ *p        & 255] +
5214 			           lut[(*p >>  8) & 255] +
5215 			           lut[(*p >> 16) & 255] +
5216 			           lut[(*p >> 24)      ];
5217 		}
5218 		switch (br % 4) {
5219 			case 3:  nr_free += lut[*(buf + br - 3)];
5220 			case 2:  nr_free += lut[*(buf + br - 2)];
5221 			case 1:  nr_free += lut[*(buf + br - 1)];
5222 		}
5223 	}
5224 	free(buf);
5225 out:
5226 	free(lut);
5227 	if (!total || br < 0)
5228 		return -1;
5229 	return nr_free;
5230 }
5231 
5232