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