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