]> asedeno.scripts.mit.edu Git - linux.git/blob - fs/cifs/readdir.c
Merge tag 'nfsd-5.6' of git://linux-nfs.org/~bfields/linux
[linux.git] / fs / cifs / readdir.c
1 /*
2  *   fs/cifs/readdir.c
3  *
4  *   Directory search handling
5  *
6  *   Copyright (C) International Business Machines  Corp., 2004, 2008
7  *   Copyright (C) Red Hat, Inc., 2011
8  *   Author(s): Steve French (sfrench@us.ibm.com)
9  *
10  *   This library is free software; you can redistribute it and/or modify
11  *   it under the terms of the GNU Lesser General Public License as published
12  *   by the Free Software Foundation; either version 2.1 of the License, or
13  *   (at your option) any later version.
14  *
15  *   This library is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
18  *   the GNU Lesser General Public License for more details.
19  *
20  *   You should have received a copy of the GNU Lesser General Public License
21  *   along with this library; if not, write to the Free Software
22  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  */
24 #include <linux/fs.h>
25 #include <linux/pagemap.h>
26 #include <linux/slab.h>
27 #include <linux/stat.h>
28 #include "cifspdu.h"
29 #include "cifsglob.h"
30 #include "cifsproto.h"
31 #include "cifs_unicode.h"
32 #include "cifs_debug.h"
33 #include "cifs_fs_sb.h"
34 #include "cifsfs.h"
35
36 /*
37  * To be safe - for UCS to UTF-8 with strings loaded with the rare long
38  * characters alloc more to account for such multibyte target UTF-8
39  * characters.
40  */
41 #define UNICODE_NAME_MAX ((4 * NAME_MAX) + 2)
42
43 #ifdef CONFIG_CIFS_DEBUG2
44 static void dump_cifs_file_struct(struct file *file, char *label)
45 {
46         struct cifsFileInfo *cf;
47
48         if (file) {
49                 cf = file->private_data;
50                 if (cf == NULL) {
51                         cifs_dbg(FYI, "empty cifs private file data\n");
52                         return;
53                 }
54                 if (cf->invalidHandle)
55                         cifs_dbg(FYI, "invalid handle\n");
56                 if (cf->srch_inf.endOfSearch)
57                         cifs_dbg(FYI, "end of search\n");
58                 if (cf->srch_inf.emptyDir)
59                         cifs_dbg(FYI, "empty dir\n");
60         }
61 }
62 #else
63 static inline void dump_cifs_file_struct(struct file *file, char *label)
64 {
65 }
66 #endif /* DEBUG2 */
67
68 /*
69  * Attempt to preload the dcache with the results from the FIND_FIRST/NEXT
70  *
71  * Find the dentry that matches "name". If there isn't one, create one. If it's
72  * a negative dentry or the uniqueid or filetype(mode) changed,
73  * then drop it and recreate it.
74  */
75 static void
76 cifs_prime_dcache(struct dentry *parent, struct qstr *name,
77                     struct cifs_fattr *fattr)
78 {
79         struct dentry *dentry, *alias;
80         struct inode *inode;
81         struct super_block *sb = parent->d_sb;
82         struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
83         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
84
85         cifs_dbg(FYI, "%s: for %s\n", __func__, name->name);
86
87         dentry = d_hash_and_lookup(parent, name);
88         if (!dentry) {
89                 /*
90                  * If we know that the inode will need to be revalidated
91                  * immediately, then don't create a new dentry for it.
92                  * We'll end up doing an on the wire call either way and
93                  * this spares us an invalidation.
94                  */
95                 if (fattr->cf_flags & CIFS_FATTR_NEED_REVAL)
96                         return;
97 retry:
98                 dentry = d_alloc_parallel(parent, name, &wq);
99         }
100         if (IS_ERR(dentry))
101                 return;
102         if (!d_in_lookup(dentry)) {
103                 inode = d_inode(dentry);
104                 if (inode) {
105                         if (d_mountpoint(dentry)) {
106                                 dput(dentry);
107                                 return;
108                         }
109                         /*
110                          * If we're generating inode numbers, then we don't
111                          * want to clobber the existing one with the one that
112                          * the readdir code created.
113                          */
114                         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM))
115                                 fattr->cf_uniqueid = CIFS_I(inode)->uniqueid;
116
117                         /* update inode in place
118                          * if both i_ino and i_mode didn't change */
119                         if (CIFS_I(inode)->uniqueid == fattr->cf_uniqueid &&
120                             (inode->i_mode & S_IFMT) ==
121                             (fattr->cf_mode & S_IFMT)) {
122                                 cifs_fattr_to_inode(inode, fattr);
123                                 dput(dentry);
124                                 return;
125                         }
126                 }
127                 d_invalidate(dentry);
128                 dput(dentry);
129                 goto retry;
130         } else {
131                 inode = cifs_iget(sb, fattr);
132                 if (!inode)
133                         inode = ERR_PTR(-ENOMEM);
134                 alias = d_splice_alias(inode, dentry);
135                 d_lookup_done(dentry);
136                 if (alias && !IS_ERR(alias))
137                         dput(alias);
138         }
139         dput(dentry);
140 }
141
142 static bool reparse_file_needs_reval(const struct cifs_fattr *fattr)
143 {
144         if (!(fattr->cf_cifsattrs & ATTR_REPARSE))
145                 return false;
146         /*
147          * The DFS tags should be only intepreted by server side as per
148          * MS-FSCC 2.1.2.1, but let's include them anyway.
149          *
150          * Besides, if cf_cifstag is unset (0), then we still need it to be
151          * revalidated to know exactly what reparse point it is.
152          */
153         switch (fattr->cf_cifstag) {
154         case IO_REPARSE_TAG_DFS:
155         case IO_REPARSE_TAG_DFSR:
156         case IO_REPARSE_TAG_SYMLINK:
157         case IO_REPARSE_TAG_NFS:
158         case 0:
159                 return true;
160         }
161         return false;
162 }
163
164 static void
165 cifs_fill_common_info(struct cifs_fattr *fattr, struct cifs_sb_info *cifs_sb)
166 {
167         fattr->cf_uid = cifs_sb->mnt_uid;
168         fattr->cf_gid = cifs_sb->mnt_gid;
169
170         if (fattr->cf_cifsattrs & ATTR_DIRECTORY) {
171                 fattr->cf_mode = S_IFDIR | cifs_sb->mnt_dir_mode;
172                 fattr->cf_dtype = DT_DIR;
173         } else {
174                 fattr->cf_mode = S_IFREG | cifs_sb->mnt_file_mode;
175                 fattr->cf_dtype = DT_REG;
176         }
177
178         /*
179          * We need to revalidate it further to make a decision about whether it
180          * is a symbolic link, DFS referral or a reparse point with a direct
181          * access like junctions, deduplicated files, NFS symlinks.
182          */
183         if (reparse_file_needs_reval(fattr))
184                 fattr->cf_flags |= CIFS_FATTR_NEED_REVAL;
185
186         /* non-unix readdir doesn't provide nlink */
187         fattr->cf_flags |= CIFS_FATTR_UNKNOWN_NLINK;
188
189         if (fattr->cf_cifsattrs & ATTR_READONLY)
190                 fattr->cf_mode &= ~S_IWUGO;
191
192         /*
193          * We of course don't get ACL info in FIND_FIRST/NEXT results, so
194          * mark it for revalidation so that "ls -l" will look right. It might
195          * be super-slow, but if we don't do this then the ownership of files
196          * may look wrong since the inodes may not have timed out by the time
197          * "ls" does a stat() call on them.
198          */
199         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_ACL)
200                 fattr->cf_flags |= CIFS_FATTR_NEED_REVAL;
201
202         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL &&
203             fattr->cf_cifsattrs & ATTR_SYSTEM) {
204                 if (fattr->cf_eof == 0)  {
205                         fattr->cf_mode &= ~S_IFMT;
206                         fattr->cf_mode |= S_IFIFO;
207                         fattr->cf_dtype = DT_FIFO;
208                 } else {
209                         /*
210                          * trying to get the type and mode via SFU can be slow,
211                          * so just call those regular files for now, and mark
212                          * for reval
213                          */
214                         fattr->cf_flags |= CIFS_FATTR_NEED_REVAL;
215                 }
216         }
217 }
218
219 static void __dir_info_to_fattr(struct cifs_fattr *fattr, const void *info)
220 {
221         const FILE_DIRECTORY_INFO *fi = info;
222
223         memset(fattr, 0, sizeof(*fattr));
224         fattr->cf_cifsattrs = le32_to_cpu(fi->ExtFileAttributes);
225         fattr->cf_eof = le64_to_cpu(fi->EndOfFile);
226         fattr->cf_bytes = le64_to_cpu(fi->AllocationSize);
227         fattr->cf_createtime = le64_to_cpu(fi->CreationTime);
228         fattr->cf_atime = cifs_NTtimeToUnix(fi->LastAccessTime);
229         fattr->cf_ctime = cifs_NTtimeToUnix(fi->ChangeTime);
230         fattr->cf_mtime = cifs_NTtimeToUnix(fi->LastWriteTime);
231 }
232
233 void
234 cifs_dir_info_to_fattr(struct cifs_fattr *fattr, FILE_DIRECTORY_INFO *info,
235                        struct cifs_sb_info *cifs_sb)
236 {
237         __dir_info_to_fattr(fattr, info);
238         cifs_fill_common_info(fattr, cifs_sb);
239 }
240
241 static void cifs_fulldir_info_to_fattr(struct cifs_fattr *fattr,
242                                        SEARCH_ID_FULL_DIR_INFO *info,
243                                        struct cifs_sb_info *cifs_sb)
244 {
245         __dir_info_to_fattr(fattr, info);
246
247         /* See MS-FSCC 2.4.18 FileIdFullDirectoryInformation */
248         if (fattr->cf_cifsattrs & ATTR_REPARSE)
249                 fattr->cf_cifstag = le32_to_cpu(info->EaSize);
250         cifs_fill_common_info(fattr, cifs_sb);
251 }
252
253 static void
254 cifs_std_info_to_fattr(struct cifs_fattr *fattr, FIND_FILE_STANDARD_INFO *info,
255                        struct cifs_sb_info *cifs_sb)
256 {
257         int offset = cifs_sb_master_tcon(cifs_sb)->ses->server->timeAdj;
258
259         memset(fattr, 0, sizeof(*fattr));
260         fattr->cf_atime = cnvrtDosUnixTm(info->LastAccessDate,
261                                             info->LastAccessTime, offset);
262         fattr->cf_ctime = cnvrtDosUnixTm(info->LastWriteDate,
263                                             info->LastWriteTime, offset);
264         fattr->cf_mtime = cnvrtDosUnixTm(info->LastWriteDate,
265                                             info->LastWriteTime, offset);
266
267         fattr->cf_cifsattrs = le16_to_cpu(info->Attributes);
268         fattr->cf_bytes = le32_to_cpu(info->AllocationSize);
269         fattr->cf_eof = le32_to_cpu(info->DataSize);
270
271         cifs_fill_common_info(fattr, cifs_sb);
272 }
273
274 /* BB eventually need to add the following helper function to
275       resolve NT_STATUS_STOPPED_ON_SYMLINK return code when
276       we try to do FindFirst on (NTFS) directory symlinks */
277 /*
278 int get_symlink_reparse_path(char *full_path, struct cifs_sb_info *cifs_sb,
279                              unsigned int xid)
280 {
281         __u16 fid;
282         int len;
283         int oplock = 0;
284         int rc;
285         struct cifs_tcon *ptcon = cifs_sb_tcon(cifs_sb);
286         char *tmpbuffer;
287
288         rc = CIFSSMBOpen(xid, ptcon, full_path, FILE_OPEN, GENERIC_READ,
289                         OPEN_REPARSE_POINT, &fid, &oplock, NULL,
290                         cifs_sb->local_nls,
291                         cifs_remap(cifs_sb);
292         if (!rc) {
293                 tmpbuffer = kmalloc(maxpath);
294                 rc = CIFSSMBQueryReparseLinkInfo(xid, ptcon, full_path,
295                                 tmpbuffer,
296                                 maxpath -1,
297                                 fid,
298                                 cifs_sb->local_nls);
299                 if (CIFSSMBClose(xid, ptcon, fid)) {
300                         cifs_dbg(FYI, "Error closing temporary reparsepoint open\n");
301                 }
302         }
303 }
304  */
305
306 static int
307 initiate_cifs_search(const unsigned int xid, struct file *file)
308 {
309         __u16 search_flags;
310         int rc = 0;
311         char *full_path = NULL;
312         struct cifsFileInfo *cifsFile;
313         struct cifs_sb_info *cifs_sb = CIFS_FILE_SB(file);
314         struct tcon_link *tlink = NULL;
315         struct cifs_tcon *tcon;
316         struct TCP_Server_Info *server;
317
318         if (file->private_data == NULL) {
319                 tlink = cifs_sb_tlink(cifs_sb);
320                 if (IS_ERR(tlink))
321                         return PTR_ERR(tlink);
322
323                 cifsFile = kzalloc(sizeof(struct cifsFileInfo), GFP_KERNEL);
324                 if (cifsFile == NULL) {
325                         rc = -ENOMEM;
326                         goto error_exit;
327                 }
328                 spin_lock_init(&cifsFile->file_info_lock);
329                 file->private_data = cifsFile;
330                 cifsFile->tlink = cifs_get_tlink(tlink);
331                 tcon = tlink_tcon(tlink);
332         } else {
333                 cifsFile = file->private_data;
334                 tcon = tlink_tcon(cifsFile->tlink);
335         }
336
337         server = tcon->ses->server;
338
339         if (!server->ops->query_dir_first) {
340                 rc = -ENOSYS;
341                 goto error_exit;
342         }
343
344         cifsFile->invalidHandle = true;
345         cifsFile->srch_inf.endOfSearch = false;
346
347         full_path = build_path_from_dentry(file_dentry(file));
348         if (full_path == NULL) {
349                 rc = -ENOMEM;
350                 goto error_exit;
351         }
352
353         cifs_dbg(FYI, "Full path: %s start at: %lld\n", full_path, file->f_pos);
354
355 ffirst_retry:
356         /* test for Unix extensions */
357         /* but now check for them on the share/mount not on the SMB session */
358         /* if (cap_unix(tcon->ses) { */
359         if (tcon->unix_ext)
360                 cifsFile->srch_inf.info_level = SMB_FIND_FILE_UNIX;
361         else if ((tcon->ses->capabilities &
362                   tcon->ses->server->vals->cap_nt_find) == 0) {
363                 cifsFile->srch_inf.info_level = SMB_FIND_FILE_INFO_STANDARD;
364         } else if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
365                 cifsFile->srch_inf.info_level = SMB_FIND_FILE_ID_FULL_DIR_INFO;
366         } else /* not srvinos - BB fixme add check for backlevel? */ {
367                 cifsFile->srch_inf.info_level = SMB_FIND_FILE_DIRECTORY_INFO;
368         }
369
370         search_flags = CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME;
371         if (backup_cred(cifs_sb))
372                 search_flags |= CIFS_SEARCH_BACKUP_SEARCH;
373
374         rc = server->ops->query_dir_first(xid, tcon, full_path, cifs_sb,
375                                           &cifsFile->fid, search_flags,
376                                           &cifsFile->srch_inf);
377
378         if (rc == 0)
379                 cifsFile->invalidHandle = false;
380         /* BB add following call to handle readdir on new NTFS symlink errors
381         else if STATUS_STOPPED_ON_SYMLINK
382                 call get_symlink_reparse_path and retry with new path */
383         else if ((rc == -EOPNOTSUPP) &&
384                 (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM)) {
385                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
386                 goto ffirst_retry;
387         }
388 error_exit:
389         kfree(full_path);
390         cifs_put_tlink(tlink);
391         return rc;
392 }
393
394 /* return length of unicode string in bytes */
395 static int cifs_unicode_bytelen(const char *str)
396 {
397         int len;
398         const __le16 *ustr = (const __le16 *)str;
399
400         for (len = 0; len <= PATH_MAX; len++) {
401                 if (ustr[len] == 0)
402                         return len << 1;
403         }
404         cifs_dbg(FYI, "Unicode string longer than PATH_MAX found\n");
405         return len << 1;
406 }
407
408 static char *nxt_dir_entry(char *old_entry, char *end_of_smb, int level)
409 {
410         char *new_entry;
411         FILE_DIRECTORY_INFO *pDirInfo = (FILE_DIRECTORY_INFO *)old_entry;
412
413         if (level == SMB_FIND_FILE_INFO_STANDARD) {
414                 FIND_FILE_STANDARD_INFO *pfData;
415                 pfData = (FIND_FILE_STANDARD_INFO *)pDirInfo;
416
417                 new_entry = old_entry + sizeof(FIND_FILE_STANDARD_INFO) +
418                                 pfData->FileNameLength;
419         } else {
420                 u32 next_offset = le32_to_cpu(pDirInfo->NextEntryOffset);
421
422                 if (old_entry + next_offset < old_entry) {
423                         cifs_dbg(VFS, "invalid offset %u\n", next_offset);
424                         return NULL;
425                 }
426                 new_entry = old_entry + next_offset;
427         }
428         cifs_dbg(FYI, "new entry %p old entry %p\n", new_entry, old_entry);
429         /* validate that new_entry is not past end of SMB */
430         if (new_entry >= end_of_smb) {
431                 cifs_dbg(VFS, "search entry %p began after end of SMB %p old entry %p\n",
432                          new_entry, end_of_smb, old_entry);
433                 return NULL;
434         } else if (((level == SMB_FIND_FILE_INFO_STANDARD) &&
435                     (new_entry + sizeof(FIND_FILE_STANDARD_INFO) > end_of_smb))
436                   || ((level != SMB_FIND_FILE_INFO_STANDARD) &&
437                    (new_entry + sizeof(FILE_DIRECTORY_INFO) > end_of_smb)))  {
438                 cifs_dbg(VFS, "search entry %p extends after end of SMB %p\n",
439                          new_entry, end_of_smb);
440                 return NULL;
441         } else
442                 return new_entry;
443
444 }
445
446 struct cifs_dirent {
447         const char      *name;
448         size_t          namelen;
449         u32             resume_key;
450         u64             ino;
451 };
452
453 static void cifs_fill_dirent_unix(struct cifs_dirent *de,
454                 const FILE_UNIX_INFO *info, bool is_unicode)
455 {
456         de->name = &info->FileName[0];
457         if (is_unicode)
458                 de->namelen = cifs_unicode_bytelen(de->name);
459         else
460                 de->namelen = strnlen(de->name, PATH_MAX);
461         de->resume_key = info->ResumeKey;
462         de->ino = le64_to_cpu(info->basic.UniqueId);
463 }
464
465 static void cifs_fill_dirent_dir(struct cifs_dirent *de,
466                 const FILE_DIRECTORY_INFO *info)
467 {
468         de->name = &info->FileName[0];
469         de->namelen = le32_to_cpu(info->FileNameLength);
470         de->resume_key = info->FileIndex;
471 }
472
473 static void cifs_fill_dirent_full(struct cifs_dirent *de,
474                 const FILE_FULL_DIRECTORY_INFO *info)
475 {
476         de->name = &info->FileName[0];
477         de->namelen = le32_to_cpu(info->FileNameLength);
478         de->resume_key = info->FileIndex;
479 }
480
481 static void cifs_fill_dirent_search(struct cifs_dirent *de,
482                 const SEARCH_ID_FULL_DIR_INFO *info)
483 {
484         de->name = &info->FileName[0];
485         de->namelen = le32_to_cpu(info->FileNameLength);
486         de->resume_key = info->FileIndex;
487         de->ino = le64_to_cpu(info->UniqueId);
488 }
489
490 static void cifs_fill_dirent_both(struct cifs_dirent *de,
491                 const FILE_BOTH_DIRECTORY_INFO *info)
492 {
493         de->name = &info->FileName[0];
494         de->namelen = le32_to_cpu(info->FileNameLength);
495         de->resume_key = info->FileIndex;
496 }
497
498 static void cifs_fill_dirent_std(struct cifs_dirent *de,
499                 const FIND_FILE_STANDARD_INFO *info)
500 {
501         de->name = &info->FileName[0];
502         /* one byte length, no endianess conversion */
503         de->namelen = info->FileNameLength;
504         de->resume_key = info->ResumeKey;
505 }
506
507 static int cifs_fill_dirent(struct cifs_dirent *de, const void *info,
508                 u16 level, bool is_unicode)
509 {
510         memset(de, 0, sizeof(*de));
511
512         switch (level) {
513         case SMB_FIND_FILE_UNIX:
514                 cifs_fill_dirent_unix(de, info, is_unicode);
515                 break;
516         case SMB_FIND_FILE_DIRECTORY_INFO:
517                 cifs_fill_dirent_dir(de, info);
518                 break;
519         case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
520                 cifs_fill_dirent_full(de, info);
521                 break;
522         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
523                 cifs_fill_dirent_search(de, info);
524                 break;
525         case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
526                 cifs_fill_dirent_both(de, info);
527                 break;
528         case SMB_FIND_FILE_INFO_STANDARD:
529                 cifs_fill_dirent_std(de, info);
530                 break;
531         default:
532                 cifs_dbg(FYI, "Unknown findfirst level %d\n", level);
533                 return -EINVAL;
534         }
535
536         return 0;
537 }
538
539 #define UNICODE_DOT cpu_to_le16(0x2e)
540
541 /* return 0 if no match and 1 for . (current directory) and 2 for .. (parent) */
542 static int cifs_entry_is_dot(struct cifs_dirent *de, bool is_unicode)
543 {
544         int rc = 0;
545
546         if (!de->name)
547                 return 0;
548
549         if (is_unicode) {
550                 __le16 *ufilename = (__le16 *)de->name;
551                 if (de->namelen == 2) {
552                         /* check for . */
553                         if (ufilename[0] == UNICODE_DOT)
554                                 rc = 1;
555                 } else if (de->namelen == 4) {
556                         /* check for .. */
557                         if (ufilename[0] == UNICODE_DOT &&
558                             ufilename[1] == UNICODE_DOT)
559                                 rc = 2;
560                 }
561         } else /* ASCII */ {
562                 if (de->namelen == 1) {
563                         if (de->name[0] == '.')
564                                 rc = 1;
565                 } else if (de->namelen == 2) {
566                         if (de->name[0] == '.' && de->name[1] == '.')
567                                 rc = 2;
568                 }
569         }
570
571         return rc;
572 }
573
574 /* Check if directory that we are searching has changed so we can decide
575    whether we can use the cached search results from the previous search */
576 static int is_dir_changed(struct file *file)
577 {
578         struct inode *inode = file_inode(file);
579         struct cifsInodeInfo *cifsInfo = CIFS_I(inode);
580
581         if (cifsInfo->time == 0)
582                 return 1; /* directory was changed, perhaps due to unlink */
583         else
584                 return 0;
585
586 }
587
588 static int cifs_save_resume_key(const char *current_entry,
589         struct cifsFileInfo *file_info)
590 {
591         struct cifs_dirent de;
592         int rc;
593
594         rc = cifs_fill_dirent(&de, current_entry, file_info->srch_inf.info_level,
595                               file_info->srch_inf.unicode);
596         if (!rc) {
597                 file_info->srch_inf.presume_name = de.name;
598                 file_info->srch_inf.resume_name_len = de.namelen;
599                 file_info->srch_inf.resume_key = de.resume_key;
600         }
601         return rc;
602 }
603
604 /*
605  * Find the corresponding entry in the search. Note that the SMB server returns
606  * search entries for . and .. which complicates logic here if we choose to
607  * parse for them and we do not assume that they are located in the findfirst
608  * return buffer. We start counting in the buffer with entry 2 and increment for
609  * every entry (do not increment for . or .. entry).
610  */
611 static int
612 find_cifs_entry(const unsigned int xid, struct cifs_tcon *tcon, loff_t pos,
613                 struct file *file, char **current_entry, int *num_to_ret)
614 {
615         __u16 search_flags;
616         int rc = 0;
617         int pos_in_buf = 0;
618         loff_t first_entry_in_buffer;
619         loff_t index_to_find = pos;
620         struct cifsFileInfo *cfile = file->private_data;
621         struct cifs_sb_info *cifs_sb = CIFS_FILE_SB(file);
622         struct TCP_Server_Info *server = tcon->ses->server;
623         /* check if index in the buffer */
624
625         if (!server->ops->query_dir_first || !server->ops->query_dir_next)
626                 return -ENOSYS;
627
628         if ((cfile == NULL) || (current_entry == NULL) || (num_to_ret == NULL))
629                 return -ENOENT;
630
631         *current_entry = NULL;
632         first_entry_in_buffer = cfile->srch_inf.index_of_last_entry -
633                                         cfile->srch_inf.entries_in_buffer;
634
635         /*
636          * If first entry in buf is zero then is first buffer
637          * in search response data which means it is likely . and ..
638          * will be in this buffer, although some servers do not return
639          * . and .. for the root of a drive and for those we need
640          * to start two entries earlier.
641          */
642
643         dump_cifs_file_struct(file, "In fce ");
644         if (((index_to_find < cfile->srch_inf.index_of_last_entry) &&
645              is_dir_changed(file)) || (index_to_find < first_entry_in_buffer)) {
646                 /* close and restart search */
647                 cifs_dbg(FYI, "search backing up - close and restart search\n");
648                 spin_lock(&cfile->file_info_lock);
649                 if (server->ops->dir_needs_close(cfile)) {
650                         cfile->invalidHandle = true;
651                         spin_unlock(&cfile->file_info_lock);
652                         if (server->ops->close_dir)
653                                 server->ops->close_dir(xid, tcon, &cfile->fid);
654                 } else
655                         spin_unlock(&cfile->file_info_lock);
656                 if (cfile->srch_inf.ntwrk_buf_start) {
657                         cifs_dbg(FYI, "freeing SMB ff cache buf on search rewind\n");
658                         if (cfile->srch_inf.smallBuf)
659                                 cifs_small_buf_release(cfile->srch_inf.
660                                                 ntwrk_buf_start);
661                         else
662                                 cifs_buf_release(cfile->srch_inf.
663                                                 ntwrk_buf_start);
664                         cfile->srch_inf.ntwrk_buf_start = NULL;
665                 }
666                 rc = initiate_cifs_search(xid, file);
667                 if (rc) {
668                         cifs_dbg(FYI, "error %d reinitiating a search on rewind\n",
669                                  rc);
670                         return rc;
671                 }
672                 /* FindFirst/Next set last_entry to NULL on malformed reply */
673                 if (cfile->srch_inf.last_entry)
674                         cifs_save_resume_key(cfile->srch_inf.last_entry, cfile);
675         }
676
677         search_flags = CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME;
678         if (backup_cred(cifs_sb))
679                 search_flags |= CIFS_SEARCH_BACKUP_SEARCH;
680
681         while ((index_to_find >= cfile->srch_inf.index_of_last_entry) &&
682                (rc == 0) && !cfile->srch_inf.endOfSearch) {
683                 cifs_dbg(FYI, "calling findnext2\n");
684                 rc = server->ops->query_dir_next(xid, tcon, &cfile->fid,
685                                                  search_flags,
686                                                  &cfile->srch_inf);
687                 /* FindFirst/Next set last_entry to NULL on malformed reply */
688                 if (cfile->srch_inf.last_entry)
689                         cifs_save_resume_key(cfile->srch_inf.last_entry, cfile);
690                 if (rc)
691                         return -ENOENT;
692         }
693         if (index_to_find < cfile->srch_inf.index_of_last_entry) {
694                 /* we found the buffer that contains the entry */
695                 /* scan and find it */
696                 int i;
697                 char *cur_ent;
698                 char *end_of_smb;
699
700                 if (cfile->srch_inf.ntwrk_buf_start == NULL) {
701                         cifs_dbg(VFS, "ntwrk_buf_start is NULL during readdir\n");
702                         return -EIO;
703                 }
704
705                 end_of_smb = cfile->srch_inf.ntwrk_buf_start +
706                         server->ops->calc_smb_size(
707                                         cfile->srch_inf.ntwrk_buf_start,
708                                         server);
709
710                 cur_ent = cfile->srch_inf.srch_entries_start;
711                 first_entry_in_buffer = cfile->srch_inf.index_of_last_entry
712                                         - cfile->srch_inf.entries_in_buffer;
713                 pos_in_buf = index_to_find - first_entry_in_buffer;
714                 cifs_dbg(FYI, "found entry - pos_in_buf %d\n", pos_in_buf);
715
716                 for (i = 0; (i < (pos_in_buf)) && (cur_ent != NULL); i++) {
717                         /* go entry by entry figuring out which is first */
718                         cur_ent = nxt_dir_entry(cur_ent, end_of_smb,
719                                                 cfile->srch_inf.info_level);
720                 }
721                 if ((cur_ent == NULL) && (i < pos_in_buf)) {
722                         /* BB fixme - check if we should flag this error */
723                         cifs_dbg(VFS, "reached end of buf searching for pos in buf %d index to find %lld rc %d\n",
724                                  pos_in_buf, index_to_find, rc);
725                 }
726                 rc = 0;
727                 *current_entry = cur_ent;
728         } else {
729                 cifs_dbg(FYI, "index not in buffer - could not findnext into it\n");
730                 return 0;
731         }
732
733         if (pos_in_buf >= cfile->srch_inf.entries_in_buffer) {
734                 cifs_dbg(FYI, "can not return entries pos_in_buf beyond last\n");
735                 *num_to_ret = 0;
736         } else
737                 *num_to_ret = cfile->srch_inf.entries_in_buffer - pos_in_buf;
738
739         return rc;
740 }
741
742 static int cifs_filldir(char *find_entry, struct file *file,
743                 struct dir_context *ctx,
744                 char *scratch_buf, unsigned int max_len)
745 {
746         struct cifsFileInfo *file_info = file->private_data;
747         struct super_block *sb = file_inode(file)->i_sb;
748         struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
749         struct cifs_dirent de = { NULL, };
750         struct cifs_fattr fattr;
751         struct qstr name;
752         int rc = 0;
753         ino_t ino;
754
755         rc = cifs_fill_dirent(&de, find_entry, file_info->srch_inf.info_level,
756                               file_info->srch_inf.unicode);
757         if (rc)
758                 return rc;
759
760         if (de.namelen > max_len) {
761                 cifs_dbg(VFS, "bad search response length %zd past smb end\n",
762                          de.namelen);
763                 return -EINVAL;
764         }
765
766         /* skip . and .. since we added them first */
767         if (cifs_entry_is_dot(&de, file_info->srch_inf.unicode))
768                 return 0;
769
770         if (file_info->srch_inf.unicode) {
771                 struct nls_table *nlt = cifs_sb->local_nls;
772                 int map_type;
773
774                 map_type = cifs_remap(cifs_sb);
775                 name.name = scratch_buf;
776                 name.len =
777                         cifs_from_utf16((char *)name.name, (__le16 *)de.name,
778                                         UNICODE_NAME_MAX,
779                                         min_t(size_t, de.namelen,
780                                               (size_t)max_len), nlt, map_type);
781                 name.len -= nls_nullsize(nlt);
782         } else {
783                 name.name = de.name;
784                 name.len = de.namelen;
785         }
786
787         switch (file_info->srch_inf.info_level) {
788         case SMB_FIND_FILE_UNIX:
789                 cifs_unix_basic_to_fattr(&fattr,
790                                          &((FILE_UNIX_INFO *)find_entry)->basic,
791                                          cifs_sb);
792                 break;
793         case SMB_FIND_FILE_INFO_STANDARD:
794                 cifs_std_info_to_fattr(&fattr,
795                                        (FIND_FILE_STANDARD_INFO *)find_entry,
796                                        cifs_sb);
797                 break;
798         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
799                 cifs_fulldir_info_to_fattr(&fattr,
800                                            (SEARCH_ID_FULL_DIR_INFO *)find_entry,
801                                            cifs_sb);
802                 break;
803         default:
804                 cifs_dir_info_to_fattr(&fattr,
805                                        (FILE_DIRECTORY_INFO *)find_entry,
806                                        cifs_sb);
807                 break;
808         }
809
810         if (de.ino && (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM)) {
811                 fattr.cf_uniqueid = de.ino;
812         } else {
813                 fattr.cf_uniqueid = iunique(sb, ROOT_I);
814                 cifs_autodisable_serverino(cifs_sb);
815         }
816
817         if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MF_SYMLINKS) &&
818             couldbe_mf_symlink(&fattr))
819                 /*
820                  * trying to get the type and mode can be slow,
821                  * so just call those regular files for now, and mark
822                  * for reval
823                  */
824                 fattr.cf_flags |= CIFS_FATTR_NEED_REVAL;
825
826         cifs_prime_dcache(file_dentry(file), &name, &fattr);
827
828         ino = cifs_uniqueid_to_ino_t(fattr.cf_uniqueid);
829         return !dir_emit(ctx, name.name, name.len, ino, fattr.cf_dtype);
830 }
831
832
833 int cifs_readdir(struct file *file, struct dir_context *ctx)
834 {
835         int rc = 0;
836         unsigned int xid;
837         int i;
838         struct cifs_tcon *tcon;
839         struct cifsFileInfo *cifsFile = NULL;
840         char *current_entry;
841         int num_to_fill = 0;
842         char *tmp_buf = NULL;
843         char *end_of_smb;
844         unsigned int max_len;
845
846         xid = get_xid();
847
848         /*
849          * Ensure FindFirst doesn't fail before doing filldir() for '.' and
850          * '..'. Otherwise we won't be able to notify VFS in case of failure.
851          */
852         if (file->private_data == NULL) {
853                 rc = initiate_cifs_search(xid, file);
854                 cifs_dbg(FYI, "initiate cifs search rc %d\n", rc);
855                 if (rc)
856                         goto rddir2_exit;
857         }
858
859         if (!dir_emit_dots(file, ctx))
860                 goto rddir2_exit;
861
862         /* 1) If search is active,
863                 is in current search buffer?
864                 if it before then restart search
865                 if after then keep searching till find it */
866
867         cifsFile = file->private_data;
868         if (cifsFile->srch_inf.endOfSearch) {
869                 if (cifsFile->srch_inf.emptyDir) {
870                         cifs_dbg(FYI, "End of search, empty dir\n");
871                         rc = 0;
872                         goto rddir2_exit;
873                 }
874         } /* else {
875                 cifsFile->invalidHandle = true;
876                 tcon->ses->server->close(xid, tcon, &cifsFile->fid);
877         } */
878
879         tcon = tlink_tcon(cifsFile->tlink);
880         rc = find_cifs_entry(xid, tcon, ctx->pos, file, &current_entry,
881                              &num_to_fill);
882         if (rc) {
883                 cifs_dbg(FYI, "fce error %d\n", rc);
884                 goto rddir2_exit;
885         } else if (current_entry != NULL) {
886                 cifs_dbg(FYI, "entry %lld found\n", ctx->pos);
887         } else {
888                 cifs_dbg(FYI, "could not find entry\n");
889                 goto rddir2_exit;
890         }
891         cifs_dbg(FYI, "loop through %d times filling dir for net buf %p\n",
892                  num_to_fill, cifsFile->srch_inf.ntwrk_buf_start);
893         max_len = tcon->ses->server->ops->calc_smb_size(
894                         cifsFile->srch_inf.ntwrk_buf_start,
895                         tcon->ses->server);
896         end_of_smb = cifsFile->srch_inf.ntwrk_buf_start + max_len;
897
898         tmp_buf = kmalloc(UNICODE_NAME_MAX, GFP_KERNEL);
899         if (tmp_buf == NULL) {
900                 rc = -ENOMEM;
901                 goto rddir2_exit;
902         }
903
904         for (i = 0; i < num_to_fill; i++) {
905                 if (current_entry == NULL) {
906                         /* evaluate whether this case is an error */
907                         cifs_dbg(VFS, "past SMB end,  num to fill %d i %d\n",
908                                  num_to_fill, i);
909                         break;
910                 }
911                 /*
912                  * if buggy server returns . and .. late do we want to
913                  * check for that here?
914                  */
915                 *tmp_buf = 0;
916                 rc = cifs_filldir(current_entry, file, ctx,
917                                   tmp_buf, max_len);
918                 if (rc) {
919                         if (rc > 0)
920                                 rc = 0;
921                         break;
922                 }
923
924                 ctx->pos++;
925                 if (ctx->pos ==
926                         cifsFile->srch_inf.index_of_last_entry) {
927                         cifs_dbg(FYI, "last entry in buf at pos %lld %s\n",
928                                  ctx->pos, tmp_buf);
929                         cifs_save_resume_key(current_entry, cifsFile);
930                         break;
931                 } else
932                         current_entry =
933                                 nxt_dir_entry(current_entry, end_of_smb,
934                                         cifsFile->srch_inf.info_level);
935         }
936         kfree(tmp_buf);
937
938 rddir2_exit:
939         free_xid(xid);
940         return rc;
941 }