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