patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / fs / ntfs / inode.c
1 /**
2  * inode.c - NTFS kernel inode handling. Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2001-2004 Anton Altaparmakov
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/pagemap.h>
23 #include <linux/buffer_head.h>
24 #include <linux/smp_lock.h>
25 #include <linux/quotaops.h>
26 #include <linux/mount.h>
27
28 #include "ntfs.h"
29 #include "dir.h"
30 #include "inode.h"
31 #include "attrib.h"
32 #include "time.h"
33
34 /**
35  * ntfs_test_inode - compare two (possibly fake) inodes for equality
36  * @vi:         vfs inode which to test
37  * @na:         ntfs attribute which is being tested with
38  *
39  * Compare the ntfs attribute embedded in the ntfs specific part of the vfs
40  * inode @vi for equality with the ntfs attribute @na.
41  *
42  * If searching for the normal file/directory inode, set @na->type to AT_UNUSED.
43  * @na->name and @na->name_len are then ignored.
44  *
45  * Return 1 if the attributes match and 0 if not.
46  *
47  * NOTE: This function runs with the inode_lock spin lock held so it is not
48  * allowed to sleep.
49  */
50 int ntfs_test_inode(struct inode *vi, ntfs_attr *na)
51 {
52         ntfs_inode *ni;
53
54         if (vi->i_ino != na->mft_no)
55                 return 0;
56         ni = NTFS_I(vi);
57         /* If !NInoAttr(ni), @vi is a normal file or directory inode. */
58         if (likely(!NInoAttr(ni))) {
59                 /* If not looking for a normal inode this is a mismatch. */
60                 if (unlikely(na->type != AT_UNUSED))
61                         return 0;
62         } else {
63                 /* A fake inode describing an attribute. */
64                 if (ni->type != na->type)
65                         return 0;
66                 if (ni->name_len != na->name_len)
67                         return 0;
68                 if (na->name_len && memcmp(ni->name, na->name,
69                                 na->name_len * sizeof(ntfschar)))
70                         return 0;
71         }
72         /* Match! */
73         return 1;
74 }
75
76 /**
77  * ntfs_init_locked_inode - initialize an inode
78  * @vi:         vfs inode to initialize
79  * @na:         ntfs attribute which to initialize @vi to
80  *
81  * Initialize the vfs inode @vi with the values from the ntfs attribute @na in
82  * order to enable ntfs_test_inode() to do its work.
83  *
84  * If initializing the normal file/directory inode, set @na->type to AT_UNUSED.
85  * In that case, @na->name and @na->name_len should be set to NULL and 0,
86  * respectively. Although that is not strictly necessary as
87  * ntfs_read_inode_locked() will fill them in later.
88  *
89  * Return 0 on success and -errno on error.
90  *
91  * NOTE: This function runs with the inode_lock spin lock held so it is not
92  * allowed to sleep. (Hence the GFP_ATOMIC allocation.)
93  */
94 static int ntfs_init_locked_inode(struct inode *vi, ntfs_attr *na)
95 {
96         ntfs_inode *ni = NTFS_I(vi);
97
98         vi->i_ino = na->mft_no;
99
100         ni->type = na->type;
101         if (na->type == AT_INDEX_ALLOCATION)
102                 NInoSetMstProtected(ni);
103
104         ni->name = na->name;
105         ni->name_len = na->name_len;
106
107         /* If initializing a normal inode, we are done. */
108         if (likely(na->type == AT_UNUSED))
109                 return 0;
110
111         /* It is a fake inode. */
112         NInoSetAttr(ni);
113
114         /*
115          * We have I30 global constant as an optimization as it is the name
116          * in >99.9% of named attributes! The other <0.1% incur a GFP_ATOMIC
117          * allocation but that is ok. And most attributes are unnamed anyway,
118          * thus the fraction of named attributes with name != I30 is actually
119          * absolutely tiny.
120          */
121         if (na->name && na->name_len && na->name != I30) {
122                 unsigned int i;
123
124                 i = na->name_len * sizeof(ntfschar);
125                 ni->name = (ntfschar*)kmalloc(i + sizeof(ntfschar), GFP_ATOMIC);
126                 if (!ni->name)
127                         return -ENOMEM;
128                 memcpy(ni->name, na->name, i);
129                 ni->name[i] = cpu_to_le16('\0');
130         }
131         return 0;
132 }
133
134 typedef int (*set_t)(struct inode *, void *);
135 static int ntfs_read_locked_inode(struct inode *vi);
136 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi);
137
138 /**
139  * ntfs_iget - obtain a struct inode corresponding to a specific normal inode
140  * @sb:         super block of mounted volume
141  * @mft_no:     mft record number / inode number to obtain
142  *
143  * Obtain the struct inode corresponding to a specific normal inode (i.e. a
144  * file or directory).
145  *
146  * If the inode is in the cache, it is just returned with an increased
147  * reference count. Otherwise, a new struct inode is allocated and initialized,
148  * and finally ntfs_read_locked_inode() is called to read in the inode and
149  * fill in the remainder of the inode structure.
150  *
151  * Return the struct inode on success. Check the return value with IS_ERR() and
152  * if true, the function failed and the error code is obtained from PTR_ERR().
153  */
154 struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no)
155 {
156         struct inode *vi;
157         ntfs_attr na;
158         int err;
159
160         na.mft_no = mft_no;
161         na.type = AT_UNUSED;
162         na.name = NULL;
163         na.name_len = 0;
164
165         vi = iget5_locked(sb, mft_no, (test_t)ntfs_test_inode,
166                         (set_t)ntfs_init_locked_inode, &na);
167         if (!vi)
168                 return ERR_PTR(-ENOMEM);
169
170         err = 0;
171
172         /* If this is a freshly allocated inode, need to read it now. */
173         if (vi->i_state & I_NEW) {
174                 err = ntfs_read_locked_inode(vi);
175                 unlock_new_inode(vi);
176         }
177         /*
178          * There is no point in keeping bad inodes around if the failure was
179          * due to ENOMEM. We want to be able to retry again later.
180          */
181         if (err == -ENOMEM) {
182                 iput(vi);
183                 vi = ERR_PTR(err);
184         }
185         return vi;
186 }
187
188 /**
189  * ntfs_attr_iget - obtain a struct inode corresponding to an attribute
190  * @base_vi:    vfs base inode containing the attribute
191  * @type:       attribute type
192  * @name:       Unicode name of the attribute (NULL if unnamed)
193  * @name_len:   length of @name in Unicode characters (0 if unnamed)
194  *
195  * Obtain the (fake) struct inode corresponding to the attribute specified by
196  * @type, @name, and @name_len, which is present in the base mft record
197  * specified by the vfs inode @base_vi.
198  *
199  * If the attribute inode is in the cache, it is just returned with an
200  * increased reference count. Otherwise, a new struct inode is allocated and
201  * initialized, and finally ntfs_read_locked_attr_inode() is called to read the
202  * attribute and fill in the inode structure.
203  *
204  * Return the struct inode of the attribute inode on success. Check the return
205  * value with IS_ERR() and if true, the function failed and the error code is
206  * obtained from PTR_ERR().
207  */
208 struct inode *ntfs_attr_iget(struct inode *base_vi, ATTR_TYPES type,
209                 ntfschar *name, u32 name_len)
210 {
211         struct inode *vi;
212         ntfs_attr na;
213         int err;
214
215         na.mft_no = base_vi->i_ino;
216         na.type = type;
217         na.name = name;
218         na.name_len = name_len;
219
220         vi = iget5_locked(base_vi->i_sb, na.mft_no, (test_t)ntfs_test_inode,
221                         (set_t)ntfs_init_locked_inode, &na);
222         if (!vi)
223                 return ERR_PTR(-ENOMEM);
224
225         err = 0;
226
227         /* If this is a freshly allocated inode, need to read it now. */
228         if (vi->i_state & I_NEW) {
229                 err = ntfs_read_locked_attr_inode(base_vi, vi);
230                 unlock_new_inode(vi);
231         }
232         /*
233          * There is no point in keeping bad attribute inodes around. This also
234          * simplifies things in that we never need to check for bad attribute
235          * inodes elsewhere.
236          */
237         if (err) {
238                 iput(vi);
239                 vi = ERR_PTR(err);
240         }
241         return vi;
242 }
243
244 struct inode *ntfs_alloc_big_inode(struct super_block *sb)
245 {
246         ntfs_inode *ni;
247
248         ntfs_debug("Entering.");
249         ni = (ntfs_inode *)kmem_cache_alloc(ntfs_big_inode_cache,
250                         SLAB_NOFS);
251         if (likely(ni != NULL)) {
252                 ni->state = 0;
253                 return VFS_I(ni);
254         }
255         ntfs_error(sb, "Allocation of NTFS big inode structure failed.");
256         return NULL;
257 }
258
259 void ntfs_destroy_big_inode(struct inode *inode)
260 {
261         ntfs_inode *ni = NTFS_I(inode);
262
263         ntfs_debug("Entering.");
264         BUG_ON(ni->page);
265         if (!atomic_dec_and_test(&ni->count))
266                 BUG();
267         kmem_cache_free(ntfs_big_inode_cache, NTFS_I(inode));
268 }
269
270 static inline ntfs_inode *ntfs_alloc_extent_inode(void)
271 {
272         ntfs_inode *ni;
273
274         ntfs_debug("Entering.");
275         ni = (ntfs_inode *)kmem_cache_alloc(ntfs_inode_cache, SLAB_NOFS);
276         if (likely(ni != NULL)) {
277                 ni->state = 0;
278                 return ni;
279         }
280         ntfs_error(NULL, "Allocation of NTFS inode structure failed.");
281         return NULL;
282 }
283
284 void ntfs_destroy_extent_inode(ntfs_inode *ni)
285 {
286         ntfs_debug("Entering.");
287         BUG_ON(ni->page);
288         if (!atomic_dec_and_test(&ni->count))
289                 BUG();
290         kmem_cache_free(ntfs_inode_cache, ni);
291 }
292
293 /**
294  * __ntfs_init_inode - initialize ntfs specific part of an inode
295  * @sb:         super block of mounted volume
296  * @ni:         freshly allocated ntfs inode which to initialize
297  *
298  * Initialize an ntfs inode to defaults.
299  *
300  * NOTE: ni->mft_no, ni->state, ni->type, ni->name, and ni->name_len are left
301  * untouched. Make sure to initialize them elsewhere.
302  *
303  * Return zero on success and -ENOMEM on error.
304  */
305 static void __ntfs_init_inode(struct super_block *sb, ntfs_inode *ni)
306 {
307         ntfs_debug("Entering.");
308         ni->initialized_size = ni->allocated_size = 0;
309         ni->seq_no = 0;
310         atomic_set(&ni->count, 1);
311         ni->vol = NTFS_SB(sb);
312         init_run_list(&ni->run_list);
313         init_MUTEX(&ni->mrec_lock);
314         ni->page = NULL;
315         ni->page_ofs = 0;
316         ni->attr_list_size = 0;
317         ni->attr_list = NULL;
318         init_run_list(&ni->attr_list_rl);
319         ni->itype.index.bmp_ino = NULL;
320         ni->itype.index.block_size = 0;
321         ni->itype.index.vcn_size = 0;
322         ni->itype.index.block_size_bits = 0;
323         ni->itype.index.vcn_size_bits = 0;
324         init_MUTEX(&ni->extent_lock);
325         ni->nr_extents = 0;
326         ni->ext.base_ntfs_ino = NULL;
327         return;
328 }
329
330 static inline void ntfs_init_big_inode(struct inode *vi)
331 {
332         ntfs_inode *ni = NTFS_I(vi);
333
334         ntfs_debug("Entering.");
335         __ntfs_init_inode(vi->i_sb, ni);
336         ni->mft_no = vi->i_ino;
337         return;
338 }
339
340 inline ntfs_inode *ntfs_new_extent_inode(struct super_block *sb,
341                 unsigned long mft_no)
342 {
343         ntfs_inode *ni = ntfs_alloc_extent_inode();
344
345         ntfs_debug("Entering.");
346         if (likely(ni != NULL)) {
347                 __ntfs_init_inode(sb, ni);
348                 ni->mft_no = mft_no;
349                 ni->type = AT_UNUSED;
350                 ni->name = NULL;
351                 ni->name_len = 0;
352         }
353         return ni;
354 }
355
356 /**
357  * ntfs_is_extended_system_file - check if a file is in the $Extend directory
358  * @ctx:        initialized attribute search context
359  *
360  * Search all file name attributes in the inode described by the attribute
361  * search context @ctx and check if any of the names are in the $Extend system
362  * directory.
363  *
364  * Return values:
365  *         1: file is in $Extend directory
366  *         0: file is not in $Extend directory
367  *      -EIO: file is corrupt
368  */
369 static int ntfs_is_extended_system_file(attr_search_context *ctx)
370 {
371         int nr_links;
372
373         /* Restart search. */
374         reinit_attr_search_ctx(ctx);
375
376         /* Get number of hard links. */
377         nr_links = le16_to_cpu(ctx->mrec->link_count);
378
379         /* Loop through all hard links. */
380         while (lookup_attr(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0, ctx)) {
381                 FILE_NAME_ATTR *file_name_attr;
382                 ATTR_RECORD *attr = ctx->attr;
383                 u8 *p, *p2;
384
385                 nr_links--;
386                 /*
387                  * Maximum sanity checking as we are called on an inode that
388                  * we suspect might be corrupt.
389                  */
390                 p = (u8*)attr + le32_to_cpu(attr->length);
391                 if (p < (u8*)ctx->mrec || (u8*)p > (u8*)ctx->mrec +
392                                 le32_to_cpu(ctx->mrec->bytes_in_use)) {
393 err_corrupt_attr:
394                         ntfs_error(ctx->ntfs_ino->vol->sb, "Corrupt file name "
395                                         "attribute. You should run chkdsk.");
396                         return -EIO;
397                 }
398                 if (attr->non_resident) {
399                         ntfs_error(ctx->ntfs_ino->vol->sb, "Non-resident file "
400                                         "name. You should run chkdsk.");
401                         return -EIO;
402                 }
403                 if (attr->flags) {
404                         ntfs_error(ctx->ntfs_ino->vol->sb, "File name with "
405                                         "invalid flags. You should run "
406                                         "chkdsk.");
407                         return -EIO;
408                 }
409                 if (!(attr->data.resident.flags & RESIDENT_ATTR_IS_INDEXED)) {
410                         ntfs_error(ctx->ntfs_ino->vol->sb, "Unindexed file "
411                                         "name. You should run chkdsk.");
412                         return -EIO;
413                 }
414                 file_name_attr = (FILE_NAME_ATTR*)((u8*)attr +
415                                 le16_to_cpu(attr->data.resident.value_offset));
416                 p2 = (u8*)attr + le32_to_cpu(attr->data.resident.value_length);
417                 if (p2 < (u8*)attr || p2 > p)
418                         goto err_corrupt_attr;
419                 /* This attribute is ok, but is it in the $Extend directory? */
420                 if (MREF_LE(file_name_attr->parent_directory) == FILE_Extend)
421                         return 1;       /* YES, it's an extended system file. */
422         }
423         if (nr_links) {
424                 ntfs_error(ctx->ntfs_ino->vol->sb, "Inode hard link count "
425                                 "doesn't match number of name attributes. You "
426                                 "should run chkdsk.");
427                 return -EIO;
428         }
429         return 0;       /* NO, it is not an extended system file. */
430 }
431
432 /**
433  * ntfs_read_locked_inode - read an inode from its device
434  * @vi:         inode to read
435  *
436  * ntfs_read_locked_inode() is called from ntfs_iget() to read the inode
437  * described by @vi into memory from the device.
438  *
439  * The only fields in @vi that we need to/can look at when the function is
440  * called are i_sb, pointing to the mounted device's super block, and i_ino,
441  * the number of the inode to load. If this is a fake inode, i.e. NInoAttr(),
442  * then the fields type, name, and name_len are also valid, and describe the
443  * attribute which this fake inode represents.
444  *
445  * ntfs_read_locked_inode() maps, pins and locks the mft record number i_ino
446  * for reading and sets up the necessary @vi fields as well as initializing
447  * the ntfs inode.
448  *
449  * Q: What locks are held when the function is called?
450  * A: i_state has I_LOCK set, hence the inode is locked, also
451  *    i_count is set to 1, so it is not going to go away
452  *    i_flags is set to 0 and we have no business touching it. Only an ioctl()
453  *    is allowed to write to them. We should of course be honouring them but
454  *    we need to do that using the IS_* macros defined in include/linux/fs.h.
455  *    In any case ntfs_read_locked_inode() has nothing to do with i_flags.
456  *
457  * Return 0 on success and -errno on error. In the error case, the inode will
458  * have had make_bad_inode() executed on it.
459  */
460 static int ntfs_read_locked_inode(struct inode *vi)
461 {
462         ntfs_volume *vol = NTFS_SB(vi->i_sb);
463         ntfs_inode *ni;
464         MFT_RECORD *m;
465         STANDARD_INFORMATION *si;
466         attr_search_context *ctx;
467         int err = 0;
468
469         ntfs_debug("Entering for i_ino 0x%lx.", vi->i_ino);
470
471         /* Setup the generic vfs inode parts now. */
472
473         /* This is the optimal IO size (for stat), not the fs block size. */
474         vi->i_blksize = PAGE_CACHE_SIZE;
475         /*
476          * This is for checking whether an inode has changed w.r.t. a file so
477          * that the file can be updated if necessary (compare with f_version).
478          */
479         vi->i_version = 1;
480
481         vi->i_uid = vol->uid;
482         vi->i_gid = vol->gid;
483         vi->i_mode = 0;
484
485         /*
486          * Initialize the ntfs specific part of @vi special casing
487          * FILE_MFT which we need to do at mount time.
488          */
489         if (vi->i_ino != FILE_MFT)
490                 ntfs_init_big_inode(vi);
491         ni = NTFS_I(vi);
492
493         m = map_mft_record(ni);
494         if (IS_ERR(m)) {
495                 err = PTR_ERR(m);
496                 goto err_out;
497         }
498         ctx = get_attr_search_ctx(ni, m);
499         if (!ctx) {
500                 err = -ENOMEM;
501                 goto unm_err_out;
502         }
503
504         if (!(m->flags & MFT_RECORD_IN_USE)) {
505                 ntfs_error(vi->i_sb, "Inode is not in use! You should "
506                                 "run chkdsk.");
507                 goto unm_err_out;
508         }
509         if (m->base_mft_record) {
510                 ntfs_error(vi->i_sb, "Inode is an extent inode! You should "
511                                 "run chkdsk.");
512                 goto unm_err_out;
513         }
514
515         /* Transfer information from mft record into vfs and ntfs inodes. */
516         vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
517
518         /*
519          * FIXME: Keep in mind that link_count is two for files which have both
520          * a long file name and a short file name as separate entries, so if
521          * we are hiding short file names this will be too high. Either we need
522          * to account for the short file names by subtracting them or we need
523          * to make sure we delete files even though i_nlink is not zero which
524          * might be tricky due to vfs interactions. Need to think about this
525          * some more when implementing the unlink command.
526          */
527         vi->i_nlink = le16_to_cpu(m->link_count);
528         /*
529          * FIXME: Reparse points can have the directory bit set even though
530          * they would be S_IFLNK. Need to deal with this further below when we
531          * implement reparse points / symbolic links but it will do for now.
532          * Also if not a directory, it could be something else, rather than
533          * a regular file. But again, will do for now.
534          */
535         if (m->flags & MFT_RECORD_IS_DIRECTORY) {
536                 vi->i_mode |= S_IFDIR;
537                 /* Things break without this kludge! */
538                 if (vi->i_nlink > 1)
539                         vi->i_nlink = 1;
540         } else
541                 vi->i_mode |= S_IFREG;
542
543         /*
544          * Find the standard information attribute in the mft record. At this
545          * stage we haven't setup the attribute list stuff yet, so this could
546          * in fact fail if the standard information is in an extent record, but
547          * I don't think this actually ever happens.
548          */
549         if (!lookup_attr(AT_STANDARD_INFORMATION, NULL, 0, 0, 0, NULL, 0,
550                         ctx)) {
551                 /*
552                  * TODO: We should be performing a hot fix here (if the recover
553                  * mount option is set) by creating a new attribute.
554                  */
555                 ntfs_error(vi->i_sb, "$STANDARD_INFORMATION attribute is "
556                                 "missing.");
557                 goto unm_err_out;
558         }
559         /* Get the standard information attribute value. */
560         si = (STANDARD_INFORMATION*)((char*)ctx->attr +
561                         le16_to_cpu(ctx->attr->data.resident.value_offset));
562
563         /* Transfer information from the standard information into vfs_ino. */
564         /*
565          * Note: The i_?times do not quite map perfectly onto the NTFS times,
566          * but they are close enough, and in the end it doesn't really matter
567          * that much...
568          */
569         /*
570          * mtime is the last change of the data within the file. Not changed
571          * when only metadata is changed, e.g. a rename doesn't affect mtime.
572          */
573         vi->i_mtime = ntfs2utc(si->last_data_change_time);
574         /*
575          * ctime is the last change of the metadata of the file. This obviously
576          * always changes, when mtime is changed. ctime can be changed on its
577          * own, mtime is then not changed, e.g. when a file is renamed.
578          */
579         vi->i_ctime = ntfs2utc(si->last_mft_change_time);
580         /*
581          * Last access to the data within the file. Not changed during a rename
582          * for example but changed whenever the file is written to.
583          */
584         vi->i_atime = ntfs2utc(si->last_access_time);
585
586         /* Find the attribute list attribute if present. */
587         reinit_attr_search_ctx(ctx);
588         if (lookup_attr(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx)) {
589                 if (vi->i_ino == FILE_MFT)
590                         goto skip_attr_list_load;
591                 ntfs_debug("Attribute list found in inode 0x%lx.", vi->i_ino);
592                 NInoSetAttrList(ni);
593                 if (ctx->attr->flags & ATTR_IS_ENCRYPTED ||
594                                 ctx->attr->flags & ATTR_COMPRESSION_MASK ||
595                                 ctx->attr->flags & ATTR_IS_SPARSE) {
596                         ntfs_error(vi->i_sb, "Attribute list attribute is "
597                                         "compressed/encrypted/sparse. Not "
598                                         "allowed. Corrupt inode. You should "
599                                         "run chkdsk.");
600                         goto unm_err_out;
601                 }
602                 /* Now allocate memory for the attribute list. */
603                 ni->attr_list_size = (u32)attribute_value_length(ctx->attr);
604                 ni->attr_list = ntfs_malloc_nofs(ni->attr_list_size);
605                 if (!ni->attr_list) {
606                         ntfs_error(vi->i_sb, "Not enough memory to allocate "
607                                         "buffer for attribute list.");
608                         err = -ENOMEM;
609                         goto unm_err_out;
610                 }
611                 if (ctx->attr->non_resident) {
612                         NInoSetAttrListNonResident(ni);
613                         if (ctx->attr->data.non_resident.lowest_vcn) {
614                                 ntfs_error(vi->i_sb, "Attribute list has non "
615                                                 "zero lowest_vcn. Inode is "
616                                                 "corrupt. You should run "
617                                                 "chkdsk.");
618                                 goto unm_err_out;
619                         }
620                         /*
621                          * Setup the run list. No need for locking as we have
622                          * exclusive access to the inode at this time.
623                          */
624                         ni->attr_list_rl.rl = decompress_mapping_pairs(vol,
625                                         ctx->attr, NULL);
626                         if (IS_ERR(ni->attr_list_rl.rl)) {
627                                 err = PTR_ERR(ni->attr_list_rl.rl);
628                                 ni->attr_list_rl.rl = NULL;
629                                 ntfs_error(vi->i_sb, "Mapping pairs "
630                                                 "decompression failed with "
631                                                 "error code %i. Corrupt "
632                                                 "attribute list in inode.",
633                                                 -err);
634                                 goto unm_err_out;
635                         }
636                         /* Now load the attribute list. */
637                         if ((err = load_attribute_list(vol, &ni->attr_list_rl,
638                                         ni->attr_list, ni->attr_list_size,
639                                         sle64_to_cpu(ctx->attr->data.
640                                         non_resident.initialized_size)))) {
641                                 ntfs_error(vi->i_sb, "Failed to load "
642                                                 "attribute list attribute.");
643                                 goto unm_err_out;
644                         }
645                 } else /* if (!ctx.attr->non_resident) */ {
646                         if ((u8*)ctx->attr + le16_to_cpu(
647                                         ctx->attr->data.resident.value_offset) +
648                                         le32_to_cpu(
649                                         ctx->attr->data.resident.value_length) >
650                                         (u8*)ctx->mrec + vol->mft_record_size) {
651                                 ntfs_error(vi->i_sb, "Corrupt attribute list "
652                                                 "in inode.");
653                                 goto unm_err_out;
654                         }
655                         /* Now copy the attribute list. */
656                         memcpy(ni->attr_list, (u8*)ctx->attr + le16_to_cpu(
657                                         ctx->attr->data.resident.value_offset),
658                                         le32_to_cpu(
659                                         ctx->attr->data.resident.value_length));
660                 }
661         }
662 skip_attr_list_load:
663         /*
664          * If an attribute list is present we now have the attribute list value
665          * in ntfs_ino->attr_list and it is ntfs_ino->attr_list_size bytes.
666          */
667         if (S_ISDIR(vi->i_mode)) {
668                 struct inode *bvi;
669                 ntfs_inode *bni;
670                 INDEX_ROOT *ir;
671                 char *ir_end, *index_end;
672
673                 /* It is a directory, find index root attribute. */
674                 reinit_attr_search_ctx(ctx);
675                 if (!lookup_attr(AT_INDEX_ROOT, I30, 4, CASE_SENSITIVE, 0,
676                                 NULL, 0, ctx)) {
677                         // FIXME: File is corrupt! Hot-fix with empty index
678                         // root attribute if recovery option is set.
679                         ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is "
680                                         "missing.");
681                         goto unm_err_out;
682                 }
683                 /* Set up the state. */
684                 if (ctx->attr->non_resident) {
685                         ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is "
686                                         "not resident. Not allowed.");
687                         goto unm_err_out;
688                 }
689                 /*
690                  * Compressed/encrypted index root just means that the newly
691                  * created files in that directory should be created compressed/
692                  * encrypted. However index root cannot be both compressed and
693                  * encrypted.
694                  */
695                 if (ctx->attr->flags & ATTR_COMPRESSION_MASK)
696                         NInoSetCompressed(ni);
697                 if (ctx->attr->flags & ATTR_IS_ENCRYPTED) {
698                         if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
699                                 ntfs_error(vi->i_sb, "Found encrypted and "
700                                                 "compressed attribute. Not "
701                                                 "allowed.");
702                                 goto unm_err_out;
703                         }
704                         NInoSetEncrypted(ni);
705                 }
706                 if (ctx->attr->flags & ATTR_IS_SPARSE)
707                         NInoSetSparse(ni);
708                 ir = (INDEX_ROOT*)((char*)ctx->attr + le16_to_cpu(
709                                 ctx->attr->data.resident.value_offset));
710                 ir_end = (char*)ir + le32_to_cpu(
711                                 ctx->attr->data.resident.value_length);
712                 if (ir_end > (char*)ctx->mrec + vol->mft_record_size) {
713                         ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is "
714                                         "corrupt.");
715                         goto unm_err_out;
716                 }
717                 index_end = (char*)&ir->index +
718                                 le32_to_cpu(ir->index.index_length);
719                 if (index_end > ir_end) {
720                         ntfs_error(vi->i_sb, "Directory index is corrupt.");
721                         goto unm_err_out;
722                 }
723                 if (ir->type != AT_FILE_NAME) {
724                         ntfs_error(vi->i_sb, "Indexed attribute is not "
725                                         "$FILE_NAME. Not allowed.");
726                         goto unm_err_out;
727                 }
728                 if (ir->collation_rule != COLLATION_FILE_NAME) {
729                         ntfs_error(vi->i_sb, "Index collation rule is not "
730                                         "COLLATION_FILE_NAME. Not allowed.");
731                         goto unm_err_out;
732                 }
733                 ni->itype.index.block_size = le32_to_cpu(ir->index_block_size);
734                 if (ni->itype.index.block_size &
735                                 (ni->itype.index.block_size - 1)) {
736                         ntfs_error(vi->i_sb, "Index block size (%u) is not a "
737                                         "power of two.",
738                                         ni->itype.index.block_size);
739                         goto unm_err_out;
740                 }
741                 if (ni->itype.index.block_size > PAGE_CACHE_SIZE) {
742                         ntfs_error(vi->i_sb, "Index block size (%u) > "
743                                         "PAGE_CACHE_SIZE (%ld) is not "
744                                         "supported. Sorry.",
745                                         ni->itype.index.block_size,
746                                         PAGE_CACHE_SIZE);
747                         err = -EOPNOTSUPP;
748                         goto unm_err_out;
749                 }
750                 if (ni->itype.index.block_size < NTFS_BLOCK_SIZE) {
751                         ntfs_error(vi->i_sb, "Index block size (%u) < "
752                                         "NTFS_BLOCK_SIZE (%i) is not "
753                                         "supported. Sorry.",
754                                         ni->itype.index.block_size,
755                                         NTFS_BLOCK_SIZE);
756                         err = -EOPNOTSUPP;
757                         goto unm_err_out;
758                 }
759                 ni->itype.index.block_size_bits =
760                                 ffs(ni->itype.index.block_size) - 1;
761                 /* Determine the size of a vcn in the directory index. */
762                 if (vol->cluster_size <= ni->itype.index.block_size) {
763                         ni->itype.index.vcn_size = vol->cluster_size;
764                         ni->itype.index.vcn_size_bits = vol->cluster_size_bits;
765                 } else {
766                         ni->itype.index.vcn_size = vol->sector_size;
767                         ni->itype.index.vcn_size_bits = vol->sector_size_bits;
768                 }
769
770                 /* Setup the index allocation attribute, even if not present. */
771                 NInoSetMstProtected(ni);
772                 ni->type = AT_INDEX_ALLOCATION;
773                 ni->name = I30;
774                 ni->name_len = 4;
775
776                 if (!(ir->index.flags & LARGE_INDEX)) {
777                         /* No index allocation. */
778                         vi->i_size = ni->initialized_size =
779                                         ni->allocated_size = 0;
780                         /* We are done with the mft record, so we release it. */
781                         put_attr_search_ctx(ctx);
782                         unmap_mft_record(ni);
783                         m = NULL;
784                         ctx = NULL;
785                         goto skip_large_dir_stuff;
786                 } /* LARGE_INDEX: Index allocation present. Setup state. */
787                 NInoSetIndexAllocPresent(ni);
788                 /* Find index allocation attribute. */
789                 reinit_attr_search_ctx(ctx);
790                 if (!lookup_attr(AT_INDEX_ALLOCATION, I30, 4, CASE_SENSITIVE,
791                                 0, NULL, 0, ctx)) {
792                         ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
793                                         "is not present but $INDEX_ROOT "
794                                         "indicated it is.");
795                         goto unm_err_out;
796                 }
797                 if (!ctx->attr->non_resident) {
798                         ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
799                                         "is resident.");
800                         goto unm_err_out;
801                 }
802                 if (ctx->attr->flags & ATTR_IS_ENCRYPTED) {
803                         ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
804                                         "is encrypted.");
805                         goto unm_err_out;
806                 }
807                 if (ctx->attr->flags & ATTR_IS_SPARSE) {
808                         ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
809                                         "is sparse.");
810                         goto unm_err_out;
811                 }
812                 if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
813                         ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute "
814                                         "is compressed.");
815                         goto unm_err_out;
816                 }
817                 if (ctx->attr->data.non_resident.lowest_vcn) {
818                         ntfs_error(vi->i_sb, "First extent of "
819                                         "$INDEX_ALLOCATION attribute has non "
820                                         "zero lowest_vcn. Inode is corrupt. "
821                                         "You should run chkdsk.");
822                         goto unm_err_out;
823                 }
824                 vi->i_size = sle64_to_cpu(
825                                 ctx->attr->data.non_resident.data_size);
826                 ni->initialized_size = sle64_to_cpu(
827                                 ctx->attr->data.non_resident.initialized_size);
828                 ni->allocated_size = sle64_to_cpu(
829                                 ctx->attr->data.non_resident.allocated_size);
830                 /*
831                  * We are done with the mft record, so we release it. Otherwise
832                  * we would deadlock in ntfs_attr_iget().
833                  */
834                 put_attr_search_ctx(ctx);
835                 unmap_mft_record(ni);
836                 m = NULL;
837                 ctx = NULL;
838                 /* Get the index bitmap attribute inode. */
839                 bvi = ntfs_attr_iget(vi, AT_BITMAP, I30, 4);
840                 if (unlikely(IS_ERR(bvi))) {
841                         ntfs_error(vi->i_sb, "Failed to get bitmap attribute.");
842                         err = PTR_ERR(bvi);
843                         goto unm_err_out;
844                 }
845                 ni->itype.index.bmp_ino = bvi;
846                 bni = NTFS_I(bvi);
847                 if (NInoCompressed(bni) || NInoEncrypted(bni) ||
848                                 NInoSparse(bni)) {
849                         ntfs_error(vi->i_sb, "$BITMAP attribute is compressed "
850                                         "and/or encrypted and/or sparse.");
851                         goto unm_err_out;
852                 }
853                 /* Consistency check bitmap size vs. index allocation size. */
854                 if ((bvi->i_size << 3) < (vi->i_size >>
855                                 ni->itype.index.block_size_bits)) {
856                         ntfs_error(vi->i_sb, "Index bitmap too small (0x%llx) "
857                                         "for index allocation (0x%llx).",
858                                         bvi->i_size << 3, vi->i_size);
859                         goto unm_err_out;
860                 }
861 skip_large_dir_stuff:
862                 /* Everyone gets read and scan permissions. */
863                 vi->i_mode |= S_IRUGO | S_IXUGO;
864                 /* If not read-only, set write permissions. */
865                 if (!IS_RDONLY(vi))
866                         vi->i_mode |= S_IWUGO;
867                 /*
868                  * Apply the directory permissions mask set in the mount
869                  * options.
870                  */
871                 vi->i_mode &= ~vol->dmask;
872                 /* Setup the operations for this inode. */
873                 vi->i_op = &ntfs_dir_inode_ops;
874                 vi->i_fop = &ntfs_dir_ops;
875                 vi->i_mapping->a_ops = &ntfs_mst_aops;
876         } else {
877                 /* It is a file. */
878                 reinit_attr_search_ctx(ctx);
879
880                 /* Setup the data attribute, even if not present. */
881                 ni->type = AT_DATA;
882                 ni->name = NULL;
883                 ni->name_len = 0;
884
885                 /* Find first extent of the unnamed data attribute. */
886                 if (!lookup_attr(AT_DATA, NULL, 0, 0, 0, NULL, 0, ctx)) {
887                         vi->i_size = ni->initialized_size =
888                                         ni->allocated_size = 0LL;
889                         /*
890                          * FILE_Secure does not have an unnamed $DATA
891                          * attribute, so we special case it here.
892                          */
893                         if (vi->i_ino == FILE_Secure)
894                                 goto no_data_attr_special_case;
895                         /*
896                          * Most if not all the system files in the $Extend
897                          * system directory do not have unnamed data
898                          * attributes so we need to check if the parent
899                          * directory of the file is FILE_Extend and if it is
900                          * ignore this error. To do this we need to get the
901                          * name of this inode from the mft record as the name
902                          * contains the back reference to the parent directory.
903                          */
904                         if (ntfs_is_extended_system_file(ctx) > 0)
905                                 goto no_data_attr_special_case;
906                         // FIXME: File is corrupt! Hot-fix with empty data
907                         // attribute if recovery option is set.
908                         ntfs_error(vi->i_sb, "$DATA attribute is "
909                                         "missing.");
910                         goto unm_err_out;
911                 }
912                 /* Setup the state. */
913                 if (ctx->attr->non_resident) {
914                         NInoSetNonResident(ni);
915                         if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
916                                 NInoSetCompressed(ni);
917                                 if (vol->cluster_size > 4096) {
918                                         ntfs_error(vi->i_sb, "Found "
919                                                 "compressed data but "
920                                                 "compression is disabled due "
921                                                 "to cluster size (%i) > 4kiB.",
922                                                 vol->cluster_size);
923                                         goto unm_err_out;
924                                 }
925                                 if ((ctx->attr->flags & ATTR_COMPRESSION_MASK)
926                                                 != ATTR_IS_COMPRESSED) {
927                                         ntfs_error(vi->i_sb, "Found "
928                                                 "unknown compression method or "
929                                                 "corrupt file.");
930                                         goto unm_err_out;
931                                 }
932                                 ni->itype.compressed.block_clusters = 1U <<
933                                                 ctx->attr->data.non_resident.
934                                                 compression_unit;
935                                 if (ctx->attr->data.non_resident.
936                                                 compression_unit != 4) {
937                                         ntfs_error(vi->i_sb, "Found "
938                                                 "nonstandard compression unit "
939                                                 "(%u instead of 4). Cannot "
940                                                 "handle this. This might "
941                                                 "indicate corruption so you "
942                                                 "should run chkdsk.",
943                                                 ctx->attr->data.non_resident.
944                                                 compression_unit);
945                                         err = -EOPNOTSUPP;
946                                         goto unm_err_out;
947                                 }
948                                 ni->itype.compressed.block_size = 1U << (
949                                                 ctx->attr->data.non_resident.
950                                                 compression_unit +
951                                                 vol->cluster_size_bits);
952                                 ni->itype.compressed.block_size_bits = ffs(
953                                         ni->itype.compressed.block_size) - 1;
954                         }
955                         if (ctx->attr->flags & ATTR_IS_ENCRYPTED) {
956                                 if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
957                                         ntfs_error(vi->i_sb, "Found encrypted "
958                                                         "and compressed data.");
959                                         goto unm_err_out;
960                                 }
961                                 NInoSetEncrypted(ni);
962                         }
963                         if (ctx->attr->flags & ATTR_IS_SPARSE)
964                                 NInoSetSparse(ni);
965                         if (ctx->attr->data.non_resident.lowest_vcn) {
966                                 ntfs_error(vi->i_sb, "First extent of $DATA "
967                                                 "attribute has non zero "
968                                                 "lowest_vcn. Inode is corrupt. "
969                                                 "You should run chkdsk.");
970                                 goto unm_err_out;
971                         }
972                         /* Setup all the sizes. */
973                         vi->i_size = sle64_to_cpu(
974                                         ctx->attr->data.non_resident.data_size);
975                         ni->initialized_size = sle64_to_cpu(
976                                         ctx->attr->data.non_resident.
977                                         initialized_size);
978                         ni->allocated_size = sle64_to_cpu(
979                                         ctx->attr->data.non_resident.
980                                         allocated_size);
981                         if (NInoCompressed(ni)) {
982                                 ni->itype.compressed.size = sle64_to_cpu(
983                                                 ctx->attr->data.non_resident.
984                                                 compressed_size);
985                         }
986                 } else { /* Resident attribute. */
987                         /*
988                          * Make all sizes equal for simplicity in read code
989                          * paths. FIXME: Need to keep this in mind when
990                          * converting to non-resident attribute in write code
991                          * path. (Probably only affects truncate().)
992                          */
993                         vi->i_size = ni->initialized_size = ni->allocated_size =
994                                         le32_to_cpu(
995                                         ctx->attr->data.resident.value_length);
996                 }
997 no_data_attr_special_case:
998                 /* We are done with the mft record, so we release it. */
999                 put_attr_search_ctx(ctx);
1000                 unmap_mft_record(ni);
1001                 m = NULL;
1002                 ctx = NULL;
1003                 /* Everyone gets all permissions. */
1004                 vi->i_mode |= S_IRWXUGO;
1005                 /* If read-only, noone gets write permissions. */
1006                 if (IS_RDONLY(vi))
1007                         vi->i_mode &= ~S_IWUGO;
1008                 /* Apply the file permissions mask set in the mount options. */
1009                 vi->i_mode &= ~vol->fmask;
1010                 /* Setup the operations for this inode. */
1011                 vi->i_op = &ntfs_file_inode_ops;
1012                 vi->i_fop = &ntfs_file_ops;
1013                 vi->i_mapping->a_ops = &ntfs_aops;
1014         }
1015         /*
1016          * The number of 512-byte blocks used on disk (for stat). This is in so
1017          * far inaccurate as it doesn't account for any named streams or other
1018          * special non-resident attributes, but that is how Windows works, too,
1019          * so we are at least consistent with Windows, if not entirely
1020          * consistent with the Linux Way. Doing it the Linux Way would cause a
1021          * significant slowdown as it would involve iterating over all
1022          * attributes in the mft record and adding the allocated/compressed
1023          * sizes of all non-resident attributes present to give us the Linux
1024          * correct size that should go into i_blocks (after division by 512).
1025          */
1026         if (S_ISDIR(vi->i_mode) || !NInoCompressed(ni))
1027                 vi->i_blocks = ni->allocated_size >> 9;
1028         else
1029                 vi->i_blocks = ni->itype.compressed.size >> 9;
1030
1031         ntfs_debug("Done.");
1032         return 0;
1033
1034 unm_err_out:
1035         if (!err)
1036                 err = -EIO;
1037         if (ctx)
1038                 put_attr_search_ctx(ctx);
1039         if (m)
1040                 unmap_mft_record(ni);
1041 err_out:
1042         ntfs_error(vi->i_sb, "Failed with error code %i. Marking inode 0x%lx "
1043                         "as bad.", -err, vi->i_ino);
1044         make_bad_inode(vi);
1045         return err;
1046 }
1047
1048 /**
1049  * ntfs_read_locked_attr_inode - read an attribute inode from its base inode
1050  * @base_vi:    base inode
1051  * @vi:         attribute inode to read
1052  *
1053  * ntfs_read_locked_attr_inode() is called from the ntfs_attr_iget() to read
1054  * the attribute inode described by @vi into memory from the base mft record
1055  * described by @base_ni.
1056  *
1057  * ntfs_read_locked_attr_inode() maps, pins and locks the base inode for
1058  * reading and looks up the attribute described by @vi before setting up the
1059  * necessary fields in @vi as well as initializing the ntfs inode.
1060  *
1061  * Q: What locks are held when the function is called?
1062  * A: i_state has I_LOCK set, hence the inode is locked, also
1063  *    i_count is set to 1, so it is not going to go away
1064  */
1065 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
1066 {
1067         ntfs_volume *vol = NTFS_SB(vi->i_sb);
1068         ntfs_inode *ni, *base_ni;
1069         MFT_RECORD *m;
1070         attr_search_context *ctx;
1071         int err = 0;
1072
1073         ntfs_debug("Entering for i_ino 0x%lx.", vi->i_ino);
1074
1075         ntfs_init_big_inode(vi);
1076
1077         ni      = NTFS_I(vi);
1078         base_ni = NTFS_I(base_vi);
1079
1080         /* Just mirror the values from the base inode. */
1081         vi->i_blksize   = base_vi->i_blksize;
1082         vi->i_version   = base_vi->i_version;
1083         vi->i_uid       = base_vi->i_uid;
1084         vi->i_gid       = base_vi->i_gid;
1085         vi->i_nlink     = base_vi->i_nlink;
1086         vi->i_mtime     = base_vi->i_mtime;
1087         vi->i_ctime     = base_vi->i_ctime;
1088         vi->i_atime     = base_vi->i_atime;
1089         vi->i_generation = ni->seq_no = base_ni->seq_no;
1090
1091         /* Set inode type to zero but preserve permissions. */
1092         vi->i_mode      = base_vi->i_mode & ~S_IFMT;
1093
1094         m = map_mft_record(base_ni);
1095         if (IS_ERR(m)) {
1096                 err = PTR_ERR(m);
1097                 goto err_out;
1098         }
1099         ctx = get_attr_search_ctx(base_ni, m);
1100         if (!ctx) {
1101                 err = -ENOMEM;
1102                 goto unm_err_out;
1103         }
1104
1105         /* Find the attribute. */
1106         if (!lookup_attr(ni->type, ni->name, ni->name_len, IGNORE_CASE, 0,
1107                         NULL, 0, ctx))
1108                 goto unm_err_out;
1109
1110         if (!ctx->attr->non_resident) {
1111                 if (NInoMstProtected(ni) || ctx->attr->flags) {
1112                         ntfs_error(vi->i_sb, "Found mst protected attribute "
1113                                         "or attribute with non-zero flags but "
1114                                         "the attribute is resident (mft_no "
1115                                         "0x%lx, type 0x%x, name_len %i). "
1116                                         "Please report you saw this message "
1117                                         "to linux-ntfs-dev@lists."
1118                                         "sourceforge.net",
1119                                         vi->i_ino, ni->type, ni->name_len);
1120                         goto unm_err_out;
1121                 }
1122                 /*
1123                  * Resident attribute. Make all sizes equal for simplicity in
1124                  * read code paths.
1125                  */
1126                 vi->i_size = ni->initialized_size = ni->allocated_size =
1127                         le32_to_cpu(ctx->attr->data.resident.value_length);
1128         } else {
1129                 NInoSetNonResident(ni);
1130                 if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
1131                         if (NInoMstProtected(ni)) {
1132                                 ntfs_error(vi->i_sb, "Found mst protected "
1133                                                 "attribute but the attribute "
1134                                                 "is compressed (mft_no 0x%lx, "
1135                                                 "type 0x%x, name_len %i). "
1136                                                 "Please report you saw this "
1137                                                 "message to linux-ntfs-dev@"
1138                                                 "lists.sourceforge.net",
1139                                                 vi->i_ino, ni->type,
1140                                                 ni->name_len);
1141                                 goto unm_err_out;
1142                         }
1143                         NInoSetCompressed(ni);
1144                         if ((ni->type != AT_DATA) || (ni->type == AT_DATA &&
1145                                         ni->name_len)) {
1146                                 ntfs_error(vi->i_sb, "Found compressed non-"
1147                                                 "data or named data attribute "
1148                                                 "(mft_no 0x%lx, type 0x%x, "
1149                                                 "name_len %i). Please report "
1150                                                 "you saw this message to "
1151                                                 "linux-ntfs-dev@lists."
1152                                                 "sourceforge.net",
1153                                                 vi->i_ino, ni->type,
1154                                                 ni->name_len);
1155                                 goto unm_err_out;
1156                         }
1157                         if (vol->cluster_size > 4096) {
1158                                 ntfs_error(vi->i_sb, "Found "
1159                                         "compressed attribute but "
1160                                         "compression is disabled due "
1161                                         "to cluster size (%i) > 4kiB.",
1162                                         vol->cluster_size);
1163                                 goto unm_err_out;
1164                         }
1165                         if ((ctx->attr->flags & ATTR_COMPRESSION_MASK)
1166                                         != ATTR_IS_COMPRESSED) {
1167                                 ntfs_error(vi->i_sb, "Found unknown "
1168                                                 "compression method or "
1169                                                 "corrupt file.");
1170                                 goto unm_err_out;
1171                         }
1172                         ni->itype.compressed.block_clusters = 1U <<
1173                                         ctx->attr->data.non_resident.
1174                                         compression_unit;
1175                         if (ctx->attr->data.non_resident.compression_unit != 4) {
1176                                 ntfs_error(vi->i_sb, "Found "
1177                                         "nonstandard compression unit "
1178                                         "(%u instead of 4). Cannot "
1179                                         "handle this. This might "
1180                                         "indicate corruption so you "
1181                                         "should run chkdsk.",
1182                                         ctx->attr->data.non_resident.
1183                                         compression_unit);
1184                                 err = -EOPNOTSUPP;
1185                                 goto unm_err_out;
1186                         }
1187                         ni->itype.compressed.block_size = 1U << (
1188                                         ctx->attr->data.non_resident.
1189                                         compression_unit +
1190                                         vol->cluster_size_bits);
1191                         ni->itype.compressed.block_size_bits = ffs(
1192                                 ni->itype.compressed.block_size) - 1;
1193                 }
1194                 if (ctx->attr->flags & ATTR_IS_ENCRYPTED) {
1195                         if (ctx->attr->flags & ATTR_COMPRESSION_MASK) {
1196                                 ntfs_error(vi->i_sb, "Found encrypted "
1197                                                 "and compressed data.");
1198                                 goto unm_err_out;
1199                         }
1200                         if (NInoMstProtected(ni)) {
1201                                 ntfs_error(vi->i_sb, "Found mst protected "
1202                                                 "attribute but the attribute "
1203                                                 "is encrypted (mft_no 0x%lx, "
1204                                                 "type 0x%x, name_len %i). "
1205                                                 "Please report you saw this "
1206                                                 "message to linux-ntfs-dev@"
1207                                                 "lists.sourceforge.net",
1208                                                 vi->i_ino, ni->type,
1209                                                 ni->name_len);
1210                                 goto unm_err_out;
1211                         }
1212                         NInoSetEncrypted(ni);
1213                 }
1214                 if (ctx->attr->flags & ATTR_IS_SPARSE) {
1215                         if (NInoMstProtected(ni)) {
1216                                 ntfs_error(vi->i_sb, "Found mst protected "
1217                                                 "attribute but the attribute "
1218                                                 "is sparse (mft_no 0x%lx, "
1219                                                 "type 0x%x, name_len %i). "
1220                                                 "Please report you saw this "
1221                                                 "message to linux-ntfs-dev@"
1222                                                 "lists.sourceforge.net",
1223                                                 vi->i_ino, ni->type,
1224                                                 ni->name_len);
1225                                 goto unm_err_out;
1226                         }
1227                         NInoSetSparse(ni);
1228                 }
1229                 if (ctx->attr->data.non_resident.lowest_vcn) {
1230                         ntfs_error(vi->i_sb, "First extent of attribute has "
1231                                         "non-zero lowest_vcn. Inode is "
1232                                         "corrupt. You should run chkdsk.");
1233                         goto unm_err_out;
1234                 }
1235                 /* Setup all the sizes. */
1236                 vi->i_size = sle64_to_cpu(
1237                                 ctx->attr->data.non_resident.data_size);
1238                 ni->initialized_size = sle64_to_cpu(
1239                                 ctx->attr->data.non_resident.initialized_size);
1240                 ni->allocated_size = sle64_to_cpu(
1241                                 ctx->attr->data.non_resident.allocated_size);
1242                 if (NInoCompressed(ni)) {
1243                         ni->itype.compressed.size = sle64_to_cpu(
1244                                         ctx->attr->data.non_resident.
1245                                         compressed_size);
1246                 }
1247         }
1248
1249         /* Setup the operations for this attribute inode. */
1250         vi->i_op = NULL;
1251         vi->i_fop = NULL;
1252         if (NInoMstProtected(ni))
1253                 vi->i_mapping->a_ops = &ntfs_mst_aops;
1254         else
1255                 vi->i_mapping->a_ops = &ntfs_aops;
1256
1257         if (!NInoCompressed(ni))
1258                 vi->i_blocks = ni->allocated_size >> 9;
1259         else
1260                 vi->i_blocks = ni->itype.compressed.size >> 9;
1261
1262         /*
1263          * Make sure the base inode doesn't go away and attach it to the
1264          * attribute inode.
1265          */
1266         igrab(base_vi);
1267         ni->ext.base_ntfs_ino = base_ni;
1268         ni->nr_extents = -1;
1269
1270         put_attr_search_ctx(ctx);
1271         unmap_mft_record(base_ni);
1272
1273         ntfs_debug("Done.");
1274         return 0;
1275
1276 unm_err_out:
1277         if (!err)
1278                 err = -EIO;
1279         if (ctx)
1280                 put_attr_search_ctx(ctx);
1281         unmap_mft_record(base_ni);
1282 err_out:
1283         ntfs_error(vi->i_sb, "Failed with error code %i while reading "
1284                         "attribute inode (mft_no 0x%lx, type 0x%x, name_len "
1285                         "%i.", -err, vi->i_ino, ni->type, ni->name_len);
1286         make_bad_inode(vi);
1287         return err;
1288 }
1289
1290 /**
1291  * ntfs_read_inode_mount - special read_inode for mount time use only
1292  * @vi:         inode to read
1293  *
1294  * Read inode FILE_MFT at mount time, only called with super_block lock
1295  * held from within the read_super() code path.
1296  *
1297  * This function exists because when it is called the page cache for $MFT/$DATA
1298  * is not initialized and hence we cannot get at the contents of mft records
1299  * by calling map_mft_record*().
1300  *
1301  * Further it needs to cope with the circular references problem, i.e. can't
1302  * load any attributes other than $ATTRIBUTE_LIST until $DATA is loaded, because
1303  * we don't know where the other extent mft records are yet and again, because
1304  * we cannot call map_mft_record*() yet. Obviously this applies only when an
1305  * attribute list is actually present in $MFT inode.
1306  *
1307  * We solve these problems by starting with the $DATA attribute before anything
1308  * else and iterating using lookup_attr($DATA) over all extents. As each extent
1309  * is found, we decompress_mapping_pairs() including the implied
1310  * merge_run_lists(). Each step of the iteration necessarily provides
1311  * sufficient information for the next step to complete.
1312  *
1313  * This should work but there are two possible pit falls (see inline comments
1314  * below), but only time will tell if they are real pits or just smoke...
1315  */
1316 int ntfs_read_inode_mount(struct inode *vi)
1317 {
1318         VCN next_vcn, last_vcn, highest_vcn;
1319         s64 block;
1320         struct super_block *sb = vi->i_sb;
1321         ntfs_volume *vol = NTFS_SB(sb);
1322         struct buffer_head *bh;
1323         ntfs_inode *ni;
1324         MFT_RECORD *m = NULL;
1325         ATTR_RECORD *attr;
1326         attr_search_context *ctx;
1327         unsigned int i, nr_blocks;
1328         int err;
1329
1330         ntfs_debug("Entering.");
1331
1332         /* Initialize the ntfs specific part of @vi. */
1333         ntfs_init_big_inode(vi);
1334
1335         ni = NTFS_I(vi);
1336
1337         /* Setup the data attribute. It is special as it is mst protected. */
1338         NInoSetNonResident(ni);
1339         NInoSetMstProtected(ni);
1340         ni->type = AT_DATA;
1341         ni->name = NULL;
1342         ni->name_len = 0;
1343
1344         /*
1345          * This sets up our little cheat allowing us to reuse the async read io
1346          * completion handler for directories.
1347          */
1348         ni->itype.index.block_size = vol->mft_record_size;
1349         ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1350
1351         /* Very important! Needed to be able to call map_mft_record*(). */
1352         vol->mft_ino = vi;
1353
1354         /* Allocate enough memory to read the first mft record. */
1355         if (vol->mft_record_size > 64 * 1024) {
1356                 ntfs_error(sb, "Unsupported mft record size %i (max 64kiB).",
1357                                 vol->mft_record_size);
1358                 goto err_out;
1359         }
1360         i = vol->mft_record_size;
1361         if (i < sb->s_blocksize)
1362                 i = sb->s_blocksize;
1363         m = (MFT_RECORD*)ntfs_malloc_nofs(i);
1364         if (!m) {
1365                 ntfs_error(sb, "Failed to allocate buffer for $MFT record 0.");
1366                 goto err_out;
1367         }
1368
1369         /* Determine the first block of the $MFT/$DATA attribute. */
1370         block = vol->mft_lcn << vol->cluster_size_bits >>
1371                         sb->s_blocksize_bits;
1372         nr_blocks = vol->mft_record_size >> sb->s_blocksize_bits;
1373         if (!nr_blocks)
1374                 nr_blocks = 1;
1375
1376         /* Load $MFT/$DATA's first mft record. */
1377         for (i = 0; i < nr_blocks; i++) {
1378                 bh = sb_bread(sb, block++);
1379                 if (!bh) {
1380                         ntfs_error(sb, "Device read failed.");
1381                         goto err_out;
1382                 }
1383                 memcpy((char*)m + (i << sb->s_blocksize_bits), bh->b_data,
1384                                 sb->s_blocksize);
1385                 brelse(bh);
1386         }
1387
1388         /* Apply the mst fixups. */
1389         if (post_read_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size)) {
1390                 /* FIXME: Try to use the $MFTMirr now. */
1391                 ntfs_error(sb, "MST fixup failed. $MFT is corrupt.");
1392                 goto err_out;
1393         }
1394
1395         /* Need this to sanity check attribute list references to $MFT. */
1396         vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
1397
1398         /* Provides readpage() and sync_page() for map_mft_record(). */
1399         vi->i_mapping->a_ops = &ntfs_mft_aops;
1400
1401         ctx = get_attr_search_ctx(ni, m);
1402         if (!ctx) {
1403                 err = -ENOMEM;
1404                 goto err_out;
1405         }
1406
1407         /* Find the attribute list attribute if present. */
1408         if (lookup_attr(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx)) {
1409                 ATTR_LIST_ENTRY *al_entry, *next_al_entry;
1410                 u8 *al_end;
1411
1412                 ntfs_debug("Attribute list attribute found in $MFT.");
1413                 NInoSetAttrList(ni);
1414                 if (ctx->attr->flags & ATTR_IS_ENCRYPTED ||
1415                                 ctx->attr->flags & ATTR_COMPRESSION_MASK ||
1416                                 ctx->attr->flags & ATTR_IS_SPARSE) {
1417                         ntfs_error(sb, "Attribute list attribute is "
1418                                         "compressed/encrypted/sparse. Not "
1419                                         "allowed. $MFT is corrupt. You should "
1420                                         "run chkdsk.");
1421                         goto put_err_out;
1422                 }
1423                 /* Now allocate memory for the attribute list. */
1424                 ni->attr_list_size = (u32)attribute_value_length(ctx->attr);
1425                 ni->attr_list = ntfs_malloc_nofs(ni->attr_list_size);
1426                 if (!ni->attr_list) {
1427                         ntfs_error(sb, "Not enough memory to allocate buffer "
1428                                         "for attribute list.");
1429                         goto put_err_out;
1430                 }
1431                 if (ctx->attr->non_resident) {
1432                         NInoSetAttrListNonResident(ni);
1433                         if (ctx->attr->data.non_resident.lowest_vcn) {
1434                                 ntfs_error(sb, "Attribute list has non zero "
1435                                                 "lowest_vcn. $MFT is corrupt. "
1436                                                 "You should run chkdsk.");
1437                                 goto put_err_out;
1438                         }
1439                         /* Setup the run list. */
1440                         ni->attr_list_rl.rl = decompress_mapping_pairs(vol,
1441                                         ctx->attr, NULL);
1442                         if (IS_ERR(ni->attr_list_rl.rl)) {
1443                                 err = PTR_ERR(ni->attr_list_rl.rl);
1444                                 ni->attr_list_rl.rl = NULL;
1445                                 ntfs_error(sb, "Mapping pairs decompression "
1446                                                 "failed with error code %i.",
1447                                                 -err);
1448                                 goto put_err_out;
1449                         }
1450                         /* Now load the attribute list. */
1451                         if ((err = load_attribute_list(vol, &ni->attr_list_rl,
1452                                         ni->attr_list, ni->attr_list_size,
1453                                         sle64_to_cpu(ctx->attr->data.
1454                                         non_resident.initialized_size)))) {
1455                                 ntfs_error(sb, "Failed to load attribute list "
1456                                                 "attribute with error code %i.",
1457                                                 -err);
1458                                 goto put_err_out;
1459                         }
1460                 } else /* if (!ctx.attr->non_resident) */ {
1461                         if ((u8*)ctx->attr + le16_to_cpu(
1462                                         ctx->attr->data.resident.value_offset) +
1463                                         le32_to_cpu(
1464                                         ctx->attr->data.resident.value_length) >
1465                                         (u8*)ctx->mrec + vol->mft_record_size) {
1466                                 ntfs_error(sb, "Corrupt attribute list "
1467                                                 "attribute.");
1468                                 goto put_err_out;
1469                         }
1470                         /* Now copy the attribute list. */
1471                         memcpy(ni->attr_list, (u8*)ctx->attr + le16_to_cpu(
1472                                         ctx->attr->data.resident.value_offset),
1473                                         le32_to_cpu(
1474                                         ctx->attr->data.resident.value_length));
1475                 }
1476                 /* The attribute list is now setup in memory. */
1477                 /*
1478                  * FIXME: I don't know if this case is actually possible.
1479                  * According to logic it is not possible but I have seen too
1480                  * many weird things in MS software to rely on logic... Thus we
1481                  * perform a manual search and make sure the first $MFT/$DATA
1482                  * extent is in the base inode. If it is not we abort with an
1483                  * error and if we ever see a report of this error we will need
1484                  * to do some magic in order to have the necessary mft record
1485                  * loaded and in the right place in the page cache. But
1486                  * hopefully logic will prevail and this never happens...
1487                  */
1488                 al_entry = (ATTR_LIST_ENTRY*)ni->attr_list;
1489                 al_end = (u8*)al_entry + ni->attr_list_size;
1490                 for (;; al_entry = next_al_entry) {
1491                         /* Out of bounds check. */
1492                         if ((u8*)al_entry < ni->attr_list ||
1493                                         (u8*)al_entry > al_end)
1494                                 goto em_put_err_out;
1495                         /* Catch the end of the attribute list. */
1496                         if ((u8*)al_entry == al_end)
1497                                 goto em_put_err_out;
1498                         if (!al_entry->length)
1499                                 goto em_put_err_out;
1500                         if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
1501                                         le16_to_cpu(al_entry->length) > al_end)
1502                                 goto em_put_err_out;
1503                         next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
1504                                         le16_to_cpu(al_entry->length));
1505                         if (le32_to_cpu(al_entry->type) >
1506                                         const_le32_to_cpu(AT_DATA))
1507                                 goto em_put_err_out;
1508                         if (AT_DATA != al_entry->type)
1509                                 continue;
1510                         /* We want an unnamed attribute. */
1511                         if (al_entry->name_length)
1512                                 goto em_put_err_out;
1513                         /* Want the first entry, i.e. lowest_vcn == 0. */
1514                         if (al_entry->lowest_vcn)
1515                                 goto em_put_err_out;
1516                         /* First entry has to be in the base mft record. */
1517                         if (MREF_LE(al_entry->mft_reference) != vi->i_ino) {
1518                                 /* MFT references do not match, logic fails. */
1519                                 ntfs_error(sb, "BUG: The first $DATA extent "
1520                                                 "of $MFT is not in the base "
1521                                                 "mft record. Please report "
1522                                                 "you saw this message to "
1523                                                 "linux-ntfs-dev@lists."
1524                                                 "sourceforge.net");
1525                                 goto put_err_out;
1526                         } else {
1527                                 /* Sequence numbers must match. */
1528                                 if (MSEQNO_LE(al_entry->mft_reference) !=
1529                                                 ni->seq_no)
1530                                         goto em_put_err_out;
1531                                 /* Got it. All is ok. We can stop now. */
1532                                 break;
1533                         }
1534                 }
1535         }
1536
1537         reinit_attr_search_ctx(ctx);
1538
1539         /* Now load all attribute extents. */
1540         attr = NULL;
1541         next_vcn = last_vcn = highest_vcn = 0;
1542         while (lookup_attr(AT_DATA, NULL, 0, 0, next_vcn, NULL, 0, ctx)) {
1543                 run_list_element *nrl;
1544
1545                 /* Cache the current attribute. */
1546                 attr = ctx->attr;
1547                 /* $MFT must be non-resident. */
1548                 if (!attr->non_resident) {
1549                         ntfs_error(sb, "$MFT must be non-resident but a "
1550                                         "resident extent was found. $MFT is "
1551                                         "corrupt. Run chkdsk.");
1552                         goto put_err_out;
1553                 }
1554                 /* $MFT must be uncompressed and unencrypted. */
1555                 if (attr->flags & ATTR_COMPRESSION_MASK ||
1556                                 attr->flags & ATTR_IS_ENCRYPTED ||
1557                                 attr->flags & ATTR_IS_SPARSE) {
1558                         ntfs_error(sb, "$MFT must be uncompressed, "
1559                                         "non-sparse, and unencrypted but a "
1560                                         "compressed/sparse/encrypted extent "
1561                                         "was found. $MFT is corrupt. Run "
1562                                         "chkdsk.");
1563                         goto put_err_out;
1564                 }
1565                 /*
1566                  * Decompress the mapping pairs array of this extent and merge
1567                  * the result into the existing run list. No need for locking
1568                  * as we have exclusive access to the inode at this time and we
1569                  * are a mount in progress task, too.
1570                  */
1571                 nrl = decompress_mapping_pairs(vol, attr, ni->run_list.rl);
1572                 if (IS_ERR(nrl)) {
1573                         ntfs_error(sb, "decompress_mapping_pairs() failed with "
1574                                         "error code %ld. $MFT is corrupt.",
1575                                         PTR_ERR(nrl));
1576                         goto put_err_out;
1577                 }
1578                 ni->run_list.rl = nrl;
1579
1580                 /* Are we in the first extent? */
1581                 if (!next_vcn) {
1582                         u64 ll;
1583
1584                         if (attr->data.non_resident.lowest_vcn) {
1585                                 ntfs_error(sb, "First extent of $DATA "
1586                                                 "attribute has non zero "
1587                                                 "lowest_vcn. $MFT is corrupt. "
1588                                                 "You should run chkdsk.");
1589                                 goto put_err_out;
1590                         }
1591                         /* Get the last vcn in the $DATA attribute. */
1592                         last_vcn = sle64_to_cpu(
1593                                         attr->data.non_resident.allocated_size)
1594                                         >> vol->cluster_size_bits;
1595                         /* Fill in the inode size. */
1596                         vi->i_size = sle64_to_cpu(
1597                                         attr->data.non_resident.data_size);
1598                         ni->initialized_size = sle64_to_cpu(attr->data.
1599                                         non_resident.initialized_size);
1600                         ni->allocated_size = sle64_to_cpu(
1601                                         attr->data.non_resident.allocated_size);
1602                         /* Set the number of mft records. */
1603                         ll = vi->i_size >> vol->mft_record_size_bits;
1604                         /*
1605                          * Verify the number of mft records does not exceed
1606                          * 2^32 - 1.
1607                          */
1608                         if (ll >= (1ULL << 32)) {
1609                                 ntfs_error(sb, "$MFT is too big! Aborting.");
1610                                 goto put_err_out;
1611                         }
1612                         vol->nr_mft_records = ll;
1613                         /*
1614                          * We have got the first extent of the run_list for
1615                          * $MFT which means it is now relatively safe to call
1616                          * the normal ntfs_read_inode() function.
1617                          * Complete reading the inode, this will actually
1618                          * re-read the mft record for $MFT, this time entering
1619                          * it into the page cache with which we complete the
1620                          * kick start of the volume. It should be safe to do
1621                          * this now as the first extent of $MFT/$DATA is
1622                          * already known and we would hope that we don't need
1623                          * further extents in order to find the other
1624                          * attributes belonging to $MFT. Only time will tell if
1625                          * this is really the case. If not we will have to play
1626                          * magic at this point, possibly duplicating a lot of
1627                          * ntfs_read_inode() at this point. We will need to
1628                          * ensure we do enough of its work to be able to call
1629                          * ntfs_read_inode() on extents of $MFT/$DATA. But lets
1630                          * hope this never happens...
1631                          */
1632                         ntfs_read_locked_inode(vi);
1633                         if (is_bad_inode(vi)) {
1634                                 ntfs_error(sb, "ntfs_read_inode() of $MFT "
1635                                                 "failed. BUG or corrupt $MFT. "
1636                                                 "Run chkdsk and if no errors "
1637                                                 "are found, please report you "
1638                                                 "saw this message to "
1639                                                 "linux-ntfs-dev@lists."
1640                                                 "sourceforge.net");
1641                                 put_attr_search_ctx(ctx);
1642                                 /* Revert to the safe super operations. */
1643                                 ntfs_free(m);
1644                                 return -1;
1645                         }
1646                         /*
1647                          * Re-initialize some specifics about $MFT's inode as
1648                          * ntfs_read_inode() will have set up the default ones.
1649                          */
1650                         /* Set uid and gid to root. */
1651                         vi->i_uid = vi->i_gid = 0;
1652                         /* Regular file. No access for anyone. */
1653                         vi->i_mode = S_IFREG;
1654                         /* No VFS initiated operations allowed for $MFT. */
1655                         vi->i_op = &ntfs_empty_inode_ops;
1656                         vi->i_fop = &ntfs_empty_file_ops;
1657                         /* Put back our special address space operations. */
1658                         vi->i_mapping->a_ops = &ntfs_mft_aops;
1659                 }
1660
1661                 /* Get the lowest vcn for the next extent. */
1662                 highest_vcn = sle64_to_cpu(attr->data.non_resident.highest_vcn);
1663                 next_vcn = highest_vcn + 1;
1664
1665                 /* Only one extent or error, which we catch below. */
1666                 if (next_vcn <= 0)
1667                         break;
1668
1669                 /* Avoid endless loops due to corruption. */
1670                 if (next_vcn < sle64_to_cpu(
1671                                 attr->data.non_resident.lowest_vcn)) {
1672                         ntfs_error(sb, "$MFT has corrupt attribute list "
1673                                         "attribute. Run chkdsk.");
1674                         goto put_err_out;
1675                 }
1676         }
1677         if (!attr) {
1678                 ntfs_error(sb, "$MFT/$DATA attribute not found. $MFT is "
1679                                 "corrupt. Run chkdsk.");
1680                 goto put_err_out;
1681         }
1682         if (highest_vcn && highest_vcn != last_vcn - 1) {
1683                 ntfs_error(sb, "Failed to load the complete run list "
1684                                 "for $MFT/$DATA. Driver bug or "
1685                                 "corrupt $MFT. Run chkdsk.");
1686                 ntfs_debug("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx",
1687                                 (unsigned long long)highest_vcn,
1688                                 (unsigned long long)last_vcn - 1);
1689                 goto put_err_out;
1690         }
1691         put_attr_search_ctx(ctx);
1692         ntfs_debug("Done.");
1693         ntfs_free(m);
1694         return 0;
1695
1696 em_put_err_out:
1697         ntfs_error(sb, "Couldn't find first extent of $DATA attribute in "
1698                         "attribute list. $MFT is corrupt. Run chkdsk.");
1699 put_err_out:
1700         put_attr_search_ctx(ctx);
1701 err_out:
1702         ntfs_error(sb, "Failed. Marking inode as bad.");
1703         make_bad_inode(vi);
1704         ntfs_free(m);
1705         return -1;
1706 }
1707
1708 /**
1709  * ntfs_put_inode - handler for when the inode reference count is decremented
1710  * @vi:         vfs inode
1711  *
1712  * The VFS calls ntfs_put_inode() every time the inode reference count (i_count)
1713  * is about to be decremented (but before the decrement itself.
1714  *
1715  * If the inode @vi is a directory with a single reference, we need to put the
1716  * attribute inode for the directory index bitmap, if it is present, otherwise
1717  * the directory inode would remain pinned for ever (or rather until umount()
1718  * time.
1719  */
1720 void ntfs_put_inode(struct inode *vi)
1721 {
1722         if (S_ISDIR(vi->i_mode) && (atomic_read(&vi->i_count) == 2)) {
1723                 ntfs_inode *ni;
1724
1725                 ni = NTFS_I(vi);
1726                 if (NInoIndexAllocPresent(ni) && ni->itype.index.bmp_ino) {
1727                         iput(ni->itype.index.bmp_ino);
1728                         ni->itype.index.bmp_ino = NULL;
1729                 }
1730         }
1731         return;
1732 }
1733
1734 void __ntfs_clear_inode(ntfs_inode *ni)
1735 {
1736         /* Free all alocated memory. */
1737         down_write(&ni->run_list.lock);
1738         if (ni->run_list.rl) {
1739                 ntfs_free(ni->run_list.rl);
1740                 ni->run_list.rl = NULL;
1741         }
1742         up_write(&ni->run_list.lock);
1743
1744         if (ni->attr_list) {
1745                 ntfs_free(ni->attr_list);
1746                 ni->attr_list = NULL;
1747         }
1748
1749         down_write(&ni->attr_list_rl.lock);
1750         if (ni->attr_list_rl.rl) {
1751                 ntfs_free(ni->attr_list_rl.rl);
1752                 ni->attr_list_rl.rl = NULL;
1753         }
1754         up_write(&ni->attr_list_rl.lock);
1755
1756         if (ni->name_len && ni->name != I30) {
1757                 /* Catch bugs... */
1758                 BUG_ON(!ni->name);
1759                 kfree(ni->name);
1760         }
1761 }
1762
1763 void ntfs_clear_extent_inode(ntfs_inode *ni)
1764 {
1765         ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
1766
1767         BUG_ON(NInoAttr(ni));
1768         BUG_ON(ni->nr_extents != -1);
1769
1770 #ifdef NTFS_RW
1771         if (NInoDirty(ni)) {
1772                 if (!is_bad_inode(VFS_I(ni->ext.base_ntfs_ino)))
1773                         ntfs_error(ni->vol->sb, "Clearing dirty extent inode!  "
1774                                         "Losing data!  This is a BUG!!!");
1775                 // FIXME:  Do something!!!
1776         }
1777 #endif /* NTFS_RW */
1778
1779         __ntfs_clear_inode(ni);
1780
1781         /* Bye, bye... */
1782         ntfs_destroy_extent_inode(ni);
1783 }
1784
1785 /**
1786  * ntfs_clear_big_inode - clean up the ntfs specific part of an inode
1787  * @vi:         vfs inode pending annihilation
1788  *
1789  * When the VFS is going to remove an inode from memory, ntfs_clear_big_inode()
1790  * is called, which deallocates all memory belonging to the NTFS specific part
1791  * of the inode and returns.
1792  *
1793  * If the MFT record is dirty, we commit it before doing anything else.
1794  */
1795 void ntfs_clear_big_inode(struct inode *vi)
1796 {
1797         ntfs_inode *ni = NTFS_I(vi);
1798
1799 #ifdef NTFS_RW
1800         if (NInoDirty(ni)) {
1801                 BOOL was_bad = (is_bad_inode(vi));
1802
1803                 /* Committing the inode also commits all extent inodes. */
1804                 ntfs_commit_inode(vi);
1805
1806                 if (!was_bad && (is_bad_inode(vi) || NInoDirty(ni))) {
1807                         ntfs_error(vi->i_sb, "Failed to commit dirty inode "
1808                                         "0x%lx.  Losing data!", vi->i_ino);
1809                         // FIXME:  Do something!!!
1810                 }
1811         }
1812 #endif /* NTFS_RW */
1813
1814         /* No need to lock at this stage as no one else has a reference. */
1815         if (ni->nr_extents > 0) {
1816                 int i;
1817
1818                 for (i = 0; i < ni->nr_extents; i++)
1819                         ntfs_clear_extent_inode(ni->ext.extent_ntfs_inos[i]);
1820                 kfree(ni->ext.extent_ntfs_inos);
1821         }
1822
1823         __ntfs_clear_inode(ni);
1824
1825         if (NInoAttr(ni)) {
1826                 /* Release the base inode if we are holding it. */
1827                 if (ni->nr_extents == -1) {
1828                         iput(VFS_I(ni->ext.base_ntfs_ino));
1829                         ni->nr_extents = 0;
1830                         ni->ext.base_ntfs_ino = NULL;
1831                 }
1832         }
1833         return;
1834 }
1835
1836 /**
1837  * ntfs_show_options - show mount options in /proc/mounts
1838  * @sf:         seq_file in which to write our mount options
1839  * @mnt:        vfs mount whose mount options to display
1840  *
1841  * Called by the VFS once for each mounted ntfs volume when someone reads
1842  * /proc/mounts in order to display the NTFS specific mount options of each
1843  * mount. The mount options of the vfs mount @mnt are written to the seq file
1844  * @sf and success is returned.
1845  */
1846 int ntfs_show_options(struct seq_file *sf, struct vfsmount *mnt)
1847 {
1848         ntfs_volume *vol = NTFS_SB(mnt->mnt_sb);
1849         int i;
1850
1851         seq_printf(sf, ",uid=%i", vol->uid);
1852         seq_printf(sf, ",gid=%i", vol->gid);
1853         if (vol->fmask == vol->dmask)
1854                 seq_printf(sf, ",umask=0%o", vol->fmask);
1855         else {
1856                 seq_printf(sf, ",fmask=0%o", vol->fmask);
1857                 seq_printf(sf, ",dmask=0%o", vol->dmask);
1858         }
1859         seq_printf(sf, ",nls=%s", vol->nls_map->charset);
1860         if (NVolCaseSensitive(vol))
1861                 seq_printf(sf, ",case_sensitive");
1862         if (NVolShowSystemFiles(vol))
1863                 seq_printf(sf, ",show_sys_files");
1864         for (i = 0; on_errors_arr[i].val; i++) {
1865                 if (on_errors_arr[i].val & vol->on_errors)
1866                         seq_printf(sf, ",errors=%s", on_errors_arr[i].str);
1867         }
1868         seq_printf(sf, ",mft_zone_multiplier=%i", vol->mft_zone_multiplier);
1869         return 0;
1870 }
1871
1872 #ifdef NTFS_RW
1873
1874 /**
1875  * ntfs_truncate - called when the i_size of an ntfs inode is changed
1876  * @vi:         inode for which the i_size was changed
1877  *
1878  * We don't support i_size changes yet.
1879  *
1880  * Called with ->i_sem held.
1881  */
1882 void ntfs_truncate(struct inode *vi)
1883 {
1884         // TODO: Implement...
1885         ntfs_warning(vi->i_sb, "Eeek: i_size may have changed! If you see "
1886                         "this right after a message from "
1887                         "ntfs_{prepare,commit}_{,nonresident_}write() then "
1888                         "just ignore it. Otherwise it is bad news.");
1889         // TODO: reset i_size now!
1890         return;
1891 }
1892
1893 /**
1894  * ntfs_setattr - called from notify_change() when an attribute is being changed
1895  * @dentry:     dentry whose attributes to change
1896  * @attr:       structure describing the attributes and the changes
1897  *
1898  * We have to trap VFS attempts to truncate the file described by @dentry as
1899  * soon as possible, because we do not implement changes in i_size yet. So we
1900  * abort all i_size changes here.
1901  *
1902  * Called with ->i_sem held.
1903  *
1904  * Basically this is a copy of generic notify_change() and inode_setattr()
1905  * functionality, except we intercept and abort changes in i_size.
1906  */
1907 int ntfs_setattr(struct dentry *dentry, struct iattr *attr)
1908 {
1909         struct inode *vi;
1910         int err;
1911         unsigned int ia_valid = attr->ia_valid;
1912
1913         vi = dentry->d_inode;
1914
1915         err = inode_change_ok(vi, attr);
1916         if (err)
1917                 return err;
1918
1919         if ((ia_valid & ATTR_UID && attr->ia_uid != vi->i_uid) ||
1920                         (ia_valid & ATTR_GID && attr->ia_gid != vi->i_gid)) {
1921                 err = DQUOT_TRANSFER(vi, attr) ? -EDQUOT : 0;
1922                 if (err)
1923                         return err;
1924         }
1925
1926         lock_kernel();
1927
1928         if (ia_valid & ATTR_SIZE) {
1929                 ntfs_error(vi->i_sb, "Changes in i_size are not supported "
1930                                 "yet. Sorry.");
1931                 // TODO: Implement...
1932                 // err = vmtruncate(vi, attr->ia_size);
1933                 err = -EOPNOTSUPP;
1934                 if (err)
1935                         goto trunc_err;
1936         }
1937
1938         if (ia_valid & ATTR_UID)
1939                 vi->i_uid = attr->ia_uid;
1940         if (ia_valid & ATTR_GID)
1941                 vi->i_gid = attr->ia_gid;
1942         if (ia_valid & ATTR_ATIME)
1943                 vi->i_atime = attr->ia_atime;
1944         if (ia_valid & ATTR_MTIME)
1945                 vi->i_mtime = attr->ia_mtime;
1946         if (ia_valid & ATTR_CTIME)
1947                 vi->i_ctime = attr->ia_ctime;
1948         if (ia_valid & ATTR_MODE) {
1949                 vi->i_mode = attr->ia_mode;
1950                 if (!in_group_p(vi->i_gid) &&
1951                                 !capable(CAP_FSETID))
1952                         vi->i_mode &= ~S_ISGID;
1953         }
1954         mark_inode_dirty(vi);
1955
1956 trunc_err:
1957
1958         unlock_kernel();
1959
1960         return err;
1961 }
1962
1963 /**
1964  * ntfs_write_inode - write out a dirty inode
1965  * @vi:         inode to write out
1966  * @sync:       if true, write out synchronously
1967  *
1968  * Write out a dirty inode to disk including any extent inodes if present.
1969  *
1970  * If @sync is true, commit the inode to disk and wait for io completion.  This
1971  * is done using write_mft_record().
1972  *
1973  * If @sync is false, just schedule the write to happen but do not wait for i/o
1974  * completion.  In 2.6 kernels, scheduling usually happens just by virtue of
1975  * marking the page (and in this case mft record) dirty but we do not implement
1976  * this yet as write_mft_record() largely ignores the @sync parameter and
1977  * always performs synchronous writes.
1978  */
1979 void ntfs_write_inode(struct inode *vi, int sync)
1980 {
1981         ntfs_inode *ni = NTFS_I(vi);
1982 #if 0
1983         attr_search_context *ctx;
1984 #endif
1985         MFT_RECORD *m;
1986         int err = 0;
1987
1988         ntfs_debug("Entering for %sinode 0x%lx.", NInoAttr(ni) ? "attr " : "",
1989                         vi->i_ino);
1990         /*
1991          * Dirty attribute inodes are written via their real inodes so just
1992          * clean them here.  TODO:  Take care of access time updates.
1993          */
1994         if (NInoAttr(ni)) {
1995                 NInoClearDirty(ni);
1996                 return;
1997         }
1998         /* Map, pin, and lock the mft record belonging to the inode. */
1999         m = map_mft_record(ni);
2000         if (unlikely(IS_ERR(m))) {
2001                 err = PTR_ERR(m);
2002                 goto err_out;
2003         }
2004 #if 0
2005         /* Obtain the standard information attribute. */
2006         ctx = get_attr_search_ctx(ni, m);
2007         if (unlikely(!ctx)) {
2008                 err = -ENOMEM;
2009                 goto unm_err_out;
2010         }
2011         if (unlikely(!lookup_attr(AT_STANDARD_INFORMATION, NULL, 0,
2012                         IGNORE_CASE, 0, NULL, 0, ctx))) {
2013                 put_attr_search_ctx(ctx);
2014                 err = -ENOENT;
2015                 goto unm_err_out;
2016         }
2017         // TODO:  Update the access times in the standard information attribute
2018         // which is now in ctx->attr.
2019         // - Probably want to have use sops->dirty_inode() to set a flag that
2020         //   we need to update the times here rather than having to blindly do
2021         //   it every time.  Or even don't do it here at all and do it in
2022         //   sops->dirty_inode() instead.  Problem with this would be that
2023         //   sops->dirty_inode() must be atomic under certain circumstances
2024         //   and mapping mft records and such like is not atomic.
2025         // - For atime updates also need to check whether they are enabled in
2026         //   the superblock flags.
2027         ntfs_warning(vi->i_sb, "Access time updates not implement yet.");
2028         /*
2029          * We just modified the mft record containing the standard information
2030          * attribute.  So need to mark the mft record dirty, too, but we do it
2031          * manually so that mark_inode_dirty() is not called again.
2032          * TODO:  Only do this if there was a change in any of the times!
2033          */
2034         if (!NInoTestSetDirty(ctx->ntfs_ino))
2035                 __set_page_dirty_nobuffers(ctx->ntfs_ino->page);
2036         put_attr_search_ctx(ctx);
2037 #endif
2038         /* Write this base mft record. */
2039         if (NInoDirty(ni))
2040                 err = write_mft_record(ni, m, sync);
2041         /* Write all attached extent mft records. */
2042         down(&ni->extent_lock);
2043         if (ni->nr_extents > 0) {
2044                 ntfs_inode **extent_nis = ni->ext.extent_ntfs_inos;
2045                 int i;
2046
2047                 ntfs_debug("Writing %i extent inodes.", ni->nr_extents);
2048                 for (i = 0; i < ni->nr_extents; i++) {
2049                         ntfs_inode *tni = extent_nis[i];
2050
2051                         if (NInoDirty(tni)) {
2052                                 MFT_RECORD *tm = map_mft_record(tni);
2053                                 int ret;
2054
2055                                 if (unlikely(IS_ERR(tm))) {
2056                                         if (!err || err == -ENOMEM)
2057                                                 err = PTR_ERR(tm);
2058                                         continue;
2059                                 }
2060                                 ret = write_mft_record(tni, tm, sync);
2061                                 unmap_mft_record(tni);
2062                                 if (unlikely(ret)) {
2063                                         if (!err || err == -ENOMEM)
2064                                                 err = ret;
2065                                 }
2066                         }
2067                 }
2068         }
2069         up(&ni->extent_lock);
2070         unmap_mft_record(ni);
2071         if (unlikely(err))
2072                 goto err_out;
2073         ntfs_debug("Done.");
2074         return;
2075 #if 0
2076 unm_err_out:
2077         unmap_mft_record(ni);
2078 #endif
2079 err_out:
2080         if (err == -ENOMEM) {
2081                 ntfs_warning(vi->i_sb, "Not enough memory to write inode.  "
2082                                 "Marking the inode dirty again, so the VFS "
2083                                 "retries later.");
2084                 mark_inode_dirty(vi);
2085         } else {
2086                 ntfs_error(vi->i_sb, "Failed (error code %i):  Marking inode "
2087                                 "as bad.  You should run chkdsk.", -err);
2088                 make_bad_inode(vi);
2089         }
2090         return;
2091 }
2092
2093 #endif /* NTFS_RW */