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