vserver 1.9.3
[linux-2.6.git] / fs / ntfs / dir.c
1 /**
2  * dir.c - NTFS kernel directory operations. Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2001-2004 Anton Altaparmakov
5  * Copyright (c) 2002 Richard Russon
6  *
7  * This program/include file is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License as published
9  * by the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program/include file is distributed in the hope that it will be
13  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program (in the main directory of the Linux-NTFS
19  * distribution in the file COPYING); if not, write to the Free Software
20  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <linux/smp_lock.h>
24 #include "ntfs.h"
25 #include "dir.h"
26
27 /**
28  * The little endian Unicode string $I30 as a global constant.
29  */
30 ntfschar I30[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('I'),
31                 const_cpu_to_le16('3'), const_cpu_to_le16('0'), 0 };
32
33 /**
34  * ntfs_lookup_inode_by_name - find an inode in a directory given its name
35  * @dir_ni:     ntfs inode of the directory in which to search for the name
36  * @uname:      Unicode name for which to search in the directory
37  * @uname_len:  length of the name @uname in Unicode characters
38  * @res:        return the found file name if necessary (see below)
39  *
40  * Look for an inode with name @uname in the directory with inode @dir_ni.
41  * ntfs_lookup_inode_by_name() walks the contents of the directory looking for
42  * the Unicode name. If the name is found in the directory, the corresponding
43  * inode number (>= 0) is returned as a mft reference in cpu format, i.e. it
44  * is a 64-bit number containing the sequence number.
45  *
46  * On error, a negative value is returned corresponding to the error code. In
47  * particular if the inode is not found -ENOENT is returned. Note that you
48  * can't just check the return value for being negative, you have to check the
49  * inode number for being negative which you can extract using MREC(return
50  * value).
51  *
52  * Note, @uname_len does not include the (optional) terminating NULL character.
53  *
54  * Note, we look for a case sensitive match first but we also look for a case
55  * insensitive match at the same time. If we find a case insensitive match, we
56  * save that for the case that we don't find an exact match, where we return
57  * the case insensitive match and setup @res (which we allocate!) with the mft
58  * reference, the file name type, length and with a copy of the little endian
59  * Unicode file name itself. If we match a file name which is in the DOS name
60  * space, we only return the mft reference and file name type in @res.
61  * ntfs_lookup() then uses this to find the long file name in the inode itself.
62  * This is to avoid polluting the dcache with short file names. We want them to
63  * work but we don't care for how quickly one can access them. This also fixes
64  * the dcache aliasing issues.
65  *
66  * Locking:  - Caller must hold i_sem on the directory.
67  *           - Each page cache page in the index allocation mapping must be
68  *             locked whilst being accessed otherwise we may find a corrupt
69  *             page due to it being under ->writepage at the moment which
70  *             applies the mst protection fixups before writing out and then
71  *             removes them again after the write is complete after which it 
72  *             unlocks the page.
73  */
74 MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,
75                 const int uname_len, ntfs_name **res)
76 {
77         ntfs_volume *vol = dir_ni->vol;
78         struct super_block *sb = vol->sb;
79         MFT_RECORD *m;
80         INDEX_ROOT *ir;
81         INDEX_ENTRY *ie;
82         INDEX_ALLOCATION *ia;
83         u8 *index_end;
84         u64 mref;
85         ntfs_attr_search_ctx *ctx;
86         int err, rc;
87         VCN vcn, old_vcn;
88         struct address_space *ia_mapping;
89         struct page *page;
90         u8 *kaddr;
91         ntfs_name *name = NULL;
92
93         BUG_ON(!S_ISDIR(VFS_I(dir_ni)->i_mode));
94         BUG_ON(NInoAttr(dir_ni));
95         /* Get hold of the mft record for the directory. */
96         m = map_mft_record(dir_ni);
97         if (IS_ERR(m)) {
98                 ntfs_error(sb, "map_mft_record() failed with error code %ld.",
99                                 -PTR_ERR(m));
100                 return ERR_MREF(PTR_ERR(m));
101         }
102         ctx = ntfs_attr_get_search_ctx(dir_ni, m);
103         if (unlikely(!ctx)) {
104                 err = -ENOMEM;
105                 goto err_out;
106         }
107         /* Find the index root attribute in the mft record. */
108         err = ntfs_attr_lookup(AT_INDEX_ROOT, I30, 4, CASE_SENSITIVE, 0, NULL,
109                         0, ctx);
110         if (unlikely(err)) {
111                 if (err == -ENOENT) {
112                         ntfs_error(sb, "Index root attribute missing in "
113                                         "directory inode 0x%lx.",
114                                         dir_ni->mft_no);
115                         err = -EIO;
116                 }
117                 goto err_out;
118         }
119         /* Get to the index root value (it's been verified in read_inode). */
120         ir = (INDEX_ROOT*)((u8*)ctx->attr +
121                         le16_to_cpu(ctx->attr->data.resident.value_offset));
122         index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
123         /* The first index entry. */
124         ie = (INDEX_ENTRY*)((u8*)&ir->index +
125                         le32_to_cpu(ir->index.entries_offset));
126         /*
127          * Loop until we exceed valid memory (corruption case) or until we
128          * reach the last entry.
129          */
130         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
131                 /* Bounds checks. */
132                 if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie +
133                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
134                                 (u8*)ie + le16_to_cpu(ie->key_length) >
135                                 index_end)
136                         goto dir_err_out;
137                 /*
138                  * The last entry cannot contain a name. It can however contain
139                  * a pointer to a child node in the B+tree so we just break out.
140                  */
141                 if (ie->flags & INDEX_ENTRY_END)
142                         break;
143                 /*
144                  * We perform a case sensitive comparison and if that matches
145                  * we are done and return the mft reference of the inode (i.e.
146                  * the inode number together with the sequence number for
147                  * consistency checking). We convert it to cpu format before
148                  * returning.
149                  */
150                 if (ntfs_are_names_equal(uname, uname_len,
151                                 (ntfschar*)&ie->key.file_name.file_name,
152                                 ie->key.file_name.file_name_length,
153                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len)) {
154 found_it:
155                         /*
156                          * We have a perfect match, so we don't need to care
157                          * about having matched imperfectly before, so we can
158                          * free name and set *res to NULL.
159                          * However, if the perfect match is a short file name,
160                          * we need to signal this through *res, so that
161                          * ntfs_lookup() can fix dcache aliasing issues.
162                          * As an optimization we just reuse an existing
163                          * allocation of *res.
164                          */
165                         if (ie->key.file_name.file_name_type == FILE_NAME_DOS) {
166                                 if (!name) {
167                                         name = kmalloc(sizeof(ntfs_name),
168                                                         GFP_NOFS);
169                                         if (!name) {
170                                                 err = -ENOMEM;
171                                                 goto err_out;
172                                         }
173                                 }
174                                 name->mref = le64_to_cpu(
175                                                 ie->data.dir.indexed_file);
176                                 name->type = FILE_NAME_DOS;
177                                 name->len = 0;
178                                 *res = name;
179                         } else {
180                                 if (name)
181                                         kfree(name);
182                                 *res = NULL;
183                         }
184                         mref = le64_to_cpu(ie->data.dir.indexed_file);
185                         ntfs_attr_put_search_ctx(ctx);
186                         unmap_mft_record(dir_ni);
187                         return mref;
188                 }
189                 /*
190                  * For a case insensitive mount, we also perform a case
191                  * insensitive comparison (provided the file name is not in the
192                  * POSIX namespace). If the comparison matches, and the name is
193                  * in the WIN32 namespace, we cache the filename in *res so
194                  * that the caller, ntfs_lookup(), can work on it. If the
195                  * comparison matches, and the name is in the DOS namespace, we
196                  * only cache the mft reference and the file name type (we set
197                  * the name length to zero for simplicity).
198                  */
199                 if (!NVolCaseSensitive(vol) &&
200                                 ie->key.file_name.file_name_type &&
201                                 ntfs_are_names_equal(uname, uname_len,
202                                 (ntfschar*)&ie->key.file_name.file_name,
203                                 ie->key.file_name.file_name_length,
204                                 IGNORE_CASE, vol->upcase, vol->upcase_len)) {
205                         int name_size = sizeof(ntfs_name);
206                         u8 type = ie->key.file_name.file_name_type;
207                         u8 len = ie->key.file_name.file_name_length;
208
209                         /* Only one case insensitive matching name allowed. */
210                         if (name) {
211                                 ntfs_error(sb, "Found already allocated name "
212                                                 "in phase 1. Please run chkdsk "
213                                                 "and if that doesn't find any "
214                                                 "errors please report you saw "
215                                                 "this message to "
216                                                 "linux-ntfs-dev@lists."
217                                                 "sourceforge.net.");
218                                 goto dir_err_out;
219                         }
220
221                         if (type != FILE_NAME_DOS)
222                                 name_size += len * sizeof(ntfschar);
223                         name = kmalloc(name_size, GFP_NOFS);
224                         if (!name) {
225                                 err = -ENOMEM;
226                                 goto err_out;
227                         }
228                         name->mref = le64_to_cpu(ie->data.dir.indexed_file);
229                         name->type = type;
230                         if (type != FILE_NAME_DOS) {
231                                 name->len = len;
232                                 memcpy(name->name, ie->key.file_name.file_name,
233                                                 len * sizeof(ntfschar));
234                         } else
235                                 name->len = 0;
236                         *res = name;
237                 }
238                 /*
239                  * Not a perfect match, need to do full blown collation so we
240                  * know which way in the B+tree we have to go.
241                  */
242                 rc = ntfs_collate_names(uname, uname_len,
243                                 (ntfschar*)&ie->key.file_name.file_name,
244                                 ie->key.file_name.file_name_length, 1,
245                                 IGNORE_CASE, vol->upcase, vol->upcase_len);
246                 /*
247                  * If uname collates before the name of the current entry, there
248                  * is definitely no such name in this index but we might need to
249                  * descend into the B+tree so we just break out of the loop.
250                  */
251                 if (rc == -1)
252                         break;
253                 /* The names are not equal, continue the search. */
254                 if (rc)
255                         continue;
256                 /*
257                  * Names match with case insensitive comparison, now try the
258                  * case sensitive comparison, which is required for proper
259                  * collation.
260                  */
261                 rc = ntfs_collate_names(uname, uname_len,
262                                 (ntfschar*)&ie->key.file_name.file_name,
263                                 ie->key.file_name.file_name_length, 1,
264                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len);
265                 if (rc == -1)
266                         break;
267                 if (rc)
268                         continue;
269                 /*
270                  * Perfect match, this will never happen as the
271                  * ntfs_are_names_equal() call will have gotten a match but we
272                  * still treat it correctly.
273                  */
274                 goto found_it;
275         }
276         /*
277          * We have finished with this index without success. Check for the
278          * presence of a child node and if not present return -ENOENT, unless
279          * we have got a matching name cached in name in which case return the
280          * mft reference associated with it.
281          */
282         if (!(ie->flags & INDEX_ENTRY_NODE)) {
283                 if (name) {
284                         ntfs_attr_put_search_ctx(ctx);
285                         unmap_mft_record(dir_ni);
286                         return name->mref;
287                 }
288                 ntfs_debug("Entry not found.");
289                 err = -ENOENT;
290                 goto err_out;
291         } /* Child node present, descend into it. */
292         /* Consistency check: Verify that an index allocation exists. */
293         if (!NInoIndexAllocPresent(dir_ni)) {
294                 ntfs_error(sb, "No index allocation attribute but index entry "
295                                 "requires one. Directory inode 0x%lx is "
296                                 "corrupt or driver bug.", dir_ni->mft_no);
297                 err = -EIO;
298                 goto err_out;
299         }
300         /* Get the starting vcn of the index_block holding the child node. */
301         vcn = sle64_to_cpup((sle64*)((u8*)ie + le16_to_cpu(ie->length) - 8));
302         ia_mapping = VFS_I(dir_ni)->i_mapping;
303         /*
304          * We are done with the index root and the mft record. Release them,
305          * otherwise we deadlock with ntfs_map_page().
306          */
307         ntfs_attr_put_search_ctx(ctx);
308         unmap_mft_record(dir_ni);
309         m = NULL;
310         ctx = NULL;
311 descend_into_child_node:
312         /*
313          * Convert vcn to index into the index allocation attribute in units
314          * of PAGE_CACHE_SIZE and map the page cache page, reading it from
315          * disk if necessary.
316          */
317         page = ntfs_map_page(ia_mapping, vcn <<
318                         dir_ni->itype.index.vcn_size_bits >> PAGE_CACHE_SHIFT);
319         if (IS_ERR(page)) {
320                 ntfs_error(sb, "Failed to map directory index page, error %ld.",
321                                 -PTR_ERR(page));
322                 err = PTR_ERR(page);
323                 goto err_out;
324         }
325         lock_page(page);
326         kaddr = (u8*)page_address(page);
327 fast_descend_into_child_node:
328         /* Get to the index allocation block. */
329         ia = (INDEX_ALLOCATION*)(kaddr + ((vcn <<
330                         dir_ni->itype.index.vcn_size_bits) & ~PAGE_CACHE_MASK));
331         /* Bounds checks. */
332         if ((u8*)ia < kaddr || (u8*)ia > kaddr + PAGE_CACHE_SIZE) {
333                 ntfs_error(sb, "Out of bounds check failed. Corrupt directory "
334                                 "inode 0x%lx or driver bug.", dir_ni->mft_no);
335                 err = -EIO;
336                 goto unm_err_out;
337         }
338         if (sle64_to_cpu(ia->index_block_vcn) != vcn) {
339                 ntfs_error(sb, "Actual VCN (0x%llx) of index buffer is "
340                                 "different from expected VCN (0x%llx). "
341                                 "Directory inode 0x%lx is corrupt or driver "
342                                 "bug.", (unsigned long long)
343                                 sle64_to_cpu(ia->index_block_vcn),
344                                 (unsigned long long)vcn, dir_ni->mft_no);
345                 err = -EIO;
346                 goto unm_err_out;
347         }
348         if (le32_to_cpu(ia->index.allocated_size) + 0x18 !=
349                         dir_ni->itype.index.block_size) {
350                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
351                                 "0x%lx has a size (%u) differing from the "
352                                 "directory specified size (%u). Directory "
353                                 "inode is corrupt or driver bug.",
354                                 (unsigned long long)vcn, dir_ni->mft_no,
355                                 le32_to_cpu(ia->index.allocated_size) + 0x18,
356                                 dir_ni->itype.index.block_size);
357                 err = -EIO;
358                 goto unm_err_out;
359         }
360         index_end = (u8*)ia + dir_ni->itype.index.block_size;
361         if (index_end > kaddr + PAGE_CACHE_SIZE) {
362                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
363                                 "0x%lx crosses page boundary. Impossible! "
364                                 "Cannot access! This is probably a bug in the "
365                                 "driver.", (unsigned long long)vcn,
366                                 dir_ni->mft_no);
367                 err = -EIO;
368                 goto unm_err_out;
369         }
370         index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length);
371         if (index_end > (u8*)ia + dir_ni->itype.index.block_size) {
372                 ntfs_error(sb, "Size of index buffer (VCN 0x%llx) of directory "
373                                 "inode 0x%lx exceeds maximum size.",
374                                 (unsigned long long)vcn, dir_ni->mft_no);
375                 err = -EIO;
376                 goto unm_err_out;
377         }
378         /* The first index entry. */
379         ie = (INDEX_ENTRY*)((u8*)&ia->index +
380                         le32_to_cpu(ia->index.entries_offset));
381         /*
382          * Iterate similar to above big loop but applied to index buffer, thus
383          * loop until we exceed valid memory (corruption case) or until we
384          * reach the last entry.
385          */
386         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
387                 /* Bounds check. */
388                 if ((u8*)ie < (u8*)ia || (u8*)ie +
389                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
390                                 (u8*)ie + le16_to_cpu(ie->key_length) >
391                                 index_end) {
392                         ntfs_error(sb, "Index entry out of bounds in "
393                                         "directory inode 0x%lx.",
394                                         dir_ni->mft_no);
395                         err = -EIO;
396                         goto unm_err_out;
397                 }
398                 /*
399                  * The last entry cannot contain a name. It can however contain
400                  * a pointer to a child node in the B+tree so we just break out.
401                  */
402                 if (ie->flags & INDEX_ENTRY_END)
403                         break;
404                 /*
405                  * We perform a case sensitive comparison and if that matches
406                  * we are done and return the mft reference of the inode (i.e.
407                  * the inode number together with the sequence number for
408                  * consistency checking). We convert it to cpu format before
409                  * returning.
410                  */
411                 if (ntfs_are_names_equal(uname, uname_len,
412                                 (ntfschar*)&ie->key.file_name.file_name,
413                                 ie->key.file_name.file_name_length,
414                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len)) {
415 found_it2:
416                         /*
417                          * We have a perfect match, so we don't need to care
418                          * about having matched imperfectly before, so we can
419                          * free name and set *res to NULL.
420                          * However, if the perfect match is a short file name,
421                          * we need to signal this through *res, so that
422                          * ntfs_lookup() can fix dcache aliasing issues.
423                          * As an optimization we just reuse an existing
424                          * allocation of *res.
425                          */
426                         if (ie->key.file_name.file_name_type == FILE_NAME_DOS) {
427                                 if (!name) {
428                                         name = kmalloc(sizeof(ntfs_name),
429                                                         GFP_NOFS);
430                                         if (!name) {
431                                                 err = -ENOMEM;
432                                                 goto unm_err_out;
433                                         }
434                                 }
435                                 name->mref = le64_to_cpu(
436                                                 ie->data.dir.indexed_file);
437                                 name->type = FILE_NAME_DOS;
438                                 name->len = 0;
439                                 *res = name;
440                         } else {
441                                 if (name)
442                                         kfree(name);
443                                 *res = NULL;
444                         }
445                         mref = le64_to_cpu(ie->data.dir.indexed_file);
446                         unlock_page(page);
447                         ntfs_unmap_page(page);
448                         return mref;
449                 }
450                 /*
451                  * For a case insensitive mount, we also perform a case
452                  * insensitive comparison (provided the file name is not in the
453                  * POSIX namespace). If the comparison matches, and the name is
454                  * in the WIN32 namespace, we cache the filename in *res so
455                  * that the caller, ntfs_lookup(), can work on it. If the
456                  * comparison matches, and the name is in the DOS namespace, we
457                  * only cache the mft reference and the file name type (we set
458                  * the name length to zero for simplicity).
459                  */
460                 if (!NVolCaseSensitive(vol) &&
461                                 ie->key.file_name.file_name_type &&
462                                 ntfs_are_names_equal(uname, uname_len,
463                                 (ntfschar*)&ie->key.file_name.file_name,
464                                 ie->key.file_name.file_name_length,
465                                 IGNORE_CASE, vol->upcase, vol->upcase_len)) {
466                         int name_size = sizeof(ntfs_name);
467                         u8 type = ie->key.file_name.file_name_type;
468                         u8 len = ie->key.file_name.file_name_length;
469
470                         /* Only one case insensitive matching name allowed. */
471                         if (name) {
472                                 ntfs_error(sb, "Found already allocated name "
473                                                 "in phase 2. Please run chkdsk "
474                                                 "and if that doesn't find any "
475                                                 "errors please report you saw "
476                                                 "this message to "
477                                                 "linux-ntfs-dev@lists."
478                                                 "sourceforge.net.");
479                                 unlock_page(page);
480                                 ntfs_unmap_page(page);
481                                 goto dir_err_out;
482                         }
483
484                         if (type != FILE_NAME_DOS)
485                                 name_size += len * sizeof(ntfschar);
486                         name = kmalloc(name_size, GFP_NOFS);
487                         if (!name) {
488                                 err = -ENOMEM;
489                                 goto unm_err_out;
490                         }
491                         name->mref = le64_to_cpu(ie->data.dir.indexed_file);
492                         name->type = type;
493                         if (type != FILE_NAME_DOS) {
494                                 name->len = len;
495                                 memcpy(name->name, ie->key.file_name.file_name,
496                                                 len * sizeof(ntfschar));
497                         } else
498                                 name->len = 0;
499                         *res = name;
500                 }
501                 /*
502                  * Not a perfect match, need to do full blown collation so we
503                  * know which way in the B+tree we have to go.
504                  */
505                 rc = ntfs_collate_names(uname, uname_len,
506                                 (ntfschar*)&ie->key.file_name.file_name,
507                                 ie->key.file_name.file_name_length, 1,
508                                 IGNORE_CASE, vol->upcase, vol->upcase_len);
509                 /*
510                  * If uname collates before the name of the current entry, there
511                  * is definitely no such name in this index but we might need to
512                  * descend into the B+tree so we just break out of the loop.
513                  */
514                 if (rc == -1)
515                         break;
516                 /* The names are not equal, continue the search. */
517                 if (rc)
518                         continue;
519                 /*
520                  * Names match with case insensitive comparison, now try the
521                  * case sensitive comparison, which is required for proper
522                  * collation.
523                  */
524                 rc = ntfs_collate_names(uname, uname_len,
525                                 (ntfschar*)&ie->key.file_name.file_name,
526                                 ie->key.file_name.file_name_length, 1,
527                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len);
528                 if (rc == -1)
529                         break;
530                 if (rc)
531                         continue;
532                 /*
533                  * Perfect match, this will never happen as the
534                  * ntfs_are_names_equal() call will have gotten a match but we
535                  * still treat it correctly.
536                  */
537                 goto found_it2;
538         }
539         /*
540          * We have finished with this index buffer without success. Check for
541          * the presence of a child node.
542          */
543         if (ie->flags & INDEX_ENTRY_NODE) {
544                 if ((ia->index.flags & NODE_MASK) == LEAF_NODE) {
545                         ntfs_error(sb, "Index entry with child node found in "
546                                         "a leaf node in directory inode 0x%lx.",
547                                         dir_ni->mft_no);
548                         err = -EIO;
549                         goto unm_err_out;
550                 }
551                 /* Child node present, descend into it. */
552                 old_vcn = vcn;
553                 vcn = sle64_to_cpup((sle64*)((u8*)ie +
554                                 le16_to_cpu(ie->length) - 8));
555                 if (vcn >= 0) {
556                         /* If vcn is in the same page cache page as old_vcn we
557                          * recycle the mapped page. */
558                         if (old_vcn << vol->cluster_size_bits >>
559                                         PAGE_CACHE_SHIFT == vcn <<
560                                         vol->cluster_size_bits >>
561                                         PAGE_CACHE_SHIFT)
562                                 goto fast_descend_into_child_node;
563                         unlock_page(page);
564                         ntfs_unmap_page(page);
565                         goto descend_into_child_node;
566                 }
567                 ntfs_error(sb, "Negative child node vcn in directory inode "
568                                 "0x%lx.", dir_ni->mft_no);
569                 err = -EIO;
570                 goto unm_err_out;
571         }
572         /*
573          * No child node present, return -ENOENT, unless we have got a matching
574          * name cached in name in which case return the mft reference
575          * associated with it.
576          */
577         if (name) {
578                 unlock_page(page);
579                 ntfs_unmap_page(page);
580                 return name->mref;
581         }
582         ntfs_debug("Entry not found.");
583         err = -ENOENT;
584 unm_err_out:
585         unlock_page(page);
586         ntfs_unmap_page(page);
587 err_out:
588         if (ctx)
589                 ntfs_attr_put_search_ctx(ctx);
590         if (m)
591                 unmap_mft_record(dir_ni);
592         if (name) {
593                 kfree(name);
594                 *res = NULL;
595         }
596         return ERR_MREF(err);
597 dir_err_out:
598         ntfs_error(sb, "Corrupt directory. Aborting lookup.");
599         err = -EIO;
600         goto err_out;
601 }
602
603 #if 0
604
605 // TODO: (AIA)
606 // The algorithm embedded in this code will be required for the time when we
607 // want to support adding of entries to directories, where we require correct
608 // collation of file names in order not to cause corruption of the file system.
609
610 /**
611  * ntfs_lookup_inode_by_name - find an inode in a directory given its name
612  * @dir_ni:     ntfs inode of the directory in which to search for the name
613  * @uname:      Unicode name for which to search in the directory
614  * @uname_len:  length of the name @uname in Unicode characters
615  *
616  * Look for an inode with name @uname in the directory with inode @dir_ni.
617  * ntfs_lookup_inode_by_name() walks the contents of the directory looking for
618  * the Unicode name. If the name is found in the directory, the corresponding
619  * inode number (>= 0) is returned as a mft reference in cpu format, i.e. it
620  * is a 64-bit number containing the sequence number.
621  *
622  * On error, a negative value is returned corresponding to the error code. In
623  * particular if the inode is not found -ENOENT is returned. Note that you
624  * can't just check the return value for being negative, you have to check the
625  * inode number for being negative which you can extract using MREC(return
626  * value).
627  *
628  * Note, @uname_len does not include the (optional) terminating NULL character.
629  */
630 u64 ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,
631                 const int uname_len)
632 {
633         ntfs_volume *vol = dir_ni->vol;
634         struct super_block *sb = vol->sb;
635         MFT_RECORD *m;
636         INDEX_ROOT *ir;
637         INDEX_ENTRY *ie;
638         INDEX_ALLOCATION *ia;
639         u8 *index_end;
640         u64 mref;
641         ntfs_attr_search_ctx *ctx;
642         int err, rc;
643         IGNORE_CASE_BOOL ic;
644         VCN vcn, old_vcn;
645         struct address_space *ia_mapping;
646         struct page *page;
647         u8 *kaddr;
648
649         /* Get hold of the mft record for the directory. */
650         m = map_mft_record(dir_ni);
651         if (IS_ERR(m)) {
652                 ntfs_error(sb, "map_mft_record() failed with error code %ld.",
653                                 -PTR_ERR(m));
654                 return ERR_MREF(PTR_ERR(m));
655         }
656         ctx = ntfs_attr_get_search_ctx(dir_ni, m);
657         if (!ctx) {
658                 err = -ENOMEM;
659                 goto err_out;
660         }
661         /* Find the index root attribute in the mft record. */
662         err = ntfs_attr_lookup(AT_INDEX_ROOT, I30, 4, CASE_SENSITIVE, 0, NULL,
663                         0, ctx);
664         if (unlikely(err)) {
665                 if (err == -ENOENT) {
666                         ntfs_error(sb, "Index root attribute missing in "
667                                         "directory inode 0x%lx.",
668                                         dir_ni->mft_no);
669                         err = -EIO;
670                 }
671                 goto err_out;
672         }
673         /* Get to the index root value (it's been verified in read_inode). */
674         ir = (INDEX_ROOT*)((u8*)ctx->attr +
675                         le16_to_cpu(ctx->attr->data.resident.value_offset));
676         index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
677         /* The first index entry. */
678         ie = (INDEX_ENTRY*)((u8*)&ir->index +
679                         le32_to_cpu(ir->index.entries_offset));
680         /*
681          * Loop until we exceed valid memory (corruption case) or until we
682          * reach the last entry.
683          */
684         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
685                 /* Bounds checks. */
686                 if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie +
687                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
688                                 (u8*)ie + le16_to_cpu(ie->key_length) >
689                                 index_end)
690                         goto dir_err_out;
691                 /*
692                  * The last entry cannot contain a name. It can however contain
693                  * a pointer to a child node in the B+tree so we just break out.
694                  */
695                 if (ie->flags & INDEX_ENTRY_END)
696                         break;
697                 /*
698                  * If the current entry has a name type of POSIX, the name is
699                  * case sensitive and not otherwise. This has the effect of us
700                  * not being able to access any POSIX file names which collate
701                  * after the non-POSIX one when they only differ in case, but
702                  * anyone doing screwy stuff like that deserves to burn in
703                  * hell... Doing that kind of stuff on NT4 actually causes
704                  * corruption on the partition even when using SP6a and Linux
705                  * is not involved at all.
706                  */
707                 ic = ie->key.file_name.file_name_type ? IGNORE_CASE :
708                                 CASE_SENSITIVE;
709                 /*
710                  * If the names match perfectly, we are done and return the
711                  * mft reference of the inode (i.e. the inode number together
712                  * with the sequence number for consistency checking. We
713                  * convert it to cpu format before returning.
714                  */
715                 if (ntfs_are_names_equal(uname, uname_len,
716                                 (ntfschar*)&ie->key.file_name.file_name,
717                                 ie->key.file_name.file_name_length, ic,
718                                 vol->upcase, vol->upcase_len)) {
719 found_it:
720                         mref = le64_to_cpu(ie->data.dir.indexed_file);
721                         ntfs_attr_put_search_ctx(ctx);
722                         unmap_mft_record(dir_ni);
723                         return mref;
724                 }
725                 /*
726                  * Not a perfect match, need to do full blown collation so we
727                  * know which way in the B+tree we have to go.
728                  */
729                 rc = ntfs_collate_names(uname, uname_len,
730                                 (ntfschar*)&ie->key.file_name.file_name,
731                                 ie->key.file_name.file_name_length, 1,
732                                 IGNORE_CASE, vol->upcase, vol->upcase_len);
733                 /*
734                  * If uname collates before the name of the current entry, there
735                  * is definitely no such name in this index but we might need to
736                  * descend into the B+tree so we just break out of the loop.
737                  */
738                 if (rc == -1)
739                         break;
740                 /* The names are not equal, continue the search. */
741                 if (rc)
742                         continue;
743                 /*
744                  * Names match with case insensitive comparison, now try the
745                  * case sensitive comparison, which is required for proper
746                  * collation.
747                  */
748                 rc = ntfs_collate_names(uname, uname_len,
749                                 (ntfschar*)&ie->key.file_name.file_name,
750                                 ie->key.file_name.file_name_length, 1,
751                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len);
752                 if (rc == -1)
753                         break;
754                 if (rc)
755                         continue;
756                 /*
757                  * Perfect match, this will never happen as the
758                  * ntfs_are_names_equal() call will have gotten a match but we
759                  * still treat it correctly.
760                  */
761                 goto found_it;
762         }
763         /*
764          * We have finished with this index without success. Check for the
765          * presence of a child node.
766          */
767         if (!(ie->flags & INDEX_ENTRY_NODE)) {
768                 /* No child node, return -ENOENT. */
769                 err = -ENOENT;
770                 goto err_out;
771         } /* Child node present, descend into it. */
772         /* Consistency check: Verify that an index allocation exists. */
773         if (!NInoIndexAllocPresent(dir_ni)) {
774                 ntfs_error(sb, "No index allocation attribute but index entry "
775                                 "requires one. Directory inode 0x%lx is "
776                                 "corrupt or driver bug.", dir_ni->mft_no);
777                 err = -EIO;
778                 goto err_out;
779         }
780         /* Get the starting vcn of the index_block holding the child node. */
781         vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8);
782         ia_mapping = VFS_I(dir_ni)->i_mapping;
783         /*
784          * We are done with the index root and the mft record. Release them,
785          * otherwise we deadlock with ntfs_map_page().
786          */
787         ntfs_attr_put_search_ctx(ctx);
788         unmap_mft_record(dir_ni);
789         m = NULL;
790         ctx = NULL;
791 descend_into_child_node:
792         /*
793          * Convert vcn to index into the index allocation attribute in units
794          * of PAGE_CACHE_SIZE and map the page cache page, reading it from
795          * disk if necessary.
796          */
797         page = ntfs_map_page(ia_mapping, vcn <<
798                         dir_ni->itype.index.vcn_size_bits >> PAGE_CACHE_SHIFT);
799         if (IS_ERR(page)) {
800                 ntfs_error(sb, "Failed to map directory index page, error %ld.",
801                                 -PTR_ERR(page));
802                 err = PTR_ERR(page);
803                 goto err_out;
804         }
805         lock_page(page);
806         kaddr = (u8*)page_address(page);
807 fast_descend_into_child_node:
808         /* Get to the index allocation block. */
809         ia = (INDEX_ALLOCATION*)(kaddr + ((vcn <<
810                         dir_ni->itype.index.vcn_size_bits) & ~PAGE_CACHE_MASK));
811         /* Bounds checks. */
812         if ((u8*)ia < kaddr || (u8*)ia > kaddr + PAGE_CACHE_SIZE) {
813                 ntfs_error(sb, "Out of bounds check failed. Corrupt directory "
814                                 "inode 0x%lx or driver bug.", dir_ni->mft_no);
815                 err = -EIO;
816                 goto unm_err_out;
817         }
818         if (sle64_to_cpu(ia->index_block_vcn) != vcn) {
819                 ntfs_error(sb, "Actual VCN (0x%llx) of index buffer is "
820                                 "different from expected VCN (0x%llx). "
821                                 "Directory inode 0x%lx is corrupt or driver "
822                                 "bug.", (unsigned long long)
823                                 sle64_to_cpu(ia->index_block_vcn),
824                                 (unsigned long long)vcn, dir_ni->mft_no);
825                 err = -EIO;
826                 goto unm_err_out;
827         }
828         if (le32_to_cpu(ia->index.allocated_size) + 0x18 !=
829                         dir_ni->itype.index.block_size) {
830                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
831                                 "0x%lx has a size (%u) differing from the "
832                                 "directory specified size (%u). Directory "
833                                 "inode is corrupt or driver bug.",
834                                 (unsigned long long)vcn, dir_ni->mft_no,
835                                 le32_to_cpu(ia->index.allocated_size) + 0x18,
836                                 dir_ni->itype.index.block_size);
837                 err = -EIO;
838                 goto unm_err_out;
839         }
840         index_end = (u8*)ia + dir_ni->itype.index.block_size;
841         if (index_end > kaddr + PAGE_CACHE_SIZE) {
842                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
843                                 "0x%lx crosses page boundary. Impossible! "
844                                 "Cannot access! This is probably a bug in the "
845                                 "driver.", (unsigned long long)vcn,
846                                 dir_ni->mft_no);
847                 err = -EIO;
848                 goto unm_err_out;
849         }
850         index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length);
851         if (index_end > (u8*)ia + dir_ni->itype.index.block_size) {
852                 ntfs_error(sb, "Size of index buffer (VCN 0x%llx) of directory "
853                                 "inode 0x%lx exceeds maximum size.",
854                                 (unsigned long long)vcn, dir_ni->mft_no);
855                 err = -EIO;
856                 goto unm_err_out;
857         }
858         /* The first index entry. */
859         ie = (INDEX_ENTRY*)((u8*)&ia->index +
860                         le32_to_cpu(ia->index.entries_offset));
861         /*
862          * Iterate similar to above big loop but applied to index buffer, thus
863          * loop until we exceed valid memory (corruption case) or until we
864          * reach the last entry.
865          */
866         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
867                 /* Bounds check. */
868                 if ((u8*)ie < (u8*)ia || (u8*)ie +
869                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
870                                 (u8*)ie + le16_to_cpu(ie->key_length) >
871                                 index_end) {
872                         ntfs_error(sb, "Index entry out of bounds in "
873                                         "directory inode 0x%lx.",
874                                         dir_ni->mft_no);
875                         err = -EIO;
876                         goto unm_err_out;
877                 }
878                 /*
879                  * The last entry cannot contain a name. It can however contain
880                  * a pointer to a child node in the B+tree so we just break out.
881                  */
882                 if (ie->flags & INDEX_ENTRY_END)
883                         break;
884                 /*
885                  * If the current entry has a name type of POSIX, the name is
886                  * case sensitive and not otherwise. This has the effect of us
887                  * not being able to access any POSIX file names which collate
888                  * after the non-POSIX one when they only differ in case, but
889                  * anyone doing screwy stuff like that deserves to burn in
890                  * hell... Doing that kind of stuff on NT4 actually causes
891                  * corruption on the partition even when using SP6a and Linux
892                  * is not involved at all.
893                  */
894                 ic = ie->key.file_name.file_name_type ? IGNORE_CASE :
895                                 CASE_SENSITIVE;
896                 /*
897                  * If the names match perfectly, we are done and return the
898                  * mft reference of the inode (i.e. the inode number together
899                  * with the sequence number for consistency checking. We
900                  * convert it to cpu format before returning.
901                  */
902                 if (ntfs_are_names_equal(uname, uname_len,
903                                 (ntfschar*)&ie->key.file_name.file_name,
904                                 ie->key.file_name.file_name_length, ic,
905                                 vol->upcase, vol->upcase_len)) {
906 found_it2:
907                         mref = le64_to_cpu(ie->data.dir.indexed_file);
908                         unlock_page(page);
909                         ntfs_unmap_page(page);
910                         return mref;
911                 }
912                 /*
913                  * Not a perfect match, need to do full blown collation so we
914                  * know which way in the B+tree we have to go.
915                  */
916                 rc = ntfs_collate_names(uname, uname_len,
917                                 (ntfschar*)&ie->key.file_name.file_name,
918                                 ie->key.file_name.file_name_length, 1,
919                                 IGNORE_CASE, vol->upcase, vol->upcase_len);
920                 /*
921                  * If uname collates before the name of the current entry, there
922                  * is definitely no such name in this index but we might need to
923                  * descend into the B+tree so we just break out of the loop.
924                  */
925                 if (rc == -1)
926                         break;
927                 /* The names are not equal, continue the search. */
928                 if (rc)
929                         continue;
930                 /*
931                  * Names match with case insensitive comparison, now try the
932                  * case sensitive comparison, which is required for proper
933                  * collation.
934                  */
935                 rc = ntfs_collate_names(uname, uname_len,
936                                 (ntfschar*)&ie->key.file_name.file_name,
937                                 ie->key.file_name.file_name_length, 1,
938                                 CASE_SENSITIVE, vol->upcase, vol->upcase_len);
939                 if (rc == -1)
940                         break;
941                 if (rc)
942                         continue;
943                 /*
944                  * Perfect match, this will never happen as the
945                  * ntfs_are_names_equal() call will have gotten a match but we
946                  * still treat it correctly.
947                  */
948                 goto found_it2;
949         }
950         /*
951          * We have finished with this index buffer without success. Check for
952          * the presence of a child node.
953          */
954         if (ie->flags & INDEX_ENTRY_NODE) {
955                 if ((ia->index.flags & NODE_MASK) == LEAF_NODE) {
956                         ntfs_error(sb, "Index entry with child node found in "
957                                         "a leaf node in directory inode 0x%lx.",
958                                         dir_ni->mft_no);
959                         err = -EIO;
960                         goto unm_err_out;
961                 }
962                 /* Child node present, descend into it. */
963                 old_vcn = vcn;
964                 vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8);
965                 if (vcn >= 0) {
966                         /* If vcn is in the same page cache page as old_vcn we
967                          * recycle the mapped page. */
968                         if (old_vcn << vol->cluster_size_bits >>
969                                         PAGE_CACHE_SHIFT == vcn <<
970                                         vol->cluster_size_bits >>
971                                         PAGE_CACHE_SHIFT)
972                                 goto fast_descend_into_child_node;
973                         unlock_page(page);
974                         ntfs_unmap_page(page);
975                         goto descend_into_child_node;
976                 }
977                 ntfs_error(sb, "Negative child node vcn in directory inode "
978                                 "0x%lx.", dir_ni->mft_no);
979                 err = -EIO;
980                 goto unm_err_out;
981         }
982         /* No child node, return -ENOENT. */
983         ntfs_debug("Entry not found.");
984         err = -ENOENT;
985 unm_err_out:
986         unlock_page(page);
987         ntfs_unmap_page(page);
988 err_out:
989         if (ctx)
990                 ntfs_attr_put_search_ctx(ctx);
991         if (m)
992                 unmap_mft_record(dir_ni);
993         return ERR_MREF(err);
994 dir_err_out:
995         ntfs_error(sb, "Corrupt directory. Aborting lookup.");
996         err = -EIO;
997         goto err_out;
998 }
999
1000 #endif
1001
1002 /**
1003  * ntfs_filldir - ntfs specific filldir method
1004  * @vol:        current ntfs volume
1005  * @fpos:       position in the directory
1006  * @ndir:       ntfs inode of current directory
1007  * @ia_page:    page in which the index allocation buffer @ie is in resides
1008  * @ie:         current index entry
1009  * @name:       buffer to use for the converted name
1010  * @dirent:     vfs filldir callback context
1011  * @filldir:    vfs filldir callback
1012  *
1013  * Convert the Unicode @name to the loaded NLS and pass it to the @filldir
1014  * callback.
1015  *
1016  * If @ia_page is not NULL it is the locked page containing the index
1017  * allocation block containing the index entry @ie.
1018  *
1019  * Note, we drop (and then reacquire) the page lock on @ia_page across the
1020  * @filldir() call otherwise we would deadlock with NFSd when it calls ->lookup
1021  * since ntfs_lookup() will lock the same page.  As an optimization, we do not
1022  * retake the lock if we are returning a non-zero value as ntfs_readdir()
1023  * would need to drop the lock immediately anyway.
1024  */
1025 static inline int ntfs_filldir(ntfs_volume *vol, loff_t fpos,
1026                 ntfs_inode *ndir, struct page *ia_page, INDEX_ENTRY *ie,
1027                 u8 *name, void *dirent, filldir_t filldir)
1028 {
1029         unsigned long mref;
1030         int name_len, rc;
1031         unsigned dt_type;
1032         FILE_NAME_TYPE_FLAGS name_type;
1033
1034         name_type = ie->key.file_name.file_name_type;
1035         if (name_type == FILE_NAME_DOS) {
1036                 ntfs_debug("Skipping DOS name space entry.");
1037                 return 0;
1038         }
1039         if (MREF_LE(ie->data.dir.indexed_file) == FILE_root) {
1040                 ntfs_debug("Skipping root directory self reference entry.");
1041                 return 0;
1042         }
1043         if (MREF_LE(ie->data.dir.indexed_file) < FILE_first_user &&
1044                         !NVolShowSystemFiles(vol)) {
1045                 ntfs_debug("Skipping system file.");
1046                 return 0;
1047         }
1048         name_len = ntfs_ucstonls(vol, (ntfschar*)&ie->key.file_name.file_name,
1049                         ie->key.file_name.file_name_length, &name,
1050                         NTFS_MAX_NAME_LEN * NLS_MAX_CHARSET_SIZE + 1);
1051         if (name_len <= 0) {
1052                 ntfs_debug("Skipping unrepresentable file.");
1053                 return 0;
1054         }
1055         if (ie->key.file_name.file_attributes &
1056                         FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT)
1057                 dt_type = DT_DIR;
1058         else
1059                 dt_type = DT_REG;
1060         mref = MREF_LE(ie->data.dir.indexed_file);
1061         /*
1062          * Drop the page lock otherwise we deadlock with NFS when it calls
1063          * ->lookup since ntfs_lookup() will lock the same page.
1064          */
1065         if (ia_page)
1066                 unlock_page(ia_page);
1067         ntfs_debug("Calling filldir for %s with len %i, fpos 0x%llx, inode "
1068                         "0x%lx, DT_%s.", name, name_len, fpos, mref,
1069                         dt_type == DT_DIR ? "DIR" : "REG");
1070         rc = filldir(dirent, name, name_len, fpos, mref, dt_type);
1071         /* Relock the page but not if we are aborting ->readdir. */
1072         if (!rc && ia_page)
1073                 lock_page(ia_page);
1074         return rc;
1075 }
1076
1077 /*
1078  * We use the same basic approach as the old NTFS driver, i.e. we parse the
1079  * index root entries and then the index allocation entries that are marked
1080  * as in use in the index bitmap.
1081  *
1082  * While this will return the names in random order this doesn't matter for
1083  * ->readdir but OTOH results in a faster ->readdir.
1084  *
1085  * VFS calls ->readdir without BKL but with i_sem held. This protects the VFS
1086  * parts (e.g. ->f_pos and ->i_size, and it also protects against directory
1087  * modifications).
1088  *
1089  * Locking:  - Caller must hold i_sem on the directory.
1090  *           - Each page cache page in the index allocation mapping must be
1091  *             locked whilst being accessed otherwise we may find a corrupt
1092  *             page due to it being under ->writepage at the moment which
1093  *             applies the mst protection fixups before writing out and then
1094  *             removes them again after the write is complete after which it 
1095  *             unlocks the page.
1096  */
1097 static int ntfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
1098 {
1099         s64 ia_pos, ia_start, prev_ia_pos, bmp_pos;
1100         loff_t fpos;
1101         struct inode *bmp_vi, *vdir = filp->f_dentry->d_inode;
1102         struct super_block *sb = vdir->i_sb;
1103         ntfs_inode *ndir = NTFS_I(vdir);
1104         ntfs_volume *vol = NTFS_SB(sb);
1105         MFT_RECORD *m;
1106         INDEX_ROOT *ir = NULL;
1107         INDEX_ENTRY *ie;
1108         INDEX_ALLOCATION *ia;
1109         u8 *name = NULL;
1110         int rc, err, ir_pos, cur_bmp_pos;
1111         struct address_space *ia_mapping, *bmp_mapping;
1112         struct page *bmp_page = NULL, *ia_page = NULL;
1113         u8 *kaddr, *bmp, *index_end;
1114         ntfs_attr_search_ctx *ctx;
1115
1116         fpos = filp->f_pos;
1117         ntfs_debug("Entering for inode 0x%lx, fpos 0x%llx.",
1118                         vdir->i_ino, fpos);
1119         rc = err = 0;
1120         /* Are we at end of dir yet? */
1121         if (fpos >= vdir->i_size + vol->mft_record_size)
1122                 goto done;
1123         /* Emulate . and .. for all directories. */
1124         if (!fpos) {
1125                 ntfs_debug("Calling filldir for . with len 1, fpos 0x0, "
1126                                 "inode 0x%lx, DT_DIR.", vdir->i_ino);
1127                 rc = filldir(dirent, ".", 1, fpos, vdir->i_ino, DT_DIR);
1128                 if (rc)
1129                         goto done;
1130                 fpos++;
1131         }
1132         if (fpos == 1) {
1133                 ntfs_debug("Calling filldir for .. with len 2, fpos 0x1, "
1134                                 "inode 0x%lx, DT_DIR.",
1135                                 parent_ino(filp->f_dentry));
1136                 rc = filldir(dirent, "..", 2, fpos,
1137                                 parent_ino(filp->f_dentry), DT_DIR);
1138                 if (rc)
1139                         goto done;
1140                 fpos++;
1141         }
1142         m = NULL;
1143         ctx = NULL;
1144         /*
1145          * Allocate a buffer to store the current name being processed
1146          * converted to format determined by current NLS.
1147          */
1148         name = (u8*)kmalloc(NTFS_MAX_NAME_LEN * NLS_MAX_CHARSET_SIZE + 1,
1149                         GFP_NOFS);
1150         if (unlikely(!name)) {
1151                 err = -ENOMEM;
1152                 goto err_out;
1153         }
1154         /* Are we jumping straight into the index allocation attribute? */
1155         if (fpos >= vol->mft_record_size)
1156                 goto skip_index_root;
1157         /* Get hold of the mft record for the directory. */
1158         m = map_mft_record(ndir);
1159         if (IS_ERR(m)) {
1160                 err = PTR_ERR(m);
1161                 m = NULL;
1162                 goto err_out;
1163         }
1164         ctx = ntfs_attr_get_search_ctx(ndir, m);
1165         if (unlikely(!ctx)) {
1166                 err = -ENOMEM;
1167                 goto err_out;
1168         }
1169         /* Get the offset into the index root attribute. */
1170         ir_pos = (s64)fpos;
1171         /* Find the index root attribute in the mft record. */
1172         err = ntfs_attr_lookup(AT_INDEX_ROOT, I30, 4, CASE_SENSITIVE, 0, NULL,
1173                         0, ctx);
1174         if (unlikely(err)) {
1175                 ntfs_error(sb, "Index root attribute missing in directory "
1176                                 "inode 0x%lx.", vdir->i_ino);
1177                 goto err_out;
1178         }
1179         /*
1180          * Copy the index root attribute value to a buffer so that we can put
1181          * the search context and unmap the mft record before calling the
1182          * filldir() callback.  We need to do this because of NFSd which calls
1183          * ->lookup() from its filldir callback() and this causes NTFS to
1184          * deadlock as ntfs_lookup() maps the mft record of the directory and
1185          * we have got it mapped here already.  The only solution is for us to
1186          * unmap the mft record here so that a call to ntfs_lookup() is able to
1187          * map the mft record without deadlocking.
1188          */
1189         rc = le32_to_cpu(ctx->attr->data.resident.value_length);
1190         ir = (INDEX_ROOT*)kmalloc(rc, GFP_NOFS);
1191         if (unlikely(!ir)) {
1192                 err = -ENOMEM;
1193                 goto err_out;
1194         }
1195         /* Copy the index root value (it has been verified in read_inode). */
1196         memcpy(ir, (u8*)ctx->attr +
1197                         le16_to_cpu(ctx->attr->data.resident.value_offset), rc);
1198         ntfs_attr_put_search_ctx(ctx);
1199         unmap_mft_record(ndir);
1200         ctx = NULL;
1201         m = NULL;
1202         index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
1203         /* The first index entry. */
1204         ie = (INDEX_ENTRY*)((u8*)&ir->index +
1205                         le32_to_cpu(ir->index.entries_offset));
1206         /*
1207          * Loop until we exceed valid memory (corruption case) or until we
1208          * reach the last entry or until filldir tells us it has had enough
1209          * or signals an error (both covered by the rc test).
1210          */
1211         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
1212                 ntfs_debug("In index root, offset 0x%zx.", (u8*)ie - (u8*)ir);
1213                 /* Bounds checks. */
1214                 if (unlikely((u8*)ie < (u8*)ir || (u8*)ie +
1215                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
1216                                 (u8*)ie + le16_to_cpu(ie->key_length) >
1217                                 index_end))
1218                         goto err_out;
1219                 /* The last entry cannot contain a name. */
1220                 if (ie->flags & INDEX_ENTRY_END)
1221                         break;
1222                 /* Skip index root entry if continuing previous readdir. */
1223                 if (ir_pos > (u8*)ie - (u8*)ir)
1224                         continue;
1225                 /* Advance the position even if going to skip the entry. */
1226                 fpos = (u8*)ie - (u8*)ir;
1227                 /* Submit the name to the filldir callback. */
1228                 rc = ntfs_filldir(vol, fpos, ndir, NULL, ie, name, dirent,
1229                                 filldir);
1230                 if (rc) {
1231                         kfree(ir);
1232                         goto abort;
1233                 }
1234         }
1235         /* We are done with the index root and can free the buffer. */
1236         kfree(ir);
1237         ir = NULL;
1238         /* If there is no index allocation attribute we are finished. */
1239         if (!NInoIndexAllocPresent(ndir))
1240                 goto EOD;
1241         /* Advance fpos to the beginning of the index allocation. */
1242         fpos = vol->mft_record_size;
1243 skip_index_root:
1244         kaddr = NULL;
1245         prev_ia_pos = -1LL;
1246         /* Get the offset into the index allocation attribute. */
1247         ia_pos = (s64)fpos - vol->mft_record_size;
1248         ia_mapping = vdir->i_mapping;
1249         bmp_vi = ndir->itype.index.bmp_ino;
1250         if (unlikely(!bmp_vi)) {
1251                 ntfs_debug("Inode 0x%lx, regetting index bitmap.", vdir->i_ino);
1252                 bmp_vi = ntfs_attr_iget(vdir, AT_BITMAP, I30, 4);
1253                 if (IS_ERR(bmp_vi)) {
1254                         ntfs_error(sb, "Failed to get bitmap attribute.");
1255                         err = PTR_ERR(bmp_vi);
1256                         goto err_out;
1257                 }
1258                 ndir->itype.index.bmp_ino = bmp_vi;
1259         }
1260         bmp_mapping = bmp_vi->i_mapping;
1261         /* Get the starting bitmap bit position and sanity check it. */
1262         bmp_pos = ia_pos >> ndir->itype.index.block_size_bits;
1263         if (unlikely(bmp_pos >> 3 >= bmp_vi->i_size)) {
1264                 ntfs_error(sb, "Current index allocation position exceeds "
1265                                 "index bitmap size.");
1266                 goto err_out;
1267         }
1268         /* Get the starting bit position in the current bitmap page. */
1269         cur_bmp_pos = bmp_pos & ((PAGE_CACHE_SIZE * 8) - 1);
1270         bmp_pos &= ~(u64)((PAGE_CACHE_SIZE * 8) - 1);
1271 get_next_bmp_page:
1272         ntfs_debug("Reading bitmap with page index 0x%llx, bit ofs 0x%llx",
1273                         (unsigned long long)bmp_pos >> (3 + PAGE_CACHE_SHIFT),
1274                         (unsigned long long)bmp_pos &
1275                         ((PAGE_CACHE_SIZE * 8) - 1));
1276         bmp_page = ntfs_map_page(bmp_mapping,
1277                         bmp_pos >> (3 + PAGE_CACHE_SHIFT));
1278         if (IS_ERR(bmp_page)) {
1279                 ntfs_error(sb, "Reading index bitmap failed.");
1280                 err = PTR_ERR(bmp_page);
1281                 bmp_page = NULL;
1282                 goto err_out;
1283         }
1284         bmp = (u8*)page_address(bmp_page);
1285         /* Find next index block in use. */
1286         while (!(bmp[cur_bmp_pos >> 3] & (1 << (cur_bmp_pos & 7)))) {
1287 find_next_index_buffer:
1288                 cur_bmp_pos++;
1289                 /*
1290                  * If we have reached the end of the bitmap page, get the next
1291                  * page, and put away the old one.
1292                  */
1293                 if (unlikely((cur_bmp_pos >> 3) >= PAGE_CACHE_SIZE)) {
1294                         ntfs_unmap_page(bmp_page);
1295                         bmp_pos += PAGE_CACHE_SIZE * 8;
1296                         cur_bmp_pos = 0;
1297                         goto get_next_bmp_page;
1298                 }
1299                 /* If we have reached the end of the bitmap, we are done. */
1300                 if (unlikely(((bmp_pos + cur_bmp_pos) >> 3) >= vdir->i_size))
1301                         goto unm_EOD;
1302                 ia_pos = (bmp_pos + cur_bmp_pos) <<
1303                                 ndir->itype.index.block_size_bits;
1304         }
1305         ntfs_debug("Handling index buffer 0x%llx.",
1306                         (unsigned long long)bmp_pos + cur_bmp_pos);
1307         /* If the current index buffer is in the same page we reuse the page. */
1308         if ((prev_ia_pos & PAGE_CACHE_MASK) != (ia_pos & PAGE_CACHE_MASK)) {
1309                 prev_ia_pos = ia_pos;
1310                 if (likely(ia_page != NULL)) {
1311                         unlock_page(ia_page);
1312                         ntfs_unmap_page(ia_page);
1313                 }
1314                 /*
1315                  * Map the page cache page containing the current ia_pos,
1316                  * reading it from disk if necessary.
1317                  */
1318                 ia_page = ntfs_map_page(ia_mapping, ia_pos >> PAGE_CACHE_SHIFT);
1319                 if (IS_ERR(ia_page)) {
1320                         ntfs_error(sb, "Reading index allocation data failed.");
1321                         err = PTR_ERR(ia_page);
1322                         ia_page = NULL;
1323                         goto err_out;
1324                 }
1325                 lock_page(ia_page);
1326                 kaddr = (u8*)page_address(ia_page);
1327         }
1328         /* Get the current index buffer. */
1329         ia = (INDEX_ALLOCATION*)(kaddr + (ia_pos & ~PAGE_CACHE_MASK &
1330                         ~(s64)(ndir->itype.index.block_size - 1)));
1331         /* Bounds checks. */
1332         if (unlikely((u8*)ia < kaddr || (u8*)ia > kaddr + PAGE_CACHE_SIZE)) {
1333                 ntfs_error(sb, "Out of bounds check failed. Corrupt directory "
1334                                 "inode 0x%lx or driver bug.", vdir->i_ino);
1335                 goto err_out;
1336         }
1337         if (unlikely(sle64_to_cpu(ia->index_block_vcn) != (ia_pos &
1338                         ~(s64)(ndir->itype.index.block_size - 1)) >>
1339                         ndir->itype.index.vcn_size_bits)) {
1340                 ntfs_error(sb, "Actual VCN (0x%llx) of index buffer is "
1341                                 "different from expected VCN (0x%llx). "
1342                                 "Directory inode 0x%lx is corrupt or driver "
1343                                 "bug. ", (unsigned long long)
1344                                 sle64_to_cpu(ia->index_block_vcn),
1345                                 (unsigned long long)ia_pos >>
1346                                 ndir->itype.index.vcn_size_bits, vdir->i_ino);
1347                 goto err_out;
1348         }
1349         if (unlikely(le32_to_cpu(ia->index.allocated_size) + 0x18 !=
1350                         ndir->itype.index.block_size)) {
1351                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
1352                                 "0x%lx has a size (%u) differing from the "
1353                                 "directory specified size (%u). Directory "
1354                                 "inode is corrupt or driver bug.",
1355                                 (unsigned long long)ia_pos >>
1356                                 ndir->itype.index.vcn_size_bits, vdir->i_ino,
1357                                 le32_to_cpu(ia->index.allocated_size) + 0x18,
1358                                 ndir->itype.index.block_size);
1359                 goto err_out;
1360         }
1361         index_end = (u8*)ia + ndir->itype.index.block_size;
1362         if (unlikely(index_end > kaddr + PAGE_CACHE_SIZE)) {
1363                 ntfs_error(sb, "Index buffer (VCN 0x%llx) of directory inode "
1364                                 "0x%lx crosses page boundary. Impossible! "
1365                                 "Cannot access! This is probably a bug in the "
1366                                 "driver.", (unsigned long long)ia_pos >>
1367                                 ndir->itype.index.vcn_size_bits, vdir->i_ino);
1368                 goto err_out;
1369         }
1370         ia_start = ia_pos & ~(s64)(ndir->itype.index.block_size - 1);
1371         index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length);
1372         if (unlikely(index_end > (u8*)ia + ndir->itype.index.block_size)) {
1373                 ntfs_error(sb, "Size of index buffer (VCN 0x%llx) of directory "
1374                                 "inode 0x%lx exceeds maximum size.",
1375                                 (unsigned long long)ia_pos >>
1376                                 ndir->itype.index.vcn_size_bits, vdir->i_ino);
1377                 goto err_out;
1378         }
1379         /* The first index entry in this index buffer. */
1380         ie = (INDEX_ENTRY*)((u8*)&ia->index +
1381                         le32_to_cpu(ia->index.entries_offset));
1382         /*
1383          * Loop until we exceed valid memory (corruption case) or until we
1384          * reach the last entry or until filldir tells us it has had enough
1385          * or signals an error (both covered by the rc test).
1386          */
1387         for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
1388                 ntfs_debug("In index allocation, offset 0x%llx.",
1389                                 (unsigned long long)ia_start + ((u8*)ie -
1390                                 (u8*)ia));
1391                 /* Bounds checks. */
1392                 if (unlikely((u8*)ie < (u8*)ia || (u8*)ie +
1393                                 sizeof(INDEX_ENTRY_HEADER) > index_end ||
1394                                 (u8*)ie + le16_to_cpu(ie->key_length) >
1395                                 index_end))
1396                         goto err_out;
1397                 /* The last entry cannot contain a name. */
1398                 if (ie->flags & INDEX_ENTRY_END)
1399                         break;
1400                 /* Skip index block entry if continuing previous readdir. */
1401                 if (ia_pos - ia_start > (u8*)ie - (u8*)ia)
1402                         continue;
1403                 /* Advance the position even if going to skip the entry. */
1404                 fpos = (u8*)ie - (u8*)ia +
1405                                 (sle64_to_cpu(ia->index_block_vcn) <<
1406                                 ndir->itype.index.vcn_size_bits) +
1407                                 vol->mft_record_size;
1408                 /*
1409                  * Submit the name to the @filldir callback.  Note,
1410                  * ntfs_filldir() drops the lock on @ia_page but it retakes it
1411                  * before returning, unless a non-zero value is returned in
1412                  * which case the page is left unlocked.
1413                  */
1414                 rc = ntfs_filldir(vol, fpos, ndir, ia_page, ie, name, dirent,
1415                                 filldir);
1416                 if (rc) {
1417                         /* @ia_page is already unlocked in this case. */
1418                         ntfs_unmap_page(ia_page);
1419                         ntfs_unmap_page(bmp_page);
1420                         goto abort;
1421                 }
1422         }
1423         goto find_next_index_buffer;
1424 unm_EOD:
1425         if (ia_page) {
1426                 unlock_page(ia_page);
1427                 ntfs_unmap_page(ia_page);
1428         }
1429         ntfs_unmap_page(bmp_page);
1430 EOD:
1431         /* We are finished, set fpos to EOD. */
1432         fpos = vdir->i_size + vol->mft_record_size;
1433 abort:
1434         kfree(name);
1435 done:
1436 #ifdef DEBUG
1437         if (!rc)
1438                 ntfs_debug("EOD, fpos 0x%llx, returning 0.", fpos);
1439         else
1440                 ntfs_debug("filldir returned %i, fpos 0x%llx, returning 0.",
1441                                 rc, fpos);
1442 #endif
1443         filp->f_pos = fpos;
1444         return 0;
1445 err_out:
1446         if (bmp_page)
1447                 ntfs_unmap_page(bmp_page);
1448         if (ia_page) {
1449                 unlock_page(ia_page);
1450                 ntfs_unmap_page(ia_page);
1451         }
1452         if (ir)
1453                 kfree(ir);
1454         if (name)
1455                 kfree(name);
1456         if (ctx)
1457                 ntfs_attr_put_search_ctx(ctx);
1458         if (m)
1459                 unmap_mft_record(ndir);
1460         if (!err)
1461                 err = -EIO;
1462         ntfs_debug("Failed. Returning error code %i.", -err);
1463         filp->f_pos = fpos;
1464         return err;
1465 }
1466
1467 /**
1468  * ntfs_dir_open - called when an inode is about to be opened
1469  * @vi:         inode to be opened
1470  * @filp:       file structure describing the inode
1471  *
1472  * Limit directory size to the page cache limit on architectures where unsigned
1473  * long is 32-bits. This is the most we can do for now without overflowing the
1474  * page cache page index. Doing it this way means we don't run into problems
1475  * because of existing too large directories. It would be better to allow the
1476  * user to read the accessible part of the directory but I doubt very much
1477  * anyone is going to hit this check on a 32-bit architecture, so there is no
1478  * point in adding the extra complexity required to support this.
1479  *
1480  * On 64-bit architectures, the check is hopefully optimized away by the
1481  * compiler.
1482  */
1483 static int ntfs_dir_open(struct inode *vi, struct file *filp)
1484 {
1485         if (sizeof(unsigned long) < 8) {
1486                 if (vi->i_size > MAX_LFS_FILESIZE)
1487                         return -EFBIG;
1488         }
1489         return 0;
1490 }
1491
1492 #ifdef NTFS_RW
1493
1494 /**
1495  * ntfs_dir_fsync - sync a directory to disk
1496  * @filp:       directory to be synced
1497  * @dentry:     dentry describing the directory to sync
1498  * @datasync:   if non-zero only flush user data and not metadata
1499  *
1500  * Data integrity sync of a directory to disk.  Used for fsync, fdatasync, and
1501  * msync system calls.  This function is based on file.c::ntfs_file_fsync().
1502  *
1503  * Write the mft record and all associated extent mft records as well as the
1504  * $INDEX_ALLOCATION and $BITMAP attributes and then sync the block device.
1505  *
1506  * If @datasync is true, we do not wait on the inode(s) to be written out
1507  * but we always wait on the page cache pages to be written out.
1508  *
1509  * Note: In the past @filp could be NULL so we ignore it as we don't need it
1510  * anyway.
1511  *
1512  * Locking: Caller must hold i_sem on the inode.
1513  *
1514  * TODO: We should probably also write all attribute/index inodes associated
1515  * with this inode but since we have no simple way of getting to them we ignore
1516  * this problem for now.  We do write the $BITMAP attribute if it is present
1517  * which is the important one for a directory so things are not too bad.
1518  */
1519 static int ntfs_dir_fsync(struct file *filp, struct dentry *dentry,
1520                 int datasync)
1521 {
1522         struct inode *vi = dentry->d_inode;
1523         ntfs_inode *ni = NTFS_I(vi);
1524         int err, ret;
1525
1526         ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
1527         BUG_ON(!S_ISDIR(vi->i_mode));
1528         if (NInoIndexAllocPresent(ni) && ni->itype.index.bmp_ino)
1529                 write_inode_now(ni->itype.index.bmp_ino, !datasync);
1530         ret = ntfs_write_inode(vi, 1);
1531         write_inode_now(vi, !datasync);
1532         err = sync_blockdev(vi->i_sb->s_bdev);
1533         if (unlikely(err && !ret))
1534                 ret = err;
1535         if (likely(!ret))
1536                 ntfs_debug("Done.");
1537         else
1538                 ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx.  Error "
1539                                 "%u.", datasync ? "data" : "", vi->i_ino, -ret);
1540         return ret;
1541 }
1542
1543 #endif /* NTFS_RW */
1544
1545 struct file_operations ntfs_dir_ops = {
1546         .llseek         = generic_file_llseek,  /* Seek inside directory. */
1547         .read           = generic_read_dir,     /* Return -EISDIR. */
1548         .readdir        = ntfs_readdir,         /* Read directory contents. */
1549 #ifdef NTFS_RW
1550         .fsync          = ntfs_dir_fsync,       /* Sync a directory to disk. */
1551         /*.aio_fsync    = ,*/                   /* Sync all outstanding async
1552                                                    i/o operations on a kiocb. */
1553 #endif /* NTFS_RW */
1554         /*.ioctl        = ,*/                   /* Perform function on the
1555                                                    mounted filesystem. */
1556         .open           = ntfs_dir_open,        /* Open directory. */
1557 };