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