Mention branches and keyring.
[releases.git] / 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 (!res) {
1606                 inode = d_inode(dentry);
1607                 if ((lookup_flags & LOOKUP_DIRECTORY) && inode &&
1608                     !(S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)))
1609                         res = ERR_PTR(-ENOTDIR);
1610                 else if (inode && S_ISREG(inode->i_mode))
1611                         res = ERR_PTR(-EOPENSTALE);
1612         } else if (!IS_ERR(res)) {
1613                 inode = d_inode(res);
1614                 if ((lookup_flags & LOOKUP_DIRECTORY) && inode &&
1615                     !(S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))) {
1616                         dput(res);
1617                         res = ERR_PTR(-ENOTDIR);
1618                 } else if (inode && S_ISREG(inode->i_mode)) {
1619                         dput(res);
1620                         res = ERR_PTR(-EOPENSTALE);
1621                 }
1622         }
1623         if (switched) {
1624                 d_lookup_done(dentry);
1625                 if (!res)
1626                         res = dentry;
1627                 else
1628                         dput(dentry);
1629         }
1630         if (IS_ERR(res))
1631                 return PTR_ERR(res);
1632         return finish_no_open(file, res);
1633 }
1634 EXPORT_SYMBOL_GPL(nfs_atomic_open);
1635
1636 static int nfs4_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1637 {
1638         struct inode *inode;
1639         int ret = 0;
1640
1641         if (!(flags & LOOKUP_OPEN) || (flags & LOOKUP_DIRECTORY))
1642                 goto no_open;
1643         if (d_mountpoint(dentry))
1644                 goto no_open;
1645         if (NFS_SB(dentry->d_sb)->caps & NFS_CAP_ATOMIC_OPEN_V1)
1646                 goto no_open;
1647
1648         inode = d_inode(dentry);
1649
1650         /* We can't create new files in nfs_open_revalidate(), so we
1651          * optimize away revalidation of negative dentries.
1652          */
1653         if (inode == NULL) {
1654                 struct dentry *parent;
1655                 struct inode *dir;
1656
1657                 if (flags & LOOKUP_RCU) {
1658                         parent = ACCESS_ONCE(dentry->d_parent);
1659                         dir = d_inode_rcu(parent);
1660                         if (!dir)
1661                                 return -ECHILD;
1662                 } else {
1663                         parent = dget_parent(dentry);
1664                         dir = d_inode(parent);
1665                 }
1666                 if (!nfs_neg_need_reval(dir, dentry, flags))
1667                         ret = 1;
1668                 else if (flags & LOOKUP_RCU)
1669                         ret = -ECHILD;
1670                 if (!(flags & LOOKUP_RCU))
1671                         dput(parent);
1672                 else if (parent != ACCESS_ONCE(dentry->d_parent))
1673                         return -ECHILD;
1674                 goto out;
1675         }
1676
1677         /* NFS only supports OPEN on regular files */
1678         if (!S_ISREG(inode->i_mode))
1679                 goto no_open;
1680         /* We cannot do exclusive creation on a positive dentry */
1681         if (flags & LOOKUP_EXCL)
1682                 goto no_open;
1683
1684         /* Let f_op->open() actually open (and revalidate) the file */
1685         ret = 1;
1686
1687 out:
1688         return ret;
1689
1690 no_open:
1691         return nfs_lookup_revalidate(dentry, flags);
1692 }
1693
1694 #endif /* CONFIG_NFSV4 */
1695
1696 /*
1697  * Code common to create, mkdir, and mknod.
1698  */
1699 int nfs_instantiate(struct dentry *dentry, struct nfs_fh *fhandle,
1700                                 struct nfs_fattr *fattr,
1701                                 struct nfs4_label *label)
1702 {
1703         struct dentry *parent = dget_parent(dentry);
1704         struct inode *dir = d_inode(parent);
1705         struct inode *inode;
1706         int error = -EACCES;
1707
1708         d_drop(dentry);
1709
1710         /* We may have been initialized further down */
1711         if (d_really_is_positive(dentry))
1712                 goto out;
1713         if (fhandle->size == 0) {
1714                 error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, NULL);
1715                 if (error)
1716                         goto out_error;
1717         }
1718         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1719         if (!(fattr->valid & NFS_ATTR_FATTR)) {
1720                 struct nfs_server *server = NFS_SB(dentry->d_sb);
1721                 error = server->nfs_client->rpc_ops->getattr(server, fhandle, fattr, NULL);
1722                 if (error < 0)
1723                         goto out_error;
1724         }
1725         inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1726         error = PTR_ERR(inode);
1727         if (IS_ERR(inode))
1728                 goto out_error;
1729         d_add(dentry, inode);
1730 out:
1731         dput(parent);
1732         return 0;
1733 out_error:
1734         nfs_mark_for_revalidate(dir);
1735         dput(parent);
1736         return error;
1737 }
1738 EXPORT_SYMBOL_GPL(nfs_instantiate);
1739
1740 /*
1741  * Following a failed create operation, we drop the dentry rather
1742  * than retain a negative dentry. This avoids a problem in the event
1743  * that the operation succeeded on the server, but an error in the
1744  * reply path made it appear to have failed.
1745  */
1746 int nfs_create(struct inode *dir, struct dentry *dentry,
1747                 umode_t mode, bool excl)
1748 {
1749         struct iattr attr;
1750         int open_flags = excl ? O_CREAT | O_EXCL : O_CREAT;
1751         int error;
1752
1753         dfprintk(VFS, "NFS: create(%s/%lu), %pd\n",
1754                         dir->i_sb->s_id, dir->i_ino, dentry);
1755
1756         attr.ia_mode = mode;
1757         attr.ia_valid = ATTR_MODE;
1758
1759         trace_nfs_create_enter(dir, dentry, open_flags);
1760         error = NFS_PROTO(dir)->create(dir, dentry, &attr, open_flags);
1761         trace_nfs_create_exit(dir, dentry, open_flags, error);
1762         if (error != 0)
1763                 goto out_err;
1764         return 0;
1765 out_err:
1766         d_drop(dentry);
1767         return error;
1768 }
1769 EXPORT_SYMBOL_GPL(nfs_create);
1770
1771 /*
1772  * See comments for nfs_proc_create regarding failed operations.
1773  */
1774 int
1775 nfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev)
1776 {
1777         struct iattr attr;
1778         int status;
1779
1780         dfprintk(VFS, "NFS: mknod(%s/%lu), %pd\n",
1781                         dir->i_sb->s_id, dir->i_ino, dentry);
1782
1783         attr.ia_mode = mode;
1784         attr.ia_valid = ATTR_MODE;
1785
1786         trace_nfs_mknod_enter(dir, dentry);
1787         status = NFS_PROTO(dir)->mknod(dir, dentry, &attr, rdev);
1788         trace_nfs_mknod_exit(dir, dentry, status);
1789         if (status != 0)
1790                 goto out_err;
1791         return 0;
1792 out_err:
1793         d_drop(dentry);
1794         return status;
1795 }
1796 EXPORT_SYMBOL_GPL(nfs_mknod);
1797
1798 /*
1799  * See comments for nfs_proc_create regarding failed operations.
1800  */
1801 int nfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
1802 {
1803         struct iattr attr;
1804         int error;
1805
1806         dfprintk(VFS, "NFS: mkdir(%s/%lu), %pd\n",
1807                         dir->i_sb->s_id, dir->i_ino, dentry);
1808
1809         attr.ia_valid = ATTR_MODE;
1810         attr.ia_mode = mode | S_IFDIR;
1811
1812         trace_nfs_mkdir_enter(dir, dentry);
1813         error = NFS_PROTO(dir)->mkdir(dir, dentry, &attr);
1814         trace_nfs_mkdir_exit(dir, dentry, error);
1815         if (error != 0)
1816                 goto out_err;
1817         return 0;
1818 out_err:
1819         d_drop(dentry);
1820         return error;
1821 }
1822 EXPORT_SYMBOL_GPL(nfs_mkdir);
1823
1824 static void nfs_dentry_handle_enoent(struct dentry *dentry)
1825 {
1826         if (simple_positive(dentry))
1827                 d_delete(dentry);
1828 }
1829
1830 int nfs_rmdir(struct inode *dir, struct dentry *dentry)
1831 {
1832         int error;
1833
1834         dfprintk(VFS, "NFS: rmdir(%s/%lu), %pd\n",
1835                         dir->i_sb->s_id, dir->i_ino, dentry);
1836
1837         trace_nfs_rmdir_enter(dir, dentry);
1838         if (d_really_is_positive(dentry)) {
1839                 down_write(&NFS_I(d_inode(dentry))->rmdir_sem);
1840                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1841                 /* Ensure the VFS deletes this inode */
1842                 switch (error) {
1843                 case 0:
1844                         clear_nlink(d_inode(dentry));
1845                         break;
1846                 case -ENOENT:
1847                         nfs_dentry_handle_enoent(dentry);
1848                 }
1849                 up_write(&NFS_I(d_inode(dentry))->rmdir_sem);
1850         } else
1851                 error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1852         trace_nfs_rmdir_exit(dir, dentry, error);
1853
1854         return error;
1855 }
1856 EXPORT_SYMBOL_GPL(nfs_rmdir);
1857
1858 /*
1859  * Remove a file after making sure there are no pending writes,
1860  * and after checking that the file has only one user. 
1861  *
1862  * We invalidate the attribute cache and free the inode prior to the operation
1863  * to avoid possible races if the server reuses the inode.
1864  */
1865 static int nfs_safe_remove(struct dentry *dentry)
1866 {
1867         struct inode *dir = d_inode(dentry->d_parent);
1868         struct inode *inode = d_inode(dentry);
1869         int error = -EBUSY;
1870                 
1871         dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry);
1872
1873         /* If the dentry was sillyrenamed, we simply call d_delete() */
1874         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1875                 error = 0;
1876                 goto out;
1877         }
1878
1879         trace_nfs_remove_enter(dir, dentry);
1880         if (inode != NULL) {
1881                 NFS_PROTO(inode)->return_delegation(inode);
1882                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1883                 if (error == 0)
1884                         nfs_drop_nlink(inode);
1885         } else
1886                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1887         if (error == -ENOENT)
1888                 nfs_dentry_handle_enoent(dentry);
1889         trace_nfs_remove_exit(dir, dentry, error);
1890 out:
1891         return error;
1892 }
1893
1894 /*  We do silly rename. In case sillyrename() returns -EBUSY, the inode
1895  *  belongs to an active ".nfs..." file and we return -EBUSY.
1896  *
1897  *  If sillyrename() returns 0, we do nothing, otherwise we unlink.
1898  */
1899 int nfs_unlink(struct inode *dir, struct dentry *dentry)
1900 {
1901         int error;
1902         int need_rehash = 0;
1903
1904         dfprintk(VFS, "NFS: unlink(%s/%lu, %pd)\n", dir->i_sb->s_id,
1905                 dir->i_ino, dentry);
1906
1907         trace_nfs_unlink_enter(dir, dentry);
1908         spin_lock(&dentry->d_lock);
1909         if (d_count(dentry) > 1) {
1910                 spin_unlock(&dentry->d_lock);
1911                 /* Start asynchronous writeout of the inode */
1912                 write_inode_now(d_inode(dentry), 0);
1913                 error = nfs_sillyrename(dir, dentry);
1914                 goto out;
1915         }
1916         if (!d_unhashed(dentry)) {
1917                 __d_drop(dentry);
1918                 need_rehash = 1;
1919         }
1920         spin_unlock(&dentry->d_lock);
1921         error = nfs_safe_remove(dentry);
1922         if (!error || error == -ENOENT) {
1923                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1924         } else if (need_rehash)
1925                 d_rehash(dentry);
1926 out:
1927         trace_nfs_unlink_exit(dir, dentry, error);
1928         return error;
1929 }
1930 EXPORT_SYMBOL_GPL(nfs_unlink);
1931
1932 /*
1933  * To create a symbolic link, most file systems instantiate a new inode,
1934  * add a page to it containing the path, then write it out to the disk
1935  * using prepare_write/commit_write.
1936  *
1937  * Unfortunately the NFS client can't create the in-core inode first
1938  * because it needs a file handle to create an in-core inode (see
1939  * fs/nfs/inode.c:nfs_fhget).  We only have a file handle *after* the
1940  * symlink request has completed on the server.
1941  *
1942  * So instead we allocate a raw page, copy the symname into it, then do
1943  * the SYMLINK request with the page as the buffer.  If it succeeds, we
1944  * now have a new file handle and can instantiate an in-core NFS inode
1945  * and move the raw page into its mapping.
1946  */
1947 int nfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1948 {
1949         struct page *page;
1950         char *kaddr;
1951         struct iattr attr;
1952         unsigned int pathlen = strlen(symname);
1953         int error;
1954
1955         dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s)\n", dir->i_sb->s_id,
1956                 dir->i_ino, dentry, symname);
1957
1958         if (pathlen > PAGE_SIZE)
1959                 return -ENAMETOOLONG;
1960
1961         attr.ia_mode = S_IFLNK | S_IRWXUGO;
1962         attr.ia_valid = ATTR_MODE;
1963
1964         page = alloc_page(GFP_USER);
1965         if (!page)
1966                 return -ENOMEM;
1967
1968         kaddr = page_address(page);
1969         memcpy(kaddr, symname, pathlen);
1970         if (pathlen < PAGE_SIZE)
1971                 memset(kaddr + pathlen, 0, PAGE_SIZE - pathlen);
1972
1973         trace_nfs_symlink_enter(dir, dentry);
1974         error = NFS_PROTO(dir)->symlink(dir, dentry, page, pathlen, &attr);
1975         trace_nfs_symlink_exit(dir, dentry, error);
1976         if (error != 0) {
1977                 dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s) error %d\n",
1978                         dir->i_sb->s_id, dir->i_ino,
1979                         dentry, symname, error);
1980                 d_drop(dentry);
1981                 __free_page(page);
1982                 return error;
1983         }
1984
1985         /*
1986          * No big deal if we can't add this page to the page cache here.
1987          * READLINK will get the missing page from the server if needed.
1988          */
1989         if (!add_to_page_cache_lru(page, d_inode(dentry)->i_mapping, 0,
1990                                                         GFP_KERNEL)) {
1991                 SetPageUptodate(page);
1992                 unlock_page(page);
1993                 /*
1994                  * add_to_page_cache_lru() grabs an extra page refcount.
1995                  * Drop it here to avoid leaking this page later.
1996                  */
1997                 put_page(page);
1998         } else
1999                 __free_page(page);
2000
2001         return 0;
2002 }
2003 EXPORT_SYMBOL_GPL(nfs_symlink);
2004
2005 int
2006 nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2007 {
2008         struct inode *inode = d_inode(old_dentry);
2009         int error;
2010
2011         dfprintk(VFS, "NFS: link(%pd2 -> %pd2)\n",
2012                 old_dentry, dentry);
2013
2014         trace_nfs_link_enter(inode, dir, dentry);
2015         NFS_PROTO(inode)->return_delegation(inode);
2016
2017         d_drop(dentry);
2018         error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
2019         if (error == 0) {
2020                 ihold(inode);
2021                 d_add(dentry, inode);
2022         }
2023         trace_nfs_link_exit(inode, dir, dentry, error);
2024         return error;
2025 }
2026 EXPORT_SYMBOL_GPL(nfs_link);
2027
2028 /*
2029  * RENAME
2030  * FIXME: Some nfsds, like the Linux user space nfsd, may generate a
2031  * different file handle for the same inode after a rename (e.g. when
2032  * moving to a different directory). A fail-safe method to do so would
2033  * be to look up old_dir/old_name, create a link to new_dir/new_name and
2034  * rename the old file using the sillyrename stuff. This way, the original
2035  * file in old_dir will go away when the last process iput()s the inode.
2036  *
2037  * FIXED.
2038  * 
2039  * It actually works quite well. One needs to have the possibility for
2040  * at least one ".nfs..." file in each directory the file ever gets
2041  * moved or linked to which happens automagically with the new
2042  * implementation that only depends on the dcache stuff instead of
2043  * using the inode layer
2044  *
2045  * Unfortunately, things are a little more complicated than indicated
2046  * above. For a cross-directory move, we want to make sure we can get
2047  * rid of the old inode after the operation.  This means there must be
2048  * no pending writes (if it's a file), and the use count must be 1.
2049  * If these conditions are met, we can drop the dentries before doing
2050  * the rename.
2051  */
2052 int nfs_rename(struct inode *old_dir, struct dentry *old_dentry,
2053                struct inode *new_dir, struct dentry *new_dentry,
2054                unsigned int flags)
2055 {
2056         struct inode *old_inode = d_inode(old_dentry);
2057         struct inode *new_inode = d_inode(new_dentry);
2058         struct dentry *dentry = NULL, *rehash = NULL;
2059         struct rpc_task *task;
2060         int error = -EBUSY;
2061
2062         if (flags)
2063                 return -EINVAL;
2064
2065         dfprintk(VFS, "NFS: rename(%pd2 -> %pd2, ct=%d)\n",
2066                  old_dentry, new_dentry,
2067                  d_count(new_dentry));
2068
2069         trace_nfs_rename_enter(old_dir, old_dentry, new_dir, new_dentry);
2070         /*
2071          * For non-directories, check whether the target is busy and if so,
2072          * make a copy of the dentry and then do a silly-rename. If the
2073          * silly-rename succeeds, the copied dentry is hashed and becomes
2074          * the new target.
2075          */
2076         if (new_inode && !S_ISDIR(new_inode->i_mode)) {
2077                 /*
2078                  * To prevent any new references to the target during the
2079                  * rename, we unhash the dentry in advance.
2080                  */
2081                 if (!d_unhashed(new_dentry)) {
2082                         d_drop(new_dentry);
2083                         rehash = new_dentry;
2084                 }
2085
2086                 if (d_count(new_dentry) > 2) {
2087                         int err;
2088
2089                         /* copy the target dentry's name */
2090                         dentry = d_alloc(new_dentry->d_parent,
2091                                          &new_dentry->d_name);
2092                         if (!dentry)
2093                                 goto out;
2094
2095                         /* silly-rename the existing target ... */
2096                         err = nfs_sillyrename(new_dir, new_dentry);
2097                         if (err)
2098                                 goto out;
2099
2100                         new_dentry = dentry;
2101                         rehash = NULL;
2102                         new_inode = NULL;
2103                 }
2104         }
2105
2106         NFS_PROTO(old_inode)->return_delegation(old_inode);
2107         if (new_inode != NULL)
2108                 NFS_PROTO(new_inode)->return_delegation(new_inode);
2109
2110         task = nfs_async_rename(old_dir, new_dir, old_dentry, new_dentry, NULL);
2111         if (IS_ERR(task)) {
2112                 error = PTR_ERR(task);
2113                 goto out;
2114         }
2115
2116         error = rpc_wait_for_completion_task(task);
2117         if (error == 0)
2118                 error = task->tk_status;
2119         rpc_put_task(task);
2120         nfs_mark_for_revalidate(old_inode);
2121 out:
2122         if (rehash)
2123                 d_rehash(rehash);
2124         trace_nfs_rename_exit(old_dir, old_dentry,
2125                         new_dir, new_dentry, error);
2126         if (!error) {
2127                 if (new_inode != NULL)
2128                         nfs_drop_nlink(new_inode);
2129                 d_move(old_dentry, new_dentry);
2130                 nfs_set_verifier(old_dentry,
2131                                         nfs_save_change_attribute(new_dir));
2132         } else if (error == -ENOENT)
2133                 nfs_dentry_handle_enoent(old_dentry);
2134
2135         /* new dentry created? */
2136         if (dentry)
2137                 dput(dentry);
2138         return error;
2139 }
2140 EXPORT_SYMBOL_GPL(nfs_rename);
2141
2142 static DEFINE_SPINLOCK(nfs_access_lru_lock);
2143 static LIST_HEAD(nfs_access_lru_list);
2144 static atomic_long_t nfs_access_nr_entries;
2145
2146 static unsigned long nfs_access_max_cachesize = ULONG_MAX;
2147 module_param(nfs_access_max_cachesize, ulong, 0644);
2148 MODULE_PARM_DESC(nfs_access_max_cachesize, "NFS access maximum total cache length");
2149
2150 static void nfs_access_free_entry(struct nfs_access_entry *entry)
2151 {
2152         put_rpccred(entry->cred);
2153         kfree_rcu(entry, rcu_head);
2154         smp_mb__before_atomic();
2155         atomic_long_dec(&nfs_access_nr_entries);
2156         smp_mb__after_atomic();
2157 }
2158
2159 static void nfs_access_free_list(struct list_head *head)
2160 {
2161         struct nfs_access_entry *cache;
2162
2163         while (!list_empty(head)) {
2164                 cache = list_entry(head->next, struct nfs_access_entry, lru);
2165                 list_del(&cache->lru);
2166                 nfs_access_free_entry(cache);
2167         }
2168 }
2169
2170 static unsigned long
2171 nfs_do_access_cache_scan(unsigned int nr_to_scan)
2172 {
2173         LIST_HEAD(head);
2174         struct nfs_inode *nfsi, *next;
2175         struct nfs_access_entry *cache;
2176         long freed = 0;
2177
2178         spin_lock(&nfs_access_lru_lock);
2179         list_for_each_entry_safe(nfsi, next, &nfs_access_lru_list, access_cache_inode_lru) {
2180                 struct inode *inode;
2181
2182                 if (nr_to_scan-- == 0)
2183                         break;
2184                 inode = &nfsi->vfs_inode;
2185                 spin_lock(&inode->i_lock);
2186                 if (list_empty(&nfsi->access_cache_entry_lru))
2187                         goto remove_lru_entry;
2188                 cache = list_entry(nfsi->access_cache_entry_lru.next,
2189                                 struct nfs_access_entry, lru);
2190                 list_move(&cache->lru, &head);
2191                 rb_erase(&cache->rb_node, &nfsi->access_cache);
2192                 freed++;
2193                 if (!list_empty(&nfsi->access_cache_entry_lru))
2194                         list_move_tail(&nfsi->access_cache_inode_lru,
2195                                         &nfs_access_lru_list);
2196                 else {
2197 remove_lru_entry:
2198                         list_del_init(&nfsi->access_cache_inode_lru);
2199                         smp_mb__before_atomic();
2200                         clear_bit(NFS_INO_ACL_LRU_SET, &nfsi->flags);
2201                         smp_mb__after_atomic();
2202                 }
2203                 spin_unlock(&inode->i_lock);
2204         }
2205         spin_unlock(&nfs_access_lru_lock);
2206         nfs_access_free_list(&head);
2207         return freed;
2208 }
2209
2210 unsigned long
2211 nfs_access_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
2212 {
2213         int nr_to_scan = sc->nr_to_scan;
2214         gfp_t gfp_mask = sc->gfp_mask;
2215
2216         if ((gfp_mask & GFP_KERNEL) != GFP_KERNEL)
2217                 return SHRINK_STOP;
2218         return nfs_do_access_cache_scan(nr_to_scan);
2219 }
2220
2221
2222 unsigned long
2223 nfs_access_cache_count(struct shrinker *shrink, struct shrink_control *sc)
2224 {
2225         return vfs_pressure_ratio(atomic_long_read(&nfs_access_nr_entries));
2226 }
2227
2228 static void
2229 nfs_access_cache_enforce_limit(void)
2230 {
2231         long nr_entries = atomic_long_read(&nfs_access_nr_entries);
2232         unsigned long diff;
2233         unsigned int nr_to_scan;
2234
2235         if (nr_entries < 0 || nr_entries <= nfs_access_max_cachesize)
2236                 return;
2237         nr_to_scan = 100;
2238         diff = nr_entries - nfs_access_max_cachesize;
2239         if (diff < nr_to_scan)
2240                 nr_to_scan = diff;
2241         nfs_do_access_cache_scan(nr_to_scan);
2242 }
2243
2244 static void __nfs_access_zap_cache(struct nfs_inode *nfsi, struct list_head *head)
2245 {
2246         struct rb_root *root_node = &nfsi->access_cache;
2247         struct rb_node *n;
2248         struct nfs_access_entry *entry;
2249
2250         /* Unhook entries from the cache */
2251         while ((n = rb_first(root_node)) != NULL) {
2252                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2253                 rb_erase(n, root_node);
2254                 list_move(&entry->lru, head);
2255         }
2256         nfsi->cache_validity &= ~NFS_INO_INVALID_ACCESS;
2257 }
2258
2259 void nfs_access_zap_cache(struct inode *inode)
2260 {
2261         LIST_HEAD(head);
2262
2263         if (test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags) == 0)
2264                 return;
2265         /* Remove from global LRU init */
2266         spin_lock(&nfs_access_lru_lock);
2267         if (test_and_clear_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2268                 list_del_init(&NFS_I(inode)->access_cache_inode_lru);
2269
2270         spin_lock(&inode->i_lock);
2271         __nfs_access_zap_cache(NFS_I(inode), &head);
2272         spin_unlock(&inode->i_lock);
2273         spin_unlock(&nfs_access_lru_lock);
2274         nfs_access_free_list(&head);
2275 }
2276 EXPORT_SYMBOL_GPL(nfs_access_zap_cache);
2277
2278 static struct nfs_access_entry *nfs_access_search_rbtree(struct inode *inode, struct rpc_cred *cred)
2279 {
2280         struct rb_node *n = NFS_I(inode)->access_cache.rb_node;
2281         struct nfs_access_entry *entry;
2282
2283         while (n != NULL) {
2284                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
2285
2286                 if (cred < entry->cred)
2287                         n = n->rb_left;
2288                 else if (cred > entry->cred)
2289                         n = n->rb_right;
2290                 else
2291                         return entry;
2292         }
2293         return NULL;
2294 }
2295
2296 static int nfs_access_get_cached(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res, bool may_block)
2297 {
2298         struct nfs_inode *nfsi = NFS_I(inode);
2299         struct nfs_access_entry *cache;
2300         bool retry = true;
2301         int err;
2302
2303         spin_lock(&inode->i_lock);
2304         for(;;) {
2305                 if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2306                         goto out_zap;
2307                 cache = nfs_access_search_rbtree(inode, cred);
2308                 err = -ENOENT;
2309                 if (cache == NULL)
2310                         goto out;
2311                 /* Found an entry, is our attribute cache valid? */
2312                 if (!nfs_attribute_cache_expired(inode) &&
2313                     !(nfsi->cache_validity & NFS_INO_INVALID_ATTR))
2314                         break;
2315                 err = -ECHILD;
2316                 if (!may_block)
2317                         goto out;
2318                 if (!retry)
2319                         goto out_zap;
2320                 spin_unlock(&inode->i_lock);
2321                 err = __nfs_revalidate_inode(NFS_SERVER(inode), inode);
2322                 if (err)
2323                         return err;
2324                 spin_lock(&inode->i_lock);
2325                 retry = false;
2326         }
2327         res->jiffies = cache->jiffies;
2328         res->cred = cache->cred;
2329         res->mask = cache->mask;
2330         list_move_tail(&cache->lru, &nfsi->access_cache_entry_lru);
2331         err = 0;
2332 out:
2333         spin_unlock(&inode->i_lock);
2334         return err;
2335 out_zap:
2336         spin_unlock(&inode->i_lock);
2337         nfs_access_zap_cache(inode);
2338         return -ENOENT;
2339 }
2340
2341 static int nfs_access_get_cached_rcu(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2342 {
2343         /* Only check the most recently returned cache entry,
2344          * but do it without locking.
2345          */
2346         struct nfs_inode *nfsi = NFS_I(inode);
2347         struct nfs_access_entry *cache;
2348         int err = -ECHILD;
2349         struct list_head *lh;
2350
2351         rcu_read_lock();
2352         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2353                 goto out;
2354         lh = rcu_dereference(nfsi->access_cache_entry_lru.prev);
2355         cache = list_entry(lh, struct nfs_access_entry, lru);
2356         if (lh == &nfsi->access_cache_entry_lru ||
2357             cred != cache->cred)
2358                 cache = NULL;
2359         if (cache == NULL)
2360                 goto out;
2361         err = nfs_revalidate_inode_rcu(NFS_SERVER(inode), inode);
2362         if (err)
2363                 goto out;
2364         res->jiffies = cache->jiffies;
2365         res->cred = cache->cred;
2366         res->mask = cache->mask;
2367 out:
2368         rcu_read_unlock();
2369         return err;
2370 }
2371
2372 static void nfs_access_add_rbtree(struct inode *inode, struct nfs_access_entry *set)
2373 {
2374         struct nfs_inode *nfsi = NFS_I(inode);
2375         struct rb_root *root_node = &nfsi->access_cache;
2376         struct rb_node **p = &root_node->rb_node;
2377         struct rb_node *parent = NULL;
2378         struct nfs_access_entry *entry;
2379
2380         spin_lock(&inode->i_lock);
2381         while (*p != NULL) {
2382                 parent = *p;
2383                 entry = rb_entry(parent, struct nfs_access_entry, rb_node);
2384
2385                 if (set->cred < entry->cred)
2386                         p = &parent->rb_left;
2387                 else if (set->cred > entry->cred)
2388                         p = &parent->rb_right;
2389                 else
2390                         goto found;
2391         }
2392         rb_link_node(&set->rb_node, parent, p);
2393         rb_insert_color(&set->rb_node, root_node);
2394         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2395         spin_unlock(&inode->i_lock);
2396         return;
2397 found:
2398         rb_replace_node(parent, &set->rb_node, root_node);
2399         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2400         list_del(&entry->lru);
2401         spin_unlock(&inode->i_lock);
2402         nfs_access_free_entry(entry);
2403 }
2404
2405 void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set)
2406 {
2407         struct nfs_access_entry *cache = kmalloc(sizeof(*cache), GFP_KERNEL);
2408         if (cache == NULL)
2409                 return;
2410         RB_CLEAR_NODE(&cache->rb_node);
2411         cache->jiffies = set->jiffies;
2412         cache->cred = get_rpccred(set->cred);
2413         cache->mask = set->mask;
2414
2415         /* The above field assignments must be visible
2416          * before this item appears on the lru.  We cannot easily
2417          * use rcu_assign_pointer, so just force the memory barrier.
2418          */
2419         smp_wmb();
2420         nfs_access_add_rbtree(inode, cache);
2421
2422         /* Update accounting */
2423         smp_mb__before_atomic();
2424         atomic_long_inc(&nfs_access_nr_entries);
2425         smp_mb__after_atomic();
2426
2427         /* Add inode to global LRU list */
2428         if (!test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags)) {
2429                 spin_lock(&nfs_access_lru_lock);
2430                 if (!test_and_set_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2431                         list_add_tail(&NFS_I(inode)->access_cache_inode_lru,
2432                                         &nfs_access_lru_list);
2433                 spin_unlock(&nfs_access_lru_lock);
2434         }
2435         nfs_access_cache_enforce_limit();
2436 }
2437 EXPORT_SYMBOL_GPL(nfs_access_add_cache);
2438
2439 void nfs_access_set_mask(struct nfs_access_entry *entry, u32 access_result)
2440 {
2441         entry->mask = 0;
2442         if (access_result & NFS4_ACCESS_READ)
2443                 entry->mask |= MAY_READ;
2444         if (access_result &
2445             (NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE))
2446                 entry->mask |= MAY_WRITE;
2447         if (access_result & (NFS4_ACCESS_LOOKUP|NFS4_ACCESS_EXECUTE))
2448                 entry->mask |= MAY_EXEC;
2449 }
2450 EXPORT_SYMBOL_GPL(nfs_access_set_mask);
2451
2452 static int nfs_do_access(struct inode *inode, struct rpc_cred *cred, int mask)
2453 {
2454         struct nfs_access_entry cache;
2455         bool may_block = (mask & MAY_NOT_BLOCK) == 0;
2456         int status;
2457
2458         trace_nfs_access_enter(inode);
2459
2460         status = nfs_access_get_cached_rcu(inode, cred, &cache);
2461         if (status != 0)
2462                 status = nfs_access_get_cached(inode, cred, &cache, may_block);
2463         if (status == 0)
2464                 goto out_cached;
2465
2466         status = -ECHILD;
2467         if (!may_block)
2468                 goto out;
2469
2470         /* Be clever: ask server to check for all possible rights */
2471         cache.mask = MAY_EXEC | MAY_WRITE | MAY_READ;
2472         cache.cred = cred;
2473         cache.jiffies = jiffies;
2474         status = NFS_PROTO(inode)->access(inode, &cache);
2475         if (status != 0) {
2476                 if (status == -ESTALE) {
2477                         nfs_zap_caches(inode);
2478                         if (!S_ISDIR(inode->i_mode))
2479                                 set_bit(NFS_INO_STALE, &NFS_I(inode)->flags);
2480                 }
2481                 goto out;
2482         }
2483         nfs_access_add_cache(inode, &cache);
2484 out_cached:
2485         if ((mask & ~cache.mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) != 0)
2486                 status = -EACCES;
2487 out:
2488         trace_nfs_access_exit(inode, status);
2489         return status;
2490 }
2491
2492 static int nfs_open_permission_mask(int openflags)
2493 {
2494         int mask = 0;
2495
2496         if (openflags & __FMODE_EXEC) {
2497                 /* ONLY check exec rights */
2498                 mask = MAY_EXEC;
2499         } else {
2500                 if ((openflags & O_ACCMODE) != O_WRONLY)
2501                         mask |= MAY_READ;
2502                 if ((openflags & O_ACCMODE) != O_RDONLY)
2503                         mask |= MAY_WRITE;
2504         }
2505
2506         return mask;
2507 }
2508
2509 int nfs_may_open(struct inode *inode, struct rpc_cred *cred, int openflags)
2510 {
2511         return nfs_do_access(inode, cred, nfs_open_permission_mask(openflags));
2512 }
2513 EXPORT_SYMBOL_GPL(nfs_may_open);
2514
2515 static int nfs_execute_ok(struct inode *inode, int mask)
2516 {
2517         struct nfs_server *server = NFS_SERVER(inode);
2518         int ret;
2519
2520         if (mask & MAY_NOT_BLOCK)
2521                 ret = nfs_revalidate_inode_rcu(server, inode);
2522         else
2523                 ret = nfs_revalidate_inode(server, inode);
2524         if (ret == 0 && !execute_ok(inode))
2525                 ret = -EACCES;
2526         return ret;
2527 }
2528
2529 int nfs_permission(struct inode *inode, int mask)
2530 {
2531         struct rpc_cred *cred;
2532         int res = 0;
2533
2534         nfs_inc_stats(inode, NFSIOS_VFSACCESS);
2535
2536         if ((mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
2537                 goto out;
2538         /* Is this sys_access() ? */
2539         if (mask & (MAY_ACCESS | MAY_CHDIR))
2540                 goto force_lookup;
2541
2542         switch (inode->i_mode & S_IFMT) {
2543                 case S_IFLNK:
2544                         goto out;
2545                 case S_IFREG:
2546                         if ((mask & MAY_OPEN) &&
2547                            nfs_server_capable(inode, NFS_CAP_ATOMIC_OPEN))
2548                                 return 0;
2549                         break;
2550                 case S_IFDIR:
2551                         /*
2552                          * Optimize away all write operations, since the server
2553                          * will check permissions when we perform the op.
2554                          */
2555                         if ((mask & MAY_WRITE) && !(mask & MAY_READ))
2556                                 goto out;
2557         }
2558
2559 force_lookup:
2560         if (!NFS_PROTO(inode)->access)
2561                 goto out_notsup;
2562
2563         /* Always try fast lookups first */
2564         rcu_read_lock();
2565         cred = rpc_lookup_cred_nonblock();
2566         if (!IS_ERR(cred))
2567                 res = nfs_do_access(inode, cred, mask|MAY_NOT_BLOCK);
2568         else
2569                 res = PTR_ERR(cred);
2570         rcu_read_unlock();
2571         if (res == -ECHILD && !(mask & MAY_NOT_BLOCK)) {
2572                 /* Fast lookup failed, try the slow way */
2573                 cred = rpc_lookup_cred();
2574                 if (!IS_ERR(cred)) {
2575                         res = nfs_do_access(inode, cred, mask);
2576                         put_rpccred(cred);
2577                 } else
2578                         res = PTR_ERR(cred);
2579         }
2580 out:
2581         if (!res && (mask & MAY_EXEC))
2582                 res = nfs_execute_ok(inode, mask);
2583
2584         dfprintk(VFS, "NFS: permission(%s/%lu), mask=0x%x, res=%d\n",
2585                 inode->i_sb->s_id, inode->i_ino, mask, res);
2586         return res;
2587 out_notsup:
2588         if (mask & MAY_NOT_BLOCK)
2589                 return -ECHILD;
2590
2591         res = nfs_revalidate_inode(NFS_SERVER(inode), inode);
2592         if (res == 0)
2593                 res = generic_permission(inode, mask);
2594         goto out;
2595 }
2596 EXPORT_SYMBOL_GPL(nfs_permission);
2597
2598 /*
2599  * Local variables:
2600  *  version-control: t
2601  *  kept-new-versions: 5
2602  * End:
2603  */