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