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