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