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