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