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