xref: /openbmc/linux/fs/ntfs/inode.c (revision 3a35093a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /**
3  * inode.c - NTFS kernel inode handling.
4  *
5  * Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc.
6  */
7 
8 #include <linux/buffer_head.h>
9 #include <linux/fs.h>
10 #include <linux/mm.h>
11 #include <linux/mount.h>
12 #include <linux/mutex.h>
13 #include <linux/pagemap.h>
14 #include <linux/quotaops.h>
15 #include <linux/slab.h>
16 #include <linux/log2.h>
17 
18 #include "aops.h"
19 #include "attrib.h"
20 #include "bitmap.h"
21 #include "dir.h"
22 #include "debug.h"
23 #include "inode.h"
24 #include "lcnalloc.h"
25 #include "malloc.h"
26 #include "mft.h"
27 #include "time.h"
28 #include "ntfs.h"
29 
30 /**
31  * ntfs_test_inode - compare two (possibly fake) inodes for equality
32  * @vi:		vfs inode which to test
33  * @data:	data which is being tested with
34  *
35  * Compare the ntfs attribute embedded in the ntfs specific part of the vfs
36  * inode @vi for equality with the ntfs attribute @data.
37  *
38  * If searching for the normal file/directory inode, set @na->type to AT_UNUSED.
39  * @na->name and @na->name_len are then ignored.
40  *
41  * Return 1 if the attributes match and 0 if not.
42  *
43  * NOTE: This function runs with the inode_hash_lock spin lock held so it is not
44  * allowed to sleep.
45  */
46 int ntfs_test_inode(struct inode *vi, void *data)
47 {
48 	ntfs_attr *na = (ntfs_attr *)data;
49 	ntfs_inode *ni;
50 
51 	if (vi->i_ino != na->mft_no)
52 		return 0;
53 	ni = NTFS_I(vi);
54 	/* If !NInoAttr(ni), @vi is a normal file or directory inode. */
55 	if (likely(!NInoAttr(ni))) {
56 		/* If not looking for a normal inode this is a mismatch. */
57 		if (unlikely(na->type != AT_UNUSED))
58 			return 0;
59 	} else {
60 		/* A fake inode describing an attribute. */
61 		if (ni->type != na->type)
62 			return 0;
63 		if (ni->name_len != na->name_len)
64 			return 0;
65 		if (na->name_len && memcmp(ni->name, na->name,
66 				na->name_len * sizeof(ntfschar)))
67 			return 0;
68 	}
69 	/* Match! */
70 	return 1;
71 }
72 
73 /**
74  * ntfs_init_locked_inode - initialize an inode
75  * @vi:		vfs inode to initialize
76  * @data:	data which to initialize @vi to
77  *
78  * Initialize the vfs inode @vi with the values from the ntfs attribute @data in
79  * order to enable ntfs_test_inode() to do its work.
80  *
81  * If initializing the normal file/directory inode, set @na->type to AT_UNUSED.
82  * In that case, @na->name and @na->name_len should be set to NULL and 0,
83  * respectively. Although that is not strictly necessary as
84  * ntfs_read_locked_inode() will fill them in later.
85  *
86  * Return 0 on success and -errno on error.
87  *
88  * NOTE: This function runs with the inode->i_lock spin lock held so it is not
89  * allowed to sleep. (Hence the GFP_ATOMIC allocation.)
90  */
91 static int ntfs_init_locked_inode(struct inode *vi, void *data)
92 {
93 	ntfs_attr *na = (ntfs_attr *)data;
94 	ntfs_inode *ni = NTFS_I(vi);
95 
96 	vi->i_ino = na->mft_no;
97 
98 	ni->type = na->type;
99 	if (na->type == AT_INDEX_ALLOCATION)
100 		NInoSetMstProtected(ni);
101 
102 	ni->name = na->name;
103 	ni->name_len = na->name_len;
104 
105 	/* If initializing a normal inode, we are done. */
106 	if (likely(na->type == AT_UNUSED)) {
107 		BUG_ON(na->name);
108 		BUG_ON(na->name_len);
109 		return 0;
110 	}
111 
112 	/* It is a fake inode. */
113 	NInoSetAttr(ni);
114 
115 	/*
116 	 * We have I30 global constant as an optimization as it is the name
117 	 * in >99.9% of named attributes! The other <0.1% incur a GFP_ATOMIC
118 	 * allocation but that is ok. And most attributes are unnamed anyway,
119 	 * thus the fraction of named attributes with name != I30 is actually
120 	 * absolutely tiny.
121 	 */
122 	if (na->name_len && na->name != I30) {
123 		unsigned int i;
124 
125 		BUG_ON(!na->name);
126 		i = na->name_len * sizeof(ntfschar);
127 		ni->name = kmalloc(i + sizeof(ntfschar), GFP_ATOMIC);
128 		if (!ni->name)
129 			return -ENOMEM;
130 		memcpy(ni->name, na->name, i);
131 		ni->name[na->name_len] = 0;
132 	}
133 	return 0;
134 }
135 
136 static int ntfs_read_locked_inode(struct inode *vi);
137 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi);
138 static int ntfs_read_locked_index_inode(struct inode *base_vi,
139 		struct inode *vi);
140 
141 /**
142  * ntfs_iget - obtain a struct inode corresponding to a specific normal inode
143  * @sb:		super block of mounted volume
144  * @mft_no:	mft record number / inode number to obtain
145  *
146  * Obtain the struct inode corresponding to a specific normal inode (i.e. a
147  * file or directory).
148  *
149  * If the inode is in the cache, it is just returned with an increased
150  * reference count. Otherwise, a new struct inode is allocated and initialized,
151  * and finally ntfs_read_locked_inode() is called to read in the inode and
152  * fill in the remainder of the inode structure.
153  *
154  * Return the struct inode on success. Check the return value with IS_ERR() and
155  * if true, the function failed and the error code is obtained from PTR_ERR().
156  */
157 struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no)
158 {
159 	struct inode *vi;
160 	int err;
161 	ntfs_attr na;
162 
163 	na.mft_no = mft_no;
164 	na.type = AT_UNUSED;
165 	na.name = NULL;
166 	na.name_len = 0;
167 
168 	vi = iget5_locked(sb, mft_no, ntfs_test_inode,
169 			ntfs_init_locked_inode, &na);
170 	if (unlikely(!vi))
171 		return ERR_PTR(-ENOMEM);
172 
173 	err = 0;
174 
175 	/* If this is a freshly allocated inode, need to read it now. */
176 	if (vi->i_state & I_NEW) {
177 		err = ntfs_read_locked_inode(vi);
178 		unlock_new_inode(vi);
179 	}
180 	/*
181 	 * There is no point in keeping bad inodes around if the failure was
182 	 * due to ENOMEM. We want to be able to retry again later.
183 	 */
184 	if (unlikely(err == -ENOMEM)) {
185 		iput(vi);
186 		vi = ERR_PTR(err);
187 	}
188 	return vi;
189 }
190 
191 /**
192  * ntfs_attr_iget - obtain a struct inode corresponding to an attribute
193  * @base_vi:	vfs base inode containing the attribute
194  * @type:	attribute type
195  * @name:	Unicode name of the attribute (NULL if unnamed)
196  * @name_len:	length of @name in Unicode characters (0 if unnamed)
197  *
198  * Obtain the (fake) struct inode corresponding to the attribute specified by
199  * @type, @name, and @name_len, which is present in the base mft record
200  * specified by the vfs inode @base_vi.
201  *
202  * If the attribute inode is in the cache, it is just returned with an
203  * increased reference count. Otherwise, a new struct inode is allocated and
204  * initialized, and finally ntfs_read_locked_attr_inode() is called to read the
205  * attribute and fill in the inode structure.
206  *
207  * Note, for index allocation attributes, you need to use ntfs_index_iget()
208  * instead of ntfs_attr_iget() as working with indices is a lot more complex.
209  *
210  * Return the struct inode of the attribute inode on success. Check the return
211  * value with IS_ERR() and if true, the function failed and the error code is
212  * obtained from PTR_ERR().
213  */
214 struct inode *ntfs_attr_iget(struct inode *base_vi, ATTR_TYPE type,
215 		ntfschar *name, u32 name_len)
216 {
217 	struct inode *vi;
218 	int err;
219 	ntfs_attr na;
220 
221 	/* Make sure no one calls ntfs_attr_iget() for indices. */
222 	BUG_ON(type == AT_INDEX_ALLOCATION);
223 
224 	na.mft_no = base_vi->i_ino;
225 	na.type = type;
226 	na.name = name;
227 	na.name_len = name_len;
228 
229 	vi = iget5_locked(base_vi->i_sb, na.mft_no, ntfs_test_inode,
230 			ntfs_init_locked_inode, &na);
231 	if (unlikely(!vi))
232 		return ERR_PTR(-ENOMEM);
233 
234 	err = 0;
235 
236 	/* If this is a freshly allocated inode, need to read it now. */
237 	if (vi->i_state & I_NEW) {
238 		err = ntfs_read_locked_attr_inode(base_vi, vi);
239 		unlock_new_inode(vi);
240 	}
241 	/*
242 	 * There is no point in keeping bad attribute inodes around. This also
243 	 * simplifies things in that we never need to check for bad attribute
244 	 * inodes elsewhere.
245 	 */
246 	if (unlikely(err)) {
247 		iput(vi);
248 		vi = ERR_PTR(err);
249 	}
250 	return vi;
251 }
252 
253 /**
254  * ntfs_index_iget - obtain a struct inode corresponding to an index
255  * @base_vi:	vfs base inode containing the index related attributes
256  * @name:	Unicode name of the index
257  * @name_len:	length of @name in Unicode characters
258  *
259  * Obtain the (fake) struct inode corresponding to the index specified by @name
260  * and @name_len, which is present in the base mft record specified by the vfs
261  * inode @base_vi.
262  *
263  * If the index inode is in the cache, it is just returned with an increased
264  * reference count.  Otherwise, a new struct inode is allocated and
265  * initialized, and finally ntfs_read_locked_index_inode() is called to read
266  * the index related attributes and fill in the inode structure.
267  *
268  * Return the struct inode of the index inode on success. Check the return
269  * value with IS_ERR() and if true, the function failed and the error code is
270  * obtained from PTR_ERR().
271  */
272 struct inode *ntfs_index_iget(struct inode *base_vi, ntfschar *name,
273 		u32 name_len)
274 {
275 	struct inode *vi;
276 	int err;
277 	ntfs_attr na;
278 
279 	na.mft_no = base_vi->i_ino;
280 	na.type = AT_INDEX_ALLOCATION;
281 	na.name = name;
282 	na.name_len = name_len;
283 
284 	vi = iget5_locked(base_vi->i_sb, na.mft_no, ntfs_test_inode,
285 			ntfs_init_locked_inode, &na);
286 	if (unlikely(!vi))
287 		return ERR_PTR(-ENOMEM);
288 
289 	err = 0;
290 
291 	/* If this is a freshly allocated inode, need to read it now. */
292 	if (vi->i_state & I_NEW) {
293 		err = ntfs_read_locked_index_inode(base_vi, vi);
294 		unlock_new_inode(vi);
295 	}
296 	/*
297 	 * There is no point in keeping bad index inodes around.  This also
298 	 * simplifies things in that we never need to check for bad index
299 	 * inodes elsewhere.
300 	 */
301 	if (unlikely(err)) {
302 		iput(vi);
303 		vi = ERR_PTR(err);
304 	}
305 	return vi;
306 }
307 
308 struct inode *ntfs_alloc_big_inode(struct super_block *sb)
309 {
310 	ntfs_inode *ni;
311 
312 	ntfs_debug("Entering.");
313 	ni = kmem_cache_alloc(ntfs_big_inode_cache, GFP_NOFS);
314 	if (likely(ni != NULL)) {
315 		ni->state = 0;
316 		return VFS_I(ni);
317 	}
318 	ntfs_error(sb, "Allocation of NTFS big inode structure failed.");
319 	return NULL;
320 }
321 
322 void ntfs_free_big_inode(struct inode *inode)
323 {
324 	kmem_cache_free(ntfs_big_inode_cache, NTFS_I(inode));
325 }
326 
327 static inline ntfs_inode *ntfs_alloc_extent_inode(void)
328 {
329 	ntfs_inode *ni;
330 
331 	ntfs_debug("Entering.");
332 	ni = kmem_cache_alloc(ntfs_inode_cache, GFP_NOFS);
333 	if (likely(ni != NULL)) {
334 		ni->state = 0;
335 		return ni;
336 	}
337 	ntfs_error(NULL, "Allocation of NTFS inode structure failed.");
338 	return NULL;
339 }
340 
341 static void ntfs_destroy_extent_inode(ntfs_inode *ni)
342 {
343 	ntfs_debug("Entering.");
344 	BUG_ON(ni->page);
345 	if (!atomic_dec_and_test(&ni->count))
346 		BUG();
347 	kmem_cache_free(ntfs_inode_cache, ni);
348 }
349 
350 /*
351  * The attribute runlist lock has separate locking rules from the
352  * normal runlist lock, so split the two lock-classes:
353  */
354 static struct lock_class_key attr_list_rl_lock_class;
355 
356 /**
357  * __ntfs_init_inode - initialize ntfs specific part of an inode
358  * @sb:		super block of mounted volume
359  * @ni:		freshly allocated ntfs inode which to initialize
360  *
361  * Initialize an ntfs inode to defaults.
362  *
363  * NOTE: ni->mft_no, ni->state, ni->type, ni->name, and ni->name_len are left
364  * untouched. Make sure to initialize them elsewhere.
365  *
366  * Return zero on success and -ENOMEM on error.
367  */
368 void __ntfs_init_inode(struct super_block *sb, ntfs_inode *ni)
369 {
370 	ntfs_debug("Entering.");
371 	rwlock_init(&ni->size_lock);
372 	ni->initialized_size = ni->allocated_size = 0;
373 	ni->seq_no = 0;
374 	atomic_set(&ni->count, 1);
375 	ni->vol = NTFS_SB(sb);
376 	ntfs_init_runlist(&ni->runlist);
377 	mutex_init(&ni->mrec_lock);
378 	ni->page = NULL;
379 	ni->page_ofs = 0;
380 	ni->attr_list_size = 0;
381 	ni->attr_list = NULL;
382 	ntfs_init_runlist(&ni->attr_list_rl);
383 	lockdep_set_class(&ni->attr_list_rl.lock,
384 				&attr_list_rl_lock_class);
385 	ni->itype.index.block_size = 0;
386 	ni->itype.index.vcn_size = 0;
387 	ni->itype.index.collation_rule = 0;
388 	ni->itype.index.block_size_bits = 0;
389 	ni->itype.index.vcn_size_bits = 0;
390 	mutex_init(&ni->extent_lock);
391 	ni->nr_extents = 0;
392 	ni->ext.base_ntfs_ino = NULL;
393 }
394 
395 /*
396  * Extent inodes get MFT-mapped in a nested way, while the base inode
397  * is still mapped. Teach this nesting to the lock validator by creating
398  * a separate class for nested inode's mrec_lock's:
399  */
400 static struct lock_class_key extent_inode_mrec_lock_key;
401 
402 inline ntfs_inode *ntfs_new_extent_inode(struct super_block *sb,
403 		unsigned long mft_no)
404 {
405 	ntfs_inode *ni = ntfs_alloc_extent_inode();
406 
407 	ntfs_debug("Entering.");
408 	if (likely(ni != NULL)) {
409 		__ntfs_init_inode(sb, ni);
410 		lockdep_set_class(&ni->mrec_lock, &extent_inode_mrec_lock_key);
411 		ni->mft_no = mft_no;
412 		ni->type = AT_UNUSED;
413 		ni->name = NULL;
414 		ni->name_len = 0;
415 	}
416 	return ni;
417 }
418 
419 /**
420  * ntfs_is_extended_system_file - check if a file is in the $Extend directory
421  * @ctx:	initialized attribute search context
422  *
423  * Search all file name attributes in the inode described by the attribute
424  * search context @ctx and check if any of the names are in the $Extend system
425  * directory.
426  *
427  * Return values:
428  *	   1: file is in $Extend directory
429  *	   0: file is not in $Extend directory
430  *    -errno: failed to determine if the file is in the $Extend directory
431  */
432 static int ntfs_is_extended_system_file(ntfs_attr_search_ctx *ctx)
433 {
434 	int nr_links, err;
435 
436 	/* Restart search. */
437 	ntfs_attr_reinit_search_ctx(ctx);
438 
439 	/* Get number of hard links. */
440 	nr_links = le16_to_cpu(ctx->mrec->link_count);
441 
442 	/* Loop through all hard links. */
443 	while (!(err = ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0,
444 			ctx))) {
445 		FILE_NAME_ATTR *file_name_attr;
446 		ATTR_RECORD *attr = ctx->attr;
447 		u8 *p, *p2;
448 
449 		nr_links--;
450 		/*
451 		 * Maximum sanity checking as we are called on an inode that
452 		 * we suspect might be corrupt.
453 		 */
454 		p = (u8*)attr + le32_to_cpu(attr->length);
455 		if (p < (u8*)ctx->mrec || (u8*)p > (u8*)ctx->mrec +
456 				le32_to_cpu(ctx->mrec->bytes_in_use)) {
457 err_corrupt_attr:
458 			ntfs_error(ctx->ntfs_ino->vol->sb, "Corrupt file name "
459 					"attribute. You should run chkdsk.");
460 			return -EIO;
461 		}
462 		if (attr->non_resident) {
463 			ntfs_error(ctx->ntfs_ino->vol->sb, "Non-resident file "
464 					"name. You should run chkdsk.");
465 			return -EIO;
466 		}
467 		if (attr->flags) {
468 			ntfs_error(ctx->ntfs_ino->vol->sb, "File name with "
469 					"invalid flags. You should run "
470 					"chkdsk.");
471 			return -EIO;
472 		}
473 		if (!(attr->data.resident.flags & RESIDENT_ATTR_IS_INDEXED)) {
474 			ntfs_error(ctx->ntfs_ino->vol->sb, "Unindexed file "
475 					"name. You should run chkdsk.");
476 			return -EIO;
477 		}
478 		file_name_attr = (FILE_NAME_ATTR*)((u8*)attr +
479 				le16_to_cpu(attr->data.resident.value_offset));
480 		p2 = (u8*)attr + le32_to_cpu(attr->data.resident.value_length);
481 		if (p2 < (u8*)attr || p2 > p)
482 			goto err_corrupt_attr;
483 		/* This attribute is ok, but is it in the $Extend directory? */
484 		if (MREF_LE(file_name_attr->parent_directory) == FILE_Extend)
485 			return 1;	/* YES, it's an extended system file. */
486 	}
487 	if (unlikely(err != -ENOENT))
488 		return err;
489 	if (unlikely(nr_links)) {
490 		ntfs_error(ctx->ntfs_ino->vol->sb, "Inode hard link count "
491 				"doesn't match number of name attributes. You "
492 				"should run chkdsk.");
493 		return -EIO;
494 	}
495 	return 0;	/* NO, it is not an extended system file. */
496 }
497 
498 /**
499  * ntfs_read_locked_inode - read an inode from its device
500  * @vi:		inode to read
501  *
502  * ntfs_read_locked_inode() is called from ntfs_iget() to read the inode
503  * described by @vi into memory from the device.
504  *
505  * The only fields in @vi that we need to/can look at when the function is
506  * called are i_sb, pointing to the mounted device's super block, and i_ino,
507  * the number of the inode to load.
508  *
509  * ntfs_read_locked_inode() maps, pins and locks the mft record number i_ino
510  * for reading and sets up the necessary @vi fields as well as initializing
511  * the ntfs inode.
512  *
513  * Q: What locks are held when the function is called?
514  * A: i_state has I_NEW set, hence the inode is locked, also
515  *    i_count is set to 1, so it is not going to go away
516  *    i_flags is set to 0 and we have no business touching it.  Only an ioctl()
517  *    is allowed to write to them. We should of course be honouring them but
518  *    we need to do that using the IS_* macros defined in include/linux/fs.h.
519  *    In any case ntfs_read_locked_inode() has nothing to do with i_flags.
520  *
521  * Return 0 on success and -errno on error.  In the error case, the inode will
522  * have had make_bad_inode() executed on it.
523  */
524 static int ntfs_read_locked_inode(struct inode *vi)
525 {
526 	ntfs_volume *vol = NTFS_SB(vi->i_sb);
527 	ntfs_inode *ni;
528 	struct inode *bvi;
529 	MFT_RECORD *m;
530 	ATTR_RECORD *a;
531 	STANDARD_INFORMATION *si;
532 	ntfs_attr_search_ctx *ctx;
533 	int err = 0;
534 
535 	ntfs_debug("Entering for i_ino 0x%lx.", vi->i_ino);
536 
537 	/* Setup the generic vfs inode parts now. */
538 	vi->i_uid = vol->uid;
539 	vi->i_gid = vol->gid;
540 	vi->i_mode = 0;
541 
542 	/*
543 	 * Initialize the ntfs specific part of @vi special casing
544 	 * FILE_MFT which we need to do at mount time.
545 	 */
546 	if (vi->i_ino != FILE_MFT)
547 		ntfs_init_big_inode(vi);
548 	ni = NTFS_I(vi);
549 
550 	m = map_mft_record(ni);
551 	if (IS_ERR(m)) {
552 		err = PTR_ERR(m);
553 		goto err_out;
554 	}
555 	ctx = ntfs_attr_get_search_ctx(ni, m);
556 	if (!ctx) {
557 		err = -ENOMEM;
558 		goto unm_err_out;
559 	}
560 
561 	if (!(m->flags & MFT_RECORD_IN_USE)) {
562 		ntfs_error(vi->i_sb, "Inode is not in use!");
563 		goto unm_err_out;
564 	}
565 	if (m->base_mft_record) {
566 		ntfs_error(vi->i_sb, "Inode is an extent inode!");
567 		goto unm_err_out;
568 	}
569 
570 	/* Transfer information from mft record into vfs and ntfs inodes. */
571 	vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
572 
573 	/*
574 	 * FIXME: Keep in mind that link_count is two for files which have both
575 	 * a long file name and a short file name as separate entries, so if
576 	 * we are hiding short file names this will be too high. Either we need
577 	 * to account for the short file names by subtracting them or we need
578 	 * to make sure we delete files even though i_nlink is not zero which
579 	 * might be tricky due to vfs interactions. Need to think about this
580 	 * some more when implementing the unlink command.
581 	 */
582 	set_nlink(vi, le16_to_cpu(m->link_count));
583 	/*
584 	 * FIXME: Reparse points can have the directory bit set even though
585 	 * they would be S_IFLNK. Need to deal with this further below when we
586 	 * implement reparse points / symbolic links but it will do for now.
587 	 * Also if not a directory, it could be something else, rather than
588 	 * a regular file. But again, will do for now.
589 	 */
590 	/* Everyone gets all permissions. */
591 	vi->i_mode |= S_IRWXUGO;
592 	/* If read-only, no one gets write permissions. */
593 	if (IS_RDONLY(vi))
594 		vi->i_mode &= ~S_IWUGO;
595 	if (m->flags & MFT_RECORD_IS_DIRECTORY) {
596 		vi->i_mode |= S_IFDIR;
597 		/*
598 		 * Apply the directory permissions mask set in the mount
599 		 * options.
600 		 */
601 		vi->i_mode &= ~vol->dmask;
602 		/* Things break without this kludge! */
603 		if (vi->i_nlink > 1)
604 			set_nlink(vi, 1);
605 	} else {
606 		vi->i_mode |= S_IFREG;
607 		/* Apply the file permissions mask set in the mount options. */
608 		vi->i_mode &= ~vol->fmask;
609 	}
610 	/*
611 	 * Find the standard information attribute in the mft record. At this
612 	 * stage we haven't setup the attribute list stuff yet, so this could
613 	 * in fact fail if the standard information is in an extent record, but
614 	 * I don't think this actually ever happens.
615 	 */
616 	err = ntfs_attr_lookup(AT_STANDARD_INFORMATION, NULL, 0, 0, 0, NULL, 0,
617 			ctx);
618 	if (unlikely(err)) {
619 		if (err == -ENOENT) {
620 			/*
621 			 * TODO: We should be performing a hot fix here (if the
622 			 * recover mount option is set) by creating a new
623 			 * attribute.
624 			 */
625 			ntfs_error(vi->i_sb, "$STANDARD_INFORMATION attribute "
626 					"is missing.");
627 		}
628 		goto unm_err_out;
629 	}
630 	a = ctx->attr;
631 	/* Get the standard information attribute value. */
632 	si = (STANDARD_INFORMATION*)((u8*)a +
633 			le16_to_cpu(a->data.resident.value_offset));
634 
635 	/* Transfer information from the standard information into vi. */
636 	/*
637 	 * Note: The i_?times do not quite map perfectly onto the NTFS times,
638 	 * but they are close enough, and in the end it doesn't really matter
639 	 * that much...
640 	 */
641 	/*
642 	 * mtime is the last change of the data within the file. Not changed
643 	 * when only metadata is changed, e.g. a rename doesn't affect mtime.
644 	 */
645 	vi->i_mtime = ntfs2utc(si->last_data_change_time);
646 	/*
647 	 * ctime is the last change of the metadata of the file. This obviously
648 	 * always changes, when mtime is changed. ctime can be changed on its
649 	 * own, mtime is then not changed, e.g. when a file is renamed.
650 	 */
651 	vi->i_ctime = ntfs2utc(si->last_mft_change_time);
652 	/*
653 	 * Last access to the data within the file. Not changed during a rename
654 	 * for example but changed whenever the file is written to.
655 	 */
656 	vi->i_atime = ntfs2utc(si->last_access_time);
657 
658 	/* Find the attribute list attribute if present. */
659 	ntfs_attr_reinit_search_ctx(ctx);
660 	err = ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx);
661 	if (err) {
662 		if (unlikely(err != -ENOENT)) {
663 			ntfs_error(vi->i_sb, "Failed to lookup attribute list "
664 					"attribute.");
665 			goto unm_err_out;
666 		}
667 	} else /* if (!err) */ {
668 		if (vi->i_ino == FILE_MFT)
669 			goto skip_attr_list_load;
670 		ntfs_debug("Attribute list found in inode 0x%lx.", vi->i_ino);
671 		NInoSetAttrList(ni);
672 		a = ctx->attr;
673 		if (a->flags & ATTR_COMPRESSION_MASK) {
674 			ntfs_error(vi->i_sb, "Attribute list attribute is "
675 					"compressed.");
676 			goto unm_err_out;
677 		}
678 		if (a->flags & ATTR_IS_ENCRYPTED ||
679 				a->flags & ATTR_IS_SPARSE) {
680 			if (a->non_resident) {
681 				ntfs_error(vi->i_sb, "Non-resident attribute "
682 						"list attribute is encrypted/"
683 						"sparse.");
684 				goto unm_err_out;
685 			}
686 			ntfs_warning(vi->i_sb, "Resident attribute list "
687 					"attribute in inode 0x%lx is marked "
688 					"encrypted/sparse which is not true.  "
689 					"However, Windows allows this and "
690 					"chkdsk does not detect or correct it "
691 					"so we will just ignore the invalid "
692 					"flags and pretend they are not set.",
693 					vi->i_ino);
694 		}
695 		/* Now allocate memory for the attribute list. */
696 		ni->attr_list_size = (u32)ntfs_attr_size(a);
697 		ni->attr_list = ntfs_malloc_nofs(ni->attr_list_size);
698 		if (!ni->attr_list) {
699 			ntfs_error(vi->i_sb, "Not enough memory to allocate "
700 					"buffer for attribute list.");
701 			err = -ENOMEM;
702 			goto unm_err_out;
703 		}
704 		if (a->non_resident) {
705 			NInoSetAttrListNonResident(ni);
706 			if (a->data.non_resident.lowest_vcn) {
707 				ntfs_error(vi->i_sb, "Attribute list has non "
708 						"zero lowest_vcn.");
709 				goto unm_err_out;
710 			}
711 			/*
712 			 * Setup the runlist. No need for locking as we have
713 			 * exclusive access to the inode at this time.
714 			 */
715 			ni->attr_list_rl.rl = ntfs_mapping_pairs_decompress(vol,
716 					a, NULL);
717 			if (IS_ERR(ni->attr_list_rl.rl)) {
718 				err = PTR_ERR(ni->attr_list_rl.rl);
719 				ni->attr_list_rl.rl = NULL;
720 				ntfs_error(vi->i_sb, "Mapping pairs "
721 						"decompression failed.");
722 				goto unm_err_out;
723 			}
724 			/* Now load the attribute list. */
725 			if ((err = load_attribute_list(vol, &ni->attr_list_rl,
726 					ni->attr_list, ni->attr_list_size,
727 					sle64_to_cpu(a->data.non_resident.
728 					initialized_size)))) {
729 				ntfs_error(vi->i_sb, "Failed to load "
730 						"attribute list attribute.");
731 				goto unm_err_out;
732 			}
733 		} else /* if (!a->non_resident) */ {
734 			if ((u8*)a + le16_to_cpu(a->data.resident.value_offset)
735 					+ le32_to_cpu(
736 					a->data.resident.value_length) >
737 					(u8*)ctx->mrec + vol->mft_record_size) {
738 				ntfs_error(vi->i_sb, "Corrupt attribute list "
739 						"in inode.");
740 				goto unm_err_out;
741 			}
742 			/* Now copy the attribute list. */
743 			memcpy(ni->attr_list, (u8*)a + le16_to_cpu(
744 					a->data.resident.value_offset),
745 					le32_to_cpu(
746 					a->data.resident.value_length));
747 		}
748 	}
749 skip_attr_list_load:
750 	/*
751 	 * If an attribute list is present we now have the attribute list value
752 	 * in ntfs_ino->attr_list and it is ntfs_ino->attr_list_size bytes.
753 	 */
754 	if (S_ISDIR(vi->i_mode)) {
755 		loff_t bvi_size;
756 		ntfs_inode *bni;
757 		INDEX_ROOT *ir;
758 		u8 *ir_end, *index_end;
759 
760 		/* It is a directory, find index root attribute. */
761 		ntfs_attr_reinit_search_ctx(ctx);
762 		err = ntfs_attr_lookup(AT_INDEX_ROOT, I30, 4, CASE_SENSITIVE,
763 				0, NULL, 0, ctx);
764 		if (unlikely(err)) {
765 			if (err == -ENOENT) {
766 				// FIXME: File is corrupt! Hot-fix with empty
767 				// index root attribute if recovery option is
768 				// set.
769 				ntfs_error(vi->i_sb, "$INDEX_ROOT attribute "
770 						"is missing.");
771 			}
772 			goto unm_err_out;
773 		}
774 		a = ctx->attr;
775 		/* Set up the state. */
776 		if (unlikely(a->non_resident)) {
777 			ntfs_error(vol->sb, "$INDEX_ROOT attribute is not "
778 					"resident.");
779 			goto unm_err_out;
780 		}
781 		/* Ensure the attribute name is placed before the value. */
782 		if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
783 				le16_to_cpu(a->data.resident.value_offset)))) {
784 			ntfs_error(vol->sb, "$INDEX_ROOT attribute name is "
785 					"placed after the attribute value.");
786 			goto unm_err_out;
787 		}
788 		/*
789 		 * Compressed/encrypted index root just means that the newly
790 		 * created files in that directory should be created compressed/
791 		 * encrypted. However index root cannot be both compressed and
792 		 * encrypted.
793 		 */
794 		if (a->flags & ATTR_COMPRESSION_MASK)
795 			NInoSetCompressed(ni);
796 		if (a->flags & ATTR_IS_ENCRYPTED) {
797 			if (a->flags & ATTR_COMPRESSION_MASK) {
798 				ntfs_error(vi->i_sb, "Found encrypted and "
799 						"compressed attribute.");
800 				goto unm_err_out;
801 			}
802 			NInoSetEncrypted(ni);
803 		}
804 		if (a->flags & ATTR_IS_SPARSE)
805 			NInoSetSparse(ni);
806 		ir = (INDEX_ROOT*)((u8*)a +
807 				le16_to_cpu(a->data.resident.value_offset));
808 		ir_end = (u8*)ir + le32_to_cpu(a->data.resident.value_length);
809 		if (ir_end > (u8*)ctx->mrec + vol->mft_record_size) {
810 			ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is "
811 					"corrupt.");
812 			goto unm_err_out;
813 		}
814 		index_end = (u8*)&ir->index +
815 				le32_to_cpu(ir->index.index_length);
816 		if (index_end > ir_end) {
817 			ntfs_error(vi->i_sb, "Directory index is corrupt.");
818 			goto unm_err_out;
819 		}
820 		if (ir->type != AT_FILE_NAME) {
821 			ntfs_error(vi->i_sb, "Indexed attribute is not "
822 					"$FILE_NAME.");
823 			goto unm_err_out;
824 		}
825 		if (ir->collation_rule != COLLATION_FILE_NAME) {
826 			ntfs_error(vi->i_sb, "Index collation rule is not "
827 					"COLLATION_FILE_NAME.");
828 			goto unm_err_out;
829 		}
830 		ni->itype.index.collation_rule = ir->collation_rule;
831 		ni->itype.index.block_size = le32_to_cpu(ir->index_block_size);
832 		if (ni->itype.index.block_size &
833 				(ni->itype.index.block_size - 1)) {
834 			ntfs_error(vi->i_sb, "Index block size (%u) is not a "
835 					"power of two.",
836 					ni->itype.index.block_size);
837 			goto unm_err_out;
838 		}
839 		if (ni->itype.index.block_size > PAGE_SIZE) {
840 			ntfs_error(vi->i_sb, "Index block size (%u) > "
841 					"PAGE_SIZE (%ld) is not "
842 					"supported.  Sorry.",
843 					ni->itype.index.block_size,
844 					PAGE_SIZE);
845 			err = -EOPNOTSUPP;
846 			goto unm_err_out;
847 		}
848 		if (ni->itype.index.block_size < NTFS_BLOCK_SIZE) {
849 			ntfs_error(vi->i_sb, "Index block size (%u) < "
850 					"NTFS_BLOCK_SIZE (%i) is not "
851 					"supported.  Sorry.",
852 					ni->itype.index.block_size,
853 					NTFS_BLOCK_SIZE);
854 			err = -EOPNOTSUPP;
855 			goto unm_err_out;
856 		}
857 		ni->itype.index.block_size_bits =
858 				ffs(ni->itype.index.block_size) - 1;
859 		/* Determine the size of a vcn in the directory index. */
860 		if (vol->cluster_size <= ni->itype.index.block_size) {
861 			ni->itype.index.vcn_size = vol->cluster_size;
862 			ni->itype.index.vcn_size_bits = vol->cluster_size_bits;
863 		} else {
864 			ni->itype.index.vcn_size = vol->sector_size;
865 			ni->itype.index.vcn_size_bits = vol->sector_size_bits;
866 		}
867 
868 		/* Setup the index allocation attribute, even if not present. */
869 		NInoSetMstProtected(ni);
870 		ni->type = AT_INDEX_ALLOCATION;
871 		ni->name = I30;
872 		ni->name_len = 4;
873 
874 		if (!(ir->index.flags & LARGE_INDEX)) {
875 			/* No index allocation. */
876 			vi->i_size = ni->initialized_size =
877 					ni->allocated_size = 0;
878 			/* We are done with the mft record, so we release it. */
879 			ntfs_attr_put_search_ctx(ctx);
880 			unmap_mft_record(ni);
881 			m = NULL;
882 			ctx = NULL;
883 			goto skip_large_dir_stuff;
884 		} /* LARGE_INDEX: Index allocation present. Setup state. */
885 		NInoSetIndexAllocPresent(ni);
886 		/* Find index allocation attribute. */
887 		ntfs_attr_reinit_search_ctx(ctx);
888 		err = ntfs_attr_lookup(AT_INDEX_ALLOCATION, I30, 4,
889 				CASE_SENSITIVE, 0, NULL, 0, ctx);
890 		if (unlikely(err)) {
891 			if (err == -ENOENT)
892 				ntfs_error(vi->i_sb, "$INDEX_ALLOCATION "
893 						"attribute is not present but "
894 						"$INDEX_ROOT indicated it is.");
895 			else
896 				ntfs_error(vi->i_sb, "Failed to lookup "
897 						"$INDEX_ALLOCATION "
898 						"attribute.");
899 			goto unm_err_out;
900 		}
901 		a = ctx->attr;
902 		if (!a->non_resident) {
903 			ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
904 					"is resident.");
905 			goto unm_err_out;
906 		}
907 		/*
908 		 * Ensure the attribute name is placed before the mapping pairs
909 		 * array.
910 		 */
911 		if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
912 				le16_to_cpu(
913 				a->data.non_resident.mapping_pairs_offset)))) {
914 			ntfs_error(vol->sb, "$INDEX_ALLOCATION attribute name "
915 					"is placed after the mapping pairs "
916 					"array.");
917 			goto unm_err_out;
918 		}
919 		if (a->flags & ATTR_IS_ENCRYPTED) {
920 			ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
921 					"is encrypted.");
922 			goto unm_err_out;
923 		}
924 		if (a->flags & ATTR_IS_SPARSE) {
925 			ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
926 					"is sparse.");
927 			goto unm_err_out;
928 		}
929 		if (a->flags & ATTR_COMPRESSION_MASK) {
930 			ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
931 					"is compressed.");
932 			goto unm_err_out;
933 		}
934 		if (a->data.non_resident.lowest_vcn) {
935 			ntfs_error(vi->i_sb, "First extent of "
936 					"$INDEX_ALLOCATION attribute has non "
937 					"zero lowest_vcn.");
938 			goto unm_err_out;
939 		}
940 		vi->i_size = sle64_to_cpu(a->data.non_resident.data_size);
941 		ni->initialized_size = sle64_to_cpu(
942 				a->data.non_resident.initialized_size);
943 		ni->allocated_size = sle64_to_cpu(
944 				a->data.non_resident.allocated_size);
945 		/*
946 		 * We are done with the mft record, so we release it. Otherwise
947 		 * we would deadlock in ntfs_attr_iget().
948 		 */
949 		ntfs_attr_put_search_ctx(ctx);
950 		unmap_mft_record(ni);
951 		m = NULL;
952 		ctx = NULL;
953 		/* Get the index bitmap attribute inode. */
954 		bvi = ntfs_attr_iget(vi, AT_BITMAP, I30, 4);
955 		if (IS_ERR(bvi)) {
956 			ntfs_error(vi->i_sb, "Failed to get bitmap attribute.");
957 			err = PTR_ERR(bvi);
958 			goto unm_err_out;
959 		}
960 		bni = NTFS_I(bvi);
961 		if (NInoCompressed(bni) || NInoEncrypted(bni) ||
962 				NInoSparse(bni)) {
963 			ntfs_error(vi->i_sb, "$BITMAP attribute is compressed "
964 					"and/or encrypted and/or sparse.");
965 			goto iput_unm_err_out;
966 		}
967 		/* Consistency check bitmap size vs. index allocation size. */
968 		bvi_size = i_size_read(bvi);
969 		if ((bvi_size << 3) < (vi->i_size >>
970 				ni->itype.index.block_size_bits)) {
971 			ntfs_error(vi->i_sb, "Index bitmap too small (0x%llx) "
972 					"for index allocation (0x%llx).",
973 					bvi_size << 3, vi->i_size);
974 			goto iput_unm_err_out;
975 		}
976 		/* No longer need the bitmap attribute inode. */
977 		iput(bvi);
978 skip_large_dir_stuff:
979 		/* Setup the operations for this inode. */
980 		vi->i_op = &ntfs_dir_inode_ops;
981 		vi->i_fop = &ntfs_dir_ops;
982 		vi->i_mapping->a_ops = &ntfs_mst_aops;
983 	} else {
984 		/* It is a file. */
985 		ntfs_attr_reinit_search_ctx(ctx);
986 
987 		/* Setup the data attribute, even if not present. */
988 		ni->type = AT_DATA;
989 		ni->name = NULL;
990 		ni->name_len = 0;
991 
992 		/* Find first extent of the unnamed data attribute. */
993 		err = ntfs_attr_lookup(AT_DATA, NULL, 0, 0, 0, NULL, 0, ctx);
994 		if (unlikely(err)) {
995 			vi->i_size = ni->initialized_size =
996 					ni->allocated_size = 0;
997 			if (err != -ENOENT) {
998 				ntfs_error(vi->i_sb, "Failed to lookup $DATA "
999 						"attribute.");
1000 				goto unm_err_out;
1001 			}
1002 			/*
1003 			 * FILE_Secure does not have an unnamed $DATA
1004 			 * attribute, so we special case it here.
1005 			 */
1006 			if (vi->i_ino == FILE_Secure)
1007 				goto no_data_attr_special_case;
1008 			/*
1009 			 * Most if not all the system files in the $Extend
1010 			 * system directory do not have unnamed data
1011 			 * attributes so we need to check if the parent
1012 			 * directory of the file is FILE_Extend and if it is
1013 			 * ignore this error. To do this we need to get the
1014 			 * name of this inode from the mft record as the name
1015 			 * contains the back reference to the parent directory.
1016 			 */
1017 			if (ntfs_is_extended_system_file(ctx) > 0)
1018 				goto no_data_attr_special_case;
1019 			// FIXME: File is corrupt! Hot-fix with empty data
1020 			// attribute if recovery option is set.
1021 			ntfs_error(vi->i_sb, "$DATA attribute is missing.");
1022 			goto unm_err_out;
1023 		}
1024 		a = ctx->attr;
1025 		/* Setup the state. */
1026 		if (a->flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) {
1027 			if (a->flags & ATTR_COMPRESSION_MASK) {
1028 				NInoSetCompressed(ni);
1029 				if (vol->cluster_size > 4096) {
1030 					ntfs_error(vi->i_sb, "Found "
1031 							"compressed data but "
1032 							"compression is "
1033 							"disabled due to "
1034 							"cluster size (%i) > "
1035 							"4kiB.",
1036 							vol->cluster_size);
1037 					goto unm_err_out;
1038 				}
1039 				if ((a->flags & ATTR_COMPRESSION_MASK)
1040 						!= ATTR_IS_COMPRESSED) {
1041 					ntfs_error(vi->i_sb, "Found unknown "
1042 							"compression method "
1043 							"or corrupt file.");
1044 					goto unm_err_out;
1045 				}
1046 			}
1047 			if (a->flags & ATTR_IS_SPARSE)
1048 				NInoSetSparse(ni);
1049 		}
1050 		if (a->flags & ATTR_IS_ENCRYPTED) {
1051 			if (NInoCompressed(ni)) {
1052 				ntfs_error(vi->i_sb, "Found encrypted and "
1053 						"compressed data.");
1054 				goto unm_err_out;
1055 			}
1056 			NInoSetEncrypted(ni);
1057 		}
1058 		if (a->non_resident) {
1059 			NInoSetNonResident(ni);
1060 			if (NInoCompressed(ni) || NInoSparse(ni)) {
1061 				if (NInoCompressed(ni) && a->data.non_resident.
1062 						compression_unit != 4) {
1063 					ntfs_error(vi->i_sb, "Found "
1064 							"non-standard "
1065 							"compression unit (%u "
1066 							"instead of 4).  "
1067 							"Cannot handle this.",
1068 							a->data.non_resident.
1069 							compression_unit);
1070 					err = -EOPNOTSUPP;
1071 					goto unm_err_out;
1072 				}
1073 				if (a->data.non_resident.compression_unit) {
1074 					ni->itype.compressed.block_size = 1U <<
1075 							(a->data.non_resident.
1076 							compression_unit +
1077 							vol->cluster_size_bits);
1078 					ni->itype.compressed.block_size_bits =
1079 							ffs(ni->itype.
1080 							compressed.
1081 							block_size) - 1;
1082 					ni->itype.compressed.block_clusters =
1083 							1U << a->data.
1084 							non_resident.
1085 							compression_unit;
1086 				} else {
1087 					ni->itype.compressed.block_size = 0;
1088 					ni->itype.compressed.block_size_bits =
1089 							0;
1090 					ni->itype.compressed.block_clusters =
1091 							0;
1092 				}
1093 				ni->itype.compressed.size = sle64_to_cpu(
1094 						a->data.non_resident.
1095 						compressed_size);
1096 			}
1097 			if (a->data.non_resident.lowest_vcn) {
1098 				ntfs_error(vi->i_sb, "First extent of $DATA "
1099 						"attribute has non zero "
1100 						"lowest_vcn.");
1101 				goto unm_err_out;
1102 			}
1103 			vi->i_size = sle64_to_cpu(
1104 					a->data.non_resident.data_size);
1105 			ni->initialized_size = sle64_to_cpu(
1106 					a->data.non_resident.initialized_size);
1107 			ni->allocated_size = sle64_to_cpu(
1108 					a->data.non_resident.allocated_size);
1109 		} else { /* Resident attribute. */
1110 			vi->i_size = ni->initialized_size = le32_to_cpu(
1111 					a->data.resident.value_length);
1112 			ni->allocated_size = le32_to_cpu(a->length) -
1113 					le16_to_cpu(
1114 					a->data.resident.value_offset);
1115 			if (vi->i_size > ni->allocated_size) {
1116 				ntfs_error(vi->i_sb, "Resident data attribute "
1117 						"is corrupt (size exceeds "
1118 						"allocation).");
1119 				goto unm_err_out;
1120 			}
1121 		}
1122 no_data_attr_special_case:
1123 		/* We are done with the mft record, so we release it. */
1124 		ntfs_attr_put_search_ctx(ctx);
1125 		unmap_mft_record(ni);
1126 		m = NULL;
1127 		ctx = NULL;
1128 		/* Setup the operations for this inode. */
1129 		vi->i_op = &ntfs_file_inode_ops;
1130 		vi->i_fop = &ntfs_file_ops;
1131 		vi->i_mapping->a_ops = &ntfs_normal_aops;
1132 		if (NInoMstProtected(ni))
1133 			vi->i_mapping->a_ops = &ntfs_mst_aops;
1134 		else if (NInoCompressed(ni))
1135 			vi->i_mapping->a_ops = &ntfs_compressed_aops;
1136 	}
1137 	/*
1138 	 * The number of 512-byte blocks used on disk (for stat). This is in so
1139 	 * far inaccurate as it doesn't account for any named streams or other
1140 	 * special non-resident attributes, but that is how Windows works, too,
1141 	 * so we are at least consistent with Windows, if not entirely
1142 	 * consistent with the Linux Way. Doing it the Linux Way would cause a
1143 	 * significant slowdown as it would involve iterating over all
1144 	 * attributes in the mft record and adding the allocated/compressed
1145 	 * sizes of all non-resident attributes present to give us the Linux
1146 	 * correct size that should go into i_blocks (after division by 512).
1147 	 */
1148 	if (S_ISREG(vi->i_mode) && (NInoCompressed(ni) || NInoSparse(ni)))
1149 		vi->i_blocks = ni->itype.compressed.size >> 9;
1150 	else
1151 		vi->i_blocks = ni->allocated_size >> 9;
1152 	ntfs_debug("Done.");
1153 	return 0;
1154 iput_unm_err_out:
1155 	iput(bvi);
1156 unm_err_out:
1157 	if (!err)
1158 		err = -EIO;
1159 	if (ctx)
1160 		ntfs_attr_put_search_ctx(ctx);
1161 	if (m)
1162 		unmap_mft_record(ni);
1163 err_out:
1164 	ntfs_error(vol->sb, "Failed with error code %i.  Marking corrupt "
1165 			"inode 0x%lx as bad.  Run chkdsk.", err, vi->i_ino);
1166 	make_bad_inode(vi);
1167 	if (err != -EOPNOTSUPP && err != -ENOMEM)
1168 		NVolSetErrors(vol);
1169 	return err;
1170 }
1171 
1172 /**
1173  * ntfs_read_locked_attr_inode - read an attribute inode from its base inode
1174  * @base_vi:	base inode
1175  * @vi:		attribute inode to read
1176  *
1177  * ntfs_read_locked_attr_inode() is called from ntfs_attr_iget() to read the
1178  * attribute inode described by @vi into memory from the base mft record
1179  * described by @base_ni.
1180  *
1181  * ntfs_read_locked_attr_inode() maps, pins and locks the base inode for
1182  * reading and looks up the attribute described by @vi before setting up the
1183  * necessary fields in @vi as well as initializing the ntfs inode.
1184  *
1185  * Q: What locks are held when the function is called?
1186  * A: i_state has I_NEW set, hence the inode is locked, also
1187  *    i_count is set to 1, so it is not going to go away
1188  *
1189  * Return 0 on success and -errno on error.  In the error case, the inode will
1190  * have had make_bad_inode() executed on it.
1191  *
1192  * Note this cannot be called for AT_INDEX_ALLOCATION.
1193  */
1194 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
1195 {
1196 	ntfs_volume *vol = NTFS_SB(vi->i_sb);
1197 	ntfs_inode *ni, *base_ni;
1198 	MFT_RECORD *m;
1199 	ATTR_RECORD *a;
1200 	ntfs_attr_search_ctx *ctx;
1201 	int err = 0;
1202 
1203 	ntfs_debug("Entering for i_ino 0x%lx.", vi->i_ino);
1204 
1205 	ntfs_init_big_inode(vi);
1206 
1207 	ni	= NTFS_I(vi);
1208 	base_ni = NTFS_I(base_vi);
1209 
1210 	/* Just mirror the values from the base inode. */
1211 	vi->i_uid	= base_vi->i_uid;
1212 	vi->i_gid	= base_vi->i_gid;
1213 	set_nlink(vi, base_vi->i_nlink);
1214 	vi->i_mtime	= base_vi->i_mtime;
1215 	vi->i_ctime	= base_vi->i_ctime;
1216 	vi->i_atime	= base_vi->i_atime;
1217 	vi->i_generation = ni->seq_no = base_ni->seq_no;
1218 
1219 	/* Set inode type to zero but preserve permissions. */
1220 	vi->i_mode	= base_vi->i_mode & ~S_IFMT;
1221 
1222 	m = map_mft_record(base_ni);
1223 	if (IS_ERR(m)) {
1224 		err = PTR_ERR(m);
1225 		goto err_out;
1226 	}
1227 	ctx = ntfs_attr_get_search_ctx(base_ni, m);
1228 	if (!ctx) {
1229 		err = -ENOMEM;
1230 		goto unm_err_out;
1231 	}
1232 	/* Find the attribute. */
1233 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1234 			CASE_SENSITIVE, 0, NULL, 0, ctx);
1235 	if (unlikely(err))
1236 		goto unm_err_out;
1237 	a = ctx->attr;
1238 	if (a->flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) {
1239 		if (a->flags & ATTR_COMPRESSION_MASK) {
1240 			NInoSetCompressed(ni);
1241 			if ((ni->type != AT_DATA) || (ni->type == AT_DATA &&
1242 					ni->name_len)) {
1243 				ntfs_error(vi->i_sb, "Found compressed "
1244 						"non-data or named data "
1245 						"attribute.  Please report "
1246 						"you saw this message to "
1247 						"linux-ntfs-dev@lists."
1248 						"sourceforge.net");
1249 				goto unm_err_out;
1250 			}
1251 			if (vol->cluster_size > 4096) {
1252 				ntfs_error(vi->i_sb, "Found compressed "
1253 						"attribute but compression is "
1254 						"disabled due to cluster size "
1255 						"(%i) > 4kiB.",
1256 						vol->cluster_size);
1257 				goto unm_err_out;
1258 			}
1259 			if ((a->flags & ATTR_COMPRESSION_MASK) !=
1260 					ATTR_IS_COMPRESSED) {
1261 				ntfs_error(vi->i_sb, "Found unknown "
1262 						"compression method.");
1263 				goto unm_err_out;
1264 			}
1265 		}
1266 		/*
1267 		 * The compressed/sparse flag set in an index root just means
1268 		 * to compress all files.
1269 		 */
1270 		if (NInoMstProtected(ni) && ni->type != AT_INDEX_ROOT) {
1271 			ntfs_error(vi->i_sb, "Found mst protected attribute "
1272 					"but the attribute is %s.  Please "
1273 					"report you saw this message to "
1274 					"linux-ntfs-dev@lists.sourceforge.net",
1275 					NInoCompressed(ni) ? "compressed" :
1276 					"sparse");
1277 			goto unm_err_out;
1278 		}
1279 		if (a->flags & ATTR_IS_SPARSE)
1280 			NInoSetSparse(ni);
1281 	}
1282 	if (a->flags & ATTR_IS_ENCRYPTED) {
1283 		if (NInoCompressed(ni)) {
1284 			ntfs_error(vi->i_sb, "Found encrypted and compressed "
1285 					"data.");
1286 			goto unm_err_out;
1287 		}
1288 		/*
1289 		 * The encryption flag set in an index root just means to
1290 		 * encrypt all files.
1291 		 */
1292 		if (NInoMstProtected(ni) && ni->type != AT_INDEX_ROOT) {
1293 			ntfs_error(vi->i_sb, "Found mst protected attribute "
1294 					"but the attribute is encrypted.  "
1295 					"Please report you saw this message "
1296 					"to linux-ntfs-dev@lists.sourceforge."
1297 					"net");
1298 			goto unm_err_out;
1299 		}
1300 		if (ni->type != AT_DATA) {
1301 			ntfs_error(vi->i_sb, "Found encrypted non-data "
1302 					"attribute.");
1303 			goto unm_err_out;
1304 		}
1305 		NInoSetEncrypted(ni);
1306 	}
1307 	if (!a->non_resident) {
1308 		/* Ensure the attribute name is placed before the value. */
1309 		if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1310 				le16_to_cpu(a->data.resident.value_offset)))) {
1311 			ntfs_error(vol->sb, "Attribute name is placed after "
1312 					"the attribute value.");
1313 			goto unm_err_out;
1314 		}
1315 		if (NInoMstProtected(ni)) {
1316 			ntfs_error(vi->i_sb, "Found mst protected attribute "
1317 					"but the attribute is resident.  "
1318 					"Please report you saw this message to "
1319 					"linux-ntfs-dev@lists.sourceforge.net");
1320 			goto unm_err_out;
1321 		}
1322 		vi->i_size = ni->initialized_size = le32_to_cpu(
1323 				a->data.resident.value_length);
1324 		ni->allocated_size = le32_to_cpu(a->length) -
1325 				le16_to_cpu(a->data.resident.value_offset);
1326 		if (vi->i_size > ni->allocated_size) {
1327 			ntfs_error(vi->i_sb, "Resident attribute is corrupt "
1328 					"(size exceeds allocation).");
1329 			goto unm_err_out;
1330 		}
1331 	} else {
1332 		NInoSetNonResident(ni);
1333 		/*
1334 		 * Ensure the attribute name is placed before the mapping pairs
1335 		 * array.
1336 		 */
1337 		if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1338 				le16_to_cpu(
1339 				a->data.non_resident.mapping_pairs_offset)))) {
1340 			ntfs_error(vol->sb, "Attribute name is placed after "
1341 					"the mapping pairs array.");
1342 			goto unm_err_out;
1343 		}
1344 		if (NInoCompressed(ni) || NInoSparse(ni)) {
1345 			if (NInoCompressed(ni) && a->data.non_resident.
1346 					compression_unit != 4) {
1347 				ntfs_error(vi->i_sb, "Found non-standard "
1348 						"compression unit (%u instead "
1349 						"of 4).  Cannot handle this.",
1350 						a->data.non_resident.
1351 						compression_unit);
1352 				err = -EOPNOTSUPP;
1353 				goto unm_err_out;
1354 			}
1355 			if (a->data.non_resident.compression_unit) {
1356 				ni->itype.compressed.block_size = 1U <<
1357 						(a->data.non_resident.
1358 						compression_unit +
1359 						vol->cluster_size_bits);
1360 				ni->itype.compressed.block_size_bits =
1361 						ffs(ni->itype.compressed.
1362 						block_size) - 1;
1363 				ni->itype.compressed.block_clusters = 1U <<
1364 						a->data.non_resident.
1365 						compression_unit;
1366 			} else {
1367 				ni->itype.compressed.block_size = 0;
1368 				ni->itype.compressed.block_size_bits = 0;
1369 				ni->itype.compressed.block_clusters = 0;
1370 			}
1371 			ni->itype.compressed.size = sle64_to_cpu(
1372 					a->data.non_resident.compressed_size);
1373 		}
1374 		if (a->data.non_resident.lowest_vcn) {
1375 			ntfs_error(vi->i_sb, "First extent of attribute has "
1376 					"non-zero lowest_vcn.");
1377 			goto unm_err_out;
1378 		}
1379 		vi->i_size = sle64_to_cpu(a->data.non_resident.data_size);
1380 		ni->initialized_size = sle64_to_cpu(
1381 				a->data.non_resident.initialized_size);
1382 		ni->allocated_size = sle64_to_cpu(
1383 				a->data.non_resident.allocated_size);
1384 	}
1385 	vi->i_mapping->a_ops = &ntfs_normal_aops;
1386 	if (NInoMstProtected(ni))
1387 		vi->i_mapping->a_ops = &ntfs_mst_aops;
1388 	else if (NInoCompressed(ni))
1389 		vi->i_mapping->a_ops = &ntfs_compressed_aops;
1390 	if ((NInoCompressed(ni) || NInoSparse(ni)) && ni->type != AT_INDEX_ROOT)
1391 		vi->i_blocks = ni->itype.compressed.size >> 9;
1392 	else
1393 		vi->i_blocks = ni->allocated_size >> 9;
1394 	/*
1395 	 * Make sure the base inode does not go away and attach it to the
1396 	 * attribute inode.
1397 	 */
1398 	igrab(base_vi);
1399 	ni->ext.base_ntfs_ino = base_ni;
1400 	ni->nr_extents = -1;
1401 
1402 	ntfs_attr_put_search_ctx(ctx);
1403 	unmap_mft_record(base_ni);
1404 
1405 	ntfs_debug("Done.");
1406 	return 0;
1407 
1408 unm_err_out:
1409 	if (!err)
1410 		err = -EIO;
1411 	if (ctx)
1412 		ntfs_attr_put_search_ctx(ctx);
1413 	unmap_mft_record(base_ni);
1414 err_out:
1415 	ntfs_error(vol->sb, "Failed with error code %i while reading attribute "
1416 			"inode (mft_no 0x%lx, type 0x%x, name_len %i).  "
1417 			"Marking corrupt inode and base inode 0x%lx as bad.  "
1418 			"Run chkdsk.", err, vi->i_ino, ni->type, ni->name_len,
1419 			base_vi->i_ino);
1420 	make_bad_inode(vi);
1421 	if (err != -ENOMEM)
1422 		NVolSetErrors(vol);
1423 	return err;
1424 }
1425 
1426 /**
1427  * ntfs_read_locked_index_inode - read an index inode from its base inode
1428  * @base_vi:	base inode
1429  * @vi:		index inode to read
1430  *
1431  * ntfs_read_locked_index_inode() is called from ntfs_index_iget() to read the
1432  * index inode described by @vi into memory from the base mft record described
1433  * by @base_ni.
1434  *
1435  * ntfs_read_locked_index_inode() maps, pins and locks the base inode for
1436  * reading and looks up the attributes relating to the index described by @vi
1437  * before setting up the necessary fields in @vi as well as initializing the
1438  * ntfs inode.
1439  *
1440  * Note, index inodes are essentially attribute inodes (NInoAttr() is true)
1441  * with the attribute type set to AT_INDEX_ALLOCATION.  Apart from that, they
1442  * are setup like directory inodes since directories are a special case of
1443  * indices ao they need to be treated in much the same way.  Most importantly,
1444  * for small indices the index allocation attribute might not actually exist.
1445  * However, the index root attribute always exists but this does not need to
1446  * have an inode associated with it and this is why we define a new inode type
1447  * index.  Also, like for directories, we need to have an attribute inode for
1448  * the bitmap attribute corresponding to the index allocation attribute and we
1449  * can store this in the appropriate field of the inode, just like we do for
1450  * normal directory inodes.
1451  *
1452  * Q: What locks are held when the function is called?
1453  * A: i_state has I_NEW set, hence the inode is locked, also
1454  *    i_count is set to 1, so it is not going to go away
1455  *
1456  * Return 0 on success and -errno on error.  In the error case, the inode will
1457  * have had make_bad_inode() executed on it.
1458  */
1459 static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)
1460 {
1461 	loff_t bvi_size;
1462 	ntfs_volume *vol = NTFS_SB(vi->i_sb);
1463 	ntfs_inode *ni, *base_ni, *bni;
1464 	struct inode *bvi;
1465 	MFT_RECORD *m;
1466 	ATTR_RECORD *a;
1467 	ntfs_attr_search_ctx *ctx;
1468 	INDEX_ROOT *ir;
1469 	u8 *ir_end, *index_end;
1470 	int err = 0;
1471 
1472 	ntfs_debug("Entering for i_ino 0x%lx.", vi->i_ino);
1473 	ntfs_init_big_inode(vi);
1474 	ni	= NTFS_I(vi);
1475 	base_ni = NTFS_I(base_vi);
1476 	/* Just mirror the values from the base inode. */
1477 	vi->i_uid	= base_vi->i_uid;
1478 	vi->i_gid	= base_vi->i_gid;
1479 	set_nlink(vi, base_vi->i_nlink);
1480 	vi->i_mtime	= base_vi->i_mtime;
1481 	vi->i_ctime	= base_vi->i_ctime;
1482 	vi->i_atime	= base_vi->i_atime;
1483 	vi->i_generation = ni->seq_no = base_ni->seq_no;
1484 	/* Set inode type to zero but preserve permissions. */
1485 	vi->i_mode	= base_vi->i_mode & ~S_IFMT;
1486 	/* Map the mft record for the base inode. */
1487 	m = map_mft_record(base_ni);
1488 	if (IS_ERR(m)) {
1489 		err = PTR_ERR(m);
1490 		goto err_out;
1491 	}
1492 	ctx = ntfs_attr_get_search_ctx(base_ni, m);
1493 	if (!ctx) {
1494 		err = -ENOMEM;
1495 		goto unm_err_out;
1496 	}
1497 	/* Find the index root attribute. */
1498 	err = ntfs_attr_lookup(AT_INDEX_ROOT, ni->name, ni->name_len,
1499 			CASE_SENSITIVE, 0, NULL, 0, ctx);
1500 	if (unlikely(err)) {
1501 		if (err == -ENOENT)
1502 			ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is "
1503 					"missing.");
1504 		goto unm_err_out;
1505 	}
1506 	a = ctx->attr;
1507 	/* Set up the state. */
1508 	if (unlikely(a->non_resident)) {
1509 		ntfs_error(vol->sb, "$INDEX_ROOT attribute is not resident.");
1510 		goto unm_err_out;
1511 	}
1512 	/* Ensure the attribute name is placed before the value. */
1513 	if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1514 			le16_to_cpu(a->data.resident.value_offset)))) {
1515 		ntfs_error(vol->sb, "$INDEX_ROOT attribute name is placed "
1516 				"after the attribute value.");
1517 		goto unm_err_out;
1518 	}
1519 	/*
1520 	 * Compressed/encrypted/sparse index root is not allowed, except for
1521 	 * directories of course but those are not dealt with here.
1522 	 */
1523 	if (a->flags & (ATTR_COMPRESSION_MASK | ATTR_IS_ENCRYPTED |
1524 			ATTR_IS_SPARSE)) {
1525 		ntfs_error(vi->i_sb, "Found compressed/encrypted/sparse index "
1526 				"root attribute.");
1527 		goto unm_err_out;
1528 	}
1529 	ir = (INDEX_ROOT*)((u8*)a + le16_to_cpu(a->data.resident.value_offset));
1530 	ir_end = (u8*)ir + le32_to_cpu(a->data.resident.value_length);
1531 	if (ir_end > (u8*)ctx->mrec + vol->mft_record_size) {
1532 		ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is corrupt.");
1533 		goto unm_err_out;
1534 	}
1535 	index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
1536 	if (index_end > ir_end) {
1537 		ntfs_error(vi->i_sb, "Index is corrupt.");
1538 		goto unm_err_out;
1539 	}
1540 	if (ir->type) {
1541 		ntfs_error(vi->i_sb, "Index type is not 0 (type is 0x%x).",
1542 				le32_to_cpu(ir->type));
1543 		goto unm_err_out;
1544 	}
1545 	ni->itype.index.collation_rule = ir->collation_rule;
1546 	ntfs_debug("Index collation rule is 0x%x.",
1547 			le32_to_cpu(ir->collation_rule));
1548 	ni->itype.index.block_size = le32_to_cpu(ir->index_block_size);
1549 	if (!is_power_of_2(ni->itype.index.block_size)) {
1550 		ntfs_error(vi->i_sb, "Index block size (%u) is not a power of "
1551 				"two.", ni->itype.index.block_size);
1552 		goto unm_err_out;
1553 	}
1554 	if (ni->itype.index.block_size > PAGE_SIZE) {
1555 		ntfs_error(vi->i_sb, "Index block size (%u) > PAGE_SIZE "
1556 				"(%ld) is not supported.  Sorry.",
1557 				ni->itype.index.block_size, PAGE_SIZE);
1558 		err = -EOPNOTSUPP;
1559 		goto unm_err_out;
1560 	}
1561 	if (ni->itype.index.block_size < NTFS_BLOCK_SIZE) {
1562 		ntfs_error(vi->i_sb, "Index block size (%u) < NTFS_BLOCK_SIZE "
1563 				"(%i) is not supported.  Sorry.",
1564 				ni->itype.index.block_size, NTFS_BLOCK_SIZE);
1565 		err = -EOPNOTSUPP;
1566 		goto unm_err_out;
1567 	}
1568 	ni->itype.index.block_size_bits = ffs(ni->itype.index.block_size) - 1;
1569 	/* Determine the size of a vcn in the index. */
1570 	if (vol->cluster_size <= ni->itype.index.block_size) {
1571 		ni->itype.index.vcn_size = vol->cluster_size;
1572 		ni->itype.index.vcn_size_bits = vol->cluster_size_bits;
1573 	} else {
1574 		ni->itype.index.vcn_size = vol->sector_size;
1575 		ni->itype.index.vcn_size_bits = vol->sector_size_bits;
1576 	}
1577 	/* Check for presence of index allocation attribute. */
1578 	if (!(ir->index.flags & LARGE_INDEX)) {
1579 		/* No index allocation. */
1580 		vi->i_size = ni->initialized_size = ni->allocated_size = 0;
1581 		/* We are done with the mft record, so we release it. */
1582 		ntfs_attr_put_search_ctx(ctx);
1583 		unmap_mft_record(base_ni);
1584 		m = NULL;
1585 		ctx = NULL;
1586 		goto skip_large_index_stuff;
1587 	} /* LARGE_INDEX:  Index allocation present.  Setup state. */
1588 	NInoSetIndexAllocPresent(ni);
1589 	/* Find index allocation attribute. */
1590 	ntfs_attr_reinit_search_ctx(ctx);
1591 	err = ntfs_attr_lookup(AT_INDEX_ALLOCATION, ni->name, ni->name_len,
1592 			CASE_SENSITIVE, 0, NULL, 0, ctx);
1593 	if (unlikely(err)) {
1594 		if (err == -ENOENT)
1595 			ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is "
1596 					"not present but $INDEX_ROOT "
1597 					"indicated it is.");
1598 		else
1599 			ntfs_error(vi->i_sb, "Failed to lookup "
1600 					"$INDEX_ALLOCATION attribute.");
1601 		goto unm_err_out;
1602 	}
1603 	a = ctx->attr;
1604 	if (!a->non_resident) {
1605 		ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is "
1606 				"resident.");
1607 		goto unm_err_out;
1608 	}
1609 	/*
1610 	 * Ensure the attribute name is placed before the mapping pairs array.
1611 	 */
1612 	if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1613 			le16_to_cpu(
1614 			a->data.non_resident.mapping_pairs_offset)))) {
1615 		ntfs_error(vol->sb, "$INDEX_ALLOCATION attribute name is "
1616 				"placed after the mapping pairs array.");
1617 		goto unm_err_out;
1618 	}
1619 	if (a->flags & ATTR_IS_ENCRYPTED) {
1620 		ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is "
1621 				"encrypted.");
1622 		goto unm_err_out;
1623 	}
1624 	if (a->flags & ATTR_IS_SPARSE) {
1625 		ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is sparse.");
1626 		goto unm_err_out;
1627 	}
1628 	if (a->flags & ATTR_COMPRESSION_MASK) {
1629 		ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is "
1630 				"compressed.");
1631 		goto unm_err_out;
1632 	}
1633 	if (a->data.non_resident.lowest_vcn) {
1634 		ntfs_error(vi->i_sb, "First extent of $INDEX_ALLOCATION "
1635 				"attribute has non zero lowest_vcn.");
1636 		goto unm_err_out;
1637 	}
1638 	vi->i_size = sle64_to_cpu(a->data.non_resident.data_size);
1639 	ni->initialized_size = sle64_to_cpu(
1640 			a->data.non_resident.initialized_size);
1641 	ni->allocated_size = sle64_to_cpu(a->data.non_resident.allocated_size);
1642 	/*
1643 	 * We are done with the mft record, so we release it.  Otherwise
1644 	 * we would deadlock in ntfs_attr_iget().
1645 	 */
1646 	ntfs_attr_put_search_ctx(ctx);
1647 	unmap_mft_record(base_ni);
1648 	m = NULL;
1649 	ctx = NULL;
1650 	/* Get the index bitmap attribute inode. */
1651 	bvi = ntfs_attr_iget(base_vi, AT_BITMAP, ni->name, ni->name_len);
1652 	if (IS_ERR(bvi)) {
1653 		ntfs_error(vi->i_sb, "Failed to get bitmap attribute.");
1654 		err = PTR_ERR(bvi);
1655 		goto unm_err_out;
1656 	}
1657 	bni = NTFS_I(bvi);
1658 	if (NInoCompressed(bni) || NInoEncrypted(bni) ||
1659 			NInoSparse(bni)) {
1660 		ntfs_error(vi->i_sb, "$BITMAP attribute is compressed and/or "
1661 				"encrypted and/or sparse.");
1662 		goto iput_unm_err_out;
1663 	}
1664 	/* Consistency check bitmap size vs. index allocation size. */
1665 	bvi_size = i_size_read(bvi);
1666 	if ((bvi_size << 3) < (vi->i_size >> ni->itype.index.block_size_bits)) {
1667 		ntfs_error(vi->i_sb, "Index bitmap too small (0x%llx) for "
1668 				"index allocation (0x%llx).", bvi_size << 3,
1669 				vi->i_size);
1670 		goto iput_unm_err_out;
1671 	}
1672 	iput(bvi);
1673 skip_large_index_stuff:
1674 	/* Setup the operations for this index inode. */
1675 	vi->i_mapping->a_ops = &ntfs_mst_aops;
1676 	vi->i_blocks = ni->allocated_size >> 9;
1677 	/*
1678 	 * Make sure the base inode doesn't go away and attach it to the
1679 	 * index inode.
1680 	 */
1681 	igrab(base_vi);
1682 	ni->ext.base_ntfs_ino = base_ni;
1683 	ni->nr_extents = -1;
1684 
1685 	ntfs_debug("Done.");
1686 	return 0;
1687 iput_unm_err_out:
1688 	iput(bvi);
1689 unm_err_out:
1690 	if (!err)
1691 		err = -EIO;
1692 	if (ctx)
1693 		ntfs_attr_put_search_ctx(ctx);
1694 	if (m)
1695 		unmap_mft_record(base_ni);
1696 err_out:
1697 	ntfs_error(vi->i_sb, "Failed with error code %i while reading index "
1698 			"inode (mft_no 0x%lx, name_len %i.", err, vi->i_ino,
1699 			ni->name_len);
1700 	make_bad_inode(vi);
1701 	if (err != -EOPNOTSUPP && err != -ENOMEM)
1702 		NVolSetErrors(vol);
1703 	return err;
1704 }
1705 
1706 /*
1707  * The MFT inode has special locking, so teach the lock validator
1708  * about this by splitting off the locking rules of the MFT from
1709  * the locking rules of other inodes. The MFT inode can never be
1710  * accessed from the VFS side (or even internally), only by the
1711  * map_mft functions.
1712  */
1713 static struct lock_class_key mft_ni_runlist_lock_key, mft_ni_mrec_lock_key;
1714 
1715 /**
1716  * ntfs_read_inode_mount - special read_inode for mount time use only
1717  * @vi:		inode to read
1718  *
1719  * Read inode FILE_MFT at mount time, only called with super_block lock
1720  * held from within the read_super() code path.
1721  *
1722  * This function exists because when it is called the page cache for $MFT/$DATA
1723  * is not initialized and hence we cannot get at the contents of mft records
1724  * by calling map_mft_record*().
1725  *
1726  * Further it needs to cope with the circular references problem, i.e. cannot
1727  * load any attributes other than $ATTRIBUTE_LIST until $DATA is loaded, because
1728  * we do not know where the other extent mft records are yet and again, because
1729  * we cannot call map_mft_record*() yet.  Obviously this applies only when an
1730  * attribute list is actually present in $MFT inode.
1731  *
1732  * We solve these problems by starting with the $DATA attribute before anything
1733  * else and iterating using ntfs_attr_lookup($DATA) over all extents.  As each
1734  * extent is found, we ntfs_mapping_pairs_decompress() including the implied
1735  * ntfs_runlists_merge().  Each step of the iteration necessarily provides
1736  * sufficient information for the next step to complete.
1737  *
1738  * This should work but there are two possible pit falls (see inline comments
1739  * below), but only time will tell if they are real pits or just smoke...
1740  */
1741 int ntfs_read_inode_mount(struct inode *vi)
1742 {
1743 	VCN next_vcn, last_vcn, highest_vcn;
1744 	s64 block;
1745 	struct super_block *sb = vi->i_sb;
1746 	ntfs_volume *vol = NTFS_SB(sb);
1747 	struct buffer_head *bh;
1748 	ntfs_inode *ni;
1749 	MFT_RECORD *m = NULL;
1750 	ATTR_RECORD *a;
1751 	ntfs_attr_search_ctx *ctx;
1752 	unsigned int i, nr_blocks;
1753 	int err;
1754 
1755 	ntfs_debug("Entering.");
1756 
1757 	/* Initialize the ntfs specific part of @vi. */
1758 	ntfs_init_big_inode(vi);
1759 
1760 	ni = NTFS_I(vi);
1761 
1762 	/* Setup the data attribute. It is special as it is mst protected. */
1763 	NInoSetNonResident(ni);
1764 	NInoSetMstProtected(ni);
1765 	NInoSetSparseDisabled(ni);
1766 	ni->type = AT_DATA;
1767 	ni->name = NULL;
1768 	ni->name_len = 0;
1769 	/*
1770 	 * This sets up our little cheat allowing us to reuse the async read io
1771 	 * completion handler for directories.
1772 	 */
1773 	ni->itype.index.block_size = vol->mft_record_size;
1774 	ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1775 
1776 	/* Very important! Needed to be able to call map_mft_record*(). */
1777 	vol->mft_ino = vi;
1778 
1779 	/* Allocate enough memory to read the first mft record. */
1780 	if (vol->mft_record_size > 64 * 1024) {
1781 		ntfs_error(sb, "Unsupported mft record size %i (max 64kiB).",
1782 				vol->mft_record_size);
1783 		goto err_out;
1784 	}
1785 	i = vol->mft_record_size;
1786 	if (i < sb->s_blocksize)
1787 		i = sb->s_blocksize;
1788 	m = (MFT_RECORD*)ntfs_malloc_nofs(i);
1789 	if (!m) {
1790 		ntfs_error(sb, "Failed to allocate buffer for $MFT record 0.");
1791 		goto err_out;
1792 	}
1793 
1794 	/* Determine the first block of the $MFT/$DATA attribute. */
1795 	block = vol->mft_lcn << vol->cluster_size_bits >>
1796 			sb->s_blocksize_bits;
1797 	nr_blocks = vol->mft_record_size >> sb->s_blocksize_bits;
1798 	if (!nr_blocks)
1799 		nr_blocks = 1;
1800 
1801 	/* Load $MFT/$DATA's first mft record. */
1802 	for (i = 0; i < nr_blocks; i++) {
1803 		bh = sb_bread(sb, block++);
1804 		if (!bh) {
1805 			ntfs_error(sb, "Device read failed.");
1806 			goto err_out;
1807 		}
1808 		memcpy((char*)m + (i << sb->s_blocksize_bits), bh->b_data,
1809 				sb->s_blocksize);
1810 		brelse(bh);
1811 	}
1812 
1813 	if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) {
1814 		ntfs_error(sb, "Incorrect mft record size %u in superblock, should be %u.",
1815 				le32_to_cpu(m->bytes_allocated), vol->mft_record_size);
1816 		goto err_out;
1817 	}
1818 
1819 	/* Apply the mst fixups. */
1820 	if (post_read_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size)) {
1821 		/* FIXME: Try to use the $MFTMirr now. */
1822 		ntfs_error(sb, "MST fixup failed. $MFT is corrupt.");
1823 		goto err_out;
1824 	}
1825 
1826 	/* Need this to sanity check attribute list references to $MFT. */
1827 	vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
1828 
1829 	/* Provides readpage() for map_mft_record(). */
1830 	vi->i_mapping->a_ops = &ntfs_mst_aops;
1831 
1832 	ctx = ntfs_attr_get_search_ctx(ni, m);
1833 	if (!ctx) {
1834 		err = -ENOMEM;
1835 		goto err_out;
1836 	}
1837 
1838 	/* Find the attribute list attribute if present. */
1839 	err = ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx);
1840 	if (err) {
1841 		if (unlikely(err != -ENOENT)) {
1842 			ntfs_error(sb, "Failed to lookup attribute list "
1843 					"attribute. You should run chkdsk.");
1844 			goto put_err_out;
1845 		}
1846 	} else /* if (!err) */ {
1847 		ATTR_LIST_ENTRY *al_entry, *next_al_entry;
1848 		u8 *al_end;
1849 		static const char *es = "  Not allowed.  $MFT is corrupt.  "
1850 				"You should run chkdsk.";
1851 
1852 		ntfs_debug("Attribute list attribute found in $MFT.");
1853 		NInoSetAttrList(ni);
1854 		a = ctx->attr;
1855 		if (a->flags & ATTR_COMPRESSION_MASK) {
1856 			ntfs_error(sb, "Attribute list attribute is "
1857 					"compressed.%s", es);
1858 			goto put_err_out;
1859 		}
1860 		if (a->flags & ATTR_IS_ENCRYPTED ||
1861 				a->flags & ATTR_IS_SPARSE) {
1862 			if (a->non_resident) {
1863 				ntfs_error(sb, "Non-resident attribute list "
1864 						"attribute is encrypted/"
1865 						"sparse.%s", es);
1866 				goto put_err_out;
1867 			}
1868 			ntfs_warning(sb, "Resident attribute list attribute "
1869 					"in $MFT system file is marked "
1870 					"encrypted/sparse which is not true.  "
1871 					"However, Windows allows this and "
1872 					"chkdsk does not detect or correct it "
1873 					"so we will just ignore the invalid "
1874 					"flags and pretend they are not set.");
1875 		}
1876 		/* Now allocate memory for the attribute list. */
1877 		ni->attr_list_size = (u32)ntfs_attr_size(a);
1878 		ni->attr_list = ntfs_malloc_nofs(ni->attr_list_size);
1879 		if (!ni->attr_list) {
1880 			ntfs_error(sb, "Not enough memory to allocate buffer "
1881 					"for attribute list.");
1882 			goto put_err_out;
1883 		}
1884 		if (a->non_resident) {
1885 			NInoSetAttrListNonResident(ni);
1886 			if (a->data.non_resident.lowest_vcn) {
1887 				ntfs_error(sb, "Attribute list has non zero "
1888 						"lowest_vcn. $MFT is corrupt. "
1889 						"You should run chkdsk.");
1890 				goto put_err_out;
1891 			}
1892 			/* Setup the runlist. */
1893 			ni->attr_list_rl.rl = ntfs_mapping_pairs_decompress(vol,
1894 					a, NULL);
1895 			if (IS_ERR(ni->attr_list_rl.rl)) {
1896 				err = PTR_ERR(ni->attr_list_rl.rl);
1897 				ni->attr_list_rl.rl = NULL;
1898 				ntfs_error(sb, "Mapping pairs decompression "
1899 						"failed with error code %i.",
1900 						-err);
1901 				goto put_err_out;
1902 			}
1903 			/* Now load the attribute list. */
1904 			if ((err = load_attribute_list(vol, &ni->attr_list_rl,
1905 					ni->attr_list, ni->attr_list_size,
1906 					sle64_to_cpu(a->data.
1907 					non_resident.initialized_size)))) {
1908 				ntfs_error(sb, "Failed to load attribute list "
1909 						"attribute with error code %i.",
1910 						-err);
1911 				goto put_err_out;
1912 			}
1913 		} else /* if (!ctx.attr->non_resident) */ {
1914 			if ((u8*)a + le16_to_cpu(
1915 					a->data.resident.value_offset) +
1916 					le32_to_cpu(
1917 					a->data.resident.value_length) >
1918 					(u8*)ctx->mrec + vol->mft_record_size) {
1919 				ntfs_error(sb, "Corrupt attribute list "
1920 						"attribute.");
1921 				goto put_err_out;
1922 			}
1923 			/* Now copy the attribute list. */
1924 			memcpy(ni->attr_list, (u8*)a + le16_to_cpu(
1925 					a->data.resident.value_offset),
1926 					le32_to_cpu(
1927 					a->data.resident.value_length));
1928 		}
1929 		/* The attribute list is now setup in memory. */
1930 		/*
1931 		 * FIXME: I don't know if this case is actually possible.
1932 		 * According to logic it is not possible but I have seen too
1933 		 * many weird things in MS software to rely on logic... Thus we
1934 		 * perform a manual search and make sure the first $MFT/$DATA
1935 		 * extent is in the base inode. If it is not we abort with an
1936 		 * error and if we ever see a report of this error we will need
1937 		 * to do some magic in order to have the necessary mft record
1938 		 * loaded and in the right place in the page cache. But
1939 		 * hopefully logic will prevail and this never happens...
1940 		 */
1941 		al_entry = (ATTR_LIST_ENTRY*)ni->attr_list;
1942 		al_end = (u8*)al_entry + ni->attr_list_size;
1943 		for (;; al_entry = next_al_entry) {
1944 			/* Out of bounds check. */
1945 			if ((u8*)al_entry < ni->attr_list ||
1946 					(u8*)al_entry > al_end)
1947 				goto em_put_err_out;
1948 			/* Catch the end of the attribute list. */
1949 			if ((u8*)al_entry == al_end)
1950 				goto em_put_err_out;
1951 			if (!al_entry->length)
1952 				goto em_put_err_out;
1953 			if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
1954 					le16_to_cpu(al_entry->length) > al_end)
1955 				goto em_put_err_out;
1956 			next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
1957 					le16_to_cpu(al_entry->length));
1958 			if (le32_to_cpu(al_entry->type) > le32_to_cpu(AT_DATA))
1959 				goto em_put_err_out;
1960 			if (AT_DATA != al_entry->type)
1961 				continue;
1962 			/* We want an unnamed attribute. */
1963 			if (al_entry->name_length)
1964 				goto em_put_err_out;
1965 			/* Want the first entry, i.e. lowest_vcn == 0. */
1966 			if (al_entry->lowest_vcn)
1967 				goto em_put_err_out;
1968 			/* First entry has to be in the base mft record. */
1969 			if (MREF_LE(al_entry->mft_reference) != vi->i_ino) {
1970 				/* MFT references do not match, logic fails. */
1971 				ntfs_error(sb, "BUG: The first $DATA extent "
1972 						"of $MFT is not in the base "
1973 						"mft record. Please report "
1974 						"you saw this message to "
1975 						"linux-ntfs-dev@lists."
1976 						"sourceforge.net");
1977 				goto put_err_out;
1978 			} else {
1979 				/* Sequence numbers must match. */
1980 				if (MSEQNO_LE(al_entry->mft_reference) !=
1981 						ni->seq_no)
1982 					goto em_put_err_out;
1983 				/* Got it. All is ok. We can stop now. */
1984 				break;
1985 			}
1986 		}
1987 	}
1988 
1989 	ntfs_attr_reinit_search_ctx(ctx);
1990 
1991 	/* Now load all attribute extents. */
1992 	a = NULL;
1993 	next_vcn = last_vcn = highest_vcn = 0;
1994 	while (!(err = ntfs_attr_lookup(AT_DATA, NULL, 0, 0, next_vcn, NULL, 0,
1995 			ctx))) {
1996 		runlist_element *nrl;
1997 
1998 		/* Cache the current attribute. */
1999 		a = ctx->attr;
2000 		/* $MFT must be non-resident. */
2001 		if (!a->non_resident) {
2002 			ntfs_error(sb, "$MFT must be non-resident but a "
2003 					"resident extent was found. $MFT is "
2004 					"corrupt. Run chkdsk.");
2005 			goto put_err_out;
2006 		}
2007 		/* $MFT must be uncompressed and unencrypted. */
2008 		if (a->flags & ATTR_COMPRESSION_MASK ||
2009 				a->flags & ATTR_IS_ENCRYPTED ||
2010 				a->flags & ATTR_IS_SPARSE) {
2011 			ntfs_error(sb, "$MFT must be uncompressed, "
2012 					"non-sparse, and unencrypted but a "
2013 					"compressed/sparse/encrypted extent "
2014 					"was found. $MFT is corrupt. Run "
2015 					"chkdsk.");
2016 			goto put_err_out;
2017 		}
2018 		/*
2019 		 * Decompress the mapping pairs array of this extent and merge
2020 		 * the result into the existing runlist. No need for locking
2021 		 * as we have exclusive access to the inode at this time and we
2022 		 * are a mount in progress task, too.
2023 		 */
2024 		nrl = ntfs_mapping_pairs_decompress(vol, a, ni->runlist.rl);
2025 		if (IS_ERR(nrl)) {
2026 			ntfs_error(sb, "ntfs_mapping_pairs_decompress() "
2027 					"failed with error code %ld.  $MFT is "
2028 					"corrupt.", PTR_ERR(nrl));
2029 			goto put_err_out;
2030 		}
2031 		ni->runlist.rl = nrl;
2032 
2033 		/* Are we in the first extent? */
2034 		if (!next_vcn) {
2035 			if (a->data.non_resident.lowest_vcn) {
2036 				ntfs_error(sb, "First extent of $DATA "
2037 						"attribute has non zero "
2038 						"lowest_vcn. $MFT is corrupt. "
2039 						"You should run chkdsk.");
2040 				goto put_err_out;
2041 			}
2042 			/* Get the last vcn in the $DATA attribute. */
2043 			last_vcn = sle64_to_cpu(
2044 					a->data.non_resident.allocated_size)
2045 					>> vol->cluster_size_bits;
2046 			/* Fill in the inode size. */
2047 			vi->i_size = sle64_to_cpu(
2048 					a->data.non_resident.data_size);
2049 			ni->initialized_size = sle64_to_cpu(
2050 					a->data.non_resident.initialized_size);
2051 			ni->allocated_size = sle64_to_cpu(
2052 					a->data.non_resident.allocated_size);
2053 			/*
2054 			 * Verify the number of mft records does not exceed
2055 			 * 2^32 - 1.
2056 			 */
2057 			if ((vi->i_size >> vol->mft_record_size_bits) >=
2058 					(1ULL << 32)) {
2059 				ntfs_error(sb, "$MFT is too big! Aborting.");
2060 				goto put_err_out;
2061 			}
2062 			/*
2063 			 * We have got the first extent of the runlist for
2064 			 * $MFT which means it is now relatively safe to call
2065 			 * the normal ntfs_read_inode() function.
2066 			 * Complete reading the inode, this will actually
2067 			 * re-read the mft record for $MFT, this time entering
2068 			 * it into the page cache with which we complete the
2069 			 * kick start of the volume. It should be safe to do
2070 			 * this now as the first extent of $MFT/$DATA is
2071 			 * already known and we would hope that we don't need
2072 			 * further extents in order to find the other
2073 			 * attributes belonging to $MFT. Only time will tell if
2074 			 * this is really the case. If not we will have to play
2075 			 * magic at this point, possibly duplicating a lot of
2076 			 * ntfs_read_inode() at this point. We will need to
2077 			 * ensure we do enough of its work to be able to call
2078 			 * ntfs_read_inode() on extents of $MFT/$DATA. But lets
2079 			 * hope this never happens...
2080 			 */
2081 			ntfs_read_locked_inode(vi);
2082 			if (is_bad_inode(vi)) {
2083 				ntfs_error(sb, "ntfs_read_inode() of $MFT "
2084 						"failed. BUG or corrupt $MFT. "
2085 						"Run chkdsk and if no errors "
2086 						"are found, please report you "
2087 						"saw this message to "
2088 						"linux-ntfs-dev@lists."
2089 						"sourceforge.net");
2090 				ntfs_attr_put_search_ctx(ctx);
2091 				/* Revert to the safe super operations. */
2092 				ntfs_free(m);
2093 				return -1;
2094 			}
2095 			/*
2096 			 * Re-initialize some specifics about $MFT's inode as
2097 			 * ntfs_read_inode() will have set up the default ones.
2098 			 */
2099 			/* Set uid and gid to root. */
2100 			vi->i_uid = GLOBAL_ROOT_UID;
2101 			vi->i_gid = GLOBAL_ROOT_GID;
2102 			/* Regular file. No access for anyone. */
2103 			vi->i_mode = S_IFREG;
2104 			/* No VFS initiated operations allowed for $MFT. */
2105 			vi->i_op = &ntfs_empty_inode_ops;
2106 			vi->i_fop = &ntfs_empty_file_ops;
2107 		}
2108 
2109 		/* Get the lowest vcn for the next extent. */
2110 		highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
2111 		next_vcn = highest_vcn + 1;
2112 
2113 		/* Only one extent or error, which we catch below. */
2114 		if (next_vcn <= 0)
2115 			break;
2116 
2117 		/* Avoid endless loops due to corruption. */
2118 		if (next_vcn < sle64_to_cpu(
2119 				a->data.non_resident.lowest_vcn)) {
2120 			ntfs_error(sb, "$MFT has corrupt attribute list "
2121 					"attribute. Run chkdsk.");
2122 			goto put_err_out;
2123 		}
2124 	}
2125 	if (err != -ENOENT) {
2126 		ntfs_error(sb, "Failed to lookup $MFT/$DATA attribute extent. "
2127 				"$MFT is corrupt. Run chkdsk.");
2128 		goto put_err_out;
2129 	}
2130 	if (!a) {
2131 		ntfs_error(sb, "$MFT/$DATA attribute not found. $MFT is "
2132 				"corrupt. Run chkdsk.");
2133 		goto put_err_out;
2134 	}
2135 	if (highest_vcn && highest_vcn != last_vcn - 1) {
2136 		ntfs_error(sb, "Failed to load the complete runlist for "
2137 				"$MFT/$DATA. Driver bug or corrupt $MFT. "
2138 				"Run chkdsk.");
2139 		ntfs_debug("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx",
2140 				(unsigned long long)highest_vcn,
2141 				(unsigned long long)last_vcn - 1);
2142 		goto put_err_out;
2143 	}
2144 	ntfs_attr_put_search_ctx(ctx);
2145 	ntfs_debug("Done.");
2146 	ntfs_free(m);
2147 
2148 	/*
2149 	 * Split the locking rules of the MFT inode from the
2150 	 * locking rules of other inodes:
2151 	 */
2152 	lockdep_set_class(&ni->runlist.lock, &mft_ni_runlist_lock_key);
2153 	lockdep_set_class(&ni->mrec_lock, &mft_ni_mrec_lock_key);
2154 
2155 	return 0;
2156 
2157 em_put_err_out:
2158 	ntfs_error(sb, "Couldn't find first extent of $DATA attribute in "
2159 			"attribute list. $MFT is corrupt. Run chkdsk.");
2160 put_err_out:
2161 	ntfs_attr_put_search_ctx(ctx);
2162 err_out:
2163 	ntfs_error(sb, "Failed. Marking inode as bad.");
2164 	make_bad_inode(vi);
2165 	ntfs_free(m);
2166 	return -1;
2167 }
2168 
2169 static void __ntfs_clear_inode(ntfs_inode *ni)
2170 {
2171 	/* Free all alocated memory. */
2172 	down_write(&ni->runlist.lock);
2173 	if (ni->runlist.rl) {
2174 		ntfs_free(ni->runlist.rl);
2175 		ni->runlist.rl = NULL;
2176 	}
2177 	up_write(&ni->runlist.lock);
2178 
2179 	if (ni->attr_list) {
2180 		ntfs_free(ni->attr_list);
2181 		ni->attr_list = NULL;
2182 	}
2183 
2184 	down_write(&ni->attr_list_rl.lock);
2185 	if (ni->attr_list_rl.rl) {
2186 		ntfs_free(ni->attr_list_rl.rl);
2187 		ni->attr_list_rl.rl = NULL;
2188 	}
2189 	up_write(&ni->attr_list_rl.lock);
2190 
2191 	if (ni->name_len && ni->name != I30) {
2192 		/* Catch bugs... */
2193 		BUG_ON(!ni->name);
2194 		kfree(ni->name);
2195 	}
2196 }
2197 
2198 void ntfs_clear_extent_inode(ntfs_inode *ni)
2199 {
2200 	ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
2201 
2202 	BUG_ON(NInoAttr(ni));
2203 	BUG_ON(ni->nr_extents != -1);
2204 
2205 #ifdef NTFS_RW
2206 	if (NInoDirty(ni)) {
2207 		if (!is_bad_inode(VFS_I(ni->ext.base_ntfs_ino)))
2208 			ntfs_error(ni->vol->sb, "Clearing dirty extent inode!  "
2209 					"Losing data!  This is a BUG!!!");
2210 		// FIXME:  Do something!!!
2211 	}
2212 #endif /* NTFS_RW */
2213 
2214 	__ntfs_clear_inode(ni);
2215 
2216 	/* Bye, bye... */
2217 	ntfs_destroy_extent_inode(ni);
2218 }
2219 
2220 /**
2221  * ntfs_evict_big_inode - clean up the ntfs specific part of an inode
2222  * @vi:		vfs inode pending annihilation
2223  *
2224  * When the VFS is going to remove an inode from memory, ntfs_clear_big_inode()
2225  * is called, which deallocates all memory belonging to the NTFS specific part
2226  * of the inode and returns.
2227  *
2228  * If the MFT record is dirty, we commit it before doing anything else.
2229  */
2230 void ntfs_evict_big_inode(struct inode *vi)
2231 {
2232 	ntfs_inode *ni = NTFS_I(vi);
2233 
2234 	truncate_inode_pages_final(&vi->i_data);
2235 	clear_inode(vi);
2236 
2237 #ifdef NTFS_RW
2238 	if (NInoDirty(ni)) {
2239 		bool was_bad = (is_bad_inode(vi));
2240 
2241 		/* Committing the inode also commits all extent inodes. */
2242 		ntfs_commit_inode(vi);
2243 
2244 		if (!was_bad && (is_bad_inode(vi) || NInoDirty(ni))) {
2245 			ntfs_error(vi->i_sb, "Failed to commit dirty inode "
2246 					"0x%lx.  Losing data!", vi->i_ino);
2247 			// FIXME:  Do something!!!
2248 		}
2249 	}
2250 #endif /* NTFS_RW */
2251 
2252 	/* No need to lock at this stage as no one else has a reference. */
2253 	if (ni->nr_extents > 0) {
2254 		int i;
2255 
2256 		for (i = 0; i < ni->nr_extents; i++)
2257 			ntfs_clear_extent_inode(ni->ext.extent_ntfs_inos[i]);
2258 		kfree(ni->ext.extent_ntfs_inos);
2259 	}
2260 
2261 	__ntfs_clear_inode(ni);
2262 
2263 	if (NInoAttr(ni)) {
2264 		/* Release the base inode if we are holding it. */
2265 		if (ni->nr_extents == -1) {
2266 			iput(VFS_I(ni->ext.base_ntfs_ino));
2267 			ni->nr_extents = 0;
2268 			ni->ext.base_ntfs_ino = NULL;
2269 		}
2270 	}
2271 	BUG_ON(ni->page);
2272 	if (!atomic_dec_and_test(&ni->count))
2273 		BUG();
2274 	return;
2275 }
2276 
2277 /**
2278  * ntfs_show_options - show mount options in /proc/mounts
2279  * @sf:		seq_file in which to write our mount options
2280  * @root:	root of the mounted tree whose mount options to display
2281  *
2282  * Called by the VFS once for each mounted ntfs volume when someone reads
2283  * /proc/mounts in order to display the NTFS specific mount options of each
2284  * mount. The mount options of fs specified by @root are written to the seq file
2285  * @sf and success is returned.
2286  */
2287 int ntfs_show_options(struct seq_file *sf, struct dentry *root)
2288 {
2289 	ntfs_volume *vol = NTFS_SB(root->d_sb);
2290 	int i;
2291 
2292 	seq_printf(sf, ",uid=%i", from_kuid_munged(&init_user_ns, vol->uid));
2293 	seq_printf(sf, ",gid=%i", from_kgid_munged(&init_user_ns, vol->gid));
2294 	if (vol->fmask == vol->dmask)
2295 		seq_printf(sf, ",umask=0%o", vol->fmask);
2296 	else {
2297 		seq_printf(sf, ",fmask=0%o", vol->fmask);
2298 		seq_printf(sf, ",dmask=0%o", vol->dmask);
2299 	}
2300 	seq_printf(sf, ",nls=%s", vol->nls_map->charset);
2301 	if (NVolCaseSensitive(vol))
2302 		seq_printf(sf, ",case_sensitive");
2303 	if (NVolShowSystemFiles(vol))
2304 		seq_printf(sf, ",show_sys_files");
2305 	if (!NVolSparseEnabled(vol))
2306 		seq_printf(sf, ",disable_sparse");
2307 	for (i = 0; on_errors_arr[i].val; i++) {
2308 		if (on_errors_arr[i].val & vol->on_errors)
2309 			seq_printf(sf, ",errors=%s", on_errors_arr[i].str);
2310 	}
2311 	seq_printf(sf, ",mft_zone_multiplier=%i", vol->mft_zone_multiplier);
2312 	return 0;
2313 }
2314 
2315 #ifdef NTFS_RW
2316 
2317 static const char *es = "  Leaving inconsistent metadata.  Unmount and run "
2318 		"chkdsk.";
2319 
2320 /**
2321  * ntfs_truncate - called when the i_size of an ntfs inode is changed
2322  * @vi:		inode for which the i_size was changed
2323  *
2324  * We only support i_size changes for normal files at present, i.e. not
2325  * compressed and not encrypted.  This is enforced in ntfs_setattr(), see
2326  * below.
2327  *
2328  * The kernel guarantees that @vi is a regular file (S_ISREG() is true) and
2329  * that the change is allowed.
2330  *
2331  * This implies for us that @vi is a file inode rather than a directory, index,
2332  * or attribute inode as well as that @vi is a base inode.
2333  *
2334  * Returns 0 on success or -errno on error.
2335  *
2336  * Called with ->i_mutex held.
2337  */
2338 int ntfs_truncate(struct inode *vi)
2339 {
2340 	s64 new_size, old_size, nr_freed, new_alloc_size, old_alloc_size;
2341 	VCN highest_vcn;
2342 	unsigned long flags;
2343 	ntfs_inode *base_ni, *ni = NTFS_I(vi);
2344 	ntfs_volume *vol = ni->vol;
2345 	ntfs_attr_search_ctx *ctx;
2346 	MFT_RECORD *m;
2347 	ATTR_RECORD *a;
2348 	const char *te = "  Leaving file length out of sync with i_size.";
2349 	int err, mp_size, size_change, alloc_change;
2350 
2351 	ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
2352 	BUG_ON(NInoAttr(ni));
2353 	BUG_ON(S_ISDIR(vi->i_mode));
2354 	BUG_ON(NInoMstProtected(ni));
2355 	BUG_ON(ni->nr_extents < 0);
2356 retry_truncate:
2357 	/*
2358 	 * Lock the runlist for writing and map the mft record to ensure it is
2359 	 * safe to mess with the attribute runlist and sizes.
2360 	 */
2361 	down_write(&ni->runlist.lock);
2362 	if (!NInoAttr(ni))
2363 		base_ni = ni;
2364 	else
2365 		base_ni = ni->ext.base_ntfs_ino;
2366 	m = map_mft_record(base_ni);
2367 	if (IS_ERR(m)) {
2368 		err = PTR_ERR(m);
2369 		ntfs_error(vi->i_sb, "Failed to map mft record for inode 0x%lx "
2370 				"(error code %d).%s", vi->i_ino, err, te);
2371 		ctx = NULL;
2372 		m = NULL;
2373 		goto old_bad_out;
2374 	}
2375 	ctx = ntfs_attr_get_search_ctx(base_ni, m);
2376 	if (unlikely(!ctx)) {
2377 		ntfs_error(vi->i_sb, "Failed to allocate a search context for "
2378 				"inode 0x%lx (not enough memory).%s",
2379 				vi->i_ino, te);
2380 		err = -ENOMEM;
2381 		goto old_bad_out;
2382 	}
2383 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2384 			CASE_SENSITIVE, 0, NULL, 0, ctx);
2385 	if (unlikely(err)) {
2386 		if (err == -ENOENT) {
2387 			ntfs_error(vi->i_sb, "Open attribute is missing from "
2388 					"mft record.  Inode 0x%lx is corrupt.  "
2389 					"Run chkdsk.%s", vi->i_ino, te);
2390 			err = -EIO;
2391 		} else
2392 			ntfs_error(vi->i_sb, "Failed to lookup attribute in "
2393 					"inode 0x%lx (error code %d).%s",
2394 					vi->i_ino, err, te);
2395 		goto old_bad_out;
2396 	}
2397 	m = ctx->mrec;
2398 	a = ctx->attr;
2399 	/*
2400 	 * The i_size of the vfs inode is the new size for the attribute value.
2401 	 */
2402 	new_size = i_size_read(vi);
2403 	/* The current size of the attribute value is the old size. */
2404 	old_size = ntfs_attr_size(a);
2405 	/* Calculate the new allocated size. */
2406 	if (NInoNonResident(ni))
2407 		new_alloc_size = (new_size + vol->cluster_size - 1) &
2408 				~(s64)vol->cluster_size_mask;
2409 	else
2410 		new_alloc_size = (new_size + 7) & ~7;
2411 	/* The current allocated size is the old allocated size. */
2412 	read_lock_irqsave(&ni->size_lock, flags);
2413 	old_alloc_size = ni->allocated_size;
2414 	read_unlock_irqrestore(&ni->size_lock, flags);
2415 	/*
2416 	 * The change in the file size.  This will be 0 if no change, >0 if the
2417 	 * size is growing, and <0 if the size is shrinking.
2418 	 */
2419 	size_change = -1;
2420 	if (new_size - old_size >= 0) {
2421 		size_change = 1;
2422 		if (new_size == old_size)
2423 			size_change = 0;
2424 	}
2425 	/* As above for the allocated size. */
2426 	alloc_change = -1;
2427 	if (new_alloc_size - old_alloc_size >= 0) {
2428 		alloc_change = 1;
2429 		if (new_alloc_size == old_alloc_size)
2430 			alloc_change = 0;
2431 	}
2432 	/*
2433 	 * If neither the size nor the allocation are being changed there is
2434 	 * nothing to do.
2435 	 */
2436 	if (!size_change && !alloc_change)
2437 		goto unm_done;
2438 	/* If the size is changing, check if new size is allowed in $AttrDef. */
2439 	if (size_change) {
2440 		err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
2441 		if (unlikely(err)) {
2442 			if (err == -ERANGE) {
2443 				ntfs_error(vol->sb, "Truncate would cause the "
2444 						"inode 0x%lx to %simum size "
2445 						"for its attribute type "
2446 						"(0x%x).  Aborting truncate.",
2447 						vi->i_ino,
2448 						new_size > old_size ? "exceed "
2449 						"the max" : "go under the min",
2450 						le32_to_cpu(ni->type));
2451 				err = -EFBIG;
2452 			} else {
2453 				ntfs_error(vol->sb, "Inode 0x%lx has unknown "
2454 						"attribute type 0x%x.  "
2455 						"Aborting truncate.",
2456 						vi->i_ino,
2457 						le32_to_cpu(ni->type));
2458 				err = -EIO;
2459 			}
2460 			/* Reset the vfs inode size to the old size. */
2461 			i_size_write(vi, old_size);
2462 			goto err_out;
2463 		}
2464 	}
2465 	if (NInoCompressed(ni) || NInoEncrypted(ni)) {
2466 		ntfs_warning(vi->i_sb, "Changes in inode size are not "
2467 				"supported yet for %s files, ignoring.",
2468 				NInoCompressed(ni) ? "compressed" :
2469 				"encrypted");
2470 		err = -EOPNOTSUPP;
2471 		goto bad_out;
2472 	}
2473 	if (a->non_resident)
2474 		goto do_non_resident_truncate;
2475 	BUG_ON(NInoNonResident(ni));
2476 	/* Resize the attribute record to best fit the new attribute size. */
2477 	if (new_size < vol->mft_record_size &&
2478 			!ntfs_resident_attr_value_resize(m, a, new_size)) {
2479 		/* The resize succeeded! */
2480 		flush_dcache_mft_record_page(ctx->ntfs_ino);
2481 		mark_mft_record_dirty(ctx->ntfs_ino);
2482 		write_lock_irqsave(&ni->size_lock, flags);
2483 		/* Update the sizes in the ntfs inode and all is done. */
2484 		ni->allocated_size = le32_to_cpu(a->length) -
2485 				le16_to_cpu(a->data.resident.value_offset);
2486 		/*
2487 		 * Note ntfs_resident_attr_value_resize() has already done any
2488 		 * necessary data clearing in the attribute record.  When the
2489 		 * file is being shrunk vmtruncate() will already have cleared
2490 		 * the top part of the last partial page, i.e. since this is
2491 		 * the resident case this is the page with index 0.  However,
2492 		 * when the file is being expanded, the page cache page data
2493 		 * between the old data_size, i.e. old_size, and the new_size
2494 		 * has not been zeroed.  Fortunately, we do not need to zero it
2495 		 * either since on one hand it will either already be zero due
2496 		 * to both readpage and writepage clearing partial page data
2497 		 * beyond i_size in which case there is nothing to do or in the
2498 		 * case of the file being mmap()ped at the same time, POSIX
2499 		 * specifies that the behaviour is unspecified thus we do not
2500 		 * have to do anything.  This means that in our implementation
2501 		 * in the rare case that the file is mmap()ped and a write
2502 		 * occurred into the mmap()ped region just beyond the file size
2503 		 * and writepage has not yet been called to write out the page
2504 		 * (which would clear the area beyond the file size) and we now
2505 		 * extend the file size to incorporate this dirty region
2506 		 * outside the file size, a write of the page would result in
2507 		 * this data being written to disk instead of being cleared.
2508 		 * Given both POSIX and the Linux mmap(2) man page specify that
2509 		 * this corner case is undefined, we choose to leave it like
2510 		 * that as this is much simpler for us as we cannot lock the
2511 		 * relevant page now since we are holding too many ntfs locks
2512 		 * which would result in a lock reversal deadlock.
2513 		 */
2514 		ni->initialized_size = new_size;
2515 		write_unlock_irqrestore(&ni->size_lock, flags);
2516 		goto unm_done;
2517 	}
2518 	/* If the above resize failed, this must be an attribute extension. */
2519 	BUG_ON(size_change < 0);
2520 	/*
2521 	 * We have to drop all the locks so we can call
2522 	 * ntfs_attr_make_non_resident().  This could be optimised by try-
2523 	 * locking the first page cache page and only if that fails dropping
2524 	 * the locks, locking the page, and redoing all the locking and
2525 	 * lookups.  While this would be a huge optimisation, it is not worth
2526 	 * it as this is definitely a slow code path as it only ever can happen
2527 	 * once for any given file.
2528 	 */
2529 	ntfs_attr_put_search_ctx(ctx);
2530 	unmap_mft_record(base_ni);
2531 	up_write(&ni->runlist.lock);
2532 	/*
2533 	 * Not enough space in the mft record, try to make the attribute
2534 	 * non-resident and if successful restart the truncation process.
2535 	 */
2536 	err = ntfs_attr_make_non_resident(ni, old_size);
2537 	if (likely(!err))
2538 		goto retry_truncate;
2539 	/*
2540 	 * Could not make non-resident.  If this is due to this not being
2541 	 * permitted for this attribute type or there not being enough space,
2542 	 * try to make other attributes non-resident.  Otherwise fail.
2543 	 */
2544 	if (unlikely(err != -EPERM && err != -ENOSPC)) {
2545 		ntfs_error(vol->sb, "Cannot truncate inode 0x%lx, attribute "
2546 				"type 0x%x, because the conversion from "
2547 				"resident to non-resident attribute failed "
2548 				"with error code %i.", vi->i_ino,
2549 				(unsigned)le32_to_cpu(ni->type), err);
2550 		if (err != -ENOMEM)
2551 			err = -EIO;
2552 		goto conv_err_out;
2553 	}
2554 	/* TODO: Not implemented from here, abort. */
2555 	if (err == -ENOSPC)
2556 		ntfs_error(vol->sb, "Not enough space in the mft record/on "
2557 				"disk for the non-resident attribute value.  "
2558 				"This case is not implemented yet.");
2559 	else /* if (err == -EPERM) */
2560 		ntfs_error(vol->sb, "This attribute type may not be "
2561 				"non-resident.  This case is not implemented "
2562 				"yet.");
2563 	err = -EOPNOTSUPP;
2564 	goto conv_err_out;
2565 #if 0
2566 	// TODO: Attempt to make other attributes non-resident.
2567 	if (!err)
2568 		goto do_resident_extend;
2569 	/*
2570 	 * Both the attribute list attribute and the standard information
2571 	 * attribute must remain in the base inode.  Thus, if this is one of
2572 	 * these attributes, we have to try to move other attributes out into
2573 	 * extent mft records instead.
2574 	 */
2575 	if (ni->type == AT_ATTRIBUTE_LIST ||
2576 			ni->type == AT_STANDARD_INFORMATION) {
2577 		// TODO: Attempt to move other attributes into extent mft
2578 		// records.
2579 		err = -EOPNOTSUPP;
2580 		if (!err)
2581 			goto do_resident_extend;
2582 		goto err_out;
2583 	}
2584 	// TODO: Attempt to move this attribute to an extent mft record, but
2585 	// only if it is not already the only attribute in an mft record in
2586 	// which case there would be nothing to gain.
2587 	err = -EOPNOTSUPP;
2588 	if (!err)
2589 		goto do_resident_extend;
2590 	/* There is nothing we can do to make enough space. )-: */
2591 	goto err_out;
2592 #endif
2593 do_non_resident_truncate:
2594 	BUG_ON(!NInoNonResident(ni));
2595 	if (alloc_change < 0) {
2596 		highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
2597 		if (highest_vcn > 0 &&
2598 				old_alloc_size >> vol->cluster_size_bits >
2599 				highest_vcn + 1) {
2600 			/*
2601 			 * This attribute has multiple extents.  Not yet
2602 			 * supported.
2603 			 */
2604 			ntfs_error(vol->sb, "Cannot truncate inode 0x%lx, "
2605 					"attribute type 0x%x, because the "
2606 					"attribute is highly fragmented (it "
2607 					"consists of multiple extents) and "
2608 					"this case is not implemented yet.",
2609 					vi->i_ino,
2610 					(unsigned)le32_to_cpu(ni->type));
2611 			err = -EOPNOTSUPP;
2612 			goto bad_out;
2613 		}
2614 	}
2615 	/*
2616 	 * If the size is shrinking, need to reduce the initialized_size and
2617 	 * the data_size before reducing the allocation.
2618 	 */
2619 	if (size_change < 0) {
2620 		/*
2621 		 * Make the valid size smaller (i_size is already up-to-date).
2622 		 */
2623 		write_lock_irqsave(&ni->size_lock, flags);
2624 		if (new_size < ni->initialized_size) {
2625 			ni->initialized_size = new_size;
2626 			a->data.non_resident.initialized_size =
2627 					cpu_to_sle64(new_size);
2628 		}
2629 		a->data.non_resident.data_size = cpu_to_sle64(new_size);
2630 		write_unlock_irqrestore(&ni->size_lock, flags);
2631 		flush_dcache_mft_record_page(ctx->ntfs_ino);
2632 		mark_mft_record_dirty(ctx->ntfs_ino);
2633 		/* If the allocated size is not changing, we are done. */
2634 		if (!alloc_change)
2635 			goto unm_done;
2636 		/*
2637 		 * If the size is shrinking it makes no sense for the
2638 		 * allocation to be growing.
2639 		 */
2640 		BUG_ON(alloc_change > 0);
2641 	} else /* if (size_change >= 0) */ {
2642 		/*
2643 		 * The file size is growing or staying the same but the
2644 		 * allocation can be shrinking, growing or staying the same.
2645 		 */
2646 		if (alloc_change > 0) {
2647 			/*
2648 			 * We need to extend the allocation and possibly update
2649 			 * the data size.  If we are updating the data size,
2650 			 * since we are not touching the initialized_size we do
2651 			 * not need to worry about the actual data on disk.
2652 			 * And as far as the page cache is concerned, there
2653 			 * will be no pages beyond the old data size and any
2654 			 * partial region in the last page between the old and
2655 			 * new data size (or the end of the page if the new
2656 			 * data size is outside the page) does not need to be
2657 			 * modified as explained above for the resident
2658 			 * attribute truncate case.  To do this, we simply drop
2659 			 * the locks we hold and leave all the work to our
2660 			 * friendly helper ntfs_attr_extend_allocation().
2661 			 */
2662 			ntfs_attr_put_search_ctx(ctx);
2663 			unmap_mft_record(base_ni);
2664 			up_write(&ni->runlist.lock);
2665 			err = ntfs_attr_extend_allocation(ni, new_size,
2666 					size_change > 0 ? new_size : -1, -1);
2667 			/*
2668 			 * ntfs_attr_extend_allocation() will have done error
2669 			 * output already.
2670 			 */
2671 			goto done;
2672 		}
2673 		if (!alloc_change)
2674 			goto alloc_done;
2675 	}
2676 	/* alloc_change < 0 */
2677 	/* Free the clusters. */
2678 	nr_freed = ntfs_cluster_free(ni, new_alloc_size >>
2679 			vol->cluster_size_bits, -1, ctx);
2680 	m = ctx->mrec;
2681 	a = ctx->attr;
2682 	if (unlikely(nr_freed < 0)) {
2683 		ntfs_error(vol->sb, "Failed to release cluster(s) (error code "
2684 				"%lli).  Unmount and run chkdsk to recover "
2685 				"the lost cluster(s).", (long long)nr_freed);
2686 		NVolSetErrors(vol);
2687 		nr_freed = 0;
2688 	}
2689 	/* Truncate the runlist. */
2690 	err = ntfs_rl_truncate_nolock(vol, &ni->runlist,
2691 			new_alloc_size >> vol->cluster_size_bits);
2692 	/*
2693 	 * If the runlist truncation failed and/or the search context is no
2694 	 * longer valid, we cannot resize the attribute record or build the
2695 	 * mapping pairs array thus we mark the inode bad so that no access to
2696 	 * the freed clusters can happen.
2697 	 */
2698 	if (unlikely(err || IS_ERR(m))) {
2699 		ntfs_error(vol->sb, "Failed to %s (error code %li).%s",
2700 				IS_ERR(m) ?
2701 				"restore attribute search context" :
2702 				"truncate attribute runlist",
2703 				IS_ERR(m) ? PTR_ERR(m) : err, es);
2704 		err = -EIO;
2705 		goto bad_out;
2706 	}
2707 	/* Get the size for the shrunk mapping pairs array for the runlist. */
2708 	mp_size = ntfs_get_size_for_mapping_pairs(vol, ni->runlist.rl, 0, -1);
2709 	if (unlikely(mp_size <= 0)) {
2710 		ntfs_error(vol->sb, "Cannot shrink allocation of inode 0x%lx, "
2711 				"attribute type 0x%x, because determining the "
2712 				"size for the mapping pairs failed with error "
2713 				"code %i.%s", vi->i_ino,
2714 				(unsigned)le32_to_cpu(ni->type), mp_size, es);
2715 		err = -EIO;
2716 		goto bad_out;
2717 	}
2718 	/*
2719 	 * Shrink the attribute record for the new mapping pairs array.  Note,
2720 	 * this cannot fail since we are making the attribute smaller thus by
2721 	 * definition there is enough space to do so.
2722 	 */
2723 	err = ntfs_attr_record_resize(m, a, mp_size +
2724 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
2725 	BUG_ON(err);
2726 	/*
2727 	 * Generate the mapping pairs array directly into the attribute record.
2728 	 */
2729 	err = ntfs_mapping_pairs_build(vol, (u8*)a +
2730 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
2731 			mp_size, ni->runlist.rl, 0, -1, NULL);
2732 	if (unlikely(err)) {
2733 		ntfs_error(vol->sb, "Cannot shrink allocation of inode 0x%lx, "
2734 				"attribute type 0x%x, because building the "
2735 				"mapping pairs failed with error code %i.%s",
2736 				vi->i_ino, (unsigned)le32_to_cpu(ni->type),
2737 				err, es);
2738 		err = -EIO;
2739 		goto bad_out;
2740 	}
2741 	/* Update the allocated/compressed size as well as the highest vcn. */
2742 	a->data.non_resident.highest_vcn = cpu_to_sle64((new_alloc_size >>
2743 			vol->cluster_size_bits) - 1);
2744 	write_lock_irqsave(&ni->size_lock, flags);
2745 	ni->allocated_size = new_alloc_size;
2746 	a->data.non_resident.allocated_size = cpu_to_sle64(new_alloc_size);
2747 	if (NInoSparse(ni) || NInoCompressed(ni)) {
2748 		if (nr_freed) {
2749 			ni->itype.compressed.size -= nr_freed <<
2750 					vol->cluster_size_bits;
2751 			BUG_ON(ni->itype.compressed.size < 0);
2752 			a->data.non_resident.compressed_size = cpu_to_sle64(
2753 					ni->itype.compressed.size);
2754 			vi->i_blocks = ni->itype.compressed.size >> 9;
2755 		}
2756 	} else
2757 		vi->i_blocks = new_alloc_size >> 9;
2758 	write_unlock_irqrestore(&ni->size_lock, flags);
2759 	/*
2760 	 * We have shrunk the allocation.  If this is a shrinking truncate we
2761 	 * have already dealt with the initialized_size and the data_size above
2762 	 * and we are done.  If the truncate is only changing the allocation
2763 	 * and not the data_size, we are also done.  If this is an extending
2764 	 * truncate, need to extend the data_size now which is ensured by the
2765 	 * fact that @size_change is positive.
2766 	 */
2767 alloc_done:
2768 	/*
2769 	 * If the size is growing, need to update it now.  If it is shrinking,
2770 	 * we have already updated it above (before the allocation change).
2771 	 */
2772 	if (size_change > 0)
2773 		a->data.non_resident.data_size = cpu_to_sle64(new_size);
2774 	/* Ensure the modified mft record is written out. */
2775 	flush_dcache_mft_record_page(ctx->ntfs_ino);
2776 	mark_mft_record_dirty(ctx->ntfs_ino);
2777 unm_done:
2778 	ntfs_attr_put_search_ctx(ctx);
2779 	unmap_mft_record(base_ni);
2780 	up_write(&ni->runlist.lock);
2781 done:
2782 	/* Update the mtime and ctime on the base inode. */
2783 	/* normally ->truncate shouldn't update ctime or mtime,
2784 	 * but ntfs did before so it got a copy & paste version
2785 	 * of file_update_time.  one day someone should fix this
2786 	 * for real.
2787 	 */
2788 	if (!IS_NOCMTIME(VFS_I(base_ni)) && !IS_RDONLY(VFS_I(base_ni))) {
2789 		struct timespec64 now = current_time(VFS_I(base_ni));
2790 		int sync_it = 0;
2791 
2792 		if (!timespec64_equal(&VFS_I(base_ni)->i_mtime, &now) ||
2793 		    !timespec64_equal(&VFS_I(base_ni)->i_ctime, &now))
2794 			sync_it = 1;
2795 		VFS_I(base_ni)->i_mtime = now;
2796 		VFS_I(base_ni)->i_ctime = now;
2797 
2798 		if (sync_it)
2799 			mark_inode_dirty_sync(VFS_I(base_ni));
2800 	}
2801 
2802 	if (likely(!err)) {
2803 		NInoClearTruncateFailed(ni);
2804 		ntfs_debug("Done.");
2805 	}
2806 	return err;
2807 old_bad_out:
2808 	old_size = -1;
2809 bad_out:
2810 	if (err != -ENOMEM && err != -EOPNOTSUPP)
2811 		NVolSetErrors(vol);
2812 	if (err != -EOPNOTSUPP)
2813 		NInoSetTruncateFailed(ni);
2814 	else if (old_size >= 0)
2815 		i_size_write(vi, old_size);
2816 err_out:
2817 	if (ctx)
2818 		ntfs_attr_put_search_ctx(ctx);
2819 	if (m)
2820 		unmap_mft_record(base_ni);
2821 	up_write(&ni->runlist.lock);
2822 out:
2823 	ntfs_debug("Failed.  Returning error code %i.", err);
2824 	return err;
2825 conv_err_out:
2826 	if (err != -ENOMEM && err != -EOPNOTSUPP)
2827 		NVolSetErrors(vol);
2828 	if (err != -EOPNOTSUPP)
2829 		NInoSetTruncateFailed(ni);
2830 	else
2831 		i_size_write(vi, old_size);
2832 	goto out;
2833 }
2834 
2835 /**
2836  * ntfs_truncate_vfs - wrapper for ntfs_truncate() that has no return value
2837  * @vi:		inode for which the i_size was changed
2838  *
2839  * Wrapper for ntfs_truncate() that has no return value.
2840  *
2841  * See ntfs_truncate() description above for details.
2842  */
2843 #ifdef NTFS_RW
2844 void ntfs_truncate_vfs(struct inode *vi) {
2845 	ntfs_truncate(vi);
2846 }
2847 #endif
2848 
2849 /**
2850  * ntfs_setattr - called from notify_change() when an attribute is being changed
2851  * @dentry:	dentry whose attributes to change
2852  * @attr:	structure describing the attributes and the changes
2853  *
2854  * We have to trap VFS attempts to truncate the file described by @dentry as
2855  * soon as possible, because we do not implement changes in i_size yet.  So we
2856  * abort all i_size changes here.
2857  *
2858  * We also abort all changes of user, group, and mode as we do not implement
2859  * the NTFS ACLs yet.
2860  *
2861  * Called with ->i_mutex held.
2862  */
2863 int ntfs_setattr(struct dentry *dentry, struct iattr *attr)
2864 {
2865 	struct inode *vi = d_inode(dentry);
2866 	int err;
2867 	unsigned int ia_valid = attr->ia_valid;
2868 
2869 	err = setattr_prepare(dentry, attr);
2870 	if (err)
2871 		goto out;
2872 	/* We do not support NTFS ACLs yet. */
2873 	if (ia_valid & (ATTR_UID | ATTR_GID | ATTR_MODE)) {
2874 		ntfs_warning(vi->i_sb, "Changes in user/group/mode are not "
2875 				"supported yet, ignoring.");
2876 		err = -EOPNOTSUPP;
2877 		goto out;
2878 	}
2879 	if (ia_valid & ATTR_SIZE) {
2880 		if (attr->ia_size != i_size_read(vi)) {
2881 			ntfs_inode *ni = NTFS_I(vi);
2882 			/*
2883 			 * FIXME: For now we do not support resizing of
2884 			 * compressed or encrypted files yet.
2885 			 */
2886 			if (NInoCompressed(ni) || NInoEncrypted(ni)) {
2887 				ntfs_warning(vi->i_sb, "Changes in inode size "
2888 						"are not supported yet for "
2889 						"%s files, ignoring.",
2890 						NInoCompressed(ni) ?
2891 						"compressed" : "encrypted");
2892 				err = -EOPNOTSUPP;
2893 			} else {
2894 				truncate_setsize(vi, attr->ia_size);
2895 				ntfs_truncate_vfs(vi);
2896 			}
2897 			if (err || ia_valid == ATTR_SIZE)
2898 				goto out;
2899 		} else {
2900 			/*
2901 			 * We skipped the truncate but must still update
2902 			 * timestamps.
2903 			 */
2904 			ia_valid |= ATTR_MTIME | ATTR_CTIME;
2905 		}
2906 	}
2907 	if (ia_valid & ATTR_ATIME)
2908 		vi->i_atime = attr->ia_atime;
2909 	if (ia_valid & ATTR_MTIME)
2910 		vi->i_mtime = attr->ia_mtime;
2911 	if (ia_valid & ATTR_CTIME)
2912 		vi->i_ctime = attr->ia_ctime;
2913 	mark_inode_dirty(vi);
2914 out:
2915 	return err;
2916 }
2917 
2918 /**
2919  * ntfs_write_inode - write out a dirty inode
2920  * @vi:		inode to write out
2921  * @sync:	if true, write out synchronously
2922  *
2923  * Write out a dirty inode to disk including any extent inodes if present.
2924  *
2925  * If @sync is true, commit the inode to disk and wait for io completion.  This
2926  * is done using write_mft_record().
2927  *
2928  * If @sync is false, just schedule the write to happen but do not wait for i/o
2929  * completion.  In 2.6 kernels, scheduling usually happens just by virtue of
2930  * marking the page (and in this case mft record) dirty but we do not implement
2931  * this yet as write_mft_record() largely ignores the @sync parameter and
2932  * always performs synchronous writes.
2933  *
2934  * Return 0 on success and -errno on error.
2935  */
2936 int __ntfs_write_inode(struct inode *vi, int sync)
2937 {
2938 	sle64 nt;
2939 	ntfs_inode *ni = NTFS_I(vi);
2940 	ntfs_attr_search_ctx *ctx;
2941 	MFT_RECORD *m;
2942 	STANDARD_INFORMATION *si;
2943 	int err = 0;
2944 	bool modified = false;
2945 
2946 	ntfs_debug("Entering for %sinode 0x%lx.", NInoAttr(ni) ? "attr " : "",
2947 			vi->i_ino);
2948 	/*
2949 	 * Dirty attribute inodes are written via their real inodes so just
2950 	 * clean them here.  Access time updates are taken care off when the
2951 	 * real inode is written.
2952 	 */
2953 	if (NInoAttr(ni)) {
2954 		NInoClearDirty(ni);
2955 		ntfs_debug("Done.");
2956 		return 0;
2957 	}
2958 	/* Map, pin, and lock the mft record belonging to the inode. */
2959 	m = map_mft_record(ni);
2960 	if (IS_ERR(m)) {
2961 		err = PTR_ERR(m);
2962 		goto err_out;
2963 	}
2964 	/* Update the access times in the standard information attribute. */
2965 	ctx = ntfs_attr_get_search_ctx(ni, m);
2966 	if (unlikely(!ctx)) {
2967 		err = -ENOMEM;
2968 		goto unm_err_out;
2969 	}
2970 	err = ntfs_attr_lookup(AT_STANDARD_INFORMATION, NULL, 0,
2971 			CASE_SENSITIVE, 0, NULL, 0, ctx);
2972 	if (unlikely(err)) {
2973 		ntfs_attr_put_search_ctx(ctx);
2974 		goto unm_err_out;
2975 	}
2976 	si = (STANDARD_INFORMATION*)((u8*)ctx->attr +
2977 			le16_to_cpu(ctx->attr->data.resident.value_offset));
2978 	/* Update the access times if they have changed. */
2979 	nt = utc2ntfs(vi->i_mtime);
2980 	if (si->last_data_change_time != nt) {
2981 		ntfs_debug("Updating mtime for inode 0x%lx: old = 0x%llx, "
2982 				"new = 0x%llx", vi->i_ino, (long long)
2983 				sle64_to_cpu(si->last_data_change_time),
2984 				(long long)sle64_to_cpu(nt));
2985 		si->last_data_change_time = nt;
2986 		modified = true;
2987 	}
2988 	nt = utc2ntfs(vi->i_ctime);
2989 	if (si->last_mft_change_time != nt) {
2990 		ntfs_debug("Updating ctime for inode 0x%lx: old = 0x%llx, "
2991 				"new = 0x%llx", vi->i_ino, (long long)
2992 				sle64_to_cpu(si->last_mft_change_time),
2993 				(long long)sle64_to_cpu(nt));
2994 		si->last_mft_change_time = nt;
2995 		modified = true;
2996 	}
2997 	nt = utc2ntfs(vi->i_atime);
2998 	if (si->last_access_time != nt) {
2999 		ntfs_debug("Updating atime for inode 0x%lx: old = 0x%llx, "
3000 				"new = 0x%llx", vi->i_ino,
3001 				(long long)sle64_to_cpu(si->last_access_time),
3002 				(long long)sle64_to_cpu(nt));
3003 		si->last_access_time = nt;
3004 		modified = true;
3005 	}
3006 	/*
3007 	 * If we just modified the standard information attribute we need to
3008 	 * mark the mft record it is in dirty.  We do this manually so that
3009 	 * mark_inode_dirty() is not called which would redirty the inode and
3010 	 * hence result in an infinite loop of trying to write the inode.
3011 	 * There is no need to mark the base inode nor the base mft record
3012 	 * dirty, since we are going to write this mft record below in any case
3013 	 * and the base mft record may actually not have been modified so it
3014 	 * might not need to be written out.
3015 	 * NOTE: It is not a problem when the inode for $MFT itself is being
3016 	 * written out as mark_ntfs_record_dirty() will only set I_DIRTY_PAGES
3017 	 * on the $MFT inode and hence ntfs_write_inode() will not be
3018 	 * re-invoked because of it which in turn is ok since the dirtied mft
3019 	 * record will be cleaned and written out to disk below, i.e. before
3020 	 * this function returns.
3021 	 */
3022 	if (modified) {
3023 		flush_dcache_mft_record_page(ctx->ntfs_ino);
3024 		if (!NInoTestSetDirty(ctx->ntfs_ino))
3025 			mark_ntfs_record_dirty(ctx->ntfs_ino->page,
3026 					ctx->ntfs_ino->page_ofs);
3027 	}
3028 	ntfs_attr_put_search_ctx(ctx);
3029 	/* Now the access times are updated, write the base mft record. */
3030 	if (NInoDirty(ni))
3031 		err = write_mft_record(ni, m, sync);
3032 	/* Write all attached extent mft records. */
3033 	mutex_lock(&ni->extent_lock);
3034 	if (ni->nr_extents > 0) {
3035 		ntfs_inode **extent_nis = ni->ext.extent_ntfs_inos;
3036 		int i;
3037 
3038 		ntfs_debug("Writing %i extent inodes.", ni->nr_extents);
3039 		for (i = 0; i < ni->nr_extents; i++) {
3040 			ntfs_inode *tni = extent_nis[i];
3041 
3042 			if (NInoDirty(tni)) {
3043 				MFT_RECORD *tm = map_mft_record(tni);
3044 				int ret;
3045 
3046 				if (IS_ERR(tm)) {
3047 					if (!err || err == -ENOMEM)
3048 						err = PTR_ERR(tm);
3049 					continue;
3050 				}
3051 				ret = write_mft_record(tni, tm, sync);
3052 				unmap_mft_record(tni);
3053 				if (unlikely(ret)) {
3054 					if (!err || err == -ENOMEM)
3055 						err = ret;
3056 				}
3057 			}
3058 		}
3059 	}
3060 	mutex_unlock(&ni->extent_lock);
3061 	unmap_mft_record(ni);
3062 	if (unlikely(err))
3063 		goto err_out;
3064 	ntfs_debug("Done.");
3065 	return 0;
3066 unm_err_out:
3067 	unmap_mft_record(ni);
3068 err_out:
3069 	if (err == -ENOMEM) {
3070 		ntfs_warning(vi->i_sb, "Not enough memory to write inode.  "
3071 				"Marking the inode dirty again, so the VFS "
3072 				"retries later.");
3073 		mark_inode_dirty(vi);
3074 	} else {
3075 		ntfs_error(vi->i_sb, "Failed (error %i):  Run chkdsk.", -err);
3076 		NVolSetErrors(ni->vol);
3077 	}
3078 	return err;
3079 }
3080 
3081 #endif /* NTFS_RW */
3082