GNU Linux-libre 4.4.285-gnu1
[releases.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 = true;
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 = true;
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                 if (entry->label)
566                         entry->label->len = NFS4_MAXLABELLEN;
567
568                 status = xdr_decode(desc, entry, &stream);
569                 if (status != 0) {
570                         if (status == -EAGAIN)
571                                 status = 0;
572                         break;
573                 }
574
575                 count++;
576
577                 if (desc->plus != 0)
578                         nfs_prime_dcache(file_dentry(desc->file), entry);
579
580                 status = nfs_readdir_add_to_array(entry, page);
581                 if (status != 0)
582                         break;
583         } while (!entry->eof);
584
585 out_nopages:
586         if (count == 0 || (status == -EBADCOOKIE && entry->eof != 0)) {
587                 array = nfs_readdir_get_array(page);
588                 if (!IS_ERR(array)) {
589                         array->eof_index = array->size;
590                         status = 0;
591                         nfs_readdir_release_array(page);
592                 } else
593                         status = PTR_ERR(array);
594         }
595
596         put_page(scratch);
597         return status;
598 }
599
600 static
601 void nfs_readdir_free_pages(struct page **pages, unsigned int npages)
602 {
603         unsigned int i;
604         for (i = 0; i < npages; i++)
605                 put_page(pages[i]);
606 }
607
608 /*
609  * nfs_readdir_large_page will allocate pages that must be freed with a call
610  * to nfs_readdir_free_pagearray
611  */
612 static
613 int nfs_readdir_alloc_pages(struct page **pages, unsigned int npages)
614 {
615         unsigned int i;
616
617         for (i = 0; i < npages; i++) {
618                 struct page *page = alloc_page(GFP_KERNEL);
619                 if (page == NULL)
620                         goto out_freepages;
621                 pages[i] = page;
622         }
623         return 0;
624
625 out_freepages:
626         nfs_readdir_free_pages(pages, i);
627         return -ENOMEM;
628 }
629
630 static
631 int nfs_readdir_xdr_to_array(nfs_readdir_descriptor_t *desc, struct page *page, struct inode *inode)
632 {
633         struct page *pages[NFS_MAX_READDIR_PAGES];
634         struct nfs_entry entry;
635         struct file     *file = desc->file;
636         struct nfs_cache_array *array;
637         int status = -ENOMEM;
638         unsigned int array_size = ARRAY_SIZE(pages);
639
640         nfs_readdir_init_array(page);
641
642         entry.prev_cookie = 0;
643         entry.cookie = desc->last_cookie;
644         entry.eof = 0;
645         entry.fh = nfs_alloc_fhandle();
646         entry.fattr = nfs_alloc_fattr();
647         entry.server = NFS_SERVER(inode);
648         if (entry.fh == NULL || entry.fattr == NULL)
649                 goto out;
650
651         entry.label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
652         if (IS_ERR(entry.label)) {
653                 status = PTR_ERR(entry.label);
654                 goto out;
655         }
656
657         array = nfs_readdir_get_array(page);
658         if (IS_ERR(array)) {
659                 status = PTR_ERR(array);
660                 goto out_label_free;
661         }
662
663         status = nfs_readdir_alloc_pages(pages, array_size);
664         if (status < 0)
665                 goto out_release_array;
666         do {
667                 unsigned int pglen;
668                 status = nfs_readdir_xdr_filler(pages, desc, &entry, file, inode);
669
670                 if (status < 0)
671                         break;
672                 pglen = status;
673                 status = nfs_readdir_page_filler(desc, &entry, pages, page, pglen);
674                 if (status < 0) {
675                         if (status == -ENOSPC)
676                                 status = 0;
677                         break;
678                 }
679         } while (array->eof_index < 0);
680
681         nfs_readdir_free_pages(pages, array_size);
682 out_release_array:
683         nfs_readdir_release_array(page);
684 out_label_free:
685         nfs4_label_free(entry.label);
686 out:
687         nfs_free_fattr(entry.fattr);
688         nfs_free_fhandle(entry.fh);
689         return status;
690 }
691
692 /*
693  * Now we cache directories properly, by converting xdr information
694  * to an array that can be used for lookups later.  This results in
695  * fewer cache pages, since we can store more information on each page.
696  * We only need to convert from xdr once so future lookups are much simpler
697  */
698 static
699 int nfs_readdir_filler(nfs_readdir_descriptor_t *desc, struct page* page)
700 {
701         struct inode    *inode = file_inode(desc->file);
702         int ret;
703
704         ret = nfs_readdir_xdr_to_array(desc, page, inode);
705         if (ret < 0)
706                 goto error;
707         SetPageUptodate(page);
708
709         if (invalidate_inode_pages2_range(inode->i_mapping, page->index + 1, -1) < 0) {
710                 /* Should never happen */
711                 nfs_zap_mapping(inode, inode->i_mapping);
712         }
713         unlock_page(page);
714         return 0;
715  error:
716         nfs_readdir_clear_array(page);
717         unlock_page(page);
718         return ret;
719 }
720
721 static
722 void cache_page_release(nfs_readdir_descriptor_t *desc)
723 {
724         page_cache_release(desc->page);
725         desc->page = NULL;
726 }
727
728 static
729 struct page *get_cache_page(nfs_readdir_descriptor_t *desc)
730 {
731         return read_cache_page(file_inode(desc->file)->i_mapping,
732                         desc->page_index, (filler_t *)nfs_readdir_filler, desc);
733 }
734
735 /*
736  * Returns 0 if desc->dir_cookie was found on page desc->page_index
737  * and locks the page to prevent removal from the page cache.
738  */
739 static
740 int find_and_lock_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         res = lock_page_killable(desc->page);
748         if (res != 0)
749                 goto error;
750         res = -EAGAIN;
751         if (desc->page->mapping != NULL) {
752                 res = nfs_readdir_search_array(desc);
753                 if (res == 0)
754                         return 0;
755         }
756         unlock_page(desc->page);
757 error:
758         cache_page_release(desc);
759         return res;
760 }
761
762 /* Search for desc->dir_cookie from the beginning of the page cache */
763 static inline
764 int readdir_search_pagecache(nfs_readdir_descriptor_t *desc)
765 {
766         int res;
767
768         if (desc->page_index == 0) {
769                 desc->current_index = 0;
770                 desc->last_cookie = 0;
771         }
772         do {
773                 res = find_and_lock_cache_page(desc);
774         } while (res == -EAGAIN);
775         return res;
776 }
777
778 /*
779  * Once we've found the start of the dirent within a page: fill 'er up...
780  */
781 static 
782 int nfs_do_filldir(nfs_readdir_descriptor_t *desc)
783 {
784         struct file     *file = desc->file;
785         int i = 0;
786         int res = 0;
787         struct nfs_cache_array *array = NULL;
788         struct nfs_open_dir_context *ctx = file->private_data;
789
790         array = nfs_readdir_get_array(desc->page);
791         if (IS_ERR(array)) {
792                 res = PTR_ERR(array);
793                 goto out;
794         }
795
796         for (i = desc->cache_entry_index; i < array->size; i++) {
797                 struct nfs_cache_array_entry *ent;
798
799                 ent = &array->array[i];
800                 if (!dir_emit(desc->ctx, ent->string.name, ent->string.len,
801                     nfs_compat_user_ino64(ent->ino), ent->d_type)) {
802                         desc->eof = true;
803                         break;
804                 }
805                 desc->ctx->pos++;
806                 if (i < (array->size-1))
807                         *desc->dir_cookie = array->array[i+1].cookie;
808                 else
809                         *desc->dir_cookie = array->last_cookie;
810                 if (ctx->duped != 0)
811                         ctx->duped = 1;
812         }
813         if (array->eof_index >= 0)
814                 desc->eof = true;
815
816         nfs_readdir_release_array(desc->page);
817 out:
818         dfprintk(DIRCACHE, "NFS: nfs_do_filldir() filling ended @ cookie %Lu; returning = %d\n",
819                         (unsigned long long)*desc->dir_cookie, res);
820         return res;
821 }
822
823 /*
824  * If we cannot find a cookie in our cache, we suspect that this is
825  * because it points to a deleted file, so we ask the server to return
826  * whatever it thinks is the next entry. We then feed this to filldir.
827  * If all goes well, we should then be able to find our way round the
828  * cache on the next call to readdir_search_pagecache();
829  *
830  * NOTE: we cannot add the anonymous page to the pagecache because
831  *       the data it contains might not be page aligned. Besides,
832  *       we should already have a complete representation of the
833  *       directory in the page cache by the time we get here.
834  */
835 static inline
836 int uncached_readdir(nfs_readdir_descriptor_t *desc)
837 {
838         struct page     *page = NULL;
839         int             status;
840         struct inode *inode = file_inode(desc->file);
841         struct nfs_open_dir_context *ctx = desc->file->private_data;
842
843         dfprintk(DIRCACHE, "NFS: uncached_readdir() searching for cookie %Lu\n",
844                         (unsigned long long)*desc->dir_cookie);
845
846         page = alloc_page(GFP_HIGHUSER);
847         if (!page) {
848                 status = -ENOMEM;
849                 goto out;
850         }
851
852         desc->page_index = 0;
853         desc->last_cookie = *desc->dir_cookie;
854         desc->page = page;
855         ctx->duped = 0;
856
857         status = nfs_readdir_xdr_to_array(desc, page, inode);
858         if (status < 0)
859                 goto out_release;
860
861         status = nfs_do_filldir(desc);
862
863  out_release:
864         nfs_readdir_clear_array(desc->page);
865         cache_page_release(desc);
866  out:
867         dfprintk(DIRCACHE, "NFS: %s: returns %d\n",
868                         __func__, status);
869         return status;
870 }
871
872 /* The file offset position represents the dirent entry number.  A
873    last cookie cache takes care of the common case of reading the
874    whole directory.
875  */
876 static int nfs_readdir(struct file *file, struct dir_context *ctx)
877 {
878         struct dentry   *dentry = file_dentry(file);
879         struct inode    *inode = d_inode(dentry);
880         nfs_readdir_descriptor_t my_desc,
881                         *desc = &my_desc;
882         struct nfs_open_dir_context *dir_ctx = file->private_data;
883         int res = 0;
884
885         dfprintk(FILE, "NFS: readdir(%pD2) starting at cookie %llu\n",
886                         file, (long long)ctx->pos);
887         nfs_inc_stats(inode, NFSIOS_VFSGETDENTS);
888
889         /*
890          * ctx->pos points to the dirent entry number.
891          * *desc->dir_cookie has the cookie for the next entry. We have
892          * to either find the entry with the appropriate number or
893          * revalidate the cookie.
894          */
895         memset(desc, 0, sizeof(*desc));
896
897         desc->file = file;
898         desc->ctx = ctx;
899         desc->dir_cookie = &dir_ctx->dir_cookie;
900         desc->decode = NFS_PROTO(inode)->decode_dirent;
901         desc->plus = nfs_use_readdirplus(inode, ctx) ? 1 : 0;
902
903         nfs_block_sillyrename(dentry);
904         if (ctx->pos == 0 || nfs_attribute_cache_expired(inode))
905                 res = nfs_revalidate_mapping(inode, file->f_mapping);
906         if (res < 0)
907                 goto out;
908
909         do {
910                 res = readdir_search_pagecache(desc);
911
912                 if (res == -EBADCOOKIE) {
913                         res = 0;
914                         /* This means either end of directory */
915                         if (*desc->dir_cookie && !desc->eof) {
916                                 /* Or that the server has 'lost' a cookie */
917                                 res = uncached_readdir(desc);
918                                 if (res == 0)
919                                         continue;
920                         }
921                         break;
922                 }
923                 if (res == -ETOOSMALL && desc->plus) {
924                         clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(inode)->flags);
925                         nfs_zap_caches(inode);
926                         desc->page_index = 0;
927                         desc->plus = 0;
928                         desc->eof = 0;
929                         continue;
930                 }
931                 if (res < 0)
932                         break;
933
934                 res = nfs_do_filldir(desc);
935                 unlock_page(desc->page);
936                 cache_page_release(desc);
937                 if (res < 0)
938                         break;
939         } while (!desc->eof);
940 out:
941         nfs_unblock_sillyrename(dentry);
942         if (res > 0)
943                 res = 0;
944         dfprintk(FILE, "NFS: readdir(%pD2) returns %d\n", file, res);
945         return res;
946 }
947
948 static loff_t nfs_llseek_dir(struct file *filp, loff_t offset, int whence)
949 {
950         struct inode *inode = file_inode(filp);
951         struct nfs_open_dir_context *dir_ctx = filp->private_data;
952
953         dfprintk(FILE, "NFS: llseek dir(%pD2, %lld, %d)\n",
954                         filp, offset, whence);
955
956         mutex_lock(&inode->i_mutex);
957         switch (whence) {
958                 case 1:
959                         offset += filp->f_pos;
960                 case 0:
961                         if (offset >= 0)
962                                 break;
963                 default:
964                         offset = -EINVAL;
965                         goto out;
966         }
967         if (offset != filp->f_pos) {
968                 filp->f_pos = offset;
969                 dir_ctx->dir_cookie = 0;
970                 dir_ctx->duped = 0;
971         }
972 out:
973         mutex_unlock(&inode->i_mutex);
974         return offset;
975 }
976
977 /*
978  * All directory operations under NFS are synchronous, so fsync()
979  * is a dummy operation.
980  */
981 static int nfs_fsync_dir(struct file *filp, loff_t start, loff_t end,
982                          int datasync)
983 {
984         struct inode *inode = file_inode(filp);
985
986         dfprintk(FILE, "NFS: fsync dir(%pD2) datasync %d\n", filp, datasync);
987
988         mutex_lock(&inode->i_mutex);
989         nfs_inc_stats(inode, NFSIOS_VFSFSYNC);
990         mutex_unlock(&inode->i_mutex);
991         return 0;
992 }
993
994 /**
995  * nfs_force_lookup_revalidate - Mark the directory as having changed
996  * @dir - pointer to directory inode
997  *
998  * This forces the revalidation code in nfs_lookup_revalidate() to do a
999  * full lookup on all child dentries of 'dir' whenever a change occurs
1000  * on the server that might have invalidated our dcache.
1001  *
1002  * The caller should be holding dir->i_lock
1003  */
1004 void nfs_force_lookup_revalidate(struct inode *dir)
1005 {
1006         NFS_I(dir)->cache_change_attribute++;
1007 }
1008 EXPORT_SYMBOL_GPL(nfs_force_lookup_revalidate);
1009
1010 /*
1011  * A check for whether or not the parent directory has changed.
1012  * In the case it has, we assume that the dentries are untrustworthy
1013  * and may need to be looked up again.
1014  * If rcu_walk prevents us from performing a full check, return 0.
1015  */
1016 static int nfs_check_verifier(struct inode *dir, struct dentry *dentry,
1017                               int rcu_walk)
1018 {
1019         int ret;
1020
1021         if (IS_ROOT(dentry))
1022                 return 1;
1023         if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONE)
1024                 return 0;
1025         if (!nfs_verify_change_attribute(dir, dentry->d_time))
1026                 return 0;
1027         /* Revalidate nfsi->cache_change_attribute before we declare a match */
1028         if (rcu_walk)
1029                 ret = nfs_revalidate_inode_rcu(NFS_SERVER(dir), dir);
1030         else
1031                 ret = nfs_revalidate_inode(NFS_SERVER(dir), dir);
1032         if (ret < 0)
1033                 return 0;
1034         if (!nfs_verify_change_attribute(dir, dentry->d_time))
1035                 return 0;
1036         return 1;
1037 }
1038
1039 /*
1040  * Use intent information to check whether or not we're going to do
1041  * an O_EXCL create using this path component.
1042  */
1043 static int nfs_is_exclusive_create(struct inode *dir, unsigned int flags)
1044 {
1045         if (NFS_PROTO(dir)->version == 2)
1046                 return 0;
1047         return flags & LOOKUP_EXCL;
1048 }
1049
1050 /*
1051  * Inode and filehandle revalidation for lookups.
1052  *
1053  * We force revalidation in the cases where the VFS sets LOOKUP_REVAL,
1054  * or if the intent information indicates that we're about to open this
1055  * particular file and the "nocto" mount flag is not set.
1056  *
1057  */
1058 static
1059 int nfs_lookup_verify_inode(struct inode *inode, unsigned int flags)
1060 {
1061         struct nfs_server *server = NFS_SERVER(inode);
1062         int ret;
1063
1064         if (IS_AUTOMOUNT(inode))
1065                 return 0;
1066         /* VFS wants an on-the-wire revalidation */
1067         if (flags & LOOKUP_REVAL)
1068                 goto out_force;
1069         /* This is an open(2) */
1070         if ((flags & LOOKUP_OPEN) && !(server->flags & NFS_MOUNT_NOCTO) &&
1071             (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)))
1072                 goto out_force;
1073 out:
1074         return (inode->i_nlink == 0) ? -ENOENT : 0;
1075 out_force:
1076         if (flags & LOOKUP_RCU)
1077                 return -ECHILD;
1078         ret = __nfs_revalidate_inode(server, inode);
1079         if (ret != 0)
1080                 return ret;
1081         goto out;
1082 }
1083
1084 /*
1085  * We judge how long we want to trust negative
1086  * dentries by looking at the parent inode mtime.
1087  *
1088  * If parent mtime has changed, we revalidate, else we wait for a
1089  * period corresponding to the parent's attribute cache timeout value.
1090  *
1091  * If LOOKUP_RCU prevents us from performing a full check, return 1
1092  * suggesting a reval is needed.
1093  */
1094 static inline
1095 int nfs_neg_need_reval(struct inode *dir, struct dentry *dentry,
1096                        unsigned int flags)
1097 {
1098         /* Don't revalidate a negative dentry if we're creating a new file */
1099         if (flags & LOOKUP_CREATE)
1100                 return 0;
1101         if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONEG)
1102                 return 1;
1103         return !nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU);
1104 }
1105
1106 /*
1107  * This is called every time the dcache has a lookup hit,
1108  * and we should check whether we can really trust that
1109  * lookup.
1110  *
1111  * NOTE! The hit can be a negative hit too, don't assume
1112  * we have an inode!
1113  *
1114  * If the parent directory is seen to have changed, we throw out the
1115  * cached dentry and do a new lookup.
1116  */
1117 static int nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1118 {
1119         struct inode *dir;
1120         struct inode *inode;
1121         struct dentry *parent;
1122         struct nfs_fh *fhandle = NULL;
1123         struct nfs_fattr *fattr = NULL;
1124         struct nfs4_label *label = NULL;
1125         int error;
1126
1127         if (flags & LOOKUP_RCU) {
1128                 parent = ACCESS_ONCE(dentry->d_parent);
1129                 dir = d_inode_rcu(parent);
1130                 if (!dir)
1131                         return -ECHILD;
1132         } else {
1133                 parent = dget_parent(dentry);
1134                 dir = d_inode(parent);
1135         }
1136         nfs_inc_stats(dir, NFSIOS_DENTRYREVALIDATE);
1137         inode = d_inode(dentry);
1138
1139         if (!inode) {
1140                 if (nfs_neg_need_reval(dir, dentry, flags)) {
1141                         if (flags & LOOKUP_RCU)
1142                                 return -ECHILD;
1143                         goto out_bad;
1144                 }
1145                 goto out_valid_noent;
1146         }
1147
1148         if (is_bad_inode(inode)) {
1149                 if (flags & LOOKUP_RCU)
1150                         return -ECHILD;
1151                 dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1152                                 __func__, dentry);
1153                 goto out_bad;
1154         }
1155
1156         if (NFS_PROTO(dir)->have_delegation(inode, FMODE_READ))
1157                 goto out_set_verifier;
1158
1159         /* Force a full look up iff the parent directory has changed */
1160         if (!nfs_is_exclusive_create(dir, flags) &&
1161             nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU)) {
1162                 error = nfs_lookup_verify_inode(inode, flags);
1163                 if (error) {
1164                         if (flags & LOOKUP_RCU)
1165                                 return -ECHILD;
1166                         if (error == -ESTALE)
1167                                 goto out_zap_parent;
1168                         goto out_error;
1169                 }
1170                 goto out_valid;
1171         }
1172
1173         if (flags & LOOKUP_RCU)
1174                 return -ECHILD;
1175
1176         if (NFS_STALE(inode))
1177                 goto out_bad;
1178
1179         error = -ENOMEM;
1180         fhandle = nfs_alloc_fhandle();
1181         fattr = nfs_alloc_fattr();
1182         if (fhandle == NULL || fattr == NULL)
1183                 goto out_error;
1184
1185         label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
1186         if (IS_ERR(label))
1187                 goto out_error;
1188
1189         trace_nfs_lookup_revalidate_enter(dir, dentry, flags);
1190         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1191         trace_nfs_lookup_revalidate_exit(dir, dentry, flags, error);
1192         if (error == -ESTALE || error == -ENOENT)
1193                 goto out_bad;
1194         if (error)
1195                 goto out_error;
1196         if (nfs_compare_fh(NFS_FH(inode), fhandle))
1197                 goto out_bad;
1198         if ((error = nfs_refresh_inode(inode, fattr)) != 0)
1199                 goto out_bad;
1200
1201         nfs_setsecurity(inode, fattr, label);
1202
1203         nfs_free_fattr(fattr);
1204         nfs_free_fhandle(fhandle);
1205         nfs4_label_free(label);
1206
1207 out_set_verifier:
1208         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1209  out_valid:
1210         /* Success: notify readdir to use READDIRPLUS */
1211         nfs_advise_use_readdirplus(dir);
1212  out_valid_noent:
1213         if (flags & LOOKUP_RCU) {
1214                 if (parent != ACCESS_ONCE(dentry->d_parent))
1215                         return -ECHILD;
1216         } else
1217                 dput(parent);
1218         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is valid\n",
1219                         __func__, dentry);
1220         return 1;
1221 out_zap_parent:
1222         nfs_zap_caches(dir);
1223  out_bad:
1224         WARN_ON(flags & LOOKUP_RCU);
1225         nfs_free_fattr(fattr);
1226         nfs_free_fhandle(fhandle);
1227         nfs4_label_free(label);
1228         nfs_mark_for_revalidate(dir);
1229         if (inode && S_ISDIR(inode->i_mode)) {
1230                 /* Purge readdir caches. */
1231                 nfs_zap_caches(inode);
1232                 /*
1233                  * We can't d_drop the root of a disconnected tree:
1234                  * its d_hash is on the s_anon list and d_drop() would hide
1235                  * it from shrink_dcache_for_unmount(), leading to busy
1236                  * inodes on unmount and further oopses.
1237                  */
1238                 if (IS_ROOT(dentry))
1239                         goto out_valid;
1240         }
1241         dput(parent);
1242         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is invalid\n",
1243                         __func__, dentry);
1244         return 0;
1245 out_error:
1246         WARN_ON(flags & LOOKUP_RCU);
1247         nfs_free_fattr(fattr);
1248         nfs_free_fhandle(fhandle);
1249         nfs4_label_free(label);
1250         dput(parent);
1251         dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) lookup returned error %d\n",
1252                         __func__, dentry, error);
1253         return error;
1254 }
1255
1256 /*
1257  * A weaker form of d_revalidate for revalidating just the d_inode(dentry)
1258  * when we don't really care about the dentry name. This is called when a
1259  * pathwalk ends on a dentry that was not found via a normal lookup in the
1260  * parent dir (e.g.: ".", "..", procfs symlinks or mountpoint traversals).
1261  *
1262  * In this situation, we just want to verify that the inode itself is OK
1263  * since the dentry might have changed on the server.
1264  */
1265 static int nfs_weak_revalidate(struct dentry *dentry, unsigned int flags)
1266 {
1267         int error;
1268         struct inode *inode = d_inode(dentry);
1269
1270         /*
1271          * I believe we can only get a negative dentry here in the case of a
1272          * procfs-style symlink. Just assume it's correct for now, but we may
1273          * eventually need to do something more here.
1274          */
1275         if (!inode) {
1276                 dfprintk(LOOKUPCACHE, "%s: %pd2 has negative inode\n",
1277                                 __func__, dentry);
1278                 return 1;
1279         }
1280
1281         if (is_bad_inode(inode)) {
1282                 dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1283                                 __func__, dentry);
1284                 return 0;
1285         }
1286
1287         error = nfs_lookup_verify_inode(inode, flags);
1288         dfprintk(LOOKUPCACHE, "NFS: %s: inode %lu is %s\n",
1289                         __func__, inode->i_ino, error ? "invalid" : "valid");
1290         return !error;
1291 }
1292
1293 /*
1294  * This is called from dput() when d_count is going to 0.
1295  */
1296 static int nfs_dentry_delete(const struct dentry *dentry)
1297 {
1298         dfprintk(VFS, "NFS: dentry_delete(%pd2, %x)\n",
1299                 dentry, dentry->d_flags);
1300
1301         /* Unhash any dentry with a stale inode */
1302         if (d_really_is_positive(dentry) && NFS_STALE(d_inode(dentry)))
1303                 return 1;
1304
1305         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1306                 /* Unhash it, so that ->d_iput() would be called */
1307                 return 1;
1308         }
1309         if (!(dentry->d_sb->s_flags & MS_ACTIVE)) {
1310                 /* Unhash it, so that ancestors of killed async unlink
1311                  * files will be cleaned up during umount */
1312                 return 1;
1313         }
1314         return 0;
1315
1316 }
1317
1318 /* Ensure that we revalidate inode->i_nlink */
1319 static void nfs_drop_nlink(struct inode *inode)
1320 {
1321         spin_lock(&inode->i_lock);
1322         /* drop the inode if we're reasonably sure this is the last link */
1323         if (inode->i_nlink == 1)
1324                 clear_nlink(inode);
1325         NFS_I(inode)->cache_validity |= NFS_INO_INVALID_ATTR;
1326         spin_unlock(&inode->i_lock);
1327 }
1328
1329 /*
1330  * Called when the dentry loses inode.
1331  * We use it to clean up silly-renamed files.
1332  */
1333 static void nfs_dentry_iput(struct dentry *dentry, struct inode *inode)
1334 {
1335         if (S_ISDIR(inode->i_mode))
1336                 /* drop any readdir cache as it could easily be old */
1337                 NFS_I(inode)->cache_validity |= NFS_INO_INVALID_DATA;
1338
1339         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1340                 nfs_complete_unlink(dentry, inode);
1341                 nfs_drop_nlink(inode);
1342         }
1343         iput(inode);
1344 }
1345
1346 static void nfs_d_release(struct dentry *dentry)
1347 {
1348         /* free cached devname value, if it survived that far */
1349         if (unlikely(dentry->d_fsdata)) {
1350                 if (dentry->d_flags & DCACHE_NFSFS_RENAMED)
1351                         WARN_ON(1);
1352                 else
1353                         kfree(dentry->d_fsdata);
1354         }
1355 }
1356
1357 const struct dentry_operations nfs_dentry_operations = {
1358         .d_revalidate   = nfs_lookup_revalidate,
1359         .d_weak_revalidate      = nfs_weak_revalidate,
1360         .d_delete       = nfs_dentry_delete,
1361         .d_iput         = nfs_dentry_iput,
1362         .d_automount    = nfs_d_automount,
1363         .d_release      = nfs_d_release,
1364 };
1365 EXPORT_SYMBOL_GPL(nfs_dentry_operations);
1366
1367 struct dentry *nfs_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
1368 {
1369         struct dentry *res;
1370         struct dentry *parent;
1371         struct inode *inode = NULL;
1372         struct nfs_fh *fhandle = NULL;
1373         struct nfs_fattr *fattr = NULL;
1374         struct nfs4_label *label = NULL;
1375         int error;
1376
1377         dfprintk(VFS, "NFS: lookup(%pd2)\n", dentry);
1378         nfs_inc_stats(dir, NFSIOS_VFSLOOKUP);
1379
1380         res = ERR_PTR(-ENAMETOOLONG);
1381         if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1382                 goto out;
1383
1384         /*
1385          * If we're doing an exclusive create, optimize away the lookup
1386          * but don't hash the dentry.
1387          */
1388         if (nfs_is_exclusive_create(dir, flags)) {
1389                 d_instantiate(dentry, NULL);
1390                 res = NULL;
1391                 goto out;
1392         }
1393
1394         res = ERR_PTR(-ENOMEM);
1395         fhandle = nfs_alloc_fhandle();
1396         fattr = nfs_alloc_fattr();
1397         if (fhandle == NULL || fattr == NULL)
1398                 goto out;
1399
1400         label = nfs4_label_alloc(NFS_SERVER(dir), GFP_NOWAIT);
1401         if (IS_ERR(label))
1402                 goto out;
1403
1404         parent = dentry->d_parent;
1405         /* Protect against concurrent sillydeletes */
1406         trace_nfs_lookup_enter(dir, dentry, flags);
1407         nfs_block_sillyrename(parent);
1408         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1409         if (error == -ENOENT)
1410                 goto no_entry;
1411         if (error < 0) {
1412                 res = ERR_PTR(error);
1413                 goto out_unblock_sillyrename;
1414         }
1415         inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1416         res = ERR_CAST(inode);
1417         if (IS_ERR(res))
1418                 goto out_unblock_sillyrename;
1419
1420         /* Success: notify readdir to use READDIRPLUS */
1421         nfs_advise_use_readdirplus(dir);
1422
1423 no_entry:
1424         res = d_splice_alias(inode, dentry);
1425         if (res != NULL) {
1426                 if (IS_ERR(res))
1427                         goto out_unblock_sillyrename;
1428                 dentry = res;
1429         }
1430         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1431 out_unblock_sillyrename:
1432         nfs_unblock_sillyrename(parent);
1433         trace_nfs_lookup_exit(dir, dentry, flags, error);
1434         nfs4_label_free(label);
1435 out:
1436         nfs_free_fattr(fattr);
1437         nfs_free_fhandle(fhandle);
1438         return res;
1439 }
1440 EXPORT_SYMBOL_GPL(nfs_lookup);
1441
1442 #if IS_ENABLED(CONFIG_NFS_V4)
1443 static int nfs4_lookup_revalidate(struct dentry *, unsigned int);
1444
1445 const struct dentry_operations nfs4_dentry_operations = {
1446         .d_revalidate   = nfs4_lookup_revalidate,
1447         .d_weak_revalidate      = nfs_weak_revalidate,
1448         .d_delete       = nfs_dentry_delete,
1449         .d_iput         = nfs_dentry_iput,
1450         .d_automount    = nfs_d_automount,
1451         .d_release      = nfs_d_release,
1452 };
1453 EXPORT_SYMBOL_GPL(nfs4_dentry_operations);
1454
1455 static fmode_t flags_to_mode(int flags)
1456 {
1457         fmode_t res = (__force fmode_t)flags & FMODE_EXEC;
1458         if ((flags & O_ACCMODE) != O_WRONLY)
1459                 res |= FMODE_READ;
1460         if ((flags & O_ACCMODE) != O_RDONLY)
1461                 res |= FMODE_WRITE;
1462         return res;
1463 }
1464
1465 static struct nfs_open_context *create_nfs_open_context(struct dentry *dentry, int open_flags)
1466 {
1467         return alloc_nfs_open_context(dentry, flags_to_mode(open_flags));
1468 }
1469
1470 static int do_open(struct inode *inode, struct file *filp)
1471 {
1472         nfs_fscache_open_file(inode, filp);
1473         return 0;
1474 }
1475
1476 static int nfs_finish_open(struct nfs_open_context *ctx,
1477                            struct dentry *dentry,
1478                            struct file *file, unsigned open_flags,
1479                            int *opened)
1480 {
1481         int err;
1482
1483         err = finish_open(file, dentry, do_open, opened);
1484         if (err)
1485                 goto out;
1486         nfs_file_set_open_context(file, ctx);
1487
1488 out:
1489         return err;
1490 }
1491
1492 int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
1493                     struct file *file, unsigned open_flags,
1494                     umode_t mode, int *opened)
1495 {
1496         struct nfs_open_context *ctx;
1497         struct dentry *res;
1498         struct iattr attr = { .ia_valid = ATTR_OPEN };
1499         struct inode *inode;
1500         unsigned int lookup_flags = 0;
1501         int err;
1502
1503         /* Expect a negative dentry */
1504         BUG_ON(d_inode(dentry));
1505
1506         dfprintk(VFS, "NFS: atomic_open(%s/%lu), %pd\n",
1507                         dir->i_sb->s_id, dir->i_ino, dentry);
1508
1509         err = nfs_check_flags(open_flags);
1510         if (err)
1511                 return err;
1512
1513         /* NFS only supports OPEN on regular files */
1514         if ((open_flags & O_DIRECTORY)) {
1515                 if (!d_unhashed(dentry)) {
1516                         /*
1517                          * Hashed negative dentry with O_DIRECTORY: dentry was
1518                          * revalidated and is fine, no need to perform lookup
1519                          * again
1520                          */
1521                         return -ENOENT;
1522                 }
1523                 lookup_flags = LOOKUP_OPEN|LOOKUP_DIRECTORY;
1524                 goto no_open;
1525         }
1526
1527         if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1528                 return -ENAMETOOLONG;
1529
1530         if (open_flags & O_CREAT) {
1531                 attr.ia_valid |= ATTR_MODE;
1532                 attr.ia_mode = mode & ~current_umask();
1533         }
1534         if (open_flags & O_TRUNC) {
1535                 attr.ia_valid |= ATTR_SIZE;
1536                 attr.ia_size = 0;
1537         }
1538
1539         ctx = create_nfs_open_context(dentry, open_flags);
1540         err = PTR_ERR(ctx);
1541         if (IS_ERR(ctx))
1542                 goto out;
1543
1544         trace_nfs_atomic_open_enter(dir, ctx, open_flags);
1545         nfs_block_sillyrename(dentry->d_parent);
1546         inode = NFS_PROTO(dir)->open_context(dir, ctx, open_flags, &attr, opened);
1547         nfs_unblock_sillyrename(dentry->d_parent);
1548         if (IS_ERR(inode)) {
1549                 err = PTR_ERR(inode);
1550                 trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1551                 put_nfs_open_context(ctx);
1552                 d_drop(dentry);
1553                 switch (err) {
1554                 case -ENOENT:
1555                         d_add(dentry, NULL);
1556                         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1557                         break;
1558                 case -EISDIR:
1559                 case -ENOTDIR:
1560                         goto no_open;
1561                 case -ELOOP:
1562                         if (!(open_flags & O_NOFOLLOW))
1563                                 goto no_open;
1564                         break;
1565                         /* case -EINVAL: */
1566                 default:
1567                         break;
1568                 }
1569                 goto out;
1570         }
1571
1572         err = nfs_finish_open(ctx, ctx->dentry, file, open_flags, opened);
1573         trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1574         put_nfs_open_context(ctx);
1575 out:
1576         return err;
1577
1578 no_open:
1579         res = nfs_lookup(dir, dentry, lookup_flags);
1580         err = PTR_ERR(res);
1581         if (IS_ERR(res))
1582                 goto out;
1583
1584         return finish_no_open(file, res);
1585 }
1586 EXPORT_SYMBOL_GPL(nfs_atomic_open);
1587
1588 static int nfs4_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1589 {
1590         struct inode *inode;
1591         int ret = 0;
1592
1593         if (!(flags & LOOKUP_OPEN) || (flags & LOOKUP_DIRECTORY))
1594                 goto no_open;
1595         if (d_mountpoint(dentry))
1596                 goto no_open;
1597         if (NFS_SB(dentry->d_sb)->caps & NFS_CAP_ATOMIC_OPEN_V1)
1598                 goto no_open;
1599
1600         inode = d_inode(dentry);
1601
1602         /* We can't create new files in nfs_open_revalidate(), so we
1603          * optimize away revalidation of negative dentries.
1604          */
1605         if (inode == NULL) {
1606                 struct dentry *parent;
1607                 struct inode *dir;
1608
1609                 if (flags & LOOKUP_RCU) {
1610                         parent = ACCESS_ONCE(dentry->d_parent);
1611                         dir = d_inode_rcu(parent);
1612                         if (!dir)
1613                                 return -ECHILD;
1614                 } else {
1615                         parent = dget_parent(dentry);
1616                         dir = d_inode(parent);
1617                 }
1618                 if (!nfs_neg_need_reval(dir, dentry, flags))
1619                         ret = 1;
1620                 else if (flags & LOOKUP_RCU)
1621                         ret = -ECHILD;
1622                 if (!(flags & LOOKUP_RCU))
1623                         dput(parent);
1624                 else if (parent != ACCESS_ONCE(dentry->d_parent))
1625                         return -ECHILD;
1626                 goto out;
1627         }
1628
1629         /* NFS only supports OPEN on regular files */
1630         if (!S_ISREG(inode->i_mode))
1631                 goto no_open;
1632         /* We cannot do exclusive creation on a positive dentry */
1633         if (flags & LOOKUP_EXCL)
1634                 goto no_open;
1635
1636         /* Let f_op->open() actually open (and revalidate) the file */
1637         ret = 1;
1638
1639 out:
1640         return ret;
1641
1642 no_open:
1643         return nfs_lookup_revalidate(dentry, flags);
1644 }
1645
1646 #endif /* CONFIG_NFSV4 */
1647
1648 /*
1649  * Code common to create, mkdir, and mknod.
1650  */
1651 int nfs_instantiate(struct dentry *dentry, struct nfs_fh *fhandle,
1652                                 struct nfs_fattr *fattr,
1653                                 struct nfs4_label *label)
1654 {
1655         struct dentry *parent = dget_parent(dentry);
1656         struct inode *dir = d_inode(parent);
1657         struct inode *inode;
1658         int error = -EACCES;
1659
1660         d_drop(dentry);
1661
1662         /* We may have been initialized further down */
1663         if (d_really_is_positive(dentry))
1664                 goto out;
1665         if (fhandle->size == 0) {
1666                 error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, NULL);
1667                 if (error)
1668                         goto out_error;
1669         }
1670         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1671         if (!(fattr->valid & NFS_ATTR_FATTR)) {
1672                 struct nfs_server *server = NFS_SB(dentry->d_sb);
1673                 error = server->nfs_client->rpc_ops->getattr(server, fhandle, fattr, NULL);
1674                 if (error < 0)
1675                         goto out_error;
1676         }
1677         inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1678         error = PTR_ERR(inode);
1679         if (IS_ERR(inode))
1680                 goto out_error;
1681         d_add(dentry, inode);
1682 out:
1683         dput(parent);
1684         return 0;
1685 out_error:
1686         nfs_mark_for_revalidate(dir);
1687         dput(parent);
1688         return error;
1689 }
1690 EXPORT_SYMBOL_GPL(nfs_instantiate);
1691
1692 /*
1693  * Following a failed create operation, we drop the dentry rather
1694  * than retain a negative dentry. This avoids a problem in the event
1695  * that the operation succeeded on the server, but an error in the
1696  * reply path made it appear to have failed.
1697  */
1698 int nfs_create(struct inode *dir, struct dentry *dentry,
1699                 umode_t mode, bool excl)
1700 {
1701         struct iattr attr;
1702         int open_flags = excl ? O_CREAT | O_EXCL : O_CREAT;
1703         int error;
1704
1705         dfprintk(VFS, "NFS: create(%s/%lu), %pd\n",
1706                         dir->i_sb->s_id, dir->i_ino, dentry);
1707
1708         attr.ia_mode = mode;
1709         attr.ia_valid = ATTR_MODE;
1710
1711         trace_nfs_create_enter(dir, dentry, open_flags);
1712         error = NFS_PROTO(dir)->create(dir, dentry, &attr, open_flags);
1713         trace_nfs_create_exit(dir, dentry, open_flags, error);
1714         if (error != 0)
1715                 goto out_err;
1716         return 0;
1717 out_err:
1718         d_drop(dentry);
1719         return error;
1720 }
1721 EXPORT_SYMBOL_GPL(nfs_create);
1722
1723 /*
1724  * See comments for nfs_proc_create regarding failed operations.
1725  */
1726 int
1727 nfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev)
1728 {
1729         struct iattr attr;
1730         int status;
1731
1732         dfprintk(VFS, "NFS: mknod(%s/%lu), %pd\n",
1733                         dir->i_sb->s_id, dir->i_ino, dentry);
1734
1735         attr.ia_mode = mode;
1736         attr.ia_valid = ATTR_MODE;
1737
1738         trace_nfs_mknod_enter(dir, dentry);
1739         status = NFS_PROTO(dir)->mknod(dir, dentry, &attr, rdev);
1740         trace_nfs_mknod_exit(dir, dentry, status);
1741         if (status != 0)
1742                 goto out_err;
1743         return 0;
1744 out_err:
1745         d_drop(dentry);
1746         return status;
1747 }
1748 EXPORT_SYMBOL_GPL(nfs_mknod);
1749
1750 /*
1751  * See comments for nfs_proc_create regarding failed operations.
1752  */
1753 int nfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
1754 {
1755         struct iattr attr;
1756         int error;
1757
1758         dfprintk(VFS, "NFS: mkdir(%s/%lu), %pd\n",
1759                         dir->i_sb->s_id, dir->i_ino, dentry);
1760
1761         attr.ia_valid = ATTR_MODE;
1762         attr.ia_mode = mode | S_IFDIR;
1763
1764         trace_nfs_mkdir_enter(dir, dentry);
1765         error = NFS_PROTO(dir)->mkdir(dir, dentry, &attr);
1766         trace_nfs_mkdir_exit(dir, dentry, error);
1767         if (error != 0)
1768                 goto out_err;
1769         return 0;
1770 out_err:
1771         d_drop(dentry);
1772         return error;
1773 }
1774 EXPORT_SYMBOL_GPL(nfs_mkdir);
1775
1776 static void nfs_dentry_handle_enoent(struct dentry *dentry)
1777 {
1778         if (simple_positive(dentry))
1779                 d_delete(dentry);
1780 }
1781
1782 int nfs_rmdir(struct inode *dir, struct dentry *dentry)
1783 {
1784         int error;
1785
1786         dfprintk(VFS, "NFS: rmdir(%s/%lu), %pd\n",
1787                         dir->i_sb->s_id, dir->i_ino, dentry);
1788
1789         trace_nfs_rmdir_enter(dir, dentry);
1790         if (d_really_is_positive(dentry)) {
1791                 nfs_wait_on_sillyrename(dentry);
1792                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1793                 /* Ensure the VFS deletes this inode */
1794                 switch (error) {
1795                 case 0:
1796                         clear_nlink(d_inode(dentry));
1797                         break;
1798                 case -ENOENT:
1799                         nfs_dentry_handle_enoent(dentry);
1800                 }
1801         } else
1802                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1803         trace_nfs_rmdir_exit(dir, dentry, error);
1804
1805         return error;
1806 }
1807 EXPORT_SYMBOL_GPL(nfs_rmdir);
1808
1809 /*
1810  * Remove a file after making sure there are no pending writes,
1811  * and after checking that the file has only one user. 
1812  *
1813  * We invalidate the attribute cache and free the inode prior to the operation
1814  * to avoid possible races if the server reuses the inode.
1815  */
1816 static int nfs_safe_remove(struct dentry *dentry)
1817 {
1818         struct inode *dir = d_inode(dentry->d_parent);
1819         struct inode *inode = d_inode(dentry);
1820         int error = -EBUSY;
1821                 
1822         dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry);
1823
1824         /* If the dentry was sillyrenamed, we simply call d_delete() */
1825         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1826                 error = 0;
1827                 goto out;
1828         }
1829
1830         trace_nfs_remove_enter(dir, dentry);
1831         if (inode != NULL) {
1832                 NFS_PROTO(inode)->return_delegation(inode);
1833                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1834                 if (error == 0)
1835                         nfs_drop_nlink(inode);
1836         } else
1837                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1838         if (error == -ENOENT)
1839                 nfs_dentry_handle_enoent(dentry);
1840         trace_nfs_remove_exit(dir, dentry, error);
1841 out:
1842         return error;
1843 }
1844
1845 /*  We do silly rename. In case sillyrename() returns -EBUSY, the inode
1846  *  belongs to an active ".nfs..." file and we return -EBUSY.
1847  *
1848  *  If sillyrename() returns 0, we do nothing, otherwise we unlink.
1849  */
1850 int nfs_unlink(struct inode *dir, struct dentry *dentry)
1851 {
1852         int error;
1853         int need_rehash = 0;
1854
1855         dfprintk(VFS, "NFS: unlink(%s/%lu, %pd)\n", dir->i_sb->s_id,
1856                 dir->i_ino, dentry);
1857
1858         trace_nfs_unlink_enter(dir, dentry);
1859         spin_lock(&dentry->d_lock);
1860         if (d_count(dentry) > 1) {
1861                 spin_unlock(&dentry->d_lock);
1862                 /* Start asynchronous writeout of the inode */
1863                 write_inode_now(d_inode(dentry), 0);
1864                 error = nfs_sillyrename(dir, dentry);
1865                 goto out;
1866         }
1867         if (!d_unhashed(dentry)) {
1868                 __d_drop(dentry);
1869                 need_rehash = 1;
1870         }
1871         spin_unlock(&dentry->d_lock);
1872         error = nfs_safe_remove(dentry);
1873         if (!error || error == -ENOENT) {
1874                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1875         } else if (need_rehash)
1876                 d_rehash(dentry);
1877 out:
1878         trace_nfs_unlink_exit(dir, dentry, error);
1879         return error;
1880 }
1881 EXPORT_SYMBOL_GPL(nfs_unlink);
1882
1883 /*
1884  * To create a symbolic link, most file systems instantiate a new inode,
1885  * add a page to it containing the path, then write it out to the disk
1886  * using prepare_write/commit_write.
1887  *
1888  * Unfortunately the NFS client can't create the in-core inode first
1889  * because it needs a file handle to create an in-core inode (see
1890  * fs/nfs/inode.c:nfs_fhget).  We only have a file handle *after* the
1891  * symlink request has completed on the server.
1892  *
1893  * So instead we allocate a raw page, copy the symname into it, then do
1894  * the SYMLINK request with the page as the buffer.  If it succeeds, we
1895  * now have a new file handle and can instantiate an in-core NFS inode
1896  * and move the raw page into its mapping.
1897  */
1898 int nfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1899 {
1900         struct page *page;
1901         char *kaddr;
1902         struct iattr attr;
1903         unsigned int pathlen = strlen(symname);
1904         int error;
1905
1906         dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s)\n", dir->i_sb->s_id,
1907                 dir->i_ino, dentry, symname);
1908
1909         if (pathlen > PAGE_SIZE)
1910                 return -ENAMETOOLONG;
1911
1912         attr.ia_mode = S_IFLNK | S_IRWXUGO;
1913         attr.ia_valid = ATTR_MODE;
1914
1915         page = alloc_page(GFP_HIGHUSER);
1916         if (!page)
1917                 return -ENOMEM;
1918
1919         kaddr = kmap_atomic(page);
1920         memcpy(kaddr, symname, pathlen);
1921         if (pathlen < PAGE_SIZE)
1922                 memset(kaddr + pathlen, 0, PAGE_SIZE - pathlen);
1923         kunmap_atomic(kaddr);
1924
1925         trace_nfs_symlink_enter(dir, dentry);
1926         error = NFS_PROTO(dir)->symlink(dir, dentry, page, pathlen, &attr);
1927         trace_nfs_symlink_exit(dir, dentry, error);
1928         if (error != 0) {
1929                 dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s) error %d\n",
1930                         dir->i_sb->s_id, dir->i_ino,
1931                         dentry, symname, error);
1932                 d_drop(dentry);
1933                 __free_page(page);
1934                 return error;
1935         }
1936
1937         /*
1938          * No big deal if we can't add this page to the page cache here.
1939          * READLINK will get the missing page from the server if needed.
1940          */
1941         if (!add_to_page_cache_lru(page, d_inode(dentry)->i_mapping, 0,
1942                                                         GFP_KERNEL)) {
1943                 SetPageUptodate(page);
1944                 unlock_page(page);
1945                 /*
1946                  * add_to_page_cache_lru() grabs an extra page refcount.
1947                  * Drop it here to avoid leaking this page later.
1948                  */
1949                 page_cache_release(page);
1950         } else
1951                 __free_page(page);
1952
1953         return 0;
1954 }
1955 EXPORT_SYMBOL_GPL(nfs_symlink);
1956
1957 int
1958 nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
1959 {
1960         struct inode *inode = d_inode(old_dentry);
1961         int error;
1962
1963         dfprintk(VFS, "NFS: link(%pd2 -> %pd2)\n",
1964                 old_dentry, dentry);
1965
1966         trace_nfs_link_enter(inode, dir, dentry);
1967         NFS_PROTO(inode)->return_delegation(inode);
1968
1969         d_drop(dentry);
1970         error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
1971         if (error == 0) {
1972                 ihold(inode);
1973                 d_add(dentry, inode);
1974         }
1975         trace_nfs_link_exit(inode, dir, dentry, error);
1976         return error;
1977 }
1978 EXPORT_SYMBOL_GPL(nfs_link);
1979
1980 /*
1981  * RENAME
1982  * FIXME: Some nfsds, like the Linux user space nfsd, may generate a
1983  * different file handle for the same inode after a rename (e.g. when
1984  * moving to a different directory). A fail-safe method to do so would
1985  * be to look up old_dir/old_name, create a link to new_dir/new_name and
1986  * rename the old file using the sillyrename stuff. This way, the original
1987  * file in old_dir will go away when the last process iput()s the inode.
1988  *
1989  * FIXED.
1990  * 
1991  * It actually works quite well. One needs to have the possibility for
1992  * at least one ".nfs..." file in each directory the file ever gets
1993  * moved or linked to which happens automagically with the new
1994  * implementation that only depends on the dcache stuff instead of
1995  * using the inode layer
1996  *
1997  * Unfortunately, things are a little more complicated than indicated
1998  * above. For a cross-directory move, we want to make sure we can get
1999  * rid of the old inode after the operation.  This means there must be
2000  * no pending writes (if it's a file), and the use count must be 1.
2001  * If these conditions are met, we can drop the dentries before doing
2002  * the rename.
2003  */
2004 int nfs_rename(struct inode *old_dir, struct dentry *old_dentry,
2005                       struct inode *new_dir, struct dentry *new_dentry)
2006 {
2007         struct inode *old_inode = d_inode(old_dentry);
2008         struct inode *new_inode = d_inode(new_dentry);
2009         struct dentry *dentry = NULL, *rehash = NULL;
2010         struct rpc_task *task;
2011         int error = -EBUSY;
2012
2013         dfprintk(VFS, "NFS: rename(%pd2 -> %pd2, ct=%d)\n",
2014                  old_dentry, new_dentry,
2015                  d_count(new_dentry));
2016
2017         trace_nfs_rename_enter(old_dir, old_dentry, new_dir, new_dentry);
2018         /*
2019          * For non-directories, check whether the target is busy and if so,
2020          * make a copy of the dentry and then do a silly-rename. If the
2021          * silly-rename succeeds, the copied dentry is hashed and becomes
2022          * the new target.
2023          */
2024         if (new_inode && !S_ISDIR(new_inode->i_mode)) {
2025                 /*
2026                  * To prevent any new references to the target during the
2027                  * rename, we unhash the dentry in advance.
2028                  */
2029                 if (!d_unhashed(new_dentry)) {
2030                         d_drop(new_dentry);
2031                         rehash = new_dentry;
2032                 }
2033
2034                 if (d_count(new_dentry) > 2) {
2035                         int err;
2036
2037                         /* copy the target dentry's name */
2038                         dentry = d_alloc(new_dentry->d_parent,
2039                                          &new_dentry->d_name);
2040                         if (!dentry)
2041                                 goto out;
2042
2043                         /* silly-rename the existing target ... */
2044                         err = nfs_sillyrename(new_dir, new_dentry);
2045                         if (err)
2046                                 goto out;
2047
2048                         new_dentry = dentry;
2049                         rehash = NULL;
2050                         new_inode = NULL;
2051                 }
2052         }
2053
2054         NFS_PROTO(old_inode)->return_delegation(old_inode);
2055         if (new_inode != NULL)
2056                 NFS_PROTO(new_inode)->return_delegation(new_inode);
2057
2058         task = nfs_async_rename(old_dir, new_dir, old_dentry, new_dentry, NULL);
2059         if (IS_ERR(task)) {
2060                 error = PTR_ERR(task);
2061                 goto out;
2062         }
2063
2064         error = rpc_wait_for_completion_task(task);
2065         if (error == 0)
2066                 error = task->tk_status;
2067         rpc_put_task(task);
2068         nfs_mark_for_revalidate(old_inode);
2069 out:
2070         if (rehash)
2071                 d_rehash(rehash);
2072         trace_nfs_rename_exit(old_dir, old_dentry,
2073                         new_dir, new_dentry, error);
2074         if (!error) {
2075                 if (new_inode != NULL)
2076                         nfs_drop_nlink(new_inode);
2077                 d_move(old_dentry, new_dentry);
2078                 nfs_set_verifier(old_dentry,
2079                                         nfs_save_change_attribute(new_dir));
2080         } else if (error == -ENOENT)
2081                 nfs_dentry_handle_enoent(old_dentry);
2082
2083         /* new dentry created? */
2084         if (dentry)
2085                 dput(dentry);
2086         return error;
2087 }
2088 EXPORT_SYMBOL_GPL(nfs_rename);
2089
2090 static DEFINE_SPINLOCK(nfs_access_lru_lock);
2091 static LIST_HEAD(nfs_access_lru_list);
2092 static atomic_long_t nfs_access_nr_entries;
2093
2094 static unsigned long nfs_access_max_cachesize = ULONG_MAX;
2095 module_param(nfs_access_max_cachesize, ulong, 0644);
2096 MODULE_PARM_DESC(nfs_access_max_cachesize, "NFS access maximum total cache length");
2097
2098 static void nfs_access_free_entry(struct nfs_access_entry *entry)
2099 {
2100         put_rpccred(entry->cred);
2101         kfree_rcu(entry, rcu_head);
2102         smp_mb__before_atomic();
2103         atomic_long_dec(&nfs_access_nr_entries);
2104         smp_mb__after_atomic();
2105 }
2106
2107 static void nfs_access_free_list(struct list_head *head)
2108 {
2109         struct nfs_access_entry *cache;
2110
2111         while (!list_empty(head)) {
2112                 cache = list_entry(head->next, struct nfs_access_entry, lru);
2113                 list_del(&cache->lru);
2114                 nfs_access_free_entry(cache);
2115         }
2116 }
2117
2118 static unsigned long
2119 nfs_do_access_cache_scan(unsigned int nr_to_scan)
2120 {
2121         LIST_HEAD(head);
2122         struct nfs_inode *nfsi, *next;
2123         struct nfs_access_entry *cache;
2124         long freed = 0;
2125
2126         spin_lock(&nfs_access_lru_lock);
2127         list_for_each_entry_safe(nfsi, next, &nfs_access_lru_list, access_cache_inode_lru) {
2128                 struct inode *inode;
2129
2130                 if (nr_to_scan-- == 0)
2131                         break;
2132                 inode = &nfsi->vfs_inode;
2133                 spin_lock(&inode->i_lock);
2134                 if (list_empty(&nfsi->access_cache_entry_lru))
2135                         goto remove_lru_entry;
2136                 cache = list_entry(nfsi->access_cache_entry_lru.next,
2137                                 struct nfs_access_entry, lru);
2138                 list_move(&cache->lru, &head);
2139                 rb_erase(&cache->rb_node, &nfsi->access_cache);
2140                 freed++;
2141                 if (!list_empty(&nfsi->access_cache_entry_lru))
2142                         list_move_tail(&nfsi->access_cache_inode_lru,
2143                                         &nfs_access_lru_list);
2144                 else {
2145 remove_lru_entry:
2146                         list_del_init(&nfsi->access_cache_inode_lru);
2147                         smp_mb__before_atomic();
2148                         clear_bit(NFS_INO_ACL_LRU_SET, &nfsi->flags);
2149                         smp_mb__after_atomic();
2150                 }
2151                 spin_unlock(&inode->i_lock);
2152         }
2153         spin_unlock(&nfs_access_lru_lock);
2154         nfs_access_free_list(&head);
2155         return freed;
2156 }
2157
2158 unsigned long
2159 nfs_access_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
2160 {
2161         int nr_to_scan = sc->nr_to_scan;
2162         gfp_t gfp_mask = sc->gfp_mask;
2163
2164         if ((gfp_mask & GFP_KERNEL) != GFP_KERNEL)
2165                 return SHRINK_STOP;
2166         return nfs_do_access_cache_scan(nr_to_scan);
2167 }
2168
2169
2170 unsigned long
2171 nfs_access_cache_count(struct shrinker *shrink, struct shrink_control *sc)
2172 {
2173         return vfs_pressure_ratio(atomic_long_read(&nfs_access_nr_entries));
2174 }
2175
2176 static void
2177 nfs_access_cache_enforce_limit(void)
2178 {
2179         long nr_entries = atomic_long_read(&nfs_access_nr_entries);
2180         unsigned long diff;
2181         unsigned int nr_to_scan;
2182
2183         if (nr_entries < 0 || nr_entries <= nfs_access_max_cachesize)
2184                 return;
2185         nr_to_scan = 100;
2186         diff = nr_entries - nfs_access_max_cachesize;
2187         if (diff < nr_to_scan)
2188                 nr_to_scan = diff;
2189         nfs_do_access_cache_scan(nr_to_scan);
2190 }
2191
2192 static void __nfs_access_zap_cache(struct nfs_inode *nfsi, struct list_head *head)
2193 {
2194         struct rb_root *root_node = &nfsi->access_cache;
2195         struct rb_node *n;
2196         struct nfs_access_entry *entry;
2197
2198         /* Unhook entries from the cache */
2199         while ((n = rb_first(root_node)) != NULL) {
2200                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2201                 rb_erase(n, root_node);
2202                 list_move(&entry->lru, head);
2203         }
2204         nfsi->cache_validity &= ~NFS_INO_INVALID_ACCESS;
2205 }
2206
2207 void nfs_access_zap_cache(struct inode *inode)
2208 {
2209         LIST_HEAD(head);
2210
2211         if (test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags) == 0)
2212                 return;
2213         /* Remove from global LRU init */
2214         spin_lock(&nfs_access_lru_lock);
2215         if (test_and_clear_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2216                 list_del_init(&NFS_I(inode)->access_cache_inode_lru);
2217
2218         spin_lock(&inode->i_lock);
2219         __nfs_access_zap_cache(NFS_I(inode), &head);
2220         spin_unlock(&inode->i_lock);
2221         spin_unlock(&nfs_access_lru_lock);
2222         nfs_access_free_list(&head);
2223 }
2224 EXPORT_SYMBOL_GPL(nfs_access_zap_cache);
2225
2226 static struct nfs_access_entry *nfs_access_search_rbtree(struct inode *inode, struct rpc_cred *cred)
2227 {
2228         struct rb_node *n = NFS_I(inode)->access_cache.rb_node;
2229         struct nfs_access_entry *entry;
2230
2231         while (n != NULL) {
2232                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2233
2234                 if (cred < entry->cred)
2235                         n = n->rb_left;
2236                 else if (cred > entry->cred)
2237                         n = n->rb_right;
2238                 else
2239                         return entry;
2240         }
2241         return NULL;
2242 }
2243
2244 static int nfs_access_get_cached(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2245 {
2246         struct nfs_inode *nfsi = NFS_I(inode);
2247         struct nfs_access_entry *cache;
2248         int err = -ENOENT;
2249
2250         spin_lock(&inode->i_lock);
2251         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2252                 goto out_zap;
2253         cache = nfs_access_search_rbtree(inode, cred);
2254         if (cache == NULL)
2255                 goto out;
2256         if (!nfs_have_delegated_attributes(inode) &&
2257             !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2258                 goto out_stale;
2259         res->jiffies = cache->jiffies;
2260         res->cred = cache->cred;
2261         res->mask = cache->mask;
2262         list_move_tail(&cache->lru, &nfsi->access_cache_entry_lru);
2263         err = 0;
2264 out:
2265         spin_unlock(&inode->i_lock);
2266         return err;
2267 out_stale:
2268         rb_erase(&cache->rb_node, &nfsi->access_cache);
2269         list_del(&cache->lru);
2270         spin_unlock(&inode->i_lock);
2271         nfs_access_free_entry(cache);
2272         return -ENOENT;
2273 out_zap:
2274         spin_unlock(&inode->i_lock);
2275         nfs_access_zap_cache(inode);
2276         return -ENOENT;
2277 }
2278
2279 static int nfs_access_get_cached_rcu(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2280 {
2281         /* Only check the most recently returned cache entry,
2282          * but do it without locking.
2283          */
2284         struct nfs_inode *nfsi = NFS_I(inode);
2285         struct nfs_access_entry *cache;
2286         int err = -ECHILD;
2287         struct list_head *lh;
2288
2289         rcu_read_lock();
2290         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2291                 goto out;
2292         lh = rcu_dereference(nfsi->access_cache_entry_lru.prev);
2293         cache = list_entry(lh, struct nfs_access_entry, lru);
2294         if (lh == &nfsi->access_cache_entry_lru ||
2295             cred != cache->cred)
2296                 cache = NULL;
2297         if (cache == NULL)
2298                 goto out;
2299         if (!nfs_have_delegated_attributes(inode) &&
2300             !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2301                 goto out;
2302         res->jiffies = cache->jiffies;
2303         res->cred = cache->cred;
2304         res->mask = cache->mask;
2305         err = 0;
2306 out:
2307         rcu_read_unlock();
2308         return err;
2309 }
2310
2311 static void nfs_access_add_rbtree(struct inode *inode, struct nfs_access_entry *set)
2312 {
2313         struct nfs_inode *nfsi = NFS_I(inode);
2314         struct rb_root *root_node = &nfsi->access_cache;
2315         struct rb_node **p = &root_node->rb_node;
2316         struct rb_node *parent = NULL;
2317         struct nfs_access_entry *entry;
2318
2319         spin_lock(&inode->i_lock);
2320         while (*p != NULL) {
2321                 parent = *p;
2322                 entry = rb_entry(parent, struct nfs_access_entry, rb_node);
2323
2324                 if (set->cred < entry->cred)
2325                         p = &parent->rb_left;
2326                 else if (set->cred > entry->cred)
2327                         p = &parent->rb_right;
2328                 else
2329                         goto found;
2330         }
2331         rb_link_node(&set->rb_node, parent, p);
2332         rb_insert_color(&set->rb_node, root_node);
2333         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2334         spin_unlock(&inode->i_lock);
2335         return;
2336 found:
2337         rb_replace_node(parent, &set->rb_node, root_node);
2338         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2339         list_del(&entry->lru);
2340         spin_unlock(&inode->i_lock);
2341         nfs_access_free_entry(entry);
2342 }
2343
2344 void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set)
2345 {
2346         struct nfs_access_entry *cache = kmalloc(sizeof(*cache), GFP_KERNEL);
2347         if (cache == NULL)
2348                 return;
2349         RB_CLEAR_NODE(&cache->rb_node);
2350         cache->jiffies = set->jiffies;
2351         cache->cred = get_rpccred(set->cred);
2352         cache->mask = set->mask;
2353
2354         /* The above field assignments must be visible
2355          * before this item appears on the lru.  We cannot easily
2356          * use rcu_assign_pointer, so just force the memory barrier.
2357          */
2358         smp_wmb();
2359         nfs_access_add_rbtree(inode, cache);
2360
2361         /* Update accounting */
2362         smp_mb__before_atomic();
2363         atomic_long_inc(&nfs_access_nr_entries);
2364         smp_mb__after_atomic();
2365
2366         /* Add inode to global LRU list */
2367         if (!test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags)) {
2368                 spin_lock(&nfs_access_lru_lock);
2369                 if (!test_and_set_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2370                         list_add_tail(&NFS_I(inode)->access_cache_inode_lru,
2371                                         &nfs_access_lru_list);
2372                 spin_unlock(&nfs_access_lru_lock);
2373         }
2374         nfs_access_cache_enforce_limit();
2375 }
2376 EXPORT_SYMBOL_GPL(nfs_access_add_cache);
2377
2378 void nfs_access_set_mask(struct nfs_access_entry *entry, u32 access_result)
2379 {
2380         entry->mask = 0;
2381         if (access_result & NFS4_ACCESS_READ)
2382                 entry->mask |= MAY_READ;
2383         if (access_result &
2384             (NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE))
2385                 entry->mask |= MAY_WRITE;
2386         if (access_result & (NFS4_ACCESS_LOOKUP|NFS4_ACCESS_EXECUTE))
2387                 entry->mask |= MAY_EXEC;
2388 }
2389 EXPORT_SYMBOL_GPL(nfs_access_set_mask);
2390
2391 static int nfs_do_access(struct inode *inode, struct rpc_cred *cred, int mask)
2392 {
2393         struct nfs_access_entry cache;
2394         int status;
2395
2396         trace_nfs_access_enter(inode);
2397
2398         status = nfs_access_get_cached_rcu(inode, cred, &cache);
2399         if (status != 0)
2400                 status = nfs_access_get_cached(inode, cred, &cache);
2401         if (status == 0)
2402                 goto out_cached;
2403
2404         status = -ECHILD;
2405         if (mask & MAY_NOT_BLOCK)
2406                 goto out;
2407
2408         /* Be clever: ask server to check for all possible rights */
2409         cache.mask = MAY_EXEC | MAY_WRITE | MAY_READ;
2410         cache.cred = cred;
2411         cache.jiffies = jiffies;
2412         status = NFS_PROTO(inode)->access(inode, &cache);
2413         if (status != 0) {
2414                 if (status == -ESTALE) {
2415                         nfs_zap_caches(inode);
2416                         if (!S_ISDIR(inode->i_mode))
2417                                 set_bit(NFS_INO_STALE, &NFS_I(inode)->flags);
2418                 }
2419                 goto out;
2420         }
2421         nfs_access_add_cache(inode, &cache);
2422 out_cached:
2423         if ((mask & ~cache.mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) != 0)
2424                 status = -EACCES;
2425 out:
2426         trace_nfs_access_exit(inode, status);
2427         return status;
2428 }
2429
2430 static int nfs_open_permission_mask(int openflags)
2431 {
2432         int mask = 0;
2433
2434         if (openflags & __FMODE_EXEC) {
2435                 /* ONLY check exec rights */
2436                 mask = MAY_EXEC;
2437         } else {
2438                 if ((openflags & O_ACCMODE) != O_WRONLY)
2439                         mask |= MAY_READ;
2440                 if ((openflags & O_ACCMODE) != O_RDONLY)
2441                         mask |= MAY_WRITE;
2442         }
2443
2444         return mask;
2445 }
2446
2447 int nfs_may_open(struct inode *inode, struct rpc_cred *cred, int openflags)
2448 {
2449         return nfs_do_access(inode, cred, nfs_open_permission_mask(openflags));
2450 }
2451 EXPORT_SYMBOL_GPL(nfs_may_open);
2452
2453 static int nfs_execute_ok(struct inode *inode, int mask)
2454 {
2455         struct nfs_server *server = NFS_SERVER(inode);
2456         int ret;
2457
2458         if (mask & MAY_NOT_BLOCK)
2459                 ret = nfs_revalidate_inode_rcu(server, inode);
2460         else
2461                 ret = nfs_revalidate_inode(server, inode);
2462         if (ret == 0 && !execute_ok(inode))
2463                 ret = -EACCES;
2464         return ret;
2465 }
2466
2467 int nfs_permission(struct inode *inode, int mask)
2468 {
2469         struct rpc_cred *cred;
2470         int res = 0;
2471
2472         nfs_inc_stats(inode, NFSIOS_VFSACCESS);
2473
2474         if ((mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
2475                 goto out;
2476         /* Is this sys_access() ? */
2477         if (mask & (MAY_ACCESS | MAY_CHDIR))
2478                 goto force_lookup;
2479
2480         switch (inode->i_mode & S_IFMT) {
2481                 case S_IFLNK:
2482                         goto out;
2483                 case S_IFREG:
2484                         if ((mask & MAY_OPEN) &&
2485                            nfs_server_capable(inode, NFS_CAP_ATOMIC_OPEN))
2486                                 return 0;
2487                         break;
2488                 case S_IFDIR:
2489                         /*
2490                          * Optimize away all write operations, since the server
2491                          * will check permissions when we perform the op.
2492                          */
2493                         if ((mask & MAY_WRITE) && !(mask & MAY_READ))
2494                                 goto out;
2495         }
2496
2497 force_lookup:
2498         if (!NFS_PROTO(inode)->access)
2499                 goto out_notsup;
2500
2501         /* Always try fast lookups first */
2502         rcu_read_lock();
2503         cred = rpc_lookup_cred_nonblock();
2504         if (!IS_ERR(cred))
2505                 res = nfs_do_access(inode, cred, mask|MAY_NOT_BLOCK);
2506         else
2507                 res = PTR_ERR(cred);
2508         rcu_read_unlock();
2509         if (res == -ECHILD && !(mask & MAY_NOT_BLOCK)) {
2510                 /* Fast lookup failed, try the slow way */
2511                 cred = rpc_lookup_cred();
2512                 if (!IS_ERR(cred)) {
2513                         res = nfs_do_access(inode, cred, mask);
2514                         put_rpccred(cred);
2515                 } else
2516                         res = PTR_ERR(cred);
2517         }
2518 out:
2519         if (!res && (mask & MAY_EXEC))
2520                 res = nfs_execute_ok(inode, mask);
2521
2522         dfprintk(VFS, "NFS: permission(%s/%lu), mask=0x%x, res=%d\n",
2523                 inode->i_sb->s_id, inode->i_ino, mask, res);
2524         return res;
2525 out_notsup:
2526         if (mask & MAY_NOT_BLOCK)
2527                 return -ECHILD;
2528
2529         res = nfs_revalidate_inode(NFS_SERVER(inode), inode);
2530         if (res == 0)
2531                 res = generic_permission(inode, mask);
2532         goto out;
2533 }
2534 EXPORT_SYMBOL_GPL(nfs_permission);
2535
2536 /*
2537  * Local variables:
2538  *  version-control: t
2539  *  kept-new-versions: 5
2540  * End:
2541  */