1/**
2 * inode.c - Inode handling code. Originated from the Linux-NTFS project.
3 *
4 * Copyright (c) 2002-2005 Anton Altaparmakov
5 * Copyright (c) 2002-2008 Szabolcs Szakacsits
6 * Copyright (c) 2004-2007 Yura Pakhuchiy
7 * Copyright (c) 2004-2005 Richard Russon
8 * Copyright (c) 2009-2010 Jean-Pierre Andre
9 *
10 * This program/include file is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as published
12 * by the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program/include file is distributed in the hope that it will be
16 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program (in the main directory of the NTFS-3G
22 * distribution in the file COPYING); if not, write to the Free Software
23 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 */
25
26#ifdef HAVE_CONFIG_H
27#include "config.h"
28#endif
29
30#ifdef HAVE_STDLIB_H
31#include <stdlib.h>
32#endif
33#ifdef HAVE_STRING_H
34#include <string.h>
35#endif
36#ifdef HAVE_ERRNO_H
37#include <errno.h>
38#endif
39
40#include "param.h"
41#include "compat.h"
42#include "types.h"
43#include "volume.h"
44#include "cache.h"
45#include "inode.h"
46#include "attrib.h"
47#include "debug.h"
48#include "mft.h"
49#include "attrlist.h"
50#include "runlist.h"
51#include "lcnalloc.h"
52#include "index.h"
53#include "dir.h"
54#include "ntfstime.h"
55#include "logging.h"
56#include "misc.h"
57#include "xattrs.h"
58
59ntfs_inode *ntfs_inode_base(ntfs_inode *ni)
60{
61	if (ni->nr_extents == -1)
62		return ni->base_ni;
63	return ni;
64}
65
66/**
67 * ntfs_inode_mark_dirty - set the inode (and its base inode if it exists) dirty
68 * @ni:		ntfs inode to set dirty
69 *
70 * Set the inode @ni dirty so it is written out later (at the latest at
71 * ntfs_inode_close() time). If @ni is an extent inode, set the base inode
72 * dirty, too.
73 *
74 * This function cannot fail.
75 */
76void ntfs_inode_mark_dirty(ntfs_inode *ni)
77{
78	NInoSetDirty(ni);
79	if (ni->nr_extents == -1)
80		NInoSetDirty(ni->base_ni);
81}
82
83/**
84 * __ntfs_inode_allocate - Create and initialise an NTFS inode object
85 * @vol:
86 *
87 * Description...
88 *
89 * Returns:
90 */
91static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol)
92{
93	ntfs_inode *ni;
94
95	ni = (ntfs_inode*)ntfs_calloc(sizeof(ntfs_inode));
96	if (ni)
97		ni->vol = vol;
98	return ni;
99}
100
101/**
102 * ntfs_inode_allocate - Create an NTFS inode object
103 * @vol:
104 *
105 * Description...
106 *
107 * Returns:
108 */
109ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol)
110{
111	return __ntfs_inode_allocate(vol);
112}
113
114/**
115 * __ntfs_inode_release - Destroy an NTFS inode object
116 * @ni:
117 *
118 * Description...
119 *
120 * Returns:
121 */
122static void __ntfs_inode_release(ntfs_inode *ni)
123{
124	if (NInoDirty(ni))
125		ntfs_log_error("Releasing dirty inode %lld!\n",
126			       (long long)ni->mft_no);
127	if (NInoAttrList(ni) && ni->attr_list)
128		free(ni->attr_list);
129	free(ni->mrec);
130	free(ni);
131	return;
132}
133
134/**
135 * ntfs_inode_open - open an inode ready for access
136 * @vol:	volume to get the inode from
137 * @mref:	inode number / mft record number to open
138 *
139 * Allocate an ntfs_inode structure and initialize it for the given inode
140 * specified by @mref. @mref specifies the inode number / mft record to read,
141 * including the sequence number, which can be 0 if no sequence number checking
142 * is to be performed.
143 *
144 * Then, allocate a buffer for the mft record, read the mft record from the
145 * volume @vol, and attach it to the ntfs_inode structure (->mrec). The
146 * mft record is mst deprotected and sanity checked for validity and we abort
147 * if deprotection or checks fail.
148 *
149 * Finally, search for an attribute list attribute in the mft record and if one
150 * is found, load the attribute list attribute value and attach it to the
151 * ntfs_inode structure (->attr_list). Also set the NI_AttrList bit to indicate
152 * this.
153 *
154 * Return a pointer to the ntfs_inode structure on success or NULL on error,
155 * with errno set to the error code.
156 */
157static ntfs_inode *ntfs_inode_real_open(ntfs_volume *vol, const MFT_REF mref)
158{
159	s64 l;
160	ntfs_inode *ni = NULL;
161	ntfs_attr_search_ctx *ctx;
162	STANDARD_INFORMATION *std_info;
163	le32 lthle;
164	int olderrno;
165
166	ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref));
167	if (!vol) {
168		errno = EINVAL;
169		goto out;
170	}
171	ni = __ntfs_inode_allocate(vol);
172	if (!ni)
173		goto out;
174	if (ntfs_file_record_read(vol, mref, &ni->mrec, NULL))
175		goto err_out;
176	if (!(ni->mrec->flags & MFT_RECORD_IN_USE)) {
177		errno = ENOENT;
178		goto err_out;
179	}
180	ni->mft_no = MREF(mref);
181	ctx = ntfs_attr_get_search_ctx(ni, NULL);
182	if (!ctx)
183		goto err_out;
184	/* Receive some basic information about inode. */
185	if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED,
186				0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
187		if (!ni->mrec->base_mft_record)
188			ntfs_log_perror("No STANDARD_INFORMATION in base record"
189					" %lld", (long long)MREF(mref));
190		goto put_err_out;
191	}
192	lthle = ctx->attr->value_length;
193	if (le32_to_cpu(lthle) < offsetof(STANDARD_INFORMATION, owner_id)) {
194		ntfs_log_error("Corrupt STANDARD_INFORMATION in base"
195			" record %lld\n",
196			(long long)MREF(mref));
197		goto put_err_out;
198	}
199	std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr +
200			le16_to_cpu(ctx->attr->value_offset));
201	ni->flags = std_info->file_attributes;
202	ni->creation_time = std_info->creation_time;
203	ni->last_data_change_time = std_info->last_data_change_time;
204	ni->last_mft_change_time = std_info->last_mft_change_time;
205	ni->last_access_time = std_info->last_access_time;
206		/* Insert v3 extensions if present */
207		/* length may be seen as 48 (v1.x) or 72 (v3.x) */
208	if (le32_to_cpu(lthle) >= offsetof(STANDARD_INFORMATION, v3_end)) {
209		set_nino_flag(ni, v3_Extensions);
210		ni->owner_id = std_info->owner_id;
211		ni->security_id = std_info->security_id;
212		ni->quota_charged = std_info->quota_charged;
213		ni->usn = std_info->usn;
214	} else {
215		clear_nino_flag(ni, v3_Extensions);
216		ni->owner_id = const_cpu_to_le32(0);
217		ni->security_id = const_cpu_to_le32(0);
218	}
219	/* Set attribute list information. */
220	olderrno = errno;
221	if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0,
222			CASE_SENSITIVE, 0, NULL, 0, ctx)) {
223		if (errno != ENOENT)
224			goto put_err_out;
225		/* Attribute list attribute does not present. */
226		/* restore previous errno to avoid misinterpretation */
227		errno = olderrno;
228		goto get_size;
229	}
230	NInoSetAttrList(ni);
231	l = ntfs_get_attribute_value_length(ctx->attr);
232	if (!l)
233		goto put_err_out;
234	if ((u64)l > 0x40000) {
235		errno = EIO;
236		ntfs_log_perror("Too large attrlist attribute (%llu), inode "
237				"%lld", (long long)l, (long long)MREF(mref));
238		goto put_err_out;
239	}
240	ni->attr_list_size = l;
241	ni->attr_list = ntfs_malloc(ni->attr_list_size);
242	if (!ni->attr_list)
243		goto put_err_out;
244	l = ntfs_get_attribute_value(vol, ctx->attr, ni->attr_list);
245	if (!l)
246		goto put_err_out;
247	if (l != ni->attr_list_size) {
248		errno = EIO;
249		ntfs_log_perror("Unexpected attrlist size (%lld <> %u), inode "
250				"%lld", (long long)l, ni->attr_list_size,
251				(long long)MREF(mref));
252		goto put_err_out;
253	}
254get_size:
255	olderrno = errno;
256	if (ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) {
257		if (errno != ENOENT)
258			goto put_err_out;
259		/* Directory or special file. */
260		/* restore previous errno to avoid misinterpretation */
261		errno = olderrno;
262		ni->data_size = ni->allocated_size = 0;
263	} else {
264		if (ctx->attr->non_resident) {
265			ni->data_size = sle64_to_cpu(ctx->attr->data_size);
266			if (ctx->attr->flags &
267					(ATTR_IS_COMPRESSED | ATTR_IS_SPARSE))
268				ni->allocated_size = sle64_to_cpu(
269						ctx->attr->compressed_size);
270			else
271				ni->allocated_size = sle64_to_cpu(
272						ctx->attr->allocated_size);
273		} else {
274			ni->data_size = le32_to_cpu(ctx->attr->value_length);
275			ni->allocated_size = (ni->data_size + 7) & ~7;
276		}
277		set_nino_flag(ni,KnownSize);
278	}
279	ntfs_attr_put_search_ctx(ctx);
280out:
281	ntfs_log_leave("\n");
282	return ni;
283
284put_err_out:
285	ntfs_attr_put_search_ctx(ctx);
286err_out:
287	__ntfs_inode_release(ni);
288	ni = NULL;
289	goto out;
290}
291
292/**
293 * ntfs_inode_close - close an ntfs inode and free all associated memory
294 * @ni:		ntfs inode to close
295 *
296 * Make sure the ntfs inode @ni is clean.
297 *
298 * If the ntfs inode @ni is a base inode, close all associated extent inodes,
299 * then deallocate all memory attached to it, and finally free the ntfs inode
300 * structure itself.
301 *
302 * If it is an extent inode, we disconnect it from its base inode before we
303 * destroy it.
304 *
305 * It is OK to pass NULL to this function, it is just noop in this case.
306 *
307 * Return 0 on success or -1 on error with errno set to the error code. On
308 * error, @ni has not been freed. The user should attempt to handle the error
309 * and call ntfs_inode_close() again. The following error codes are defined:
310 *
311 *	EBUSY	@ni and/or its attribute list runlist is/are dirty and the
312 *		attempt to write it/them to disk failed.
313 *	EINVAL	@ni is invalid (probably it is an extent inode).
314 *	EIO	I/O error while trying to write inode to disk.
315 */
316
317int ntfs_inode_real_close(ntfs_inode *ni)
318{
319	int ret = -1;
320
321	if (!ni)
322		return 0;
323
324	ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no);
325
326	/* If we have dirty metadata, write it out. */
327	if (NInoDirty(ni) || NInoAttrListDirty(ni)) {
328		if (ntfs_inode_sync(ni)) {
329			if (errno != EIO)
330				errno = EBUSY;
331			goto err;
332		}
333	}
334	/* Is this a base inode with mapped extent inodes? */
335	if (ni->nr_extents > 0) {
336		while (ni->nr_extents > 0) {
337			if (ntfs_inode_real_close(ni->extent_nis[0])) {
338				if (errno != EIO)
339					errno = EBUSY;
340				goto err;
341			}
342		}
343	} else if (ni->nr_extents == -1) {
344		ntfs_inode **tmp_nis;
345		ntfs_inode *base_ni;
346		s32 i;
347
348		/*
349		 * If the inode is an extent inode, disconnect it from the
350		 * base inode before destroying it.
351		 */
352		base_ni = ni->base_ni;
353		for (i = 0; i < base_ni->nr_extents; ++i) {
354			tmp_nis = base_ni->extent_nis;
355			if (tmp_nis[i] != ni)
356				continue;
357			/* Found it. Disconnect. */
358			memmove(tmp_nis + i, tmp_nis + i + 1,
359					(base_ni->nr_extents - i - 1) *
360					sizeof(ntfs_inode *));
361			/* Buffer should be for multiple of four extents. */
362			if ((--base_ni->nr_extents) & 3) {
363				i = -1;
364				break;
365			}
366			/*
367			 * ElectricFence is unhappy with realloc(x,0) as free(x)
368			 * thus we explicitly separate these two cases.
369			 */
370			if (base_ni->nr_extents) {
371				/* Resize the memory buffer. */
372				tmp_nis = realloc(tmp_nis, base_ni->nr_extents *
373						  sizeof(ntfs_inode *));
374				/* Ignore errors, they don't really matter. */
375				if (tmp_nis)
376					base_ni->extent_nis = tmp_nis;
377			} else if (tmp_nis) {
378				free(tmp_nis);
379				base_ni->extent_nis = (ntfs_inode**)NULL;
380			}
381			/* Allow for error checking. */
382			i = -1;
383			break;
384		}
385
386		/*
387		 *  We could successfully sync, so only log this error
388		 *  and try to sync other inode extents too.
389		 */
390		if (i != -1)
391			ntfs_log_error("Extent inode %lld was not found\n",
392				       (long long)ni->mft_no);
393	}
394
395	__ntfs_inode_release(ni);
396	ret = 0;
397err:
398	ntfs_log_leave("\n");
399	return ret;
400}
401
402#if CACHE_NIDATA_SIZE
403
404/*
405 *		Free an inode structure when there is not more space
406 *	in the cache
407 */
408
409void ntfs_inode_nidata_free(const struct CACHED_GENERIC *cached)
410{
411        ntfs_inode_real_close(((const struct CACHED_NIDATA*)cached)->ni);
412}
413
414/*
415 *		Compute a hash value for an inode entry
416 */
417
418int ntfs_inode_nidata_hash(const struct CACHED_GENERIC *item)
419{
420	return (((const struct CACHED_NIDATA*)item)->inum
421			% (2*CACHE_NIDATA_SIZE));
422}
423
424/*
425 *		inum comparing for entering/fetching from cache
426 */
427
428static int idata_cache_compare(const struct CACHED_GENERIC *cached,
429			const struct CACHED_GENERIC *wanted)
430{
431	return (((const struct CACHED_NIDATA*)cached)->inum
432			!= ((const struct CACHED_NIDATA*)wanted)->inum);
433}
434
435/*
436 *		Invalidate an inode entry when not needed anymore.
437 *	The entry should have been synced, it may be reused later,
438 *	if it is requested before it is dropped from cache.
439 */
440
441void ntfs_inode_invalidate(ntfs_volume *vol, const MFT_REF mref)
442{
443	struct CACHED_NIDATA item;
444
445	item.inum = MREF(mref);
446	item.ni = (ntfs_inode*)NULL;
447	item.pathname = (const char*)NULL;
448	item.varsize = 0;
449	ntfs_invalidate_cache(vol->nidata_cache,
450				GENERIC(&item),idata_cache_compare,CACHE_FREE);
451}
452
453#endif
454
455/*
456 *		Open an inode
457 *
458 *	When possible, an entry recorded in the cache is reused
459 *
460 *	**NEVER REOPEN** an inode, this can lead to a duplicated
461 * 	cache entry (hard to detect), and to an obsolete one being
462 *	reused. System files are however protected from being cached.
463 */
464
465ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref)
466{
467	ntfs_inode *ni;
468#if CACHE_NIDATA_SIZE
469	struct CACHED_NIDATA item;
470	struct CACHED_NIDATA *cached;
471
472		/* fetch idata from cache */
473	item.inum = MREF(mref);
474	debug_double_inode(item.inum,1);
475	item.pathname = (const char*)NULL;
476	item.varsize = 0;
477	cached = (struct CACHED_NIDATA*)ntfs_fetch_cache(vol->nidata_cache,
478				GENERIC(&item),idata_cache_compare);
479	if (cached) {
480		ni = cached->ni;
481		/* do not keep open entries in cache */
482		ntfs_remove_cache(vol->nidata_cache,
483				(struct CACHED_GENERIC*)cached,0);
484	} else {
485		ni = ntfs_inode_real_open(vol, mref);
486	}
487	if (!ni) {
488		debug_double_inode(item.inum, 0);
489	}
490#else
491	ni = ntfs_inode_real_open(vol, mref);
492#endif
493	return (ni);
494}
495
496/*
497 *		Close an inode entry
498 *
499 *	If cacheing is in use, the entry is synced and kept available
500 *	in cache for further use.
501 *
502 *	System files (inode < 16 or having the IS_4 flag) are protected
503 *	against being cached.
504 */
505
506int ntfs_inode_close(ntfs_inode *ni)
507{
508	int res;
509#if CACHE_NIDATA_SIZE
510	BOOL dirty;
511	struct CACHED_NIDATA item;
512
513	if (ni) {
514		debug_double_inode(ni->mft_no,0);
515		/* do not cache system files : could lead to double entries */
516		if (ni->vol && ni->vol->nidata_cache
517			&& ((ni->mft_no == FILE_root)
518			    || ((ni->mft_no >= FILE_first_user)
519				&& !(ni->mrec->flags & MFT_RECORD_IS_4)))) {
520			/* If we have dirty metadata, write it out. */
521			dirty = NInoDirty(ni) || NInoAttrListDirty(ni);
522			if (dirty) {
523				res = ntfs_inode_sync(ni);
524					/* do a real close if sync failed */
525				if (res)
526					ntfs_inode_real_close(ni);
527			} else
528				res = 0;
529
530			if (!res) {
531					/* feed idata into cache */
532				item.inum = ni->mft_no;
533				item.ni = ni;
534				item.pathname = (const char*)NULL;
535				item.varsize = 0;
536				debug_cached_inode(ni);
537#if defined(__HAIKU__)
538				if (ntfs_fetch_cache(ni->vol->nidata_cache,
539						GENERIC(&item), idata_cache_compare)) {
540					panic("ntfs_inode_close: %llu already in cache!", ni->mft_no);
541				}
542#endif
543				ntfs_enter_cache(ni->vol->nidata_cache,
544					GENERIC(&item), idata_cache_compare);
545			}
546		} else {
547			/* cache not ready or system file, really close */
548			res = ntfs_inode_real_close(ni);
549		}
550	} else
551		res = 0;
552#else
553	res = ntfs_inode_real_close(ni);
554#endif
555	return (res);
556}
557
558/**
559 * ntfs_extent_inode_open - load an extent inode and attach it to its base
560 * @base_ni:	base ntfs inode
561 * @mref:	mft reference of the extent inode to load (in little endian)
562 *
563 * First check if the extent inode @mref is already attached to the base ntfs
564 * inode @base_ni, and if so, return a pointer to the attached extent inode.
565 *
566 * If the extent inode is not already attached to the base inode, allocate an
567 * ntfs_inode structure and initialize it for the given inode @mref. @mref
568 * specifies the inode number / mft record to read, including the sequence
569 * number, which can be 0 if no sequence number checking is to be performed.
570 *
571 * Then, allocate a buffer for the mft record, read the mft record from the
572 * volume @base_ni->vol, and attach it to the ntfs_inode structure (->mrec).
573 * The mft record is mst deprotected and sanity checked for validity and we
574 * abort if deprotection or checks fail.
575 *
576 * Finally attach the ntfs inode to its base inode @base_ni and return a
577 * pointer to the ntfs_inode structure on success or NULL on error, with errno
578 * set to the error code.
579 *
580 * Note, extent inodes are never closed directly. They are automatically
581 * disposed off by the closing of the base inode.
582 */
583ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, const leMFT_REF mref)
584{
585	u64 mft_no = MREF_LE(mref);
586	VCN extent_vcn;
587	runlist_element *rl;
588	ntfs_volume *vol;
589	ntfs_inode *ni = NULL;
590	ntfs_inode **extent_nis;
591	int i;
592
593	if (!base_ni) {
594		errno = EINVAL;
595		ntfs_log_perror("%s", __FUNCTION__);
596		return NULL;
597	}
598
599	ntfs_log_enter("Opening extent inode %lld (base mft record %lld).\n",
600			(unsigned long long)mft_no,
601			(unsigned long long)base_ni->mft_no);
602
603	if (!base_ni->mft_no) {
604			/*
605			 * When getting extents of MFT, we must be sure
606			 * they are in the MFT part which has already
607			 * been mapped, otherwise we fall into an endless
608			 * recursion.
609			 * Situations have been met where extents locations
610			 * are described in themselves.
611			 * This is a severe error which chkdsk cannot fix.
612			 */
613		vol = base_ni->vol;
614		extent_vcn = mft_no << vol->mft_record_size_bits
615				>> vol->cluster_size_bits;
616		rl = vol->mft_na->rl;
617		if (rl) {
618			while (rl->length
619			    && ((rl->vcn + rl->length) <= extent_vcn))
620				rl++;
621		}
622		if (!rl || (rl->lcn < 0)) {
623			ntfs_log_error("MFT is corrupt, cannot read"
624				" its unmapped extent record %lld\n",
625					(long long)mft_no);
626			ntfs_log_error("Note : chkdsk cannot fix this,"
627				" try ntfsfix\n");
628			errno = EIO;
629			ni = (ntfs_inode*)NULL;
630			goto out;
631		}
632	}
633
634	/* Is the extent inode already open and attached to the base inode? */
635	if (base_ni->nr_extents > 0) {
636		extent_nis = base_ni->extent_nis;
637		for (i = 0; i < base_ni->nr_extents; i++) {
638			u16 seq_no;
639
640			ni = extent_nis[i];
641			if (mft_no != ni->mft_no)
642				continue;
643			/* Verify the sequence number if given. */
644			seq_no = MSEQNO_LE(mref);
645			if (seq_no && seq_no != le16_to_cpu(
646					ni->mrec->sequence_number)) {
647				errno = EIO;
648				ntfs_log_perror("Found stale extent mft "
649					"reference mft=%lld",
650					(long long)ni->mft_no);
651				goto out;
652			}
653			goto out;
654		}
655	}
656	/* Wasn't there, we need to load the extent inode. */
657	ni = __ntfs_inode_allocate(base_ni->vol);
658	if (!ni)
659		goto out;
660	if (ntfs_file_record_read(base_ni->vol, le64_to_cpu(mref), &ni->mrec, NULL))
661		goto err_out;
662	ni->mft_no = mft_no;
663	ni->nr_extents = -1;
664	ni->base_ni = base_ni;
665	/* Attach extent inode to base inode, reallocating memory if needed. */
666	if (!(base_ni->nr_extents & 3)) {
667		i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
668
669		extent_nis = ntfs_malloc(i);
670		if (!extent_nis)
671			goto err_out;
672		if (base_ni->nr_extents) {
673			memcpy(extent_nis, base_ni->extent_nis,
674					i - 4 * sizeof(ntfs_inode *));
675			free(base_ni->extent_nis);
676		}
677		base_ni->extent_nis = extent_nis;
678	}
679	base_ni->extent_nis[base_ni->nr_extents++] = ni;
680out:
681	ntfs_log_leave("\n");
682	return ni;
683err_out:
684	__ntfs_inode_release(ni);
685	ni = NULL;
686	goto out;
687}
688
689/**
690 * ntfs_inode_attach_all_extents - attach all extents for target inode
691 * @ni:		opened ntfs inode for which perform attach
692 *
693 * Return 0 on success and -1 on error with errno set to the error code.
694 */
695int ntfs_inode_attach_all_extents(ntfs_inode *ni)
696{
697	ATTR_LIST_ENTRY *ale;
698	u64 prev_attached = 0;
699
700	if (!ni) {
701		ntfs_log_trace("Invalid arguments.\n");
702		errno = EINVAL;
703		return -1;
704	}
705
706	if (ni->nr_extents == -1)
707		ni = ni->base_ni;
708
709	ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no);
710
711	/* Inode haven't got attribute list, thus nothing to attach. */
712	if (!NInoAttrList(ni))
713		return 0;
714
715	if (!ni->attr_list) {
716		ntfs_log_trace("Corrupt in-memory struct.\n");
717		errno = EINVAL;
718		return -1;
719	}
720
721	/* Walk through attribute list and attach all extents. */
722	errno = 0;
723	ale = (ATTR_LIST_ENTRY *)ni->attr_list;
724	while ((u8*)ale < ni->attr_list + ni->attr_list_size) {
725		if (ni->mft_no != MREF_LE(ale->mft_reference) &&
726				prev_attached != MREF_LE(ale->mft_reference)) {
727			if (!ntfs_extent_inode_open(ni, ale->mft_reference)) {
728				ntfs_log_trace("Couldn't attach extent inode.\n");
729				return -1;
730			}
731			prev_attached = MREF_LE(ale->mft_reference);
732		}
733		ale = (ATTR_LIST_ENTRY *)((u8*)ale + le16_to_cpu(ale->length));
734	}
735	return 0;
736}
737
738/**
739 * ntfs_inode_sync_standard_information - update standard information attribute
740 * @ni:		ntfs inode to update standard information
741 *
742 * Return 0 on success or -1 on error with errno set to the error code.
743 */
744static int ntfs_inode_sync_standard_information(ntfs_inode *ni)
745{
746	ntfs_attr_search_ctx *ctx;
747	STANDARD_INFORMATION *std_info;
748	u32 lth;
749	le32 lthle;
750
751	ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no);
752
753	ctx = ntfs_attr_get_search_ctx(ni, NULL);
754	if (!ctx)
755		return -1;
756	if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED,
757			     0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
758		ntfs_log_perror("Failed to sync standard info (inode %lld)",
759				(long long)ni->mft_no);
760		ntfs_attr_put_search_ctx(ctx);
761		return -1;
762	}
763	std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr +
764			le16_to_cpu(ctx->attr->value_offset));
765	std_info->file_attributes = ni->flags;
766	if (!test_nino_flag(ni, TimesSet)) {
767		std_info->creation_time = ni->creation_time;
768		std_info->last_data_change_time = ni->last_data_change_time;
769		std_info->last_mft_change_time = ni->last_mft_change_time;
770		std_info->last_access_time = ni->last_access_time;
771	}
772
773		/* JPA update v3.x extensions, ensuring consistency */
774
775	lthle = ctx->attr->value_length;
776	lth = le32_to_cpu(lthle);
777	if (test_nino_flag(ni, v3_Extensions)
778	    && (lth < offsetof(STANDARD_INFORMATION, v3_end)))
779		ntfs_log_error("bad sync of standard information\n");
780
781	if (lth >= offsetof(STANDARD_INFORMATION, v3_end)) {
782		std_info->owner_id = ni->owner_id;
783		std_info->security_id = ni->security_id;
784		std_info->quota_charged = ni->quota_charged;
785		std_info->usn = ni->usn;
786	}
787	ntfs_inode_mark_dirty(ctx->ntfs_ino);
788	ntfs_attr_put_search_ctx(ctx);
789	return 0;
790}
791
792/**
793 * ntfs_inode_sync_file_name - update FILE_NAME attributes
794 * @ni:		ntfs inode to update FILE_NAME attributes
795 *
796 * Update all FILE_NAME attributes for inode @ni in the index.
797 *
798 * Return 0 on success or -1 on error with errno set to the error code.
799 */
800static int ntfs_inode_sync_file_name(ntfs_inode *ni, ntfs_inode *dir_ni)
801{
802	ntfs_attr_search_ctx *ctx = NULL;
803	ntfs_index_context *ictx;
804	ntfs_inode *index_ni;
805	FILE_NAME_ATTR *fn;
806	FILE_NAME_ATTR *fnx;
807	REPARSE_POINT *rpp;
808	le32 reparse_tag;
809	int err = 0;
810
811	ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no);
812
813	ctx = ntfs_attr_get_search_ctx(ni, NULL);
814	if (!ctx) {
815		err = errno;
816		goto err_out;
817	}
818	/* Collect the reparse tag, if any */
819	reparse_tag = const_cpu_to_le32(0);
820	if (ni->flags & FILE_ATTR_REPARSE_POINT) {
821		if (!ntfs_attr_lookup(AT_REPARSE_POINT, NULL,
822				0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
823			rpp = (REPARSE_POINT*)((u8 *)ctx->attr +
824					le16_to_cpu(ctx->attr->value_offset));
825			reparse_tag = rpp->reparse_tag;
826		}
827		ntfs_attr_reinit_search_ctx(ctx);
828	}
829	/* Walk through all FILE_NAME attributes and update them. */
830	while (!ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0, ctx)) {
831		fn = (FILE_NAME_ATTR *)((u8 *)ctx->attr +
832				le16_to_cpu(ctx->attr->value_offset));
833		if (MREF_LE(fn->parent_directory) == ni->mft_no) {
834			/*
835			 * WARNING: We cheat here and obtain 2 attribute
836			 * search contexts for one inode (first we obtained
837			 * above, second will be obtained inside
838			 * ntfs_index_lookup), it's acceptable for library,
839			 * but will deadlock in the kernel.
840			 */
841			index_ni = ni;
842		} else
843			if (dir_ni)
844				index_ni = dir_ni;
845			else
846				index_ni = ntfs_inode_open(ni->vol,
847					le64_to_cpu(fn->parent_directory));
848		if (!index_ni) {
849			if (!err)
850				err = errno;
851			ntfs_log_perror("Failed to open inode %lld with index",
852				(long long)MREF_LE(fn->parent_directory));
853			continue;
854		}
855		ictx = ntfs_index_ctx_get(index_ni, NTFS_INDEX_I30, 4);
856		if (!ictx) {
857			if (!err)
858				err = errno;
859			ntfs_log_perror("Failed to get index ctx, inode %lld",
860					(long long)index_ni->mft_no);
861			if ((ni != index_ni) && !dir_ni
862			    && ntfs_inode_close(index_ni) && !err)
863				err = errno;
864			continue;
865		}
866		if (ntfs_index_lookup(fn, sizeof(FILE_NAME_ATTR), ictx)) {
867			if (!err) {
868				if (errno == ENOENT)
869					err = EIO;
870				else
871					err = errno;
872			}
873			ntfs_log_perror("Index lookup failed, inode %lld",
874					(long long)index_ni->mft_no);
875			ntfs_index_ctx_put(ictx);
876			if (ni != index_ni && ntfs_inode_close(index_ni) && !err)
877				err = errno;
878			continue;
879		}
880		/* Update flags and file size. */
881		fnx = (FILE_NAME_ATTR *)ictx->data;
882		fnx->file_attributes =
883				(fnx->file_attributes & ~FILE_ATTR_VALID_FLAGS) |
884				(ni->flags & FILE_ATTR_VALID_FLAGS);
885		if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)
886			fnx->data_size = fnx->allocated_size
887				= const_cpu_to_sle64(0);
888		else {
889			fnx->allocated_size = cpu_to_sle64(ni->allocated_size);
890			fnx->data_size = cpu_to_sle64(ni->data_size);
891			/*
892			 * The file name record has also to be fixed if some
893			 * attribute update implied the unnamed data to be
894			 * made non-resident
895			 */
896			fn->allocated_size = fnx->allocated_size;
897		}
898			/* update or clear the reparse tag in the index */
899		fnx->reparse_point_tag = reparse_tag;
900		if (!test_nino_flag(ni, TimesSet)) {
901			fnx->creation_time = ni->creation_time;
902			fnx->last_data_change_time = ni->last_data_change_time;
903			fnx->last_mft_change_time = ni->last_mft_change_time;
904			fnx->last_access_time = ni->last_access_time;
905		} else {
906			fnx->creation_time = fn->creation_time;
907			fnx->last_data_change_time = fn->last_data_change_time;
908			fnx->last_mft_change_time = fn->last_mft_change_time;
909			fnx->last_access_time = fn->last_access_time;
910		}
911		ntfs_index_entry_mark_dirty(ictx);
912		ntfs_index_ctx_put(ictx);
913		if ((ni != index_ni) && !dir_ni
914		    && ntfs_inode_close(index_ni) && !err)
915			err = errno;
916	}
917	/* Check for real error occurred. */
918	if (errno != ENOENT) {
919		err = errno;
920		ntfs_log_perror("Attribute lookup failed, inode %lld",
921				(long long)ni->mft_no);
922		goto err_out;
923	}
924	ntfs_attr_put_search_ctx(ctx);
925	if (err) {
926		errno = err;
927		return -1;
928	}
929	return 0;
930err_out:
931	if (ctx)
932		ntfs_attr_put_search_ctx(ctx);
933	errno = err;
934	return -1;
935}
936
937/**
938 * ntfs_inode_sync - write the inode (and its dirty extents) to disk
939 * @ni:		ntfs inode to write
940 *
941 * Write the inode @ni to disk as well as its dirty extent inodes if such
942 * exist and @ni is a base inode. If @ni is an extent inode, only @ni is
943 * written completely disregarding its base inode and any other extent inodes.
944 *
945 * For a base inode with dirty extent inodes if any writes fail for whatever
946 * reason, the failing inode is skipped and the sync process is continued. At
947 * the end the error condition that brought about the failure is returned. Thus
948 * the smallest amount of data loss possible occurs.
949 *
950 * Return 0 on success or -1 on error with errno set to the error code.
951 * The following error codes are defined:
952 *	EINVAL	- Invalid arguments were passed to the function.
953 *	EBUSY	- Inode and/or one of its extents is busy, try again later.
954 *	EIO	- I/O error while writing the inode (or one of its extents).
955 */
956static int ntfs_inode_sync_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni)
957{
958	int ret = 0;
959	int err = 0;
960	if (!ni) {
961		errno = EINVAL;
962		ntfs_log_error("Failed to sync NULL inode\n");
963		return -1;
964	}
965
966	ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no);
967
968	/* Update STANDARD_INFORMATION. */
969	if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 &&
970			ntfs_inode_sync_standard_information(ni)) {
971		if (!err || errno == EIO) {
972			err = errno;
973			if (err != EIO)
974				err = EBUSY;
975		}
976	}
977
978	/* Update FILE_NAME's in the index. */
979	if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 &&
980			NInoFileNameTestAndClearDirty(ni) &&
981			ntfs_inode_sync_file_name(ni, dir_ni)) {
982		if (!err || errno == EIO) {
983			err = errno;
984			if (err != EIO)
985				err = EBUSY;
986		}
987		ntfs_log_perror("Failed to sync FILE_NAME (inode %lld)",
988				(long long)ni->mft_no);
989		NInoFileNameSetDirty(ni);
990	}
991
992	/* Write out attribute list from cache to disk. */
993	if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 &&
994			NInoAttrList(ni) && NInoAttrListTestAndClearDirty(ni)) {
995		ntfs_attr *na;
996
997		na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
998		if (!na) {
999			if (!err || errno == EIO) {
1000				err = errno;
1001				if (err != EIO)
1002					err = EBUSY;
1003				ntfs_log_perror("Attribute list sync failed "
1004						"(open, inode %lld)",
1005						(long long)ni->mft_no);
1006			}
1007			NInoAttrListSetDirty(ni);
1008			goto sync_inode;
1009		}
1010
1011		if (na->data_size == ni->attr_list_size) {
1012			if (ntfs_attr_pwrite(na, 0, ni->attr_list_size,
1013				        ni->attr_list) != ni->attr_list_size) {
1014				if (!err || errno == EIO) {
1015					err = errno;
1016					if (err != EIO)
1017						err = EBUSY;
1018					ntfs_log_perror("Attribute list sync "
1019						"failed (write, inode %lld)",
1020						(long long)ni->mft_no);
1021				}
1022				NInoAttrListSetDirty(ni);
1023			}
1024		} else {
1025			err = EIO;
1026			ntfs_log_error("Attribute list sync failed (bad size, "
1027				       "inode %lld)\n", (long long)ni->mft_no);
1028			NInoAttrListSetDirty(ni);
1029		}
1030		ntfs_attr_close(na);
1031	}
1032
1033sync_inode:
1034	/* Write this inode out to the $MFT (and $MFTMirr if applicable). */
1035	if (NInoTestAndClearDirty(ni)) {
1036		if (ntfs_mft_record_write(ni->vol, ni->mft_no, ni->mrec)) {
1037			if (!err || errno == EIO) {
1038				err = errno;
1039				if (err != EIO)
1040					err = EBUSY;
1041			}
1042			NInoSetDirty(ni);
1043			ntfs_log_perror("MFT record sync failed, inode %lld",
1044					(long long)ni->mft_no);
1045		}
1046	}
1047
1048	/* If this is a base inode with extents write all dirty extents, too. */
1049	if (ni->nr_extents > 0) {
1050		s32 i;
1051
1052		for (i = 0; i < ni->nr_extents; ++i) {
1053			ntfs_inode *eni;
1054
1055			eni = ni->extent_nis[i];
1056			if (!NInoTestAndClearDirty(eni))
1057				continue;
1058
1059			if (ntfs_mft_record_write(eni->vol, eni->mft_no,
1060						  eni->mrec)) {
1061				if (!err || errno == EIO) {
1062					err = errno;
1063					if (err != EIO)
1064						err = EBUSY;
1065				}
1066				NInoSetDirty(eni);
1067				ntfs_log_perror("Extent MFT record sync failed,"
1068						" inode %lld/%lld",
1069						(long long)ni->mft_no,
1070						(long long)eni->mft_no);
1071			}
1072		}
1073	}
1074
1075	if (err) {
1076		errno = err;
1077		ret = -1;
1078	}
1079
1080	ntfs_log_leave("\n");
1081	return ret;
1082}
1083
1084int ntfs_inode_sync(ntfs_inode *ni)
1085{
1086	return (ntfs_inode_sync_in_dir(ni, (ntfs_inode*)NULL));
1087}
1088
1089/*
1090 *		Close an inode with an open parent inode
1091 */
1092
1093int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni)
1094{
1095	int res;
1096
1097	res = ntfs_inode_sync_in_dir(ni, dir_ni);
1098	if (res) {
1099		if (errno != EIO)
1100			errno = EBUSY;
1101	} else
1102		res = ntfs_inode_close(ni);
1103	return (res);
1104}
1105
1106/**
1107 * ntfs_inode_add_attrlist - add attribute list to inode and fill it
1108 * @ni: opened ntfs inode to which add attribute list
1109 *
1110 * Return 0 on success or -1 on error with errno set to the error code.
1111 * The following error codes are defined:
1112 *	EINVAL	- Invalid arguments were passed to the function.
1113 *	EEXIST	- Attribute list already exist.
1114 *	EIO	- Input/Ouput error occurred.
1115 *	ENOMEM	- Not enough memory to perform add.
1116 */
1117int ntfs_inode_add_attrlist(ntfs_inode *ni)
1118{
1119	int err;
1120	ntfs_attr_search_ctx *ctx;
1121	u8 *al = NULL, *aln;
1122	int al_len = 0;
1123	ATTR_LIST_ENTRY *ale = NULL;
1124	ntfs_attr *na;
1125
1126	if (!ni) {
1127		errno = EINVAL;
1128		ntfs_log_perror("%s", __FUNCTION__);
1129		return -1;
1130	}
1131
1132	ntfs_log_trace("inode %llu\n", (unsigned long long) ni->mft_no);
1133
1134	if (NInoAttrList(ni) || ni->nr_extents) {
1135		errno = EEXIST;
1136		ntfs_log_perror("Inode already has attribute list");
1137		return -1;
1138	}
1139
1140	/* Form attribute list. */
1141	ctx = ntfs_attr_get_search_ctx(ni, NULL);
1142	if (!ctx) {
1143		err = errno;
1144		goto err_out;
1145	}
1146	/* Walk through all attributes. */
1147	while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) {
1148
1149		int ale_size;
1150
1151		if (ctx->attr->type == AT_ATTRIBUTE_LIST) {
1152			err = EIO;
1153			ntfs_log_perror("Attribute list already present");
1154			goto put_err_out;
1155		}
1156
1157		ale_size = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) *
1158					ctx->attr->name_length + 7) & ~7;
1159		al_len += ale_size;
1160
1161		aln = realloc(al, al_len);
1162		if (!aln) {
1163			err = errno;
1164			ntfs_log_perror("Failed to realloc %d bytes", al_len);
1165			goto put_err_out;
1166		}
1167		ale = (ATTR_LIST_ENTRY *)(aln + ((u8 *)ale - al));
1168		al = aln;
1169
1170		memset(ale, 0, ale_size);
1171
1172		/* Add attribute to attribute list. */
1173		ale->type = ctx->attr->type;
1174		ale->length = cpu_to_le16((sizeof(ATTR_LIST_ENTRY) +
1175			sizeof(ntfschar) * ctx->attr->name_length + 7) & ~7);
1176		ale->name_length = ctx->attr->name_length;
1177		ale->name_offset = (u8 *)ale->name - (u8 *)ale;
1178		if (ctx->attr->non_resident)
1179			ale->lowest_vcn = ctx->attr->lowest_vcn;
1180		else
1181			ale->lowest_vcn = const_cpu_to_sle64(0);
1182		ale->mft_reference = MK_LE_MREF(ni->mft_no,
1183			le16_to_cpu(ni->mrec->sequence_number));
1184		ale->instance = ctx->attr->instance;
1185		memcpy(ale->name, (u8 *)ctx->attr +
1186				le16_to_cpu(ctx->attr->name_offset),
1187				ctx->attr->name_length * sizeof(ntfschar));
1188		ale = (ATTR_LIST_ENTRY *)(al + al_len);
1189	}
1190	/* Check for real error occurred. */
1191	if (errno != ENOENT) {
1192		err = errno;
1193		ntfs_log_perror("%s: Attribute lookup failed, inode %lld",
1194				__FUNCTION__, (long long)ni->mft_no);
1195		goto put_err_out;
1196	}
1197
1198	/* Set in-memory attribute list. */
1199	ni->attr_list = al;
1200	ni->attr_list_size = al_len;
1201	NInoSetAttrList(ni);
1202	NInoAttrListSetDirty(ni);
1203
1204	/* Free space if there is not enough it for $ATTRIBUTE_LIST. */
1205	if (le32_to_cpu(ni->mrec->bytes_allocated) -
1206			le32_to_cpu(ni->mrec->bytes_in_use) <
1207			offsetof(ATTR_RECORD, resident_end)) {
1208		if (ntfs_inode_free_space(ni,
1209				offsetof(ATTR_RECORD, resident_end))) {
1210			/* Failed to free space. */
1211			err = errno;
1212			ntfs_log_perror("Failed to free space for attrlist");
1213			goto rollback;
1214		}
1215	}
1216
1217	/* Add $ATTRIBUTE_LIST to mft record. */
1218	if (ntfs_resident_attr_record_add(ni,
1219				AT_ATTRIBUTE_LIST, NULL, 0, NULL, 0, const_cpu_to_le16(0)) < 0) {
1220		err = errno;
1221		ntfs_log_perror("Couldn't add $ATTRIBUTE_LIST to MFT");
1222		goto rollback;
1223	}
1224
1225	/* Resize it. */
1226	na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
1227	if (!na) {
1228		err = errno;
1229		ntfs_log_perror("Failed to open just added $ATTRIBUTE_LIST");
1230		goto remove_attrlist_record;
1231	}
1232	if (ntfs_attr_truncate(na, al_len)) {
1233		err = errno;
1234		ntfs_log_perror("Failed to resize just added $ATTRIBUTE_LIST");
1235		ntfs_attr_close(na);
1236		goto remove_attrlist_record;;
1237	}
1238
1239	ntfs_attr_put_search_ctx(ctx);
1240	ntfs_attr_close(na);
1241	return 0;
1242
1243remove_attrlist_record:
1244	/* Prevent ntfs_attr_recorm_rm from freeing attribute list. */
1245	ni->attr_list = NULL;
1246	NInoClearAttrList(ni);
1247	/* Remove $ATTRIBUTE_LIST record. */
1248	ntfs_attr_reinit_search_ctx(ctx);
1249	if (!ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0,
1250				CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1251		if (ntfs_attr_record_rm(ctx))
1252			ntfs_log_perror("Rollback failed to remove attrlist");
1253	} else
1254		ntfs_log_perror("Rollback failed to find attrlist");
1255	/* Setup back in-memory runlist. */
1256	ni->attr_list = al;
1257	ni->attr_list_size = al_len;
1258	NInoSetAttrList(ni);
1259rollback:
1260	/*
1261	 * Scan attribute list for attributes that placed not in the base MFT
1262	 * record and move them to it.
1263	 */
1264	ntfs_attr_reinit_search_ctx(ctx);
1265	ale = (ATTR_LIST_ENTRY*)al;
1266	while ((u8*)ale < al + al_len) {
1267		if (MREF_LE(ale->mft_reference) != ni->mft_no) {
1268			if (!ntfs_attr_lookup(ale->type, ale->name,
1269						ale->name_length,
1270						CASE_SENSITIVE,
1271						sle64_to_cpu(ale->lowest_vcn),
1272						NULL, 0, ctx)) {
1273				if (ntfs_attr_record_move_to(ctx, ni))
1274					ntfs_log_perror("Rollback failed to "
1275							"move attribute");
1276			} else
1277				ntfs_log_perror("Rollback failed to find attr");
1278			ntfs_attr_reinit_search_ctx(ctx);
1279		}
1280		ale = (ATTR_LIST_ENTRY*)((u8*)ale + le16_to_cpu(ale->length));
1281	}
1282	/* Remove in-memory attribute list. */
1283	ni->attr_list = NULL;
1284	ni->attr_list_size = 0;
1285	NInoClearAttrList(ni);
1286	NInoAttrListClearDirty(ni);
1287put_err_out:
1288	ntfs_attr_put_search_ctx(ctx);
1289err_out:
1290	free(al);
1291	errno = err;
1292	return -1;
1293}
1294
1295/**
1296 * ntfs_inode_free_space - free space in the MFT record of an inode
1297 * @ni:		ntfs inode in which MFT record needs more free space
1298 * @size:	amount of space needed to free
1299 *
1300 * Return 0 on success or -1 on error with errno set to the error code.
1301 */
1302int ntfs_inode_free_space(ntfs_inode *ni, int size)
1303{
1304	ntfs_attr_search_ctx *ctx;
1305	int freed;
1306
1307	if (!ni || size < 0) {
1308		errno = EINVAL;
1309		ntfs_log_perror("%s: ni=%p size=%d", __FUNCTION__, ni, size);
1310		return -1;
1311	}
1312
1313	ntfs_log_trace("Entering for inode %lld, size %d\n",
1314		       (unsigned long long)ni->mft_no, size);
1315
1316	freed = (le32_to_cpu(ni->mrec->bytes_allocated) -
1317				le32_to_cpu(ni->mrec->bytes_in_use));
1318
1319	if (size <= freed)
1320		return 0;
1321
1322	ctx = ntfs_attr_get_search_ctx(ni, NULL);
1323	if (!ctx)
1324		return -1;
1325	/*
1326	 * $STANDARD_INFORMATION and $ATTRIBUTE_LIST must stay in the base MFT
1327	 * record, so position search context on the first attribute after them.
1328	 */
1329	if (ntfs_attr_position(AT_FILE_NAME, ctx))
1330		goto put_err_out;
1331
1332	while (1) {
1333		int record_size;
1334		/*
1335		 * Check whether attribute is from different MFT record. If so,
1336		 * find next, because we don't need such.
1337		 */
1338		while (ctx->ntfs_ino->mft_no != ni->mft_no) {
1339retry:
1340			if (ntfs_attr_position(AT_UNUSED, ctx))
1341				goto put_err_out;
1342		}
1343
1344		if (ntfs_inode_base(ctx->ntfs_ino)->mft_no == FILE_MFT &&
1345		    ctx->attr->type == AT_DATA)
1346			goto retry;
1347
1348		if (ctx->attr->type == AT_INDEX_ROOT)
1349			goto retry;
1350
1351		record_size = le32_to_cpu(ctx->attr->length);
1352
1353		if (ntfs_attr_record_move_away(ctx, 0)) {
1354			ntfs_log_perror("Failed to move out attribute #2");
1355			break;
1356		}
1357		freed += record_size;
1358
1359		/* Check whether we are done. */
1360		if (size <= freed) {
1361			ntfs_attr_put_search_ctx(ctx);
1362			return 0;
1363		}
1364		/*
1365		 * Reposition to first attribute after $STANDARD_INFORMATION
1366		 * and $ATTRIBUTE_LIST instead of simply skipping this attribute
1367		 * because in the case when we have got only in-memory attribute
1368		 * list then ntfs_attr_lookup will fail when it tries to find
1369		 * $ATTRIBUTE_LIST.
1370		 */
1371		ntfs_attr_reinit_search_ctx(ctx);
1372		if (ntfs_attr_position(AT_FILE_NAME, ctx))
1373			break;
1374	}
1375put_err_out:
1376	ntfs_attr_put_search_ctx(ctx);
1377	if (errno == ENOSPC)
1378		ntfs_log_trace("No attributes left that could be moved out.\n");
1379	return -1;
1380}
1381
1382/**
1383 * ntfs_inode_update_times - update selected time fields for ntfs inode
1384 * @ni:		ntfs inode for which update time fields
1385 * @mask:	select which time fields should be updated
1386 *
1387 * This function updates time fields to current time. Fields to update are
1388 * selected using @mask (see enum @ntfs_time_update_flags for posssible values).
1389 */
1390void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask)
1391{
1392	ntfs_time now;
1393
1394	if (!ni) {
1395		ntfs_log_error("%s(): Invalid arguments.\n", __FUNCTION__);
1396		return;
1397	}
1398
1399	if ((ni->mft_no < FILE_first_user && ni->mft_no != FILE_root) ||
1400			NVolReadOnly(ni->vol) || !mask)
1401		return;
1402
1403	now = ntfs_current_time();
1404	if (mask & NTFS_UPDATE_ATIME)
1405		ni->last_access_time = now;
1406	if (mask & NTFS_UPDATE_MTIME)
1407		ni->last_data_change_time = now;
1408	if (mask & NTFS_UPDATE_CTIME)
1409		ni->last_mft_change_time = now;
1410
1411	NInoFileNameSetDirty(ni);
1412	NInoSetDirty(ni);
1413}
1414
1415/**
1416 * ntfs_inode_badclus_bad - check for $Badclus:$Bad data attribute
1417 * @mft_no:		mft record number where @attr is present
1418 * @attr:		attribute record used to check for the $Bad attribute
1419 *
1420 * Check if the mft record given by @mft_no and @attr contains the bad sector
1421 * list. Please note that mft record numbers describing $Badclus extent inodes
1422 * will not match the current $Badclus:$Bad check.
1423 *
1424 * On success return 1 if the file is $Badclus:$Bad, otherwise return 0.
1425 * On error return -1 with errno set to the error code.
1426 */
1427int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr)
1428{
1429	int len, ret = 0;
1430	ntfschar *ustr;
1431
1432	if (!attr) {
1433		ntfs_log_error("Invalid argument.\n");
1434		errno = EINVAL;
1435		return -1;
1436	}
1437
1438	if (mft_no != FILE_BadClus)
1439	       	return 0;
1440
1441	if (attr->type != AT_DATA)
1442	       	return 0;
1443
1444	if ((ustr = ntfs_str2ucs("$Bad", &len)) == NULL) {
1445		ntfs_log_perror("Couldn't convert '$Bad' to Unicode");
1446		return -1;
1447	}
1448
1449	if (ustr && ntfs_names_are_equal(ustr, len,
1450			(ntfschar *)((u8 *)attr + le16_to_cpu(attr->name_offset)),
1451			attr->name_length, 0, NULL, 0))
1452		ret = 1;
1453
1454	ntfs_ucsfree(ustr);
1455
1456	return ret;
1457}
1458
1459/*
1460 *		Get high precision NTFS times
1461 *
1462 *	They are returned in following order : create, update, access, change
1463 *	provided they fit in requested size.
1464 *
1465 *	Returns the modified size if successfull (or 32 if buffer size is null)
1466 *		-errno if failed
1467 */
1468
1469int ntfs_inode_get_times(ntfs_inode *ni, char *value, size_t size)
1470{
1471	ntfs_attr_search_ctx *ctx;
1472	STANDARD_INFORMATION *std_info;
1473	u64 *times;
1474	int ret;
1475
1476	ret = 0;
1477	ctx = ntfs_attr_get_search_ctx(ni, NULL);
1478	if (ctx) {
1479		if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED,
1480				     0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
1481			ntfs_log_perror("Failed to get standard info (inode %lld)",
1482					(long long)ni->mft_no);
1483		} else {
1484			std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr +
1485					le16_to_cpu(ctx->attr->value_offset));
1486			if (value && (size >= 8)) {
1487				times = (u64*)value;
1488				times[0] = sle64_to_cpu(std_info->creation_time);
1489				ret = 8;
1490				if (size >= 16) {
1491					times[1] = sle64_to_cpu(std_info->last_data_change_time);
1492					ret = 16;
1493				}
1494				if (size >= 24) {
1495					times[2] = sle64_to_cpu(std_info->last_access_time);
1496					ret = 24;
1497				}
1498				if (size >= 32) {
1499					times[3] = sle64_to_cpu(std_info->last_mft_change_time);
1500					ret = 32;
1501				}
1502			} else
1503				if (!size)
1504					ret = 32;
1505				else
1506					ret = -ERANGE;
1507			}
1508		ntfs_attr_put_search_ctx(ctx);
1509	}
1510	return (ret ? ret : -errno);
1511}
1512
1513/*
1514 *		Set high precision NTFS times
1515 *
1516 *	They are expected in this order : create, update, access
1517 *	provided they are present in input. The change time is set to
1518 *	current time.
1519 *
1520 *	The times are inserted directly in the standard_information and
1521 *	file names attributes to avoid manipulating low precision times
1522 *
1523 *	Returns 0 if success
1524 *		-1 if there were an error (described by errno)
1525 */
1526
1527int ntfs_inode_set_times(ntfs_inode *ni, const char *value, size_t size,
1528			int flags)
1529{
1530	ntfs_attr_search_ctx *ctx;
1531	STANDARD_INFORMATION *std_info;
1532	FILE_NAME_ATTR *fn;
1533	u64 times[4];
1534	ntfs_time now;
1535	int cnt;
1536	int ret;
1537
1538	ret = -1;
1539	if ((size >= 8) && !(flags & XATTR_CREATE)) {
1540		/* Copy, to avoid alignment issue encountered on ARM */
1541		memcpy(times, value,
1542			(size < sizeof(times) ? size : sizeof(times)));
1543		now = ntfs_current_time();
1544			/* update the standard information attribute */
1545		ctx = ntfs_attr_get_search_ctx(ni, NULL);
1546		if (ctx) {
1547			if (ntfs_attr_lookup(AT_STANDARD_INFORMATION,
1548					AT_UNNAMED, 0, CASE_SENSITIVE,
1549					0, NULL, 0, ctx)) {
1550				ntfs_log_perror("Failed to get standard info (inode %lld)",
1551						(long long)ni->mft_no);
1552			} else {
1553				std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr +
1554					le16_to_cpu(ctx->attr->value_offset));
1555				/*
1556				 * Mark times set to avoid overwriting
1557				 * them when the inode is closed.
1558				 * The inode structure must also be updated
1559				 * (with loss of precision) because of cacheing.
1560				 * TODO : use NTFS precision in inode, and
1561				 * return sub-second times in getattr()
1562				 */
1563				set_nino_flag(ni, TimesSet);
1564				std_info->creation_time = cpu_to_sle64(times[0]);
1565				ni->creation_time
1566					= std_info->creation_time;
1567				if (size >= 16) {
1568					std_info->last_data_change_time = cpu_to_sle64(times[1]);
1569					ni->last_data_change_time
1570						= std_info->last_data_change_time;
1571				}
1572				if (size >= 24) {
1573					std_info->last_access_time = cpu_to_sle64(times[2]);
1574					ni->last_access_time
1575						= std_info->last_access_time;
1576				}
1577				std_info->last_mft_change_time = now;
1578				ni->last_mft_change_time = now;
1579				ntfs_inode_mark_dirty(ctx->ntfs_ino);
1580				NInoFileNameSetDirty(ni);
1581
1582				/* update the file names attributes */
1583				ntfs_attr_reinit_search_ctx(ctx);
1584				cnt = 0;
1585				while (!ntfs_attr_lookup(AT_FILE_NAME,
1586						AT_UNNAMED, 0, CASE_SENSITIVE,
1587						0, NULL, 0, ctx)) {
1588					fn = (FILE_NAME_ATTR*)((u8 *)ctx->attr +
1589						le16_to_cpu(ctx->attr->value_offset));
1590					fn->creation_time
1591						= cpu_to_sle64(times[0]);
1592					if (size >= 16)
1593						fn->last_data_change_time
1594							= cpu_to_sle64(times[1]);
1595					if (size >= 24)
1596						fn->last_access_time
1597							= cpu_to_sle64(times[2]);
1598					fn->last_mft_change_time = now;
1599					cnt++;
1600				}
1601				if (cnt)
1602					ret = 0;
1603				else {
1604					ntfs_log_perror("Failed to get file names (inode %lld)",
1605						(long long)ni->mft_no);
1606				}
1607			}
1608			ntfs_attr_put_search_ctx(ctx);
1609		}
1610	} else
1611		if (size < 8)
1612			errno = ERANGE;
1613		else
1614			errno = EEXIST;
1615	return (ret);
1616}
1617