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