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