OSDN Git Service

NFS: Fix memory leaks and corruption in readdir
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / fs / nfs / dir.c
1 /*
2  *  linux/fs/nfs/dir.c
3  *
4  *  Copyright (C) 1992  Rick Sladkey
5  *
6  *  nfs directory handling functions
7  *
8  * 10 Apr 1996  Added silly rename for unlink   --okir
9  * 28 Sep 1996  Improved directory cache --okir
10  * 23 Aug 1997  Claus Heine claus@momo.math.rwth-aachen.de 
11  *              Re-implemented silly rename for unlink, newly implemented
12  *              silly rename for nfs_rename() following the suggestions
13  *              of Olaf Kirch (okir) found in this file.
14  *              Following Linus comments on my original hack, this version
15  *              depends only on the dcache stuff and doesn't touch the inode
16  *              layer (iput() and friends).
17  *  6 Jun 1999  Cache readdir lookups in the page cache. -DaveM
18  */
19
20 #include <linux/module.h>
21 #include <linux/time.h>
22 #include <linux/errno.h>
23 #include <linux/stat.h>
24 #include <linux/fcntl.h>
25 #include <linux/string.h>
26 #include <linux/kernel.h>
27 #include <linux/slab.h>
28 #include <linux/mm.h>
29 #include <linux/sunrpc/clnt.h>
30 #include <linux/nfs_fs.h>
31 #include <linux/nfs_mount.h>
32 #include <linux/pagemap.h>
33 #include <linux/pagevec.h>
34 #include <linux/namei.h>
35 #include <linux/mount.h>
36 #include <linux/swap.h>
37 #include <linux/sched.h>
38 #include <linux/kmemleak.h>
39 #include <linux/xattr.h>
40
41 #include "delegation.h"
42 #include "iostat.h"
43 #include "internal.h"
44 #include "fscache.h"
45
46 #include "nfstrace.h"
47
48 /* #define NFS_DEBUG_VERBOSE 1 */
49
50 static int nfs_opendir(struct inode *, struct file *);
51 static int nfs_closedir(struct inode *, struct file *);
52 static int nfs_readdir(struct file *, struct dir_context *);
53 static int nfs_fsync_dir(struct file *, loff_t, loff_t, int);
54 static loff_t nfs_llseek_dir(struct file *, loff_t, int);
55 static void nfs_readdir_clear_array(struct page*);
56
57 const struct file_operations nfs_dir_operations = {
58         .llseek         = nfs_llseek_dir,
59         .read           = generic_read_dir,
60         .iterate        = nfs_readdir,
61         .open           = nfs_opendir,
62         .release        = nfs_closedir,
63         .fsync          = nfs_fsync_dir,
64 };
65
66 const struct address_space_operations nfs_dir_aops = {
67         .freepage = nfs_readdir_clear_array,
68 };
69
70 static struct nfs_open_dir_context *alloc_nfs_open_dir_context(struct inode *dir, struct rpc_cred *cred)
71 {
72         struct nfs_inode *nfsi = NFS_I(dir);
73         struct nfs_open_dir_context *ctx;
74         ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
75         if (ctx != NULL) {
76                 ctx->duped = 0;
77                 ctx->attr_gencount = nfsi->attr_gencount;
78                 ctx->dir_cookie = 0;
79                 ctx->dup_cookie = 0;
80                 ctx->cred = get_rpccred(cred);
81                 spin_lock(&dir->i_lock);
82                 list_add(&ctx->list, &nfsi->open_files);
83                 spin_unlock(&dir->i_lock);
84                 return ctx;
85         }
86         return  ERR_PTR(-ENOMEM);
87 }
88
89 static void put_nfs_open_dir_context(struct inode *dir, struct nfs_open_dir_context *ctx)
90 {
91         spin_lock(&dir->i_lock);
92         list_del(&ctx->list);
93         spin_unlock(&dir->i_lock);
94         put_rpccred(ctx->cred);
95         kfree(ctx);
96 }
97
98 /*
99  * Open file
100  */
101 static int
102 nfs_opendir(struct inode *inode, struct file *filp)
103 {
104         int res = 0;
105         struct nfs_open_dir_context *ctx;
106         struct rpc_cred *cred;
107
108         dfprintk(FILE, "NFS: open dir(%pD2)\n", filp);
109
110         nfs_inc_stats(inode, NFSIOS_VFSOPEN);
111
112         cred = rpc_lookup_cred();
113         if (IS_ERR(cred))
114                 return PTR_ERR(cred);
115         ctx = alloc_nfs_open_dir_context(inode, cred);
116         if (IS_ERR(ctx)) {
117                 res = PTR_ERR(ctx);
118                 goto out;
119         }
120         filp->private_data = ctx;
121         if (filp->f_path.dentry == filp->f_path.mnt->mnt_root) {
122                 /* This is a mountpoint, so d_revalidate will never
123                  * have been called, so we need to refresh the
124                  * inode (for close-open consistency) ourselves.
125                  */
126                 __nfs_revalidate_inode(NFS_SERVER(inode), inode);
127         }
128 out:
129         put_rpccred(cred);
130         return res;
131 }
132
133 static int
134 nfs_closedir(struct inode *inode, struct file *filp)
135 {
136         put_nfs_open_dir_context(file_inode(filp), filp->private_data);
137         return 0;
138 }
139
140 struct nfs_cache_array_entry {
141         u64 cookie;
142         u64 ino;
143         struct qstr string;
144         unsigned char d_type;
145 };
146
147 struct nfs_cache_array {
148         int size;
149         int eof_index;
150         u64 last_cookie;
151         struct nfs_cache_array_entry array[0];
152 };
153
154 typedef int (*decode_dirent_t)(struct xdr_stream *, struct nfs_entry *, int);
155 typedef struct {
156         struct file     *file;
157         struct page     *page;
158         struct dir_context *ctx;
159         unsigned long   page_index;
160         u64             *dir_cookie;
161         u64             last_cookie;
162         loff_t          current_index;
163         decode_dirent_t decode;
164
165         unsigned long   timestamp;
166         unsigned long   gencount;
167         unsigned int    cache_entry_index;
168         unsigned int    plus:1;
169         unsigned int    eof:1;
170 } nfs_readdir_descriptor_t;
171
172 static
173 void nfs_readdir_init_array(struct page *page)
174 {
175         struct nfs_cache_array *array;
176
177         array = kmap_atomic(page);
178         memset(array, 0, sizeof(struct nfs_cache_array));
179         array->eof_index = -1;
180         kunmap_atomic(array);
181 }
182
183 /*
184  * The caller is responsible for calling nfs_readdir_release_array(page)
185  */
186 static
187 struct nfs_cache_array *nfs_readdir_get_array(struct page *page)
188 {
189         void *ptr;
190         if (page == NULL)
191                 return ERR_PTR(-EIO);
192         ptr = kmap(page);
193         if (ptr == NULL)
194                 return ERR_PTR(-ENOMEM);
195         return ptr;
196 }
197
198 static
199 void nfs_readdir_release_array(struct page *page)
200 {
201         kunmap(page);
202 }
203
204 /*
205  * we are freeing strings created by nfs_add_to_readdir_array()
206  */
207 static
208 void nfs_readdir_clear_array(struct page *page)
209 {
210         struct nfs_cache_array *array;
211         int i;
212
213         array = kmap_atomic(page);
214         for (i = 0; i < array->size; i++)
215                 kfree(array->array[i].string.name);
216         array->size = 0;
217         kunmap_atomic(array);
218 }
219
220 /*
221  * the caller is responsible for freeing qstr.name
222  * when called by nfs_readdir_add_to_array, the strings will be freed in
223  * nfs_clear_readdir_array()
224  */
225 static
226 int nfs_readdir_make_qstr(struct qstr *string, const char *name, unsigned int len)
227 {
228         string->len = len;
229         string->name = kmemdup(name, len, GFP_KERNEL);
230         if (string->name == NULL)
231                 return -ENOMEM;
232         /*
233          * Avoid a kmemleak false positive. The pointer to the name is stored
234          * in a page cache page which kmemleak does not scan.
235          */
236         kmemleak_not_leak(string->name);
237         string->hash = full_name_hash(name, len);
238         return 0;
239 }
240
241 static
242 int nfs_readdir_add_to_array(struct nfs_entry *entry, struct page *page)
243 {
244         struct nfs_cache_array *array = nfs_readdir_get_array(page);
245         struct nfs_cache_array_entry *cache_entry;
246         int ret;
247
248         if (IS_ERR(array))
249                 return PTR_ERR(array);
250
251         cache_entry = &array->array[array->size];
252
253         /* Check that this entry lies within the page bounds */
254         ret = -ENOSPC;
255         if ((char *)&cache_entry[1] - (char *)page_address(page) > PAGE_SIZE)
256                 goto out;
257
258         cache_entry->cookie = entry->prev_cookie;
259         cache_entry->ino = entry->ino;
260         cache_entry->d_type = entry->d_type;
261         ret = nfs_readdir_make_qstr(&cache_entry->string, entry->name, entry->len);
262         if (ret)
263                 goto out;
264         array->last_cookie = entry->cookie;
265         array->size++;
266         if (entry->eof != 0)
267                 array->eof_index = array->size;
268 out:
269         nfs_readdir_release_array(page);
270         return ret;
271 }
272
273 static
274 int nfs_readdir_search_for_pos(struct nfs_cache_array *array, nfs_readdir_descriptor_t *desc)
275 {
276         loff_t diff = desc->ctx->pos - desc->current_index;
277         unsigned int index;
278
279         if (diff < 0)
280                 goto out_eof;
281         if (diff >= array->size) {
282                 if (array->eof_index >= 0)
283                         goto out_eof;
284                 return -EAGAIN;
285         }
286
287         index = (unsigned int)diff;
288         *desc->dir_cookie = array->array[index].cookie;
289         desc->cache_entry_index = index;
290         return 0;
291 out_eof:
292         desc->eof = 1;
293         return -EBADCOOKIE;
294 }
295
296 static bool
297 nfs_readdir_inode_mapping_valid(struct nfs_inode *nfsi)
298 {
299         if (nfsi->cache_validity & (NFS_INO_INVALID_ATTR|NFS_INO_INVALID_DATA))
300                 return false;
301         smp_rmb();
302         return !test_bit(NFS_INO_INVALIDATING, &nfsi->flags);
303 }
304
305 static
306 int nfs_readdir_search_for_cookie(struct nfs_cache_array *array, nfs_readdir_descriptor_t *desc)
307 {
308         int i;
309         loff_t new_pos;
310         int status = -EAGAIN;
311
312         for (i = 0; i < array->size; i++) {
313                 if (array->array[i].cookie == *desc->dir_cookie) {
314                         struct nfs_inode *nfsi = NFS_I(file_inode(desc->file));
315                         struct nfs_open_dir_context *ctx = desc->file->private_data;
316
317                         new_pos = desc->current_index + i;
318                         if (ctx->attr_gencount != nfsi->attr_gencount ||
319                             !nfs_readdir_inode_mapping_valid(nfsi)) {
320                                 ctx->duped = 0;
321                                 ctx->attr_gencount = nfsi->attr_gencount;
322                         } else if (new_pos < desc->ctx->pos) {
323                                 if (ctx->duped > 0
324                                     && ctx->dup_cookie == *desc->dir_cookie) {
325                                         if (printk_ratelimit()) {
326                                                 pr_notice("NFS: directory %pD2 contains a readdir loop."
327                                                                 "Please contact your server vendor.  "
328                                                                 "The file: %.*s has duplicate cookie %llu\n",
329                                                                 desc->file, array->array[i].string.len,
330                                                                 array->array[i].string.name, *desc->dir_cookie);
331                                         }
332                                         status = -ELOOP;
333                                         goto out;
334                                 }
335                                 ctx->dup_cookie = *desc->dir_cookie;
336                                 ctx->duped = -1;
337                         }
338                         desc->ctx->pos = new_pos;
339                         desc->cache_entry_index = i;
340                         return 0;
341                 }
342         }
343         if (array->eof_index >= 0) {
344                 status = -EBADCOOKIE;
345                 if (*desc->dir_cookie == array->last_cookie)
346                         desc->eof = 1;
347         }
348 out:
349         return status;
350 }
351
352 static
353 int nfs_readdir_search_array(nfs_readdir_descriptor_t *desc)
354 {
355         struct nfs_cache_array *array;
356         int status;
357
358         array = nfs_readdir_get_array(desc->page);
359         if (IS_ERR(array)) {
360                 status = PTR_ERR(array);
361                 goto out;
362         }
363
364         if (*desc->dir_cookie == 0)
365                 status = nfs_readdir_search_for_pos(array, desc);
366         else
367                 status = nfs_readdir_search_for_cookie(array, desc);
368
369         if (status == -EAGAIN) {
370                 desc->last_cookie = array->last_cookie;
371                 desc->current_index += array->size;
372                 desc->page_index++;
373         }
374         nfs_readdir_release_array(desc->page);
375 out:
376         return status;
377 }
378
379 /* Fill a page with xdr information before transferring to the cache page */
380 static
381 int nfs_readdir_xdr_filler(struct page **pages, nfs_readdir_descriptor_t *desc,
382                         struct nfs_entry *entry, struct file *file, struct inode *inode)
383 {
384         struct nfs_open_dir_context *ctx = file->private_data;
385         struct rpc_cred *cred = ctx->cred;
386         unsigned long   timestamp, gencount;
387         int             error;
388
389  again:
390         timestamp = jiffies;
391         gencount = nfs_inc_attr_generation_counter();
392         error = NFS_PROTO(inode)->readdir(file_dentry(file), cred, entry->cookie, pages,
393                                           NFS_SERVER(inode)->dtsize, desc->plus);
394         if (error < 0) {
395                 /* We requested READDIRPLUS, but the server doesn't grok it */
396                 if (error == -ENOTSUPP && desc->plus) {
397                         NFS_SERVER(inode)->caps &= ~NFS_CAP_READDIRPLUS;
398                         clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(inode)->flags);
399                         desc->plus = 0;
400                         goto again;
401                 }
402                 goto error;
403         }
404         desc->timestamp = timestamp;
405         desc->gencount = gencount;
406 error:
407         return error;
408 }
409
410 static int xdr_decode(nfs_readdir_descriptor_t *desc,
411                       struct nfs_entry *entry, struct xdr_stream *xdr)
412 {
413         int error;
414
415         error = desc->decode(xdr, entry, desc->plus);
416         if (error)
417                 return error;
418         entry->fattr->time_start = desc->timestamp;
419         entry->fattr->gencount = desc->gencount;
420         return 0;
421 }
422
423 /* Match file and dirent using either filehandle or fileid
424  * Note: caller is responsible for checking the fsid
425  */
426 static
427 int nfs_same_file(struct dentry *dentry, struct nfs_entry *entry)
428 {
429         struct nfs_inode *nfsi;
430
431         if (d_really_is_negative(dentry))
432                 return 0;
433
434         nfsi = NFS_I(d_inode(dentry));
435         if (entry->fattr->fileid == nfsi->fileid)
436                 return 1;
437         if (nfs_compare_fh(entry->fh, &nfsi->fh) == 0)
438                 return 1;
439         return 0;
440 }
441
442 static
443 bool nfs_use_readdirplus(struct inode *dir, struct dir_context *ctx)
444 {
445         if (!nfs_server_capable(dir, NFS_CAP_READDIRPLUS))
446                 return false;
447         if (test_and_clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(dir)->flags))
448                 return true;
449         if (ctx->pos == 0)
450                 return true;
451         return false;
452 }
453
454 /*
455  * This function is called by the lookup code to request the use of
456  * readdirplus to accelerate any future lookups in the same
457  * directory.
458  */
459 static
460 void nfs_advise_use_readdirplus(struct inode *dir)
461 {
462         set_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(dir)->flags);
463 }
464
465 /*
466  * This function is mainly for use by nfs_getattr().
467  *
468  * If this is an 'ls -l', we want to force use of readdirplus.
469  * Do this by checking if there is an active file descriptor
470  * and calling nfs_advise_use_readdirplus, then forcing a
471  * cache flush.
472  */
473 void nfs_force_use_readdirplus(struct inode *dir)
474 {
475         if (!list_empty(&NFS_I(dir)->open_files)) {
476                 nfs_advise_use_readdirplus(dir);
477                 invalidate_mapping_pages(dir->i_mapping, 0, -1);
478         }
479 }
480
481 static
482 void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry)
483 {
484         struct qstr filename = QSTR_INIT(entry->name, entry->len);
485         struct dentry *dentry;
486         struct dentry *alias;
487         struct inode *dir = d_inode(parent);
488         struct inode *inode;
489         int status;
490
491         if (!(entry->fattr->valid & NFS_ATTR_FATTR_FILEID))
492                 return;
493         if (!(entry->fattr->valid & NFS_ATTR_FATTR_FSID))
494                 return;
495         if (filename.name[0] == '.') {
496                 if (filename.len == 1)
497                         return;
498                 if (filename.len == 2 && filename.name[1] == '.')
499                         return;
500         }
501         filename.hash = full_name_hash(filename.name, filename.len);
502
503         dentry = d_lookup(parent, &filename);
504         if (dentry != NULL) {
505                 /* Is there a mountpoint here? If so, just exit */
506                 if (!nfs_fsid_equal(&NFS_SB(dentry->d_sb)->fsid,
507                                         &entry->fattr->fsid))
508                         goto out;
509                 if (nfs_same_file(dentry, entry)) {
510                         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
511                         status = nfs_refresh_inode(d_inode(dentry), entry->fattr);
512                         if (!status)
513                                 nfs_setsecurity(d_inode(dentry), entry->fattr, entry->label);
514                         goto out;
515                 } else {
516                         d_invalidate(dentry);
517                         dput(dentry);
518                 }
519         }
520
521         dentry = d_alloc(parent, &filename);
522         if (dentry == NULL)
523                 return;
524
525         inode = nfs_fhget(dentry->d_sb, entry->fh, entry->fattr, entry->label);
526         if (IS_ERR(inode))
527                 goto out;
528
529         alias = d_splice_alias(inode, dentry);
530         if (IS_ERR(alias))
531                 goto out;
532         else if (alias) {
533                 nfs_set_verifier(alias, nfs_save_change_attribute(dir));
534                 dput(alias);
535         } else
536                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
537
538 out:
539         dput(dentry);
540 }
541
542 /* Perform conversion from xdr to cache array */
543 static
544 int nfs_readdir_page_filler(nfs_readdir_descriptor_t *desc, struct nfs_entry *entry,
545                                 struct page **xdr_pages, struct page *page, unsigned int buflen)
546 {
547         struct xdr_stream stream;
548         struct xdr_buf buf;
549         struct page *scratch;
550         struct nfs_cache_array *array;
551         unsigned int count = 0;
552         int status;
553
554         scratch = alloc_page(GFP_KERNEL);
555         if (scratch == NULL)
556                 return -ENOMEM;
557
558         if (buflen == 0)
559                 goto out_nopages;
560
561         xdr_init_decode_pages(&stream, &buf, xdr_pages, buflen);
562         xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
563
564         do {
565                 status = xdr_decode(desc, entry, &stream);
566                 if (status != 0) {
567                         if (status == -EAGAIN)
568                                 status = 0;
569                         break;
570                 }
571
572                 count++;
573
574                 if (desc->plus != 0)
575                         nfs_prime_dcache(file_dentry(desc->file), entry);
576
577                 status = nfs_readdir_add_to_array(entry, page);
578                 if (status != 0)
579                         break;
580         } while (!entry->eof);
581
582 out_nopages:
583         if (count == 0 || (status == -EBADCOOKIE && entry->eof != 0)) {
584                 array = nfs_readdir_get_array(page);
585                 if (!IS_ERR(array)) {
586                         array->eof_index = array->size;
587                         status = 0;
588                         nfs_readdir_release_array(page);
589                 } else
590                         status = PTR_ERR(array);
591         }
592
593         put_page(scratch);
594         return status;
595 }
596
597 static
598 void nfs_readdir_free_pages(struct page **pages, unsigned int npages)
599 {
600         unsigned int i;
601         for (i = 0; i < npages; i++)
602                 put_page(pages[i]);
603 }
604
605 /*
606  * nfs_readdir_large_page will allocate pages that must be freed with a call
607  * to nfs_readdir_free_pagearray
608  */
609 static
610 int nfs_readdir_alloc_pages(struct page **pages, unsigned int npages)
611 {
612         unsigned int i;
613
614         for (i = 0; i < npages; i++) {
615                 struct page *page = alloc_page(GFP_KERNEL);
616                 if (page == NULL)
617                         goto out_freepages;
618                 pages[i] = page;
619         }
620         return 0;
621
622 out_freepages:
623         nfs_readdir_free_pages(pages, i);
624         return -ENOMEM;
625 }
626
627 static
628 int nfs_readdir_xdr_to_array(nfs_readdir_descriptor_t *desc, struct page *page, struct inode *inode)
629 {
630         struct page *pages[NFS_MAX_READDIR_PAGES];
631         struct nfs_entry entry;
632         struct file     *file = desc->file;
633         struct nfs_cache_array *array;
634         int status = -ENOMEM;
635         unsigned int array_size = ARRAY_SIZE(pages);
636
637         nfs_readdir_init_array(page);
638
639         entry.prev_cookie = 0;
640         entry.cookie = desc->last_cookie;
641         entry.eof = 0;
642         entry.fh = nfs_alloc_fhandle();
643         entry.fattr = nfs_alloc_fattr();
644         entry.server = NFS_SERVER(inode);
645         if (entry.fh == NULL || entry.fattr == NULL)
646                 goto out;
647
648         entry.label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
649         if (IS_ERR(entry.label)) {
650                 status = PTR_ERR(entry.label);
651                 goto out;
652         }
653
654         array = nfs_readdir_get_array(page);
655         if (IS_ERR(array)) {
656                 status = PTR_ERR(array);
657                 goto out_label_free;
658         }
659
660         array = kmap(page);
661
662         status = nfs_readdir_alloc_pages(pages, array_size);
663         if (status < 0)
664                 goto out_release_array;
665         do {
666                 unsigned int pglen;
667                 status = nfs_readdir_xdr_filler(pages, desc, &entry, file, inode);
668
669                 if (status < 0)
670                         break;
671                 pglen = status;
672                 status = nfs_readdir_page_filler(desc, &entry, pages, page, pglen);
673                 if (status < 0) {
674                         if (status == -ENOSPC)
675                                 status = 0;
676                         break;
677                 }
678         } while (array->eof_index < 0);
679
680         nfs_readdir_free_pages(pages, array_size);
681 out_release_array:
682         nfs_readdir_release_array(page);
683 out_label_free:
684         nfs4_label_free(entry.label);
685 out:
686         nfs_free_fattr(entry.fattr);
687         nfs_free_fhandle(entry.fh);
688         return status;
689 }
690
691 /*
692  * Now we cache directories properly, by converting xdr information
693  * to an array that can be used for lookups later.  This results in
694  * fewer cache pages, since we can store more information on each page.
695  * We only need to convert from xdr once so future lookups are much simpler
696  */
697 static
698 int nfs_readdir_filler(nfs_readdir_descriptor_t *desc, struct page* page)
699 {
700         struct inode    *inode = file_inode(desc->file);
701         int ret;
702
703         ret = nfs_readdir_xdr_to_array(desc, page, inode);
704         if (ret < 0)
705                 goto error;
706         SetPageUptodate(page);
707
708         if (invalidate_inode_pages2_range(inode->i_mapping, page->index + 1, -1) < 0) {
709                 /* Should never happen */
710                 nfs_zap_mapping(inode, inode->i_mapping);
711         }
712         unlock_page(page);
713         return 0;
714  error:
715         nfs_readdir_clear_array(page);
716         unlock_page(page);
717         return ret;
718 }
719
720 static
721 void cache_page_release(nfs_readdir_descriptor_t *desc)
722 {
723         if (!desc->page->mapping)
724                 nfs_readdir_clear_array(desc->page);
725         page_cache_release(desc->page);
726         desc->page = NULL;
727 }
728
729 static
730 struct page *get_cache_page(nfs_readdir_descriptor_t *desc)
731 {
732         return read_cache_page(file_inode(desc->file)->i_mapping,
733                         desc->page_index, (filler_t *)nfs_readdir_filler, desc);
734 }
735
736 /*
737  * Returns 0 if desc->dir_cookie was found on page desc->page_index
738  */
739 static
740 int find_cache_page(nfs_readdir_descriptor_t *desc)
741 {
742         int res;
743
744         desc->page = get_cache_page(desc);
745         if (IS_ERR(desc->page))
746                 return PTR_ERR(desc->page);
747
748         res = nfs_readdir_search_array(desc);
749         if (res != 0)
750                 cache_page_release(desc);
751         return res;
752 }
753
754 /* Search for desc->dir_cookie from the beginning of the page cache */
755 static inline
756 int readdir_search_pagecache(nfs_readdir_descriptor_t *desc)
757 {
758         int res;
759
760         if (desc->page_index == 0) {
761                 desc->current_index = 0;
762                 desc->last_cookie = 0;
763         }
764         do {
765                 res = find_cache_page(desc);
766         } while (res == -EAGAIN);
767         return res;
768 }
769
770 /*
771  * Once we've found the start of the dirent within a page: fill 'er up...
772  */
773 static 
774 int nfs_do_filldir(nfs_readdir_descriptor_t *desc)
775 {
776         struct file     *file = desc->file;
777         int i = 0;
778         int res = 0;
779         struct nfs_cache_array *array = NULL;
780         struct nfs_open_dir_context *ctx = file->private_data;
781
782         array = nfs_readdir_get_array(desc->page);
783         if (IS_ERR(array)) {
784                 res = PTR_ERR(array);
785                 goto out;
786         }
787
788         for (i = desc->cache_entry_index; i < array->size; i++) {
789                 struct nfs_cache_array_entry *ent;
790
791                 ent = &array->array[i];
792                 if (!dir_emit(desc->ctx, ent->string.name, ent->string.len,
793                     nfs_compat_user_ino64(ent->ino), ent->d_type)) {
794                         desc->eof = 1;
795                         break;
796                 }
797                 desc->ctx->pos++;
798                 if (i < (array->size-1))
799                         *desc->dir_cookie = array->array[i+1].cookie;
800                 else
801                         *desc->dir_cookie = array->last_cookie;
802                 if (ctx->duped != 0)
803                         ctx->duped = 1;
804         }
805         if (array->eof_index >= 0)
806                 desc->eof = 1;
807
808         nfs_readdir_release_array(desc->page);
809 out:
810         cache_page_release(desc);
811         dfprintk(DIRCACHE, "NFS: nfs_do_filldir() filling ended @ cookie %Lu; returning = %d\n",
812                         (unsigned long long)*desc->dir_cookie, res);
813         return res;
814 }
815
816 /*
817  * If we cannot find a cookie in our cache, we suspect that this is
818  * because it points to a deleted file, so we ask the server to return
819  * whatever it thinks is the next entry. We then feed this to filldir.
820  * If all goes well, we should then be able to find our way round the
821  * cache on the next call to readdir_search_pagecache();
822  *
823  * NOTE: we cannot add the anonymous page to the pagecache because
824  *       the data it contains might not be page aligned. Besides,
825  *       we should already have a complete representation of the
826  *       directory in the page cache by the time we get here.
827  */
828 static inline
829 int uncached_readdir(nfs_readdir_descriptor_t *desc)
830 {
831         struct page     *page = NULL;
832         int             status;
833         struct inode *inode = file_inode(desc->file);
834         struct nfs_open_dir_context *ctx = desc->file->private_data;
835
836         dfprintk(DIRCACHE, "NFS: uncached_readdir() searching for cookie %Lu\n",
837                         (unsigned long long)*desc->dir_cookie);
838
839         page = alloc_page(GFP_HIGHUSER);
840         if (!page) {
841                 status = -ENOMEM;
842                 goto out;
843         }
844
845         desc->page_index = 0;
846         desc->last_cookie = *desc->dir_cookie;
847         desc->page = page;
848         ctx->duped = 0;
849
850         status = nfs_readdir_xdr_to_array(desc, page, inode);
851         if (status < 0)
852                 goto out_release;
853
854         status = nfs_do_filldir(desc);
855
856  out:
857         dfprintk(DIRCACHE, "NFS: %s: returns %d\n",
858                         __func__, status);
859         return status;
860  out_release:
861         cache_page_release(desc);
862         goto out;
863 }
864
865 /* The file offset position represents the dirent entry number.  A
866    last cookie cache takes care of the common case of reading the
867    whole directory.
868  */
869 static int nfs_readdir(struct file *file, struct dir_context *ctx)
870 {
871         struct dentry   *dentry = file_dentry(file);
872         struct inode    *inode = d_inode(dentry);
873         nfs_readdir_descriptor_t my_desc,
874                         *desc = &my_desc;
875         struct nfs_open_dir_context *dir_ctx = file->private_data;
876         int res = 0;
877
878         dfprintk(FILE, "NFS: readdir(%pD2) starting at cookie %llu\n",
879                         file, (long long)ctx->pos);
880         nfs_inc_stats(inode, NFSIOS_VFSGETDENTS);
881
882         /*
883          * ctx->pos points to the dirent entry number.
884          * *desc->dir_cookie has the cookie for the next entry. We have
885          * to either find the entry with the appropriate number or
886          * revalidate the cookie.
887          */
888         memset(desc, 0, sizeof(*desc));
889
890         desc->file = file;
891         desc->ctx = ctx;
892         desc->dir_cookie = &dir_ctx->dir_cookie;
893         desc->decode = NFS_PROTO(inode)->decode_dirent;
894         desc->plus = nfs_use_readdirplus(inode, ctx) ? 1 : 0;
895
896         nfs_block_sillyrename(dentry);
897         if (ctx->pos == 0 || nfs_attribute_cache_expired(inode))
898                 res = nfs_revalidate_mapping(inode, file->f_mapping);
899         if (res < 0)
900                 goto out;
901
902         do {
903                 res = readdir_search_pagecache(desc);
904
905                 if (res == -EBADCOOKIE) {
906                         res = 0;
907                         /* This means either end of directory */
908                         if (*desc->dir_cookie && desc->eof == 0) {
909                                 /* Or that the server has 'lost' a cookie */
910                                 res = uncached_readdir(desc);
911                                 if (res == 0)
912                                         continue;
913                         }
914                         break;
915                 }
916                 if (res == -ETOOSMALL && desc->plus) {
917                         clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(inode)->flags);
918                         nfs_zap_caches(inode);
919                         desc->page_index = 0;
920                         desc->plus = 0;
921                         desc->eof = 0;
922                         continue;
923                 }
924                 if (res < 0)
925                         break;
926
927                 res = nfs_do_filldir(desc);
928                 if (res < 0)
929                         break;
930         } while (!desc->eof);
931 out:
932         nfs_unblock_sillyrename(dentry);
933         if (res > 0)
934                 res = 0;
935         dfprintk(FILE, "NFS: readdir(%pD2) returns %d\n", file, res);
936         return res;
937 }
938
939 static loff_t nfs_llseek_dir(struct file *filp, loff_t offset, int whence)
940 {
941         struct inode *inode = file_inode(filp);
942         struct nfs_open_dir_context *dir_ctx = filp->private_data;
943
944         dfprintk(FILE, "NFS: llseek dir(%pD2, %lld, %d)\n",
945                         filp, offset, whence);
946
947         mutex_lock(&inode->i_mutex);
948         switch (whence) {
949                 case 1:
950                         offset += filp->f_pos;
951                 case 0:
952                         if (offset >= 0)
953                                 break;
954                 default:
955                         offset = -EINVAL;
956                         goto out;
957         }
958         if (offset != filp->f_pos) {
959                 filp->f_pos = offset;
960                 dir_ctx->dir_cookie = 0;
961                 dir_ctx->duped = 0;
962         }
963 out:
964         mutex_unlock(&inode->i_mutex);
965         return offset;
966 }
967
968 /*
969  * All directory operations under NFS are synchronous, so fsync()
970  * is a dummy operation.
971  */
972 static int nfs_fsync_dir(struct file *filp, loff_t start, loff_t end,
973                          int datasync)
974 {
975         struct inode *inode = file_inode(filp);
976
977         dfprintk(FILE, "NFS: fsync dir(%pD2) datasync %d\n", filp, datasync);
978
979         mutex_lock(&inode->i_mutex);
980         nfs_inc_stats(inode, NFSIOS_VFSFSYNC);
981         mutex_unlock(&inode->i_mutex);
982         return 0;
983 }
984
985 /**
986  * nfs_force_lookup_revalidate - Mark the directory as having changed
987  * @dir - pointer to directory inode
988  *
989  * This forces the revalidation code in nfs_lookup_revalidate() to do a
990  * full lookup on all child dentries of 'dir' whenever a change occurs
991  * on the server that might have invalidated our dcache.
992  *
993  * The caller should be holding dir->i_lock
994  */
995 void nfs_force_lookup_revalidate(struct inode *dir)
996 {
997         NFS_I(dir)->cache_change_attribute++;
998 }
999 EXPORT_SYMBOL_GPL(nfs_force_lookup_revalidate);
1000
1001 /*
1002  * A check for whether or not the parent directory has changed.
1003  * In the case it has, we assume that the dentries are untrustworthy
1004  * and may need to be looked up again.
1005  * If rcu_walk prevents us from performing a full check, return 0.
1006  */
1007 static int nfs_check_verifier(struct inode *dir, struct dentry *dentry,
1008                               int rcu_walk)
1009 {
1010         int ret;
1011
1012         if (IS_ROOT(dentry))
1013                 return 1;
1014         if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONE)
1015                 return 0;
1016         if (!nfs_verify_change_attribute(dir, dentry->d_time))
1017                 return 0;
1018         /* Revalidate nfsi->cache_change_attribute before we declare a match */
1019         if (rcu_walk)
1020                 ret = nfs_revalidate_inode_rcu(NFS_SERVER(dir), dir);
1021         else
1022                 ret = nfs_revalidate_inode(NFS_SERVER(dir), dir);
1023         if (ret < 0)
1024                 return 0;
1025         if (!nfs_verify_change_attribute(dir, dentry->d_time))
1026                 return 0;
1027         return 1;
1028 }
1029
1030 /*
1031  * Use intent information to check whether or not we're going to do
1032  * an O_EXCL create using this path component.
1033  */
1034 static int nfs_is_exclusive_create(struct inode *dir, unsigned int flags)
1035 {
1036         if (NFS_PROTO(dir)->version == 2)
1037                 return 0;
1038         return flags & LOOKUP_EXCL;
1039 }
1040
1041 /*
1042  * Inode and filehandle revalidation for lookups.
1043  *
1044  * We force revalidation in the cases where the VFS sets LOOKUP_REVAL,
1045  * or if the intent information indicates that we're about to open this
1046  * particular file and the "nocto" mount flag is not set.
1047  *
1048  */
1049 static
1050 int nfs_lookup_verify_inode(struct inode *inode, unsigned int flags)
1051 {
1052         struct nfs_server *server = NFS_SERVER(inode);
1053         int ret;
1054
1055         if (IS_AUTOMOUNT(inode))
1056                 return 0;
1057         /* VFS wants an on-the-wire revalidation */
1058         if (flags & LOOKUP_REVAL)
1059                 goto out_force;
1060         /* This is an open(2) */
1061         if ((flags & LOOKUP_OPEN) && !(server->flags & NFS_MOUNT_NOCTO) &&
1062             (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)))
1063                 goto out_force;
1064 out:
1065         return (inode->i_nlink == 0) ? -ENOENT : 0;
1066 out_force:
1067         if (flags & LOOKUP_RCU)
1068                 return -ECHILD;
1069         ret = __nfs_revalidate_inode(server, inode);
1070         if (ret != 0)
1071                 return ret;
1072         goto out;
1073 }
1074
1075 /*
1076  * We judge how long we want to trust negative
1077  * dentries by looking at the parent inode mtime.
1078  *
1079  * If parent mtime has changed, we revalidate, else we wait for a
1080  * period corresponding to the parent's attribute cache timeout value.
1081  *
1082  * If LOOKUP_RCU prevents us from performing a full check, return 1
1083  * suggesting a reval is needed.
1084  */
1085 static inline
1086 int nfs_neg_need_reval(struct inode *dir, struct dentry *dentry,
1087                        unsigned int flags)
1088 {
1089         /* Don't revalidate a negative dentry if we're creating a new file */
1090         if (flags & LOOKUP_CREATE)
1091                 return 0;
1092         if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONEG)
1093                 return 1;
1094         return !nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU);
1095 }
1096
1097 /*
1098  * This is called every time the dcache has a lookup hit,
1099  * and we should check whether we can really trust that
1100  * lookup.
1101  *
1102  * NOTE! The hit can be a negative hit too, don't assume
1103  * we have an inode!
1104  *
1105  * If the parent directory is seen to have changed, we throw out the
1106  * cached dentry and do a new lookup.
1107  */
1108 static int nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1109 {
1110         struct inode *dir;
1111         struct inode *inode;
1112         struct dentry *parent;
1113         struct nfs_fh *fhandle = NULL;
1114         struct nfs_fattr *fattr = NULL;
1115         struct nfs4_label *label = NULL;
1116         int error;
1117
1118         if (flags & LOOKUP_RCU) {
1119                 parent = ACCESS_ONCE(dentry->d_parent);
1120                 dir = d_inode_rcu(parent);
1121                 if (!dir)
1122                         return -ECHILD;
1123         } else {
1124                 parent = dget_parent(dentry);
1125                 dir = d_inode(parent);
1126         }
1127         nfs_inc_stats(dir, NFSIOS_DENTRYREVALIDATE);
1128         inode = d_inode(dentry);
1129
1130         if (!inode) {
1131                 if (nfs_neg_need_reval(dir, dentry, flags)) {
1132                         if (flags & LOOKUP_RCU)
1133                                 return -ECHILD;
1134                         goto out_bad;
1135                 }
1136                 goto out_valid_noent;
1137         }
1138
1139         if (is_bad_inode(inode)) {
1140                 if (flags & LOOKUP_RCU)
1141                         return -ECHILD;
1142                 dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1143                                 __func__, dentry);
1144                 goto out_bad;
1145         }
1146
1147         if (NFS_PROTO(dir)->have_delegation(inode, FMODE_READ))
1148                 goto out_set_verifier;
1149
1150         /* Force a full look up iff the parent directory has changed */
1151         if (!nfs_is_exclusive_create(dir, flags) &&
1152             nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU)) {
1153                 error = nfs_lookup_verify_inode(inode, flags);
1154                 if (error) {
1155                         if (flags & LOOKUP_RCU)
1156                                 return -ECHILD;
1157                         if (error == -ESTALE)
1158                                 goto out_zap_parent;
1159                         goto out_error;
1160                 }
1161                 goto out_valid;
1162         }
1163
1164         if (flags & LOOKUP_RCU)
1165                 return -ECHILD;
1166
1167         if (NFS_STALE(inode))
1168                 goto out_bad;
1169
1170         error = -ENOMEM;
1171         fhandle = nfs_alloc_fhandle();
1172         fattr = nfs_alloc_fattr();
1173         if (fhandle == NULL || fattr == NULL)
1174                 goto out_error;
1175
1176         label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
1177         if (IS_ERR(label))
1178                 goto out_error;
1179
1180         trace_nfs_lookup_revalidate_enter(dir, dentry, flags);
1181         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1182         trace_nfs_lookup_revalidate_exit(dir, dentry, flags, error);
1183         if (error == -ESTALE || error == -ENOENT)
1184                 goto out_bad;
1185         if (error)
1186                 goto out_error;
1187         if (nfs_compare_fh(NFS_FH(inode), fhandle))
1188                 goto out_bad;
1189         if ((error = nfs_refresh_inode(inode, fattr)) != 0)
1190                 goto out_bad;
1191
1192         nfs_setsecurity(inode, fattr, label);
1193
1194         nfs_free_fattr(fattr);
1195         nfs_free_fhandle(fhandle);
1196         nfs4_label_free(label);
1197
1198 out_set_verifier:
1199         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1200  out_valid:
1201         /* Success: notify readdir to use READDIRPLUS */
1202         nfs_advise_use_readdirplus(dir);
1203  out_valid_noent:
1204         if (flags & LOOKUP_RCU) {
1205                 if (parent != ACCESS_ONCE(dentry->d_parent))
1206                         return -ECHILD;
1207         } else
1208                 dput(parent);
1209         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is valid\n",
1210                         __func__, dentry);
1211         return 1;
1212 out_zap_parent:
1213         nfs_zap_caches(dir);
1214  out_bad:
1215         WARN_ON(flags & LOOKUP_RCU);
1216         nfs_free_fattr(fattr);
1217         nfs_free_fhandle(fhandle);
1218         nfs4_label_free(label);
1219         nfs_mark_for_revalidate(dir);
1220         if (inode && S_ISDIR(inode->i_mode)) {
1221                 /* Purge readdir caches. */
1222                 nfs_zap_caches(inode);
1223                 /*
1224                  * We can't d_drop the root of a disconnected tree:
1225                  * its d_hash is on the s_anon list and d_drop() would hide
1226                  * it from shrink_dcache_for_unmount(), leading to busy
1227                  * inodes on unmount and further oopses.
1228                  */
1229                 if (IS_ROOT(dentry))
1230                         goto out_valid;
1231         }
1232         dput(parent);
1233         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is invalid\n",
1234                         __func__, dentry);
1235         return 0;
1236 out_error:
1237         WARN_ON(flags & LOOKUP_RCU);
1238         nfs_free_fattr(fattr);
1239         nfs_free_fhandle(fhandle);
1240         nfs4_label_free(label);
1241         dput(parent);
1242         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) lookup returned error %d\n",
1243                         __func__, dentry, error);
1244         return error;
1245 }
1246
1247 /*
1248  * A weaker form of d_revalidate for revalidating just the d_inode(dentry)
1249  * when we don't really care about the dentry name. This is called when a
1250  * pathwalk ends on a dentry that was not found via a normal lookup in the
1251  * parent dir (e.g.: ".", "..", procfs symlinks or mountpoint traversals).
1252  *
1253  * In this situation, we just want to verify that the inode itself is OK
1254  * since the dentry might have changed on the server.
1255  */
1256 static int nfs_weak_revalidate(struct dentry *dentry, unsigned int flags)
1257 {
1258         int error;
1259         struct inode *inode = d_inode(dentry);
1260
1261         /*
1262          * I believe we can only get a negative dentry here in the case of a
1263          * procfs-style symlink. Just assume it's correct for now, but we may
1264          * eventually need to do something more here.
1265          */
1266         if (!inode) {
1267                 dfprintk(LOOKUPCACHE, "%s: %pd2 has negative inode\n",
1268                                 __func__, dentry);
1269                 return 1;
1270         }
1271
1272         if (is_bad_inode(inode)) {
1273                 dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1274                                 __func__, dentry);
1275                 return 0;
1276         }
1277
1278         error = nfs_lookup_verify_inode(inode, flags);
1279         dfprintk(LOOKUPCACHE, "NFS: %s: inode %lu is %s\n",
1280                         __func__, inode->i_ino, error ? "invalid" : "valid");
1281         return !error;
1282 }
1283
1284 /*
1285  * This is called from dput() when d_count is going to 0.
1286  */
1287 static int nfs_dentry_delete(const struct dentry *dentry)
1288 {
1289         dfprintk(VFS, "NFS: dentry_delete(%pd2, %x)\n",
1290                 dentry, dentry->d_flags);
1291
1292         /* Unhash any dentry with a stale inode */
1293         if (d_really_is_positive(dentry) && NFS_STALE(d_inode(dentry)))
1294                 return 1;
1295
1296         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1297                 /* Unhash it, so that ->d_iput() would be called */
1298                 return 1;
1299         }
1300         if (!(dentry->d_sb->s_flags & MS_ACTIVE)) {
1301                 /* Unhash it, so that ancestors of killed async unlink
1302                  * files will be cleaned up during umount */
1303                 return 1;
1304         }
1305         return 0;
1306
1307 }
1308
1309 /* Ensure that we revalidate inode->i_nlink */
1310 static void nfs_drop_nlink(struct inode *inode)
1311 {
1312         spin_lock(&inode->i_lock);
1313         /* drop the inode if we're reasonably sure this is the last link */
1314         if (inode->i_nlink == 1)
1315                 clear_nlink(inode);
1316         NFS_I(inode)->cache_validity |= NFS_INO_INVALID_ATTR;
1317         spin_unlock(&inode->i_lock);
1318 }
1319
1320 /*
1321  * Called when the dentry loses inode.
1322  * We use it to clean up silly-renamed files.
1323  */
1324 static void nfs_dentry_iput(struct dentry *dentry, struct inode *inode)
1325 {
1326         if (S_ISDIR(inode->i_mode))
1327                 /* drop any readdir cache as it could easily be old */
1328                 NFS_I(inode)->cache_validity |= NFS_INO_INVALID_DATA;
1329
1330         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1331                 nfs_complete_unlink(dentry, inode);
1332                 nfs_drop_nlink(inode);
1333         }
1334         iput(inode);
1335 }
1336
1337 static void nfs_d_release(struct dentry *dentry)
1338 {
1339         /* free cached devname value, if it survived that far */
1340         if (unlikely(dentry->d_fsdata)) {
1341                 if (dentry->d_flags & DCACHE_NFSFS_RENAMED)
1342                         WARN_ON(1);
1343                 else
1344                         kfree(dentry->d_fsdata);
1345         }
1346 }
1347
1348 const struct dentry_operations nfs_dentry_operations = {
1349         .d_revalidate   = nfs_lookup_revalidate,
1350         .d_weak_revalidate      = nfs_weak_revalidate,
1351         .d_delete       = nfs_dentry_delete,
1352         .d_iput         = nfs_dentry_iput,
1353         .d_automount    = nfs_d_automount,
1354         .d_release      = nfs_d_release,
1355 };
1356 EXPORT_SYMBOL_GPL(nfs_dentry_operations);
1357
1358 struct dentry *nfs_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
1359 {
1360         struct dentry *res;
1361         struct dentry *parent;
1362         struct inode *inode = NULL;
1363         struct nfs_fh *fhandle = NULL;
1364         struct nfs_fattr *fattr = NULL;
1365         struct nfs4_label *label = NULL;
1366         int error;
1367
1368         dfprintk(VFS, "NFS: lookup(%pd2)\n", dentry);
1369         nfs_inc_stats(dir, NFSIOS_VFSLOOKUP);
1370
1371         res = ERR_PTR(-ENAMETOOLONG);
1372         if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1373                 goto out;
1374
1375         /*
1376          * If we're doing an exclusive create, optimize away the lookup
1377          * but don't hash the dentry.
1378          */
1379         if (nfs_is_exclusive_create(dir, flags)) {
1380                 d_instantiate(dentry, NULL);
1381                 res = NULL;
1382                 goto out;
1383         }
1384
1385         res = ERR_PTR(-ENOMEM);
1386         fhandle = nfs_alloc_fhandle();
1387         fattr = nfs_alloc_fattr();
1388         if (fhandle == NULL || fattr == NULL)
1389                 goto out;
1390
1391         label = nfs4_label_alloc(NFS_SERVER(dir), GFP_NOWAIT);
1392         if (IS_ERR(label))
1393                 goto out;
1394
1395         parent = dentry->d_parent;
1396         /* Protect against concurrent sillydeletes */
1397         trace_nfs_lookup_enter(dir, dentry, flags);
1398         nfs_block_sillyrename(parent);
1399         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1400         if (error == -ENOENT)
1401                 goto no_entry;
1402         if (error < 0) {
1403                 res = ERR_PTR(error);
1404                 goto out_unblock_sillyrename;
1405         }
1406         inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1407         res = ERR_CAST(inode);
1408         if (IS_ERR(res))
1409                 goto out_unblock_sillyrename;
1410
1411         /* Success: notify readdir to use READDIRPLUS */
1412         nfs_advise_use_readdirplus(dir);
1413
1414 no_entry:
1415         res = d_splice_alias(inode, dentry);
1416         if (res != NULL) {
1417                 if (IS_ERR(res))
1418                         goto out_unblock_sillyrename;
1419                 dentry = res;
1420         }
1421         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1422 out_unblock_sillyrename:
1423         nfs_unblock_sillyrename(parent);
1424         trace_nfs_lookup_exit(dir, dentry, flags, error);
1425         nfs4_label_free(label);
1426 out:
1427         nfs_free_fattr(fattr);
1428         nfs_free_fhandle(fhandle);
1429         return res;
1430 }
1431 EXPORT_SYMBOL_GPL(nfs_lookup);
1432
1433 #if IS_ENABLED(CONFIG_NFS_V4)
1434 static int nfs4_lookup_revalidate(struct dentry *, unsigned int);
1435
1436 const struct dentry_operations nfs4_dentry_operations = {
1437         .d_revalidate   = nfs4_lookup_revalidate,
1438         .d_weak_revalidate      = nfs_weak_revalidate,
1439         .d_delete       = nfs_dentry_delete,
1440         .d_iput         = nfs_dentry_iput,
1441         .d_automount    = nfs_d_automount,
1442         .d_release      = nfs_d_release,
1443 };
1444 EXPORT_SYMBOL_GPL(nfs4_dentry_operations);
1445
1446 static fmode_t flags_to_mode(int flags)
1447 {
1448         fmode_t res = (__force fmode_t)flags & FMODE_EXEC;
1449         if ((flags & O_ACCMODE) != O_WRONLY)
1450                 res |= FMODE_READ;
1451         if ((flags & O_ACCMODE) != O_RDONLY)
1452                 res |= FMODE_WRITE;
1453         return res;
1454 }
1455
1456 static struct nfs_open_context *create_nfs_open_context(struct dentry *dentry, int open_flags)
1457 {
1458         return alloc_nfs_open_context(dentry, flags_to_mode(open_flags));
1459 }
1460
1461 static int do_open(struct inode *inode, struct file *filp)
1462 {
1463         nfs_fscache_open_file(inode, filp);
1464         return 0;
1465 }
1466
1467 static int nfs_finish_open(struct nfs_open_context *ctx,
1468                            struct dentry *dentry,
1469                            struct file *file, unsigned open_flags,
1470                            int *opened)
1471 {
1472         int err;
1473
1474         err = finish_open(file, dentry, do_open, opened);
1475         if (err)
1476                 goto out;
1477         nfs_file_set_open_context(file, ctx);
1478
1479 out:
1480         return err;
1481 }
1482
1483 int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
1484                     struct file *file, unsigned open_flags,
1485                     umode_t mode, int *opened)
1486 {
1487         struct nfs_open_context *ctx;
1488         struct dentry *res;
1489         struct iattr attr = { .ia_valid = ATTR_OPEN };
1490         struct inode *inode;
1491         unsigned int lookup_flags = 0;
1492         int err;
1493
1494         /* Expect a negative dentry */
1495         BUG_ON(d_inode(dentry));
1496
1497         dfprintk(VFS, "NFS: atomic_open(%s/%lu), %pd\n",
1498                         dir->i_sb->s_id, dir->i_ino, dentry);
1499
1500         err = nfs_check_flags(open_flags);
1501         if (err)
1502                 return err;
1503
1504         /* NFS only supports OPEN on regular files */
1505         if ((open_flags & O_DIRECTORY)) {
1506                 if (!d_unhashed(dentry)) {
1507                         /*
1508                          * Hashed negative dentry with O_DIRECTORY: dentry was
1509                          * revalidated and is fine, no need to perform lookup
1510                          * again
1511                          */
1512                         return -ENOENT;
1513                 }
1514                 lookup_flags = LOOKUP_OPEN|LOOKUP_DIRECTORY;
1515                 goto no_open;
1516         }
1517
1518         if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1519                 return -ENAMETOOLONG;
1520
1521         if (open_flags & O_CREAT) {
1522                 attr.ia_valid |= ATTR_MODE;
1523                 attr.ia_mode = mode & ~current_umask();
1524         }
1525         if (open_flags & O_TRUNC) {
1526                 attr.ia_valid |= ATTR_SIZE;
1527                 attr.ia_size = 0;
1528         }
1529
1530         ctx = create_nfs_open_context(dentry, open_flags);
1531         err = PTR_ERR(ctx);
1532         if (IS_ERR(ctx))
1533                 goto out;
1534
1535         trace_nfs_atomic_open_enter(dir, ctx, open_flags);
1536         nfs_block_sillyrename(dentry->d_parent);
1537         inode = NFS_PROTO(dir)->open_context(dir, ctx, open_flags, &attr, opened);
1538         nfs_unblock_sillyrename(dentry->d_parent);
1539         if (IS_ERR(inode)) {
1540                 err = PTR_ERR(inode);
1541                 trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1542                 put_nfs_open_context(ctx);
1543                 d_drop(dentry);
1544                 switch (err) {
1545                 case -ENOENT:
1546                         d_add(dentry, NULL);
1547                         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1548                         break;
1549                 case -EISDIR:
1550                 case -ENOTDIR:
1551                         goto no_open;
1552                 case -ELOOP:
1553                         if (!(open_flags & O_NOFOLLOW))
1554                                 goto no_open;
1555                         break;
1556                         /* case -EINVAL: */
1557                 default:
1558                         break;
1559                 }
1560                 goto out;
1561         }
1562
1563         err = nfs_finish_open(ctx, ctx->dentry, file, open_flags, opened);
1564         trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1565         put_nfs_open_context(ctx);
1566 out:
1567         return err;
1568
1569 no_open:
1570         res = nfs_lookup(dir, dentry, lookup_flags);
1571         err = PTR_ERR(res);
1572         if (IS_ERR(res))
1573                 goto out;
1574
1575         return finish_no_open(file, res);
1576 }
1577 EXPORT_SYMBOL_GPL(nfs_atomic_open);
1578
1579 static int nfs4_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1580 {
1581         struct inode *inode;
1582         int ret = 0;
1583
1584         if (!(flags & LOOKUP_OPEN) || (flags & LOOKUP_DIRECTORY))
1585                 goto no_open;
1586         if (d_mountpoint(dentry))
1587                 goto no_open;
1588         if (NFS_SB(dentry->d_sb)->caps & NFS_CAP_ATOMIC_OPEN_V1)
1589                 goto no_open;
1590
1591         inode = d_inode(dentry);
1592
1593         /* We can't create new files in nfs_open_revalidate(), so we
1594          * optimize away revalidation of negative dentries.
1595          */
1596         if (inode == NULL) {
1597                 struct dentry *parent;
1598                 struct inode *dir;
1599
1600                 if (flags & LOOKUP_RCU) {
1601                         parent = ACCESS_ONCE(dentry->d_parent);
1602                         dir = d_inode_rcu(parent);
1603                         if (!dir)
1604                                 return -ECHILD;
1605                 } else {
1606                         parent = dget_parent(dentry);
1607                         dir = d_inode(parent);
1608                 }
1609                 if (!nfs_neg_need_reval(dir, dentry, flags))
1610                         ret = 1;
1611                 else if (flags & LOOKUP_RCU)
1612                         ret = -ECHILD;
1613                 if (!(flags & LOOKUP_RCU))
1614                         dput(parent);
1615                 else if (parent != ACCESS_ONCE(dentry->d_parent))
1616                         return -ECHILD;
1617                 goto out;
1618         }
1619
1620         /* NFS only supports OPEN on regular files */
1621         if (!S_ISREG(inode->i_mode))
1622                 goto no_open;
1623         /* We cannot do exclusive creation on a positive dentry */
1624         if (flags & LOOKUP_EXCL)
1625                 goto no_open;
1626
1627         /* Let f_op->open() actually open (and revalidate) the file */
1628         ret = 1;
1629
1630 out:
1631         return ret;
1632
1633 no_open:
1634         return nfs_lookup_revalidate(dentry, flags);
1635 }
1636
1637 #endif /* CONFIG_NFSV4 */
1638
1639 /*
1640  * Code common to create, mkdir, and mknod.
1641  */
1642 int nfs_instantiate(struct dentry *dentry, struct nfs_fh *fhandle,
1643                                 struct nfs_fattr *fattr,
1644                                 struct nfs4_label *label)
1645 {
1646         struct dentry *parent = dget_parent(dentry);
1647         struct inode *dir = d_inode(parent);
1648         struct inode *inode;
1649         int error = -EACCES;
1650
1651         d_drop(dentry);
1652
1653         /* We may have been initialized further down */
1654         if (d_really_is_positive(dentry))
1655                 goto out;
1656         if (fhandle->size == 0) {
1657                 error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, NULL);
1658                 if (error)
1659                         goto out_error;
1660         }
1661         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1662         if (!(fattr->valid & NFS_ATTR_FATTR)) {
1663                 struct nfs_server *server = NFS_SB(dentry->d_sb);
1664                 error = server->nfs_client->rpc_ops->getattr(server, fhandle, fattr, NULL);
1665                 if (error < 0)
1666                         goto out_error;
1667         }
1668         inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1669         error = PTR_ERR(inode);
1670         if (IS_ERR(inode))
1671                 goto out_error;
1672         d_add(dentry, inode);
1673 out:
1674         dput(parent);
1675         return 0;
1676 out_error:
1677         nfs_mark_for_revalidate(dir);
1678         dput(parent);
1679         return error;
1680 }
1681 EXPORT_SYMBOL_GPL(nfs_instantiate);
1682
1683 /*
1684  * Following a failed create operation, we drop the dentry rather
1685  * than retain a negative dentry. This avoids a problem in the event
1686  * that the operation succeeded on the server, but an error in the
1687  * reply path made it appear to have failed.
1688  */
1689 int nfs_create(struct inode *dir, struct dentry *dentry,
1690                 umode_t mode, bool excl)
1691 {
1692         struct iattr attr;
1693         int open_flags = excl ? O_CREAT | O_EXCL : O_CREAT;
1694         int error;
1695
1696         dfprintk(VFS, "NFS: create(%s/%lu), %pd\n",
1697                         dir->i_sb->s_id, dir->i_ino, dentry);
1698
1699         attr.ia_mode = mode;
1700         attr.ia_valid = ATTR_MODE;
1701
1702         trace_nfs_create_enter(dir, dentry, open_flags);
1703         error = NFS_PROTO(dir)->create(dir, dentry, &attr, open_flags);
1704         trace_nfs_create_exit(dir, dentry, open_flags, error);
1705         if (error != 0)
1706                 goto out_err;
1707         return 0;
1708 out_err:
1709         d_drop(dentry);
1710         return error;
1711 }
1712 EXPORT_SYMBOL_GPL(nfs_create);
1713
1714 /*
1715  * See comments for nfs_proc_create regarding failed operations.
1716  */
1717 int
1718 nfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev)
1719 {
1720         struct iattr attr;
1721         int status;
1722
1723         dfprintk(VFS, "NFS: mknod(%s/%lu), %pd\n",
1724                         dir->i_sb->s_id, dir->i_ino, dentry);
1725
1726         attr.ia_mode = mode;
1727         attr.ia_valid = ATTR_MODE;
1728
1729         trace_nfs_mknod_enter(dir, dentry);
1730         status = NFS_PROTO(dir)->mknod(dir, dentry, &attr, rdev);
1731         trace_nfs_mknod_exit(dir, dentry, status);
1732         if (status != 0)
1733                 goto out_err;
1734         return 0;
1735 out_err:
1736         d_drop(dentry);
1737         return status;
1738 }
1739 EXPORT_SYMBOL_GPL(nfs_mknod);
1740
1741 /*
1742  * See comments for nfs_proc_create regarding failed operations.
1743  */
1744 int nfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
1745 {
1746         struct iattr attr;
1747         int error;
1748
1749         dfprintk(VFS, "NFS: mkdir(%s/%lu), %pd\n",
1750                         dir->i_sb->s_id, dir->i_ino, dentry);
1751
1752         attr.ia_valid = ATTR_MODE;
1753         attr.ia_mode = mode | S_IFDIR;
1754
1755         trace_nfs_mkdir_enter(dir, dentry);
1756         error = NFS_PROTO(dir)->mkdir(dir, dentry, &attr);
1757         trace_nfs_mkdir_exit(dir, dentry, error);
1758         if (error != 0)
1759                 goto out_err;
1760         return 0;
1761 out_err:
1762         d_drop(dentry);
1763         return error;
1764 }
1765 EXPORT_SYMBOL_GPL(nfs_mkdir);
1766
1767 static void nfs_dentry_handle_enoent(struct dentry *dentry)
1768 {
1769         if (simple_positive(dentry))
1770                 d_delete(dentry);
1771 }
1772
1773 int nfs_rmdir(struct inode *dir, struct dentry *dentry)
1774 {
1775         int error;
1776
1777         dfprintk(VFS, "NFS: rmdir(%s/%lu), %pd\n",
1778                         dir->i_sb->s_id, dir->i_ino, dentry);
1779
1780         trace_nfs_rmdir_enter(dir, dentry);
1781         if (d_really_is_positive(dentry)) {
1782                 nfs_wait_on_sillyrename(dentry);
1783                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1784                 /* Ensure the VFS deletes this inode */
1785                 switch (error) {
1786                 case 0:
1787                         clear_nlink(d_inode(dentry));
1788                         break;
1789                 case -ENOENT:
1790                         nfs_dentry_handle_enoent(dentry);
1791                 }
1792         } else
1793                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1794         trace_nfs_rmdir_exit(dir, dentry, error);
1795
1796         return error;
1797 }
1798 EXPORT_SYMBOL_GPL(nfs_rmdir);
1799
1800 /*
1801  * Remove a file after making sure there are no pending writes,
1802  * and after checking that the file has only one user. 
1803  *
1804  * We invalidate the attribute cache and free the inode prior to the operation
1805  * to avoid possible races if the server reuses the inode.
1806  */
1807 static int nfs_safe_remove(struct dentry *dentry)
1808 {
1809         struct inode *dir = d_inode(dentry->d_parent);
1810         struct inode *inode = d_inode(dentry);
1811         int error = -EBUSY;
1812                 
1813         dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry);
1814
1815         /* If the dentry was sillyrenamed, we simply call d_delete() */
1816         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1817                 error = 0;
1818                 goto out;
1819         }
1820
1821         trace_nfs_remove_enter(dir, dentry);
1822         if (inode != NULL) {
1823                 NFS_PROTO(inode)->return_delegation(inode);
1824                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1825                 if (error == 0)
1826                         nfs_drop_nlink(inode);
1827         } else
1828                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1829         if (error == -ENOENT)
1830                 nfs_dentry_handle_enoent(dentry);
1831         trace_nfs_remove_exit(dir, dentry, error);
1832 out:
1833         return error;
1834 }
1835
1836 /*  We do silly rename. In case sillyrename() returns -EBUSY, the inode
1837  *  belongs to an active ".nfs..." file and we return -EBUSY.
1838  *
1839  *  If sillyrename() returns 0, we do nothing, otherwise we unlink.
1840  */
1841 int nfs_unlink(struct inode *dir, struct dentry *dentry)
1842 {
1843         int error;
1844         int need_rehash = 0;
1845
1846         dfprintk(VFS, "NFS: unlink(%s/%lu, %pd)\n", dir->i_sb->s_id,
1847                 dir->i_ino, dentry);
1848
1849         trace_nfs_unlink_enter(dir, dentry);
1850         spin_lock(&dentry->d_lock);
1851         if (d_count(dentry) > 1) {
1852                 spin_unlock(&dentry->d_lock);
1853                 /* Start asynchronous writeout of the inode */
1854                 write_inode_now(d_inode(dentry), 0);
1855                 error = nfs_sillyrename(dir, dentry);
1856                 goto out;
1857         }
1858         if (!d_unhashed(dentry)) {
1859                 __d_drop(dentry);
1860                 need_rehash = 1;
1861         }
1862         spin_unlock(&dentry->d_lock);
1863         error = nfs_safe_remove(dentry);
1864         if (!error || error == -ENOENT) {
1865                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1866         } else if (need_rehash)
1867                 d_rehash(dentry);
1868 out:
1869         trace_nfs_unlink_exit(dir, dentry, error);
1870         return error;
1871 }
1872 EXPORT_SYMBOL_GPL(nfs_unlink);
1873
1874 /*
1875  * To create a symbolic link, most file systems instantiate a new inode,
1876  * add a page to it containing the path, then write it out to the disk
1877  * using prepare_write/commit_write.
1878  *
1879  * Unfortunately the NFS client can't create the in-core inode first
1880  * because it needs a file handle to create an in-core inode (see
1881  * fs/nfs/inode.c:nfs_fhget).  We only have a file handle *after* the
1882  * symlink request has completed on the server.
1883  *
1884  * So instead we allocate a raw page, copy the symname into it, then do
1885  * the SYMLINK request with the page as the buffer.  If it succeeds, we
1886  * now have a new file handle and can instantiate an in-core NFS inode
1887  * and move the raw page into its mapping.
1888  */
1889 int nfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1890 {
1891         struct page *page;
1892         char *kaddr;
1893         struct iattr attr;
1894         unsigned int pathlen = strlen(symname);
1895         int error;
1896
1897         dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s)\n", dir->i_sb->s_id,
1898                 dir->i_ino, dentry, symname);
1899
1900         if (pathlen > PAGE_SIZE)
1901                 return -ENAMETOOLONG;
1902
1903         attr.ia_mode = S_IFLNK | S_IRWXUGO;
1904         attr.ia_valid = ATTR_MODE;
1905
1906         page = alloc_page(GFP_HIGHUSER);
1907         if (!page)
1908                 return -ENOMEM;
1909
1910         kaddr = kmap_atomic(page);
1911         memcpy(kaddr, symname, pathlen);
1912         if (pathlen < PAGE_SIZE)
1913                 memset(kaddr + pathlen, 0, PAGE_SIZE - pathlen);
1914         kunmap_atomic(kaddr);
1915
1916         trace_nfs_symlink_enter(dir, dentry);
1917         error = NFS_PROTO(dir)->symlink(dir, dentry, page, pathlen, &attr);
1918         trace_nfs_symlink_exit(dir, dentry, error);
1919         if (error != 0) {
1920                 dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s) error %d\n",
1921                         dir->i_sb->s_id, dir->i_ino,
1922                         dentry, symname, error);
1923                 d_drop(dentry);
1924                 __free_page(page);
1925                 return error;
1926         }
1927
1928         /*
1929          * No big deal if we can't add this page to the page cache here.
1930          * READLINK will get the missing page from the server if needed.
1931          */
1932         if (!add_to_page_cache_lru(page, d_inode(dentry)->i_mapping, 0,
1933                                                         GFP_KERNEL)) {
1934                 SetPageUptodate(page);
1935                 unlock_page(page);
1936                 /*
1937                  * add_to_page_cache_lru() grabs an extra page refcount.
1938                  * Drop it here to avoid leaking this page later.
1939                  */
1940                 page_cache_release(page);
1941         } else
1942                 __free_page(page);
1943
1944         return 0;
1945 }
1946 EXPORT_SYMBOL_GPL(nfs_symlink);
1947
1948 int
1949 nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
1950 {
1951         struct inode *inode = d_inode(old_dentry);
1952         int error;
1953
1954         dfprintk(VFS, "NFS: link(%pd2 -> %pd2)\n",
1955                 old_dentry, dentry);
1956
1957         trace_nfs_link_enter(inode, dir, dentry);
1958         NFS_PROTO(inode)->return_delegation(inode);
1959
1960         d_drop(dentry);
1961         error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
1962         if (error == 0) {
1963                 ihold(inode);
1964                 d_add(dentry, inode);
1965         }
1966         trace_nfs_link_exit(inode, dir, dentry, error);
1967         return error;
1968 }
1969 EXPORT_SYMBOL_GPL(nfs_link);
1970
1971 /*
1972  * RENAME
1973  * FIXME: Some nfsds, like the Linux user space nfsd, may generate a
1974  * different file handle for the same inode after a rename (e.g. when
1975  * moving to a different directory). A fail-safe method to do so would
1976  * be to look up old_dir/old_name, create a link to new_dir/new_name and
1977  * rename the old file using the sillyrename stuff. This way, the original
1978  * file in old_dir will go away when the last process iput()s the inode.
1979  *
1980  * FIXED.
1981  * 
1982  * It actually works quite well. One needs to have the possibility for
1983  * at least one ".nfs..." file in each directory the file ever gets
1984  * moved or linked to which happens automagically with the new
1985  * implementation that only depends on the dcache stuff instead of
1986  * using the inode layer
1987  *
1988  * Unfortunately, things are a little more complicated than indicated
1989  * above. For a cross-directory move, we want to make sure we can get
1990  * rid of the old inode after the operation.  This means there must be
1991  * no pending writes (if it's a file), and the use count must be 1.
1992  * If these conditions are met, we can drop the dentries before doing
1993  * the rename.
1994  */
1995 int nfs_rename(struct inode *old_dir, struct dentry *old_dentry,
1996                       struct inode *new_dir, struct dentry *new_dentry)
1997 {
1998         struct inode *old_inode = d_inode(old_dentry);
1999         struct inode *new_inode = d_inode(new_dentry);
2000         struct dentry *dentry = NULL, *rehash = NULL;
2001         struct rpc_task *task;
2002         int error = -EBUSY;
2003
2004         dfprintk(VFS, "NFS: rename(%pd2 -> %pd2, ct=%d)\n",
2005                  old_dentry, new_dentry,
2006                  d_count(new_dentry));
2007
2008         trace_nfs_rename_enter(old_dir, old_dentry, new_dir, new_dentry);
2009         /*
2010          * For non-directories, check whether the target is busy and if so,
2011          * make a copy of the dentry and then do a silly-rename. If the
2012          * silly-rename succeeds, the copied dentry is hashed and becomes
2013          * the new target.
2014          */
2015         if (new_inode && !S_ISDIR(new_inode->i_mode)) {
2016                 /*
2017                  * To prevent any new references to the target during the
2018                  * rename, we unhash the dentry in advance.
2019                  */
2020                 if (!d_unhashed(new_dentry)) {
2021                         d_drop(new_dentry);
2022                         rehash = new_dentry;
2023                 }
2024
2025                 if (d_count(new_dentry) > 2) {
2026                         int err;
2027
2028                         /* copy the target dentry's name */
2029                         dentry = d_alloc(new_dentry->d_parent,
2030                                          &new_dentry->d_name);
2031                         if (!dentry)
2032                                 goto out;
2033
2034                         /* silly-rename the existing target ... */
2035                         err = nfs_sillyrename(new_dir, new_dentry);
2036                         if (err)
2037                                 goto out;
2038
2039                         new_dentry = dentry;
2040                         rehash = NULL;
2041                         new_inode = NULL;
2042                 }
2043         }
2044
2045         NFS_PROTO(old_inode)->return_delegation(old_inode);
2046         if (new_inode != NULL)
2047                 NFS_PROTO(new_inode)->return_delegation(new_inode);
2048
2049         task = nfs_async_rename(old_dir, new_dir, old_dentry, new_dentry, NULL);
2050         if (IS_ERR(task)) {
2051                 error = PTR_ERR(task);
2052                 goto out;
2053         }
2054
2055         error = rpc_wait_for_completion_task(task);
2056         if (error == 0)
2057                 error = task->tk_status;
2058         rpc_put_task(task);
2059         nfs_mark_for_revalidate(old_inode);
2060 out:
2061         if (rehash)
2062                 d_rehash(rehash);
2063         trace_nfs_rename_exit(old_dir, old_dentry,
2064                         new_dir, new_dentry, error);
2065         if (!error) {
2066                 if (new_inode != NULL)
2067                         nfs_drop_nlink(new_inode);
2068                 d_move(old_dentry, new_dentry);
2069                 nfs_set_verifier(old_dentry,
2070                                         nfs_save_change_attribute(new_dir));
2071         } else if (error == -ENOENT)
2072                 nfs_dentry_handle_enoent(old_dentry);
2073
2074         /* new dentry created? */
2075         if (dentry)
2076                 dput(dentry);
2077         return error;
2078 }
2079 EXPORT_SYMBOL_GPL(nfs_rename);
2080
2081 static DEFINE_SPINLOCK(nfs_access_lru_lock);
2082 static LIST_HEAD(nfs_access_lru_list);
2083 static atomic_long_t nfs_access_nr_entries;
2084
2085 static unsigned long nfs_access_max_cachesize = ULONG_MAX;
2086 module_param(nfs_access_max_cachesize, ulong, 0644);
2087 MODULE_PARM_DESC(nfs_access_max_cachesize, "NFS access maximum total cache length");
2088
2089 static void nfs_access_free_entry(struct nfs_access_entry *entry)
2090 {
2091         put_rpccred(entry->cred);
2092         kfree_rcu(entry, rcu_head);
2093         smp_mb__before_atomic();
2094         atomic_long_dec(&nfs_access_nr_entries);
2095         smp_mb__after_atomic();
2096 }
2097
2098 static void nfs_access_free_list(struct list_head *head)
2099 {
2100         struct nfs_access_entry *cache;
2101
2102         while (!list_empty(head)) {
2103                 cache = list_entry(head->next, struct nfs_access_entry, lru);
2104                 list_del(&cache->lru);
2105                 nfs_access_free_entry(cache);
2106         }
2107 }
2108
2109 static unsigned long
2110 nfs_do_access_cache_scan(unsigned int nr_to_scan)
2111 {
2112         LIST_HEAD(head);
2113         struct nfs_inode *nfsi, *next;
2114         struct nfs_access_entry *cache;
2115         long freed = 0;
2116
2117         spin_lock(&nfs_access_lru_lock);
2118         list_for_each_entry_safe(nfsi, next, &nfs_access_lru_list, access_cache_inode_lru) {
2119                 struct inode *inode;
2120
2121                 if (nr_to_scan-- == 0)
2122                         break;
2123                 inode = &nfsi->vfs_inode;
2124                 spin_lock(&inode->i_lock);
2125                 if (list_empty(&nfsi->access_cache_entry_lru))
2126                         goto remove_lru_entry;
2127                 cache = list_entry(nfsi->access_cache_entry_lru.next,
2128                                 struct nfs_access_entry, lru);
2129                 list_move(&cache->lru, &head);
2130                 rb_erase(&cache->rb_node, &nfsi->access_cache);
2131                 freed++;
2132                 if (!list_empty(&nfsi->access_cache_entry_lru))
2133                         list_move_tail(&nfsi->access_cache_inode_lru,
2134                                         &nfs_access_lru_list);
2135                 else {
2136 remove_lru_entry:
2137                         list_del_init(&nfsi->access_cache_inode_lru);
2138                         smp_mb__before_atomic();
2139                         clear_bit(NFS_INO_ACL_LRU_SET, &nfsi->flags);
2140                         smp_mb__after_atomic();
2141                 }
2142                 spin_unlock(&inode->i_lock);
2143         }
2144         spin_unlock(&nfs_access_lru_lock);
2145         nfs_access_free_list(&head);
2146         return freed;
2147 }
2148
2149 unsigned long
2150 nfs_access_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
2151 {
2152         int nr_to_scan = sc->nr_to_scan;
2153         gfp_t gfp_mask = sc->gfp_mask;
2154
2155         if ((gfp_mask & GFP_KERNEL) != GFP_KERNEL)
2156                 return SHRINK_STOP;
2157         return nfs_do_access_cache_scan(nr_to_scan);
2158 }
2159
2160
2161 unsigned long
2162 nfs_access_cache_count(struct shrinker *shrink, struct shrink_control *sc)
2163 {
2164         return vfs_pressure_ratio(atomic_long_read(&nfs_access_nr_entries));
2165 }
2166
2167 static void
2168 nfs_access_cache_enforce_limit(void)
2169 {
2170         long nr_entries = atomic_long_read(&nfs_access_nr_entries);
2171         unsigned long diff;
2172         unsigned int nr_to_scan;
2173
2174         if (nr_entries < 0 || nr_entries <= nfs_access_max_cachesize)
2175                 return;
2176         nr_to_scan = 100;
2177         diff = nr_entries - nfs_access_max_cachesize;
2178         if (diff < nr_to_scan)
2179                 nr_to_scan = diff;
2180         nfs_do_access_cache_scan(nr_to_scan);
2181 }
2182
2183 static void __nfs_access_zap_cache(struct nfs_inode *nfsi, struct list_head *head)
2184 {
2185         struct rb_root *root_node = &nfsi->access_cache;
2186         struct rb_node *n;
2187         struct nfs_access_entry *entry;
2188
2189         /* Unhook entries from the cache */
2190         while ((n = rb_first(root_node)) != NULL) {
2191                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2192                 rb_erase(n, root_node);
2193                 list_move(&entry->lru, head);
2194         }
2195         nfsi->cache_validity &= ~NFS_INO_INVALID_ACCESS;
2196 }
2197
2198 void nfs_access_zap_cache(struct inode *inode)
2199 {
2200         LIST_HEAD(head);
2201
2202         if (test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags) == 0)
2203                 return;
2204         /* Remove from global LRU init */
2205         spin_lock(&nfs_access_lru_lock);
2206         if (test_and_clear_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2207                 list_del_init(&NFS_I(inode)->access_cache_inode_lru);
2208
2209         spin_lock(&inode->i_lock);
2210         __nfs_access_zap_cache(NFS_I(inode), &head);
2211         spin_unlock(&inode->i_lock);
2212         spin_unlock(&nfs_access_lru_lock);
2213         nfs_access_free_list(&head);
2214 }
2215 EXPORT_SYMBOL_GPL(nfs_access_zap_cache);
2216
2217 static struct nfs_access_entry *nfs_access_search_rbtree(struct inode *inode, struct rpc_cred *cred)
2218 {
2219         struct rb_node *n = NFS_I(inode)->access_cache.rb_node;
2220         struct nfs_access_entry *entry;
2221
2222         while (n != NULL) {
2223                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2224
2225                 if (cred < entry->cred)
2226                         n = n->rb_left;
2227                 else if (cred > entry->cred)
2228                         n = n->rb_right;
2229                 else
2230                         return entry;
2231         }
2232         return NULL;
2233 }
2234
2235 static int nfs_access_get_cached(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2236 {
2237         struct nfs_inode *nfsi = NFS_I(inode);
2238         struct nfs_access_entry *cache;
2239         int err = -ENOENT;
2240
2241         spin_lock(&inode->i_lock);
2242         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2243                 goto out_zap;
2244         cache = nfs_access_search_rbtree(inode, cred);
2245         if (cache == NULL)
2246                 goto out;
2247         if (!nfs_have_delegated_attributes(inode) &&
2248             !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2249                 goto out_stale;
2250         res->jiffies = cache->jiffies;
2251         res->cred = cache->cred;
2252         res->mask = cache->mask;
2253         list_move_tail(&cache->lru, &nfsi->access_cache_entry_lru);
2254         err = 0;
2255 out:
2256         spin_unlock(&inode->i_lock);
2257         return err;
2258 out_stale:
2259         rb_erase(&cache->rb_node, &nfsi->access_cache);
2260         list_del(&cache->lru);
2261         spin_unlock(&inode->i_lock);
2262         nfs_access_free_entry(cache);
2263         return -ENOENT;
2264 out_zap:
2265         spin_unlock(&inode->i_lock);
2266         nfs_access_zap_cache(inode);
2267         return -ENOENT;
2268 }
2269
2270 static int nfs_access_get_cached_rcu(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2271 {
2272         /* Only check the most recently returned cache entry,
2273          * but do it without locking.
2274          */
2275         struct nfs_inode *nfsi = NFS_I(inode);
2276         struct nfs_access_entry *cache;
2277         int err = -ECHILD;
2278         struct list_head *lh;
2279
2280         rcu_read_lock();
2281         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2282                 goto out;
2283         lh = rcu_dereference(nfsi->access_cache_entry_lru.prev);
2284         cache = list_entry(lh, struct nfs_access_entry, lru);
2285         if (lh == &nfsi->access_cache_entry_lru ||
2286             cred != cache->cred)
2287                 cache = NULL;
2288         if (cache == NULL)
2289                 goto out;
2290         if (!nfs_have_delegated_attributes(inode) &&
2291             !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2292                 goto out;
2293         res->jiffies = cache->jiffies;
2294         res->cred = cache->cred;
2295         res->mask = cache->mask;
2296         err = 0;
2297 out:
2298         rcu_read_unlock();
2299         return err;
2300 }
2301
2302 static void nfs_access_add_rbtree(struct inode *inode, struct nfs_access_entry *set)
2303 {
2304         struct nfs_inode *nfsi = NFS_I(inode);
2305         struct rb_root *root_node = &nfsi->access_cache;
2306         struct rb_node **p = &root_node->rb_node;
2307         struct rb_node *parent = NULL;
2308         struct nfs_access_entry *entry;
2309
2310         spin_lock(&inode->i_lock);
2311         while (*p != NULL) {
2312                 parent = *p;
2313                 entry = rb_entry(parent, struct nfs_access_entry, rb_node);
2314
2315                 if (set->cred < entry->cred)
2316                         p = &parent->rb_left;
2317                 else if (set->cred > entry->cred)
2318                         p = &parent->rb_right;
2319                 else
2320                         goto found;
2321         }
2322         rb_link_node(&set->rb_node, parent, p);
2323         rb_insert_color(&set->rb_node, root_node);
2324         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2325         spin_unlock(&inode->i_lock);
2326         return;
2327 found:
2328         rb_replace_node(parent, &set->rb_node, root_node);
2329         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2330         list_del(&entry->lru);
2331         spin_unlock(&inode->i_lock);
2332         nfs_access_free_entry(entry);
2333 }
2334
2335 void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set)
2336 {
2337         struct nfs_access_entry *cache = kmalloc(sizeof(*cache), GFP_KERNEL);
2338         if (cache == NULL)
2339                 return;
2340         RB_CLEAR_NODE(&cache->rb_node);
2341         cache->jiffies = set->jiffies;
2342         cache->cred = get_rpccred(set->cred);
2343         cache->mask = set->mask;
2344
2345         /* The above field assignments must be visible
2346          * before this item appears on the lru.  We cannot easily
2347          * use rcu_assign_pointer, so just force the memory barrier.
2348          */
2349         smp_wmb();
2350         nfs_access_add_rbtree(inode, cache);
2351
2352         /* Update accounting */
2353         smp_mb__before_atomic();
2354         atomic_long_inc(&nfs_access_nr_entries);
2355         smp_mb__after_atomic();
2356
2357         /* Add inode to global LRU list */
2358         if (!test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags)) {
2359                 spin_lock(&nfs_access_lru_lock);
2360                 if (!test_and_set_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2361                         list_add_tail(&NFS_I(inode)->access_cache_inode_lru,
2362                                         &nfs_access_lru_list);
2363                 spin_unlock(&nfs_access_lru_lock);
2364         }
2365         nfs_access_cache_enforce_limit();
2366 }
2367 EXPORT_SYMBOL_GPL(nfs_access_add_cache);
2368
2369 void nfs_access_set_mask(struct nfs_access_entry *entry, u32 access_result)
2370 {
2371         entry->mask = 0;
2372         if (access_result & NFS4_ACCESS_READ)
2373                 entry->mask |= MAY_READ;
2374         if (access_result &
2375             (NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE))
2376                 entry->mask |= MAY_WRITE;
2377         if (access_result & (NFS4_ACCESS_LOOKUP|NFS4_ACCESS_EXECUTE))
2378                 entry->mask |= MAY_EXEC;
2379 }
2380 EXPORT_SYMBOL_GPL(nfs_access_set_mask);
2381
2382 static int nfs_do_access(struct inode *inode, struct rpc_cred *cred, int mask)
2383 {
2384         struct nfs_access_entry cache;
2385         int status;
2386
2387         trace_nfs_access_enter(inode);
2388
2389         status = nfs_access_get_cached_rcu(inode, cred, &cache);
2390         if (status != 0)
2391                 status = nfs_access_get_cached(inode, cred, &cache);
2392         if (status == 0)
2393                 goto out_cached;
2394
2395         status = -ECHILD;
2396         if (mask & MAY_NOT_BLOCK)
2397                 goto out;
2398
2399         /* Be clever: ask server to check for all possible rights */
2400         cache.mask = MAY_EXEC | MAY_WRITE | MAY_READ;
2401         cache.cred = cred;
2402         cache.jiffies = jiffies;
2403         status = NFS_PROTO(inode)->access(inode, &cache);
2404         if (status != 0) {
2405                 if (status == -ESTALE) {
2406                         nfs_zap_caches(inode);
2407                         if (!S_ISDIR(inode->i_mode))
2408                                 set_bit(NFS_INO_STALE, &NFS_I(inode)->flags);
2409                 }
2410                 goto out;
2411         }
2412         nfs_access_add_cache(inode, &cache);
2413 out_cached:
2414         if ((mask & ~cache.mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) != 0)
2415                 status = -EACCES;
2416 out:
2417         trace_nfs_access_exit(inode, status);
2418         return status;
2419 }
2420
2421 static int nfs_open_permission_mask(int openflags)
2422 {
2423         int mask = 0;
2424
2425         if (openflags & __FMODE_EXEC) {
2426                 /* ONLY check exec rights */
2427                 mask = MAY_EXEC;
2428         } else {
2429                 if ((openflags & O_ACCMODE) != O_WRONLY)
2430                         mask |= MAY_READ;
2431                 if ((openflags & O_ACCMODE) != O_RDONLY)
2432                         mask |= MAY_WRITE;
2433         }
2434
2435         return mask;
2436 }
2437
2438 int nfs_may_open(struct inode *inode, struct rpc_cred *cred, int openflags)
2439 {
2440         return nfs_do_access(inode, cred, nfs_open_permission_mask(openflags));
2441 }
2442 EXPORT_SYMBOL_GPL(nfs_may_open);
2443
2444 static int nfs_execute_ok(struct inode *inode, int mask)
2445 {
2446         struct nfs_server *server = NFS_SERVER(inode);
2447         int ret;
2448
2449         if (mask & MAY_NOT_BLOCK)
2450                 ret = nfs_revalidate_inode_rcu(server, inode);
2451         else
2452                 ret = nfs_revalidate_inode(server, inode);
2453         if (ret == 0 && !execute_ok(inode))
2454                 ret = -EACCES;
2455         return ret;
2456 }
2457
2458 int nfs_permission(struct inode *inode, int mask)
2459 {
2460         struct rpc_cred *cred;
2461         int res = 0;
2462
2463         nfs_inc_stats(inode, NFSIOS_VFSACCESS);
2464
2465         if ((mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
2466                 goto out;
2467         /* Is this sys_access() ? */
2468         if (mask & (MAY_ACCESS | MAY_CHDIR))
2469                 goto force_lookup;
2470
2471         switch (inode->i_mode & S_IFMT) {
2472                 case S_IFLNK:
2473                         goto out;
2474                 case S_IFREG:
2475                         if ((mask & MAY_OPEN) &&
2476                            nfs_server_capable(inode, NFS_CAP_ATOMIC_OPEN))
2477                                 return 0;
2478                         break;
2479                 case S_IFDIR:
2480                         /*
2481                          * Optimize away all write operations, since the server
2482                          * will check permissions when we perform the op.
2483                          */
2484                         if ((mask & MAY_WRITE) && !(mask & MAY_READ))
2485                                 goto out;
2486         }
2487
2488 force_lookup:
2489         if (!NFS_PROTO(inode)->access)
2490                 goto out_notsup;
2491
2492         /* Always try fast lookups first */
2493         rcu_read_lock();
2494         cred = rpc_lookup_cred_nonblock();
2495         if (!IS_ERR(cred))
2496                 res = nfs_do_access(inode, cred, mask|MAY_NOT_BLOCK);
2497         else
2498                 res = PTR_ERR(cred);
2499         rcu_read_unlock();
2500         if (res == -ECHILD && !(mask & MAY_NOT_BLOCK)) {
2501                 /* Fast lookup failed, try the slow way */
2502                 cred = rpc_lookup_cred();
2503                 if (!IS_ERR(cred)) {
2504                         res = nfs_do_access(inode, cred, mask);
2505                         put_rpccred(cred);
2506                 } else
2507                         res = PTR_ERR(cred);
2508         }
2509 out:
2510         if (!res && (mask & MAY_EXEC))
2511                 res = nfs_execute_ok(inode, mask);
2512
2513         dfprintk(VFS, "NFS: permission(%s/%lu), mask=0x%x, res=%d\n",
2514                 inode->i_sb->s_id, inode->i_ino, mask, res);
2515         return res;
2516 out_notsup:
2517         if (mask & MAY_NOT_BLOCK)
2518                 return -ECHILD;
2519
2520         res = nfs_revalidate_inode(NFS_SERVER(inode), inode);
2521         if (res == 0)
2522                 res = generic_permission(inode, mask);
2523         goto out;
2524 }
2525 EXPORT_SYMBOL_GPL(nfs_permission);
2526
2527 /*
2528  * Local variables:
2529  *  version-control: t
2530  *  kept-new-versions: 5
2531  * End:
2532  */