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