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