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