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