xref: /linux/fs/nfsd/filecache.c (revision fcc202d324e5d2a21557ddd20fc3f96e08c4f72d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * The NFSD open file cache.
4  *
5  * (c) 2015 - Jeff Layton <jeff.layton@primarydata.com>
6  *
7  * An nfsd_file object is a per-file collection of open state that binds
8  * together:
9  *   - a struct file *
10  *   - a user credential
11  *   - a network namespace
12  *   - a read-ahead context
13  *   - monitoring for writeback errors
14  *
15  * nfsd_file objects are reference-counted. Consumers acquire a new
16  * object via the nfsd_file_acquire API. They manage their interest in
17  * the acquired object, and hence the object's reference count, via
18  * nfsd_file_get and nfsd_file_put. There are two varieties of nfsd_file
19  * object:
20  *
21  *  * non-garbage-collected: When a consumer wants to precisely control
22  *    the lifetime of a file's open state, it acquires a non-garbage-
23  *    collected nfsd_file. The final nfsd_file_put releases the open
24  *    state immediately.
25  *
26  *  * garbage-collected: When a consumer does not control the lifetime
27  *    of open state, it acquires a garbage-collected nfsd_file. The
28  *    final nfsd_file_put allows the open state to linger for a period
29  *    during which it may be re-used.
30  */
31 
32 #include <linux/hash.h>
33 #include <linux/slab.h>
34 #include <linux/file.h>
35 #include <linux/pagemap.h>
36 #include <linux/sched.h>
37 #include <linux/list_lru.h>
38 #include <linux/fsnotify_backend.h>
39 #include <linux/fsnotify.h>
40 #include <linux/seq_file.h>
41 #include <linux/rhashtable.h>
42 #include <linux/nfslocalio.h>
43 
44 #include "vfs.h"
45 #include "nfsd.h"
46 #include "nfserr.h"
47 #include "nfsfh.h"
48 #include "netns.h"
49 #include "filecache.h"
50 #include "trace.h"
51 
52 #define NFSD_LAUNDRETTE_DELAY		     (2 * HZ)
53 
54 #define NFSD_FILE_CACHE_UP		     (0)
55 
56 /* We only care about NFSD_MAY_READ/WRITE for this cache */
57 #define NFSD_FILE_MAY_MASK	(NFSD_MAY_READ|NFSD_MAY_WRITE|NFSD_MAY_LOCALIO)
58 
59 /* If the shrinker runs between calls to list_lru_walk_node() in
60  * nfsd_file_gc(), the "remaining" count will be wrong.  This could
61  * result in premature freeing of some files.  This may not matter much
62  * but is easy to fix with this spinlock which temporarily disables
63  * the shrinker.
64  *
65  * It also serializes callers of nfsd_file_dispose_list_delayed()
66  * against per-net shutdown.
67  */
68 static DEFINE_SPINLOCK(nfsd_gc_lock);
69 
70 static DEFINE_PER_CPU(unsigned long, nfsd_file_cache_hits);
71 static DEFINE_PER_CPU(unsigned long, nfsd_file_acquisitions);
72 static DEFINE_PER_CPU(unsigned long, nfsd_file_allocations);
73 static DEFINE_PER_CPU(unsigned long, nfsd_file_releases);
74 static DEFINE_PER_CPU(unsigned long, nfsd_file_total_age);
75 static DEFINE_PER_CPU(unsigned long, nfsd_file_evictions);
76 
77 static struct kmem_cache		*nfsd_file_slab;
78 static struct kmem_cache		*nfsd_file_mark_slab;
79 static struct list_lru			nfsd_file_lru;
80 static unsigned long			nfsd_file_flags;
81 static struct fsnotify_group		*nfsd_file_fsnotify_group;
82 static struct fsnotify_group		*nfsd_dir_fsnotify_group;
83 static struct delayed_work		nfsd_filecache_laundrette;
84 static struct rhltable			nfsd_file_rhltable
85 						____cacheline_aligned_in_smp;
86 
87 static bool
88 nfsd_match_cred(const struct cred *c1, const struct cred *c2)
89 {
90 	int i;
91 
92 	if (!uid_eq(c1->fsuid, c2->fsuid))
93 		return false;
94 	if (!gid_eq(c1->fsgid, c2->fsgid))
95 		return false;
96 	if (c1->group_info == NULL || c2->group_info == NULL)
97 		return c1->group_info == c2->group_info;
98 	if (c1->group_info->ngroups != c2->group_info->ngroups)
99 		return false;
100 	for (i = 0; i < c1->group_info->ngroups; i++) {
101 		if (!gid_eq(c1->group_info->gid[i], c2->group_info->gid[i]))
102 			return false;
103 	}
104 	return true;
105 }
106 
107 static const struct rhashtable_params nfsd_file_rhash_params = {
108 	.key_len		= sizeof_field(struct nfsd_file, nf_inode),
109 	.key_offset		= offsetof(struct nfsd_file, nf_inode),
110 	.head_offset		= offsetof(struct nfsd_file, nf_rlist),
111 
112 	/*
113 	 * Start with a single page hash table to reduce resizing churn
114 	 * on light workloads.
115 	 */
116 	.min_size		= 256,
117 	.automatic_shrinking	= true,
118 };
119 
120 static void
121 nfsd_file_schedule_laundrette(void)
122 {
123 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags))
124 		queue_delayed_work(system_dfl_wq, &nfsd_filecache_laundrette,
125 				   NFSD_LAUNDRETTE_DELAY);
126 }
127 
128 static void
129 nfsd_file_slab_free(struct rcu_head *rcu)
130 {
131 	struct nfsd_file *nf = container_of(rcu, struct nfsd_file, nf_rcu);
132 
133 	put_cred(nf->nf_cred);
134 	kmem_cache_free(nfsd_file_slab, nf);
135 }
136 
137 static void
138 nfsd_file_mark_free(struct fsnotify_mark *mark)
139 {
140 	struct nfsd_file_mark *nfm = container_of(mark, struct nfsd_file_mark,
141 						  nfm_mark);
142 
143 	kmem_cache_free(nfsd_file_mark_slab, nfm);
144 }
145 
146 static struct nfsd_file_mark *
147 nfsd_file_mark_get(struct nfsd_file_mark *nfm)
148 {
149 	if (!refcount_inc_not_zero(&nfm->nfm_ref))
150 		return NULL;
151 	return nfm;
152 }
153 
154 static void
155 nfsd_file_mark_put(struct nfsd_file_mark *nfm)
156 {
157 	if (refcount_dec_and_test(&nfm->nfm_ref)) {
158 		fsnotify_destroy_mark(&nfm->nfm_mark, nfm->nfm_mark.group);
159 		fsnotify_put_mark(&nfm->nfm_mark);
160 	}
161 }
162 
163 static struct nfsd_file_mark *
164 nfsd_file_mark_find_or_create(struct inode *inode)
165 {
166 	struct nfsd_file_mark	*nfm = NULL, *new;
167 	struct fsnotify_group	*group;
168 	struct fsnotify_mark	*mark;
169 	int			err;
170 
171 	group = S_ISDIR(inode->i_mode) ? nfsd_dir_fsnotify_group : nfsd_file_fsnotify_group;
172 
173 	do {
174 		fsnotify_group_lock(group);
175 		mark = fsnotify_find_inode_mark(inode, group);
176 		if (mark) {
177 			nfm = nfsd_file_mark_get(container_of(mark,
178 						 struct nfsd_file_mark,
179 						 nfm_mark));
180 			fsnotify_group_unlock(group);
181 			if (nfm) {
182 				fsnotify_put_mark(mark);
183 				break;
184 			}
185 			/* Avoid soft lockup race with nfsd_file_mark_put() */
186 			fsnotify_destroy_mark(mark, group);
187 			fsnotify_put_mark(mark);
188 		} else {
189 			fsnotify_group_unlock(group);
190 		}
191 
192 		/* allocate a new nfm */
193 		new = kmem_cache_alloc(nfsd_file_mark_slab, GFP_KERNEL);
194 		if (!new)
195 			return NULL;
196 		fsnotify_init_mark(&new->nfm_mark, group);
197 		new->nfm_mark.mask = FS_ATTRIB|FS_DELETE_SELF;
198 		refcount_set(&new->nfm_ref, 1);
199 		mutex_init(&new->nfm_recalc_mutex);
200 
201 		err = fsnotify_add_inode_mark(&new->nfm_mark, inode, 0);
202 
203 		/*
204 		 * If the add was successful, then return the object.
205 		 * Otherwise, we need to put the reference we hold on the
206 		 * nfm_mark. The fsnotify code will take a reference and put
207 		 * it on failure, so we can't just free it directly. It's also
208 		 * not safe to call fsnotify_destroy_mark on it as the
209 		 * mark->group will be NULL. Thus, we can't let the nfm_ref
210 		 * counter drive the destruction at this point.
211 		 */
212 		if (likely(!err))
213 			nfm = new;
214 		else
215 			fsnotify_put_mark(&new->nfm_mark);
216 	} while (unlikely(err == -EEXIST));
217 
218 	return nfm;
219 }
220 
221 static struct nfsd_file *
222 nfsd_file_alloc(struct net *net, struct inode *inode, unsigned char need,
223 		bool want_gc)
224 {
225 	struct nfsd_file *nf;
226 
227 	nf = kmem_cache_alloc(nfsd_file_slab, GFP_KERNEL);
228 	if (unlikely(!nf))
229 		return NULL;
230 
231 	this_cpu_inc(nfsd_file_allocations);
232 	INIT_LIST_HEAD(&nf->nf_lru);
233 	INIT_LIST_HEAD(&nf->nf_gc);
234 	nf->nf_birthtime = ktime_get();
235 	nf->nf_file = NULL;
236 	nf->nf_cred = get_current_cred();
237 	nf->nf_net = net;
238 	nf->nf_flags = want_gc ?
239 		BIT(NFSD_FILE_HASHED) | BIT(NFSD_FILE_PENDING) | BIT(NFSD_FILE_GC) :
240 		BIT(NFSD_FILE_HASHED) | BIT(NFSD_FILE_PENDING);
241 	nf->nf_inode = inode;
242 	refcount_set(&nf->nf_ref, 1);
243 	nf->nf_may = need;
244 	nf->nf_mark = NULL;
245 	nf->nf_dio_mem_align = 0;
246 	nf->nf_dio_offset_align = 0;
247 	nf->nf_dio_read_offset_align = 0;
248 	return nf;
249 }
250 
251 /**
252  * nfsd_file_check_write_error - check for writeback errors on a file
253  * @nf: nfsd_file to check for writeback errors
254  *
255  * Check whether a nfsd_file has an unseen error. Reset the write
256  * verifier if so.
257  */
258 static void
259 nfsd_file_check_write_error(struct nfsd_file *nf)
260 {
261 	struct file *file = nf->nf_file;
262 
263 	if ((file->f_mode & FMODE_WRITE) &&
264 	    filemap_check_wb_err(file->f_mapping, READ_ONCE(file->f_wb_err)))
265 		nfsd_reset_write_verifier(net_generic(nf->nf_net, nfsd_net_id));
266 }
267 
268 static void
269 nfsd_file_hash_remove(struct nfsd_file *nf)
270 {
271 	trace_nfsd_file_unhash(nf);
272 	rhltable_remove(&nfsd_file_rhltable, &nf->nf_rlist,
273 			nfsd_file_rhash_params);
274 }
275 
276 static bool
277 nfsd_file_unhash(struct nfsd_file *nf)
278 {
279 	if (test_and_clear_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
280 		nfsd_file_hash_remove(nf);
281 		return true;
282 	}
283 	return false;
284 }
285 
286 static void
287 nfsd_file_free(struct nfsd_file *nf)
288 {
289 	s64 age = ktime_to_ms(ktime_sub(ktime_get(), nf->nf_birthtime));
290 
291 	trace_nfsd_file_free(nf);
292 
293 	this_cpu_inc(nfsd_file_releases);
294 	this_cpu_add(nfsd_file_total_age, age);
295 
296 	nfsd_file_unhash(nf);
297 	if (nf->nf_mark)
298 		nfsd_file_mark_put(nf->nf_mark);
299 	if (nf->nf_file) {
300 		nfsd_file_check_write_error(nf);
301 		nfsd_filp_close(nf->nf_file);
302 	}
303 
304 	/*
305 	 * If this item is still linked via nf_lru, that's a bug.
306 	 * WARN and leak it to preserve system stability.
307 	 */
308 	if (WARN_ON_ONCE(!list_empty(&nf->nf_lru)))
309 		return;
310 
311 	call_rcu(&nf->nf_rcu, nfsd_file_slab_free);
312 }
313 
314 static bool
315 nfsd_file_check_writeback(struct nfsd_file *nf)
316 {
317 	struct file *file = nf->nf_file;
318 	struct address_space *mapping;
319 
320 	/* File not open for write? */
321 	if (!(file->f_mode & FMODE_WRITE))
322 		return false;
323 
324 	/*
325 	 * Some filesystems (e.g. NFS) flush all dirty data on close.
326 	 * On others, there is no need to wait for writeback.
327 	 */
328 	if (!(file_inode(file)->i_sb->s_export_op->flags & EXPORT_OP_FLUSH_ON_CLOSE))
329 		return false;
330 
331 	mapping = file->f_mapping;
332 	return mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) ||
333 		mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK);
334 }
335 
336 static void nfsd_file_lru_add(struct nfsd_file *nf)
337 {
338 	refcount_inc(&nf->nf_ref);
339 	if (list_lru_add_obj(&nfsd_file_lru, &nf->nf_lru))
340 		trace_nfsd_file_lru_add(nf);
341 	else {
342 		refcount_dec(&nf->nf_ref);
343 		WARN_ON_ONCE(1);
344 		return;
345 	}
346 	nfsd_file_schedule_laundrette();
347 }
348 
349 static bool nfsd_file_lru_remove(struct nfsd_file *nf)
350 {
351 	if (list_lru_del_obj(&nfsd_file_lru, &nf->nf_lru)) {
352 		trace_nfsd_file_lru_del(nf);
353 		return true;
354 	}
355 	return false;
356 }
357 
358 struct nfsd_file *
359 nfsd_file_get(struct nfsd_file *nf)
360 {
361 	if (nf && refcount_inc_not_zero(&nf->nf_ref))
362 		return nf;
363 	return NULL;
364 }
365 
366 /**
367  * nfsd_file_put - put the reference to a nfsd_file
368  * @nf: nfsd_file of which to put the reference
369  *
370  * Put a reference to a nfsd_file. In the non-GC case, we just put the
371  * reference immediately. In the GC case, if the reference would be
372  * the last one, the put it on the LRU instead to be cleaned up later.
373  */
374 void
375 nfsd_file_put(struct nfsd_file *nf)
376 {
377 	might_sleep();
378 	trace_nfsd_file_put(nf);
379 
380 	if (test_bit(NFSD_FILE_GC, &nf->nf_flags) &&
381 	    test_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
382 		set_bit(NFSD_FILE_REFERENCED, &nf->nf_flags);
383 		set_bit(NFSD_FILE_RECENT, &nf->nf_flags);
384 	}
385 
386 	if (refcount_dec_and_test(&nf->nf_ref))
387 		nfsd_file_free(nf);
388 }
389 
390 /**
391  * nfsd_file_put_local - put nfsd_file reference and arm nfsd_net_put in caller
392  * @pnf: nfsd_file of which to put the reference
393  *
394  * First save the associated net to return to caller, then put
395  * the reference of the nfsd_file.
396  */
397 struct net *
398 nfsd_file_put_local(struct nfsd_file __rcu **pnf)
399 {
400 	struct nfsd_file *nf;
401 	struct net *net = NULL;
402 
403 	nf = unrcu_pointer(xchg(pnf, NULL));
404 	if (nf) {
405 		net = nf->nf_net;
406 		nfsd_file_put(nf);
407 	}
408 	return net;
409 }
410 
411 /**
412  * nfsd_file_file - get the backing file of an nfsd_file
413  * @nf: nfsd_file of which to access the backing file.
414  *
415  * Return backing file for @nf.
416  */
417 struct file *
418 nfsd_file_file(struct nfsd_file *nf)
419 {
420 	return nf->nf_file;
421 }
422 
423 static void
424 nfsd_file_dispose_list(struct list_head *dispose)
425 {
426 	struct nfsd_file *nf;
427 
428 	while (!list_empty(dispose)) {
429 		nf = list_first_entry(dispose, struct nfsd_file, nf_gc);
430 		list_del_init(&nf->nf_gc);
431 		nfsd_file_free(nf);
432 	}
433 }
434 
435 /**
436  * nfsd_file_dispose_list_delayed - queue dead files for nfsd thread disposal
437  * @dispose: list of nfsd_files to be disposed
438  *
439  * Transfers each file to the dispose list in its nfsd_net and wakes an nfsd
440  * thread to do the actual close.  This keeps the cost of fput() in the nfsd
441  * threads rather than in the shrinker or GC worker.
442  *
443  * All callers must hold nfsd_gc_lock, so that nfsd_file_cache_shutdown_net()
444  * can synchronize against them before draining the per-net dispose list.
445  * This guarantees nf_net is still live when we call net_generic().
446  */
447 static void
448 nfsd_file_dispose_list_delayed(struct list_head *dispose)
449 {
450 	lockdep_assert_held(&nfsd_gc_lock);
451 
452 	while (!list_empty(dispose)) {
453 		struct nfsd_file *nf = list_first_entry(dispose,
454 						struct nfsd_file, nf_gc);
455 		struct nfsd_net *nn = net_generic(nf->nf_net, nfsd_net_id);
456 		struct svc_serv *serv;
457 
458 		spin_lock(&nn->fcache_dispose_lock);
459 		list_move_tail(&nf->nf_gc, &nn->fcache_dispose_list);
460 		spin_unlock(&nn->fcache_dispose_lock);
461 
462 		/*
463 		 * The filecache laundrette is shut down after the
464 		 * nn->nfsd_serv pointer is cleared, but before the
465 		 * svc_serv is freed.
466 		 */
467 		serv = nn->nfsd_serv;
468 		if (serv)
469 			svc_wake_up(serv);
470 	}
471 }
472 
473 /**
474  * nfsd_file_net_dispose - deal with nfsd_files waiting to be disposed.
475  * @nn: nfsd_net in which to find files to be disposed.
476  *
477  * When files held open for nfsv3 are removed from the filecache, whether
478  * due to memory pressure or garbage collection, they are queued to
479  * a per-net-ns queue.  This function completes the disposal, either
480  * directly or by waking another nfsd thread to help with the work.
481  */
482 void nfsd_file_net_dispose(struct nfsd_net *nn)
483 {
484 	if (!list_empty(&nn->fcache_dispose_list)) {
485 		LIST_HEAD(dispose);
486 		int i;
487 
488 		spin_lock(&nn->fcache_dispose_lock);
489 		for (i = 0; i < 8 && !list_empty(&nn->fcache_dispose_list); i++)
490 			list_move(nn->fcache_dispose_list.next, &dispose);
491 		spin_unlock(&nn->fcache_dispose_lock);
492 		if (!list_empty(&nn->fcache_dispose_list)) {
493 			/*
494 			 * Wake up another thread to share the work
495 			 * *before* doing any actual disposing.
496 			 *
497 			 * The filecache laundrette is shut down after
498 			 * the nn->nfsd_serv pointer is cleared, but
499 			 * before the svc_serv is freed.
500 			 */
501 			struct svc_serv *serv = nn->nfsd_serv;
502 
503 			if (serv)
504 				svc_wake_up(serv);
505 		}
506 		nfsd_file_dispose_list(&dispose);
507 	}
508 }
509 
510 /**
511  * nfsd_file_lru_cb - Examine an entry on the LRU list
512  * @item: LRU entry to examine
513  * @lru: controlling LRU
514  * @arg: dispose list
515  *
516  * Return values:
517  *   %LRU_REMOVED: @item was removed from the LRU
518  *   %LRU_ROTATE: @item is to be moved to the LRU tail
519  *   %LRU_SKIP: @item cannot be evicted
520  */
521 static enum lru_status
522 nfsd_file_lru_cb(struct list_head *item, struct list_lru_one *lru,
523 		 void *arg)
524 {
525 	struct list_head *head = arg;
526 	struct nfsd_file *nf = list_entry(item, struct nfsd_file, nf_lru);
527 
528 	/* We should only be dealing with GC entries here */
529 	WARN_ON_ONCE(!test_bit(NFSD_FILE_GC, &nf->nf_flags));
530 
531 	/*
532 	 * Don't throw out files that are still undergoing I/O or
533 	 * that have uncleared errors pending.
534 	 */
535 	if (nfsd_file_check_writeback(nf)) {
536 		trace_nfsd_file_gc_writeback(nf);
537 		return LRU_SKIP;
538 	}
539 
540 	/* If it was recently added to the list, skip it */
541 	if (test_and_clear_bit(NFSD_FILE_REFERENCED, &nf->nf_flags)) {
542 		trace_nfsd_file_gc_referenced(nf);
543 		return LRU_ROTATE;
544 	}
545 
546 	/*
547 	 * Put the reference held on behalf of the LRU if it is the last
548 	 * reference, else rotate.
549 	 */
550 	if (!refcount_dec_if_one(&nf->nf_ref)) {
551 		trace_nfsd_file_gc_in_use(nf);
552 		return LRU_ROTATE;
553 	}
554 
555 	/* Refcount went to zero. Unhash it and queue it to the dispose list */
556 	nfsd_file_unhash(nf);
557 	list_lru_isolate(lru, &nf->nf_lru);
558 	list_add(&nf->nf_gc, head);
559 	this_cpu_inc(nfsd_file_evictions);
560 	trace_nfsd_file_gc_disposed(nf);
561 	return LRU_REMOVED;
562 }
563 
564 static enum lru_status
565 nfsd_file_gc_cb(struct list_head *item, struct list_lru_one *lru,
566 		 void *arg)
567 {
568 	struct nfsd_file *nf = list_entry(item, struct nfsd_file, nf_lru);
569 
570 	if (test_and_clear_bit(NFSD_FILE_RECENT, &nf->nf_flags)) {
571 		/*
572 		 * "REFERENCED" really means "should be at the end of the
573 		 * LRU. As we are putting it there we can clear the flag.
574 		 */
575 		clear_bit(NFSD_FILE_REFERENCED, &nf->nf_flags);
576 		trace_nfsd_file_gc_aged(nf);
577 		return LRU_ROTATE;
578 	}
579 	return nfsd_file_lru_cb(item, lru, arg);
580 }
581 
582 static void
583 nfsd_file_gc(void)
584 {
585 	unsigned long ret = 0;
586 	LIST_HEAD(dispose);
587 	int nid;
588 
589 	spin_lock(&nfsd_gc_lock);
590 	for_each_node_state(nid, N_NORMAL_MEMORY) {
591 		unsigned long remaining = list_lru_count_node(&nfsd_file_lru, nid);
592 
593 		while (remaining > 0) {
594 			unsigned long nr = min(remaining, NFSD_FILE_GC_BATCH);
595 
596 			remaining -= nr;
597 			ret += list_lru_walk_node(&nfsd_file_lru, nid, nfsd_file_gc_cb,
598 						  &dispose, &nr);
599 			if (nr)
600 				/* walk aborted early */
601 				remaining = 0;
602 		}
603 	}
604 	nfsd_file_dispose_list_delayed(&dispose);
605 	spin_unlock(&nfsd_gc_lock);
606 	trace_nfsd_file_gc_removed(ret, list_lru_count(&nfsd_file_lru));
607 }
608 
609 static void
610 nfsd_file_gc_worker(struct work_struct *work)
611 {
612 	if (list_lru_count(&nfsd_file_lru))
613 		nfsd_file_gc();
614 	nfsd_file_schedule_laundrette();
615 }
616 
617 static unsigned long
618 nfsd_file_lru_count(struct shrinker *s, struct shrink_control *sc)
619 {
620 	return list_lru_count(&nfsd_file_lru);
621 }
622 
623 static unsigned long
624 nfsd_file_lru_scan(struct shrinker *s, struct shrink_control *sc)
625 {
626 	LIST_HEAD(dispose);
627 	unsigned long ret;
628 
629 	if (!spin_trylock(&nfsd_gc_lock))
630 		return SHRINK_STOP;
631 
632 	ret = list_lru_shrink_walk(&nfsd_file_lru, sc,
633 				   nfsd_file_lru_cb, &dispose);
634 	nfsd_file_dispose_list_delayed(&dispose);
635 	spin_unlock(&nfsd_gc_lock);
636 	trace_nfsd_file_shrinker_removed(ret, list_lru_count(&nfsd_file_lru));
637 	return ret;
638 }
639 
640 static struct shrinker *nfsd_file_shrinker;
641 
642 /**
643  * nfsd_file_cond_queue - conditionally unhash and queue a nfsd_file
644  * @nf: nfsd_file to attempt to queue
645  * @dispose: private list to queue successfully-put objects
646  *
647  * Unhash an nfsd_file, try to get a reference to it, and then put that
648  * reference. If it's the last reference, queue it to the dispose list.
649  */
650 static void
651 nfsd_file_cond_queue(struct nfsd_file *nf, struct list_head *dispose)
652 	__must_hold(RCU)
653 {
654 	int decrement = 1;
655 
656 	/* If we raced with someone else unhashing, ignore it */
657 	if (!nfsd_file_unhash(nf))
658 		return;
659 
660 	/* If we can't get a reference, ignore it */
661 	if (!nfsd_file_get(nf))
662 		return;
663 
664 	/* Extra decrement if we remove from the LRU */
665 	if (nfsd_file_lru_remove(nf))
666 		++decrement;
667 
668 	/* If refcount goes to 0, then put on the dispose list */
669 	if (refcount_sub_and_test(decrement, &nf->nf_ref)) {
670 		list_add(&nf->nf_gc, dispose);
671 		trace_nfsd_file_closing(nf);
672 	}
673 }
674 
675 /**
676  * nfsd_file_queue_for_close: try to close out any open nfsd_files for an inode
677  * @inode:   inode on which to close out nfsd_files
678  * @dispose: list on which to gather nfsd_files to close out
679  *
680  * An nfsd_file represents a struct file being held open on behalf of nfsd.
681  * An open file however can block other activity (such as leases), or cause
682  * undesirable behavior (e.g. spurious silly-renames when reexporting NFS).
683  *
684  * This function is intended to find open nfsd_files when this sort of
685  * conflicting access occurs and then attempt to close those files out.
686  *
687  * Populates the dispose list with entries that have already had their
688  * refcounts go to zero. The actual free of an nfsd_file can be expensive,
689  * so we leave it up to the caller whether it wants to wait or not.
690  */
691 static void
692 nfsd_file_queue_for_close(struct inode *inode, struct list_head *dispose)
693 {
694 	struct rhlist_head *tmp, *list;
695 	struct nfsd_file *nf;
696 
697 	rcu_read_lock();
698 	list = rhltable_lookup(&nfsd_file_rhltable, &inode,
699 			       nfsd_file_rhash_params);
700 	rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist) {
701 		if (!test_bit(NFSD_FILE_GC, &nf->nf_flags))
702 			continue;
703 		nfsd_file_cond_queue(nf, dispose);
704 	}
705 	rcu_read_unlock();
706 }
707 
708 /**
709  * nfsd_file_close_inode - attempt a deferred close of a nfsd_file
710  * @inode: inode of the file to attempt to remove
711  *
712  * Close out any open nfsd_files that can be reaped for @inode. The
713  * actual freeing is deferred to the nfsd service threads.
714  *
715  * This is used by the fsnotify callbacks and setlease notifier.
716  */
717 static void
718 nfsd_file_close_inode(struct inode *inode)
719 {
720 	LIST_HEAD(dispose);
721 
722 	spin_lock(&nfsd_gc_lock);
723 	nfsd_file_queue_for_close(inode, &dispose);
724 	nfsd_file_dispose_list_delayed(&dispose);
725 	spin_unlock(&nfsd_gc_lock);
726 }
727 
728 /**
729  * nfsd_file_close_inode_sync - attempt to forcibly close a nfsd_file
730  * @inode: inode of the file to attempt to remove
731  *
732  * Close out any open nfsd_files that can be reaped for @inode. The
733  * nfsd_files are closed out synchronously.
734  *
735  * This is called from nfsd_rename and nfsd_unlink to avoid silly-renames
736  * when reexporting NFS.
737  */
738 void
739 nfsd_file_close_inode_sync(struct inode *inode)
740 {
741 	LIST_HEAD(dispose);
742 
743 	trace_nfsd_file_close(inode);
744 
745 	nfsd_file_queue_for_close(inode, &dispose);
746 	nfsd_file_dispose_list(&dispose);
747 }
748 
749 /**
750  * nfsd_file_close_export - close cached file handles for an export
751  * @net: net namespace in which to operate
752  * @path: export path whose cached files should be closed
753  *
754  * Close out GC-managed nfsd_file entries whose underlying file is on
755  * the same filesystem as, and a descendant of, @path.  nfsd_file
756  * entries do not carry an export reference, so the check uses the
757  * file's dentry ancestry.  False positives (closing a cached handle
758  * that did not originate from the target export) are harmless -- the
759  * handle is simply reopened on the next access.
760  *
761  * Called from the NFSD_CMD_UNLOCK_EXPORT handler before revoking
762  * NFSv4 state, to ensure that cached file handles do not hold the
763  * filesystem busy.
764  */
765 void nfsd_file_close_export(struct net *net, const struct path *path)
766 {
767 	struct rhashtable_iter iter;
768 	struct nfsd_file *nf;
769 	LIST_HEAD(dispose);
770 
771 	rhltable_walk_enter(&nfsd_file_rhltable, &iter);
772 	do {
773 		rhashtable_walk_start(&iter);
774 
775 		nf = rhashtable_walk_next(&iter);
776 		while (!IS_ERR_OR_NULL(nf)) {
777 			if (nf->nf_net == net &&
778 			    test_bit(NFSD_FILE_GC, &nf->nf_flags) &&
779 			    nf->nf_file &&
780 			    file_inode(nf->nf_file)->i_sb ==
781 					path->dentry->d_sb &&
782 			    is_subdir(nf->nf_file->f_path.dentry,
783 				      path->dentry))
784 				nfsd_file_cond_queue(nf, &dispose);
785 			nf = rhashtable_walk_next(&iter);
786 		}
787 
788 		rhashtable_walk_stop(&iter);
789 	} while (nf == ERR_PTR(-EAGAIN));
790 	rhashtable_walk_exit(&iter);
791 
792 	nfsd_file_dispose_list(&dispose);
793 }
794 
795 static int
796 nfsd_file_lease_notifier_call(struct notifier_block *nb, unsigned long arg,
797 			    void *data)
798 {
799 	struct file_lease *fl = data;
800 
801 	/* Only close files for F_SETLEASE leases */
802 	if (fl->c.flc_flags & FL_LEASE)
803 		nfsd_file_close_inode(file_inode(fl->c.flc_file));
804 	return 0;
805 }
806 
807 static struct notifier_block nfsd_file_lease_notifier = {
808 	.notifier_call = nfsd_file_lease_notifier_call,
809 };
810 
811 static int
812 nfsd_file_fsnotify_handle_event(struct fsnotify_mark *mark, u32 mask,
813 				struct inode *inode, struct inode *dir,
814 				const struct qstr *name, u32 cookie)
815 {
816 	if (WARN_ON_ONCE(!inode))
817 		return 0;
818 
819 	trace_nfsd_file_fsnotify_handle_event(inode, mask);
820 
821 	/* Should be no marks on non-regular files */
822 	if (!S_ISREG(inode->i_mode)) {
823 		WARN_ON_ONCE(1);
824 		return 0;
825 	}
826 
827 	/* don't close files if this was not the last link */
828 	if (mask & FS_ATTRIB) {
829 		if (inode->i_nlink)
830 			return 0;
831 	}
832 
833 	nfsd_file_close_inode(inode);
834 	return 0;
835 }
836 
837 #ifdef CONFIG_NFSD_V4
838 static int
839 nfsd_dir_fsnotify_handle_event(struct fsnotify_group *group, u32 mask,
840 			       const void *data, int data_type, struct inode *dir,
841 			       const struct qstr *name, u32 cookie,
842 			       struct fsnotify_iter_info *iter_info)
843 {
844 	return nfsd_handle_dir_event(mask, dir, data, data_type, name);
845 }
846 #else
847 static int
848 nfsd_dir_fsnotify_handle_event(struct fsnotify_group *group, u32 mask,
849 			       const void *data, int data_type, struct inode *dir,
850 			       const struct qstr *name, u32 cookie,
851 			       struct fsnotify_iter_info *iter_info)
852 {
853 	return 0;
854 }
855 #endif
856 
857 static const struct fsnotify_ops nfsd_file_fsnotify_ops = {
858 	.handle_inode_event = nfsd_file_fsnotify_handle_event,
859 	.free_mark = nfsd_file_mark_free,
860 };
861 
862 static const struct fsnotify_ops nfsd_dir_fsnotify_ops = {
863 	.handle_event = nfsd_dir_fsnotify_handle_event,
864 	.free_mark = nfsd_file_mark_free,
865 };
866 
867 int
868 nfsd_file_cache_init(void)
869 {
870 	int ret;
871 
872 	lockdep_assert_held(&nfsd_mutex);
873 	if (test_and_set_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
874 		return 0;
875 
876 	ret = rhltable_init(&nfsd_file_rhltable, &nfsd_file_rhash_params);
877 	if (ret)
878 		goto out;
879 
880 	ret = -ENOMEM;
881 	nfsd_file_slab = KMEM_CACHE(nfsd_file, 0);
882 	if (!nfsd_file_slab) {
883 		pr_err("nfsd: unable to create nfsd_file_slab\n");
884 		goto out_err;
885 	}
886 
887 	nfsd_file_mark_slab = KMEM_CACHE(nfsd_file_mark, 0);
888 	if (!nfsd_file_mark_slab) {
889 		pr_err("nfsd: unable to create nfsd_file_mark_slab\n");
890 		goto out_err;
891 	}
892 
893 	ret = list_lru_init(&nfsd_file_lru);
894 	if (ret) {
895 		pr_err("nfsd: failed to init nfsd_file_lru: %d\n", ret);
896 		goto out_err;
897 	}
898 
899 	nfsd_file_shrinker = shrinker_alloc(0, "nfsd-filecache");
900 	if (!nfsd_file_shrinker) {
901 		ret = -ENOMEM;
902 		pr_err("nfsd: failed to allocate nfsd_file_shrinker\n");
903 		goto out_lru;
904 	}
905 
906 	nfsd_file_shrinker->count_objects = nfsd_file_lru_count;
907 	nfsd_file_shrinker->scan_objects = nfsd_file_lru_scan;
908 	nfsd_file_shrinker->seeks = 1;
909 
910 	shrinker_register(nfsd_file_shrinker);
911 
912 	ret = lease_register_notifier(&nfsd_file_lease_notifier);
913 	if (ret) {
914 		pr_err("nfsd: unable to register lease notifier: %d\n", ret);
915 		goto out_shrinker;
916 	}
917 
918 	nfsd_file_fsnotify_group = fsnotify_alloc_group(&nfsd_file_fsnotify_ops, 0);
919 	if (IS_ERR(nfsd_file_fsnotify_group)) {
920 		pr_err("nfsd: unable to create fsnotify group: %ld\n",
921 			PTR_ERR(nfsd_file_fsnotify_group));
922 		ret = PTR_ERR(nfsd_file_fsnotify_group);
923 		nfsd_file_fsnotify_group = NULL;
924 		goto out_notifier;
925 	}
926 
927 	nfsd_dir_fsnotify_group = fsnotify_alloc_group(&nfsd_dir_fsnotify_ops, 0);
928 	if (IS_ERR(nfsd_dir_fsnotify_group)) {
929 		pr_err("nfsd: unable to create fsnotify group: %ld\n",
930 			PTR_ERR(nfsd_dir_fsnotify_group));
931 		ret = PTR_ERR(nfsd_dir_fsnotify_group);
932 		nfsd_dir_fsnotify_group = NULL;
933 		goto out_notify_group;
934 	}
935 
936 	INIT_DELAYED_WORK(&nfsd_filecache_laundrette, nfsd_file_gc_worker);
937 out:
938 	if (ret)
939 		clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags);
940 	return ret;
941 out_notify_group:
942 	fsnotify_put_group(nfsd_file_fsnotify_group);
943 	nfsd_file_fsnotify_group = NULL;
944 out_notifier:
945 	lease_unregister_notifier(&nfsd_file_lease_notifier);
946 out_shrinker:
947 	shrinker_free(nfsd_file_shrinker);
948 out_lru:
949 	list_lru_destroy(&nfsd_file_lru);
950 out_err:
951 	kmem_cache_destroy(nfsd_file_slab);
952 	nfsd_file_slab = NULL;
953 	kmem_cache_destroy(nfsd_file_mark_slab);
954 	nfsd_file_mark_slab = NULL;
955 	rhltable_destroy(&nfsd_file_rhltable);
956 	goto out;
957 }
958 
959 /**
960  * __nfsd_file_cache_purge: clean out the cache for shutdown
961  * @net: net-namespace to shut down the cache (may be NULL)
962  *
963  * Walk the nfsd_file cache and close out any that match @net. If @net is NULL,
964  * then close out everything. Called when an nfsd instance is being shut down,
965  * and when the exports table is flushed.
966  */
967 static void
968 __nfsd_file_cache_purge(struct net *net)
969 {
970 	struct rhashtable_iter iter;
971 	struct nfsd_file *nf;
972 	LIST_HEAD(dispose);
973 
974 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
975 	if (net) {
976 		struct nfsd_net *nn = net_generic(net, nfsd_net_id);
977 		nfs_localio_invalidate_clients(&nn->local_clients,
978 					       &nn->local_clients_lock);
979 	}
980 #endif
981 
982 	rhltable_walk_enter(&nfsd_file_rhltable, &iter);
983 	do {
984 		rhashtable_walk_start(&iter);
985 
986 		nf = rhashtable_walk_next(&iter);
987 		while (!IS_ERR_OR_NULL(nf)) {
988 			if (!net || nf->nf_net == net)
989 				nfsd_file_cond_queue(nf, &dispose);
990 			nf = rhashtable_walk_next(&iter);
991 		}
992 
993 		rhashtable_walk_stop(&iter);
994 	} while (nf == ERR_PTR(-EAGAIN));
995 	rhashtable_walk_exit(&iter);
996 
997 	nfsd_file_dispose_list(&dispose);
998 }
999 
1000 int
1001 nfsd_file_cache_start_net(struct net *net)
1002 {
1003 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1004 
1005 	spin_lock_init(&nn->fcache_dispose_lock);
1006 	INIT_LIST_HEAD(&nn->fcache_dispose_list);
1007 	return 0;
1008 }
1009 
1010 /**
1011  * nfsd_file_cache_purge - Remove all cache items associated with @net
1012  * @net: target net namespace
1013  *
1014  */
1015 void
1016 nfsd_file_cache_purge(struct net *net)
1017 {
1018 	lockdep_assert_held(&nfsd_mutex);
1019 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
1020 		__nfsd_file_cache_purge(net);
1021 }
1022 
1023 void
1024 nfsd_file_cache_shutdown_net(struct net *net)
1025 {
1026 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1027 
1028 	nfsd_file_cache_purge(net);
1029 	/*
1030 	 * Ensure any in-progress shrinker, GC, or fsnotify/lease callback
1031 	 * (all of which hold nfsd_gc_lock while calling
1032 	 * nfsd_file_dispose_list_delayed()) has fully completed before
1033 	 * draining the per-net dispose list.
1034 	 */
1035 	spin_lock(&nfsd_gc_lock);
1036 	spin_unlock(&nfsd_gc_lock);
1037 	nfsd_file_dispose_list(&nn->fcache_dispose_list);
1038 }
1039 
1040 void
1041 nfsd_file_cache_shutdown(void)
1042 {
1043 	int i;
1044 
1045 	lockdep_assert_held(&nfsd_mutex);
1046 	if (test_and_clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 0)
1047 		return;
1048 
1049 	lease_unregister_notifier(&nfsd_file_lease_notifier);
1050 	shrinker_free(nfsd_file_shrinker);
1051 	/*
1052 	 * make sure all callers of nfsd_file_lru_cb are done before
1053 	 * calling nfsd_file_cache_purge
1054 	 */
1055 	cancel_delayed_work_sync(&nfsd_filecache_laundrette);
1056 	__nfsd_file_cache_purge(NULL);
1057 	list_lru_destroy(&nfsd_file_lru);
1058 	rcu_barrier();
1059 	fsnotify_put_group(nfsd_file_fsnotify_group);
1060 	nfsd_file_fsnotify_group = NULL;
1061 	fsnotify_put_group(nfsd_dir_fsnotify_group);
1062 	nfsd_dir_fsnotify_group = NULL;
1063 	kmem_cache_destroy(nfsd_file_slab);
1064 	nfsd_file_slab = NULL;
1065 	fsnotify_wait_marks_destroyed();
1066 	kmem_cache_destroy(nfsd_file_mark_slab);
1067 	nfsd_file_mark_slab = NULL;
1068 	rhltable_destroy(&nfsd_file_rhltable);
1069 
1070 	for_each_possible_cpu(i) {
1071 		per_cpu(nfsd_file_cache_hits, i) = 0;
1072 		per_cpu(nfsd_file_acquisitions, i) = 0;
1073 		per_cpu(nfsd_file_allocations, i) = 0;
1074 		per_cpu(nfsd_file_releases, i) = 0;
1075 		per_cpu(nfsd_file_total_age, i) = 0;
1076 		per_cpu(nfsd_file_evictions, i) = 0;
1077 	}
1078 }
1079 
1080 static struct nfsd_file *
1081 nfsd_file_lookup_locked(const struct net *net, const struct cred *cred,
1082 			struct inode *inode, unsigned char need,
1083 			bool want_gc)
1084 {
1085 	struct rhlist_head *tmp, *list;
1086 	struct nfsd_file *nf;
1087 
1088 	list = rhltable_lookup(&nfsd_file_rhltable, &inode,
1089 			       nfsd_file_rhash_params);
1090 	rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist) {
1091 		if (nf->nf_may != need)
1092 			continue;
1093 		if (nf->nf_net != net)
1094 			continue;
1095 		if (!nfsd_match_cred(nf->nf_cred, cred))
1096 			continue;
1097 		if (test_bit(NFSD_FILE_GC, &nf->nf_flags) != want_gc)
1098 			continue;
1099 		if (test_bit(NFSD_FILE_HASHED, &nf->nf_flags) == 0)
1100 			continue;
1101 
1102 		if (!nfsd_file_get(nf))
1103 			continue;
1104 		return nf;
1105 	}
1106 	return NULL;
1107 }
1108 
1109 /**
1110  * nfsd_file_is_cached - are there any cached open files for this inode?
1111  * @inode: inode to check
1112  *
1113  * The lookup matches inodes in all net namespaces and is atomic wrt
1114  * nfsd_file_acquire().
1115  *
1116  * Return values:
1117  *   %true: filecache contains at least one file matching this inode
1118  *   %false: filecache contains no files matching this inode
1119  */
1120 bool
1121 nfsd_file_is_cached(struct inode *inode)
1122 {
1123 	struct rhlist_head *tmp, *list;
1124 	struct nfsd_file *nf;
1125 	bool ret = false;
1126 
1127 	rcu_read_lock();
1128 	list = rhltable_lookup(&nfsd_file_rhltable, &inode,
1129 			       nfsd_file_rhash_params);
1130 	rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist)
1131 		if (test_bit(NFSD_FILE_GC, &nf->nf_flags)) {
1132 			ret = true;
1133 			break;
1134 		}
1135 	rcu_read_unlock();
1136 
1137 	trace_nfsd_file_is_cached(inode, (int)ret);
1138 	return ret;
1139 }
1140 
1141 static __be32
1142 nfsd_file_get_dio_attrs(const struct svc_fh *fhp, struct nfsd_file *nf)
1143 {
1144 	struct inode *inode = file_inode(nf->nf_file);
1145 	struct kstat stat;
1146 	__be32 status;
1147 
1148 	/* Currently only need to get DIO alignment info for regular files */
1149 	if (!S_ISREG(inode->i_mode))
1150 		return nfs_ok;
1151 
1152 	status = fh_getattr(fhp, &stat);
1153 	if (status != nfs_ok)
1154 		return status;
1155 
1156 	trace_nfsd_file_get_dio_attrs(inode, &stat);
1157 
1158 	if (stat.result_mask & STATX_DIOALIGN) {
1159 		nf->nf_dio_mem_align = stat.dio_mem_align;
1160 		nf->nf_dio_offset_align = stat.dio_offset_align;
1161 	}
1162 	if (stat.result_mask & STATX_DIO_READ_ALIGN)
1163 		nf->nf_dio_read_offset_align = stat.dio_read_offset_align;
1164 	else
1165 		nf->nf_dio_read_offset_align = nf->nf_dio_offset_align;
1166 
1167 	return nfs_ok;
1168 }
1169 
1170 static __be32
1171 nfsd_file_do_acquire(struct svc_rqst *rqstp, struct net *net,
1172 		     struct svc_cred *cred,
1173 		     struct auth_domain *client,
1174 		     struct svc_fh *fhp,
1175 		     unsigned int may_flags, struct file *file,
1176 		     umode_t type, bool want_gc, struct nfsd_file **pnf)
1177 {
1178 	unsigned char need = may_flags & NFSD_FILE_MAY_MASK;
1179 	struct nfsd_file *new, *nf;
1180 	bool stale_retry = true;
1181 	bool open_retry = true;
1182 	struct inode *inode;
1183 	__be32 status;
1184 	int ret;
1185 
1186 retry:
1187 	if (rqstp)
1188 		status = fh_verify(rqstp, fhp, type,
1189 				   may_flags|NFSD_MAY_OWNER_OVERRIDE);
1190 	else
1191 		status = fh_verify_local(net, cred, client, fhp, type,
1192 					 may_flags|NFSD_MAY_OWNER_OVERRIDE);
1193 
1194 	if (status != nfs_ok)
1195 		return status;
1196 	inode = d_inode(fhp->fh_dentry);
1197 
1198 	rcu_read_lock();
1199 	nf = nfsd_file_lookup_locked(net, current_cred(), inode, need, want_gc);
1200 	rcu_read_unlock();
1201 
1202 	if (nf)
1203 		goto wait_for_construction;
1204 
1205 	new = nfsd_file_alloc(net, inode, need, want_gc);
1206 	if (!new) {
1207 		status = nfserr_jukebox;
1208 		goto out;
1209 	}
1210 
1211 	rcu_read_lock();
1212 	spin_lock(&inode->i_lock);
1213 	nf = nfsd_file_lookup_locked(net, current_cred(), inode, need, want_gc);
1214 	if (unlikely(nf)) {
1215 		spin_unlock(&inode->i_lock);
1216 		rcu_read_unlock();
1217 		nfsd_file_free(new);
1218 		goto wait_for_construction;
1219 	}
1220 	nf = new;
1221 	ret = rhltable_insert(&nfsd_file_rhltable, &nf->nf_rlist,
1222 			      nfsd_file_rhash_params);
1223 	spin_unlock(&inode->i_lock);
1224 	rcu_read_unlock();
1225 	if (likely(ret == 0))
1226 		goto open_file;
1227 
1228 	trace_nfsd_file_insert_err(rqstp, inode, may_flags, ret);
1229 	status = nfserr_jukebox;
1230 	goto construction_err;
1231 
1232 wait_for_construction:
1233 	wait_on_bit(&nf->nf_flags, NFSD_FILE_PENDING, TASK_UNINTERRUPTIBLE);
1234 
1235 	/* Did construction of this file fail? */
1236 	if (!test_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
1237 		trace_nfsd_file_cons_err(rqstp, inode, may_flags, nf);
1238 		if (!open_retry) {
1239 			status = nfserr_jukebox;
1240 			goto construction_err;
1241 		}
1242 		nfsd_file_put(nf);
1243 		open_retry = false;
1244 		fh_put(fhp);
1245 		goto retry;
1246 	}
1247 	this_cpu_inc(nfsd_file_cache_hits);
1248 
1249 	status = nfserrno(nfsd_open_break_lease(file_inode(nf->nf_file), may_flags));
1250 	if (status != nfs_ok) {
1251 		nfsd_file_put(nf);
1252 		nf = NULL;
1253 	}
1254 
1255 out:
1256 	if (status == nfs_ok) {
1257 		this_cpu_inc(nfsd_file_acquisitions);
1258 		nfsd_file_check_write_error(nf);
1259 		*pnf = nf;
1260 	}
1261 	trace_nfsd_file_acquire(rqstp, inode, may_flags, nf, status);
1262 	return status;
1263 
1264 open_file:
1265 	trace_nfsd_file_alloc(nf);
1266 
1267 	nf->nf_mark = nfsd_file_mark_find_or_create(inode);
1268 	if (nf->nf_mark) {
1269 		if (file && (file->f_mode & FMODE_OPENED)) {
1270 			get_file(file);
1271 			nf->nf_file = file;
1272 			status = nfs_ok;
1273 			trace_nfsd_file_opened(nf, status);
1274 		} else {
1275 			ret = nfsd_open_verified(fhp, type, may_flags, &nf->nf_file);
1276 			if (ret == -EOPENSTALE && stale_retry) {
1277 				stale_retry = false;
1278 				nfsd_file_unhash(nf);
1279 				clear_and_wake_up_bit(NFSD_FILE_PENDING,
1280 						      &nf->nf_flags);
1281 				if (refcount_dec_and_test(&nf->nf_ref))
1282 					nfsd_file_free(nf);
1283 				nf = NULL;
1284 				fh_put(fhp);
1285 				goto retry;
1286 			}
1287 			status = nfserrno(ret);
1288 			trace_nfsd_file_open(nf, status);
1289 		}
1290 		if (status == nfs_ok)
1291 			status = nfsd_file_get_dio_attrs(fhp, nf);
1292 	} else
1293 		status = nfserr_jukebox;
1294 	/*
1295 	 * If construction failed, or we raced with a call to unlink()
1296 	 * then unhash.
1297 	 */
1298 	if (status != nfs_ok || inode->i_nlink == 0)
1299 		nfsd_file_unhash(nf);
1300 	else if (want_gc)
1301 		nfsd_file_lru_add(nf);
1302 
1303 	clear_and_wake_up_bit(NFSD_FILE_PENDING, &nf->nf_flags);
1304 	if (status == nfs_ok)
1305 		goto out;
1306 
1307 construction_err:
1308 	if (refcount_dec_and_test(&nf->nf_ref))
1309 		nfsd_file_free(nf);
1310 	nf = NULL;
1311 	goto out;
1312 }
1313 
1314 /**
1315  * nfsd_file_acquire_gc - Get a struct nfsd_file with an open file
1316  * @rqstp: the RPC transaction being executed
1317  * @fhp: the NFS filehandle of the file to be opened
1318  * @may_flags: NFSD_MAY_ settings for the file
1319  * @pnf: OUT: new or found "struct nfsd_file" object
1320  *
1321  * The nfsd_file object returned by this API is reference-counted
1322  * and garbage-collected. The object is retained for a few
1323  * seconds after the final nfsd_file_put() in case the caller
1324  * wants to re-use it.
1325  *
1326  * Return values:
1327  *   %nfs_ok - @pnf points to an nfsd_file with its reference
1328  *   count boosted.
1329  *
1330  * On error, an nfsstat value in network byte order is returned.
1331  */
1332 __be32
1333 nfsd_file_acquire_gc(struct svc_rqst *rqstp, struct svc_fh *fhp,
1334 		     unsigned int may_flags, struct nfsd_file **pnf)
1335 {
1336 	return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1337 				    fhp, may_flags, NULL, S_IFREG, true, pnf);
1338 }
1339 
1340 /**
1341  * nfsd_file_acquire - Get a struct nfsd_file with an open file
1342  * @rqstp: the RPC transaction being executed
1343  * @fhp: the NFS filehandle of the file to be opened
1344  * @may_flags: NFSD_MAY_ settings for the file
1345  * @pnf: OUT: new or found "struct nfsd_file" object
1346  *
1347  * The nfsd_file_object returned by this API is reference-counted
1348  * but not garbage-collected. The object is unhashed after the
1349  * final nfsd_file_put().
1350  *
1351  * Return values:
1352  *   %nfs_ok - @pnf points to an nfsd_file with its reference
1353  *   count boosted.
1354  *
1355  * On error, an nfsstat value in network byte order is returned.
1356  */
1357 __be32
1358 nfsd_file_acquire(struct svc_rqst *rqstp, struct svc_fh *fhp,
1359 		  unsigned int may_flags, struct nfsd_file **pnf)
1360 {
1361 	return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1362 				    fhp, may_flags, NULL, S_IFREG, false, pnf);
1363 }
1364 
1365 /**
1366  * nfsd_file_acquire_local - Get a struct nfsd_file with an open file for localio
1367  * @net: The network namespace in which to perform a lookup
1368  * @cred: the user credential with which to validate access
1369  * @client: the auth_domain for LOCALIO lookup
1370  * @fhp: the NFS filehandle of the file to be opened
1371  * @may_flags: NFSD_MAY_ settings for the file
1372  * @pnf: OUT: new or found "struct nfsd_file" object
1373  *
1374  * This file lookup interface provide access to a file given the
1375  * filehandle and credential.  No connection-based authorisation
1376  * is performed and in that way it is quite different to other
1377  * file access mediated by nfsd.  It allows a kernel module such as the NFS
1378  * client to reach across network and filesystem namespaces to access
1379  * a file.  The security implications of this should be carefully
1380  * considered before use.
1381  *
1382  * The nfsd_file_object returned by this API is reference-counted
1383  * but not garbage-collected. The object is unhashed after the
1384  * final nfsd_file_put().
1385  *
1386  * Return values:
1387  *   %nfs_ok - @pnf points to an nfsd_file with its reference
1388  *   count boosted.
1389  *
1390  * On error, an nfsstat value in network byte order is returned.
1391  */
1392 __be32
1393 nfsd_file_acquire_local(struct net *net, struct svc_cred *cred,
1394 			struct auth_domain *client, struct svc_fh *fhp,
1395 			unsigned int may_flags, struct nfsd_file **pnf)
1396 {
1397 	/*
1398 	 * Save creds before calling nfsd_file_do_acquire() (which calls
1399 	 * nfsd_setuser). Important because caller (LOCALIO) is from
1400 	 * client context.
1401 	 */
1402 	const struct cred *save_cred = get_current_cred();
1403 	__be32 beres;
1404 
1405 	beres = nfsd_file_do_acquire(NULL, net, cred, client, fhp, may_flags,
1406 				     NULL, S_IFREG, false, pnf);
1407 	put_cred(revert_creds(save_cred));
1408 	return beres;
1409 }
1410 
1411 /**
1412  * nfsd_file_acquire_opened - Get a struct nfsd_file using existing open file
1413  * @rqstp: the RPC transaction being executed
1414  * @fhp: the NFS filehandle of the file just created
1415  * @may_flags: NFSD_MAY_ settings for the file
1416  * @file: cached, already-open file (may be NULL or not yet opened)
1417  * @pnf: OUT: new or found "struct nfsd_file" object
1418  *
1419  * Acquire a nfsd_file object that is not GC'ed. If one doesn't already exist,
1420  * and @file has FMODE_OPENED set, use it to instantiate a new nfsd_file
1421  * instead of opening a new one.
1422  *
1423  * Return values:
1424  *   %nfs_ok - @pnf points to an nfsd_file with its reference
1425  *   count boosted.
1426  *
1427  * On error, an nfsstat value in network byte order is returned.
1428  */
1429 __be32
1430 nfsd_file_acquire_opened(struct svc_rqst *rqstp, struct svc_fh *fhp,
1431 			 unsigned int may_flags, struct file *file,
1432 			 struct nfsd_file **pnf)
1433 {
1434 	return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1435 				    fhp, may_flags, file, S_IFREG, false, pnf);
1436 }
1437 
1438 /**
1439  * nfsd_file_acquire_dir - Get a struct nfsd_file with an open directory
1440  * @rqstp: the RPC transaction being executed
1441  * @fhp: the NFS filehandle of the file to be opened
1442  * @pnf: OUT: new or found "struct nfsd_file" object
1443  *
1444  * The nfsd_file_object returned by this API is reference-counted
1445  * but not garbage-collected. The object is unhashed after the
1446  * final nfsd_file_put(). This opens directories only, and only
1447  * in O_RDONLY mode.
1448  *
1449  * Return values:
1450  *   %nfs_ok - @pnf points to an nfsd_file with its reference
1451  *   count boosted.
1452  *
1453  * On error, an nfsstat value in network byte order is returned.
1454  */
1455 __be32
1456 nfsd_file_acquire_dir(struct svc_rqst *rqstp, struct svc_fh *fhp,
1457 		      struct nfsd_file **pnf)
1458 {
1459 	return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL, fhp,
1460 				    NFSD_MAY_READ|NFSD_MAY_64BIT_COOKIE,
1461 				    NULL, S_IFDIR, false, pnf);
1462 }
1463 
1464 /*
1465  * Note that fields may be added, removed or reordered in the future. Programs
1466  * scraping this file for info should test the labels to ensure they're
1467  * getting the correct field.
1468  */
1469 int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
1470 {
1471 	unsigned long allocations = 0, releases = 0, evictions = 0;
1472 	unsigned long hits = 0, acquisitions = 0;
1473 	unsigned int i, count = 0, buckets = 0;
1474 	unsigned long lru = 0, total_age = 0;
1475 
1476 	/* Serialize with server shutdown */
1477 	mutex_lock(&nfsd_mutex);
1478 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1) {
1479 		struct bucket_table *tbl;
1480 		struct rhashtable *ht;
1481 
1482 		lru = list_lru_count(&nfsd_file_lru);
1483 
1484 		rcu_read_lock();
1485 		ht = &nfsd_file_rhltable.ht;
1486 		count = atomic_read(&ht->nelems);
1487 		tbl = rht_dereference_rcu(ht->tbl, ht);
1488 		buckets = tbl->size;
1489 		rcu_read_unlock();
1490 	}
1491 	mutex_unlock(&nfsd_mutex);
1492 
1493 	for_each_possible_cpu(i) {
1494 		hits += per_cpu(nfsd_file_cache_hits, i);
1495 		acquisitions += per_cpu(nfsd_file_acquisitions, i);
1496 		allocations += per_cpu(nfsd_file_allocations, i);
1497 		releases += per_cpu(nfsd_file_releases, i);
1498 		total_age += per_cpu(nfsd_file_total_age, i);
1499 		evictions += per_cpu(nfsd_file_evictions, i);
1500 	}
1501 
1502 	seq_printf(m, "total inodes:  %u\n", count);
1503 	seq_printf(m, "hash buckets:  %u\n", buckets);
1504 	seq_printf(m, "lru entries:   %lu\n", lru);
1505 	seq_printf(m, "cache hits:    %lu\n", hits);
1506 	seq_printf(m, "acquisitions:  %lu\n", acquisitions);
1507 	seq_printf(m, "allocations:   %lu\n", allocations);
1508 	seq_printf(m, "releases:      %lu\n", releases);
1509 	seq_printf(m, "evictions:     %lu\n", evictions);
1510 	if (releases)
1511 		seq_printf(m, "mean age (ms): %ld\n", total_age / releases);
1512 	else
1513 		seq_printf(m, "mean age (ms): -\n");
1514 	return 0;
1515 }
1516 
1517 /**
1518  * nfsd_fsnotify_recalc_mask - recalculate the fsnotify mask for a nfsd_file
1519  * @nf: nfsd_file to recalculate the mask on
1520  *
1521  * When a directory nfsd_file has a delegation added or removed, that may
1522  * change the events that nfsd requires from the VFS layer. This function
1523  * recalculates the fsnotify mask based on the leases present.
1524  */
1525 void nfsd_fsnotify_recalc_mask(struct nfsd_file *nf)
1526 {
1527 	struct inode *inode = file_inode(nf->nf_file);
1528 	u32 lease_mask, set = 0, clear = 0;
1529 	struct fsnotify_mark *mark;
1530 
1531 	/* This is only needed when adding or removing dir delegs */
1532 	if (!S_ISDIR(inode->i_mode) || !nf->nf_mark)
1533 		return;
1534 
1535 	mark = &nf->nf_mark->nfm_mark;
1536 
1537 	/*
1538 	 * The mark is shared by every nfsd_file on this inode, so concurrent
1539 	 * delegation add/remove on the same directory can recalc it in
1540 	 * parallel. Serialize the read of the lease state and the update of
1541 	 * the mark so that a recalc working from a stale snapshot of the
1542 	 * lease list can't clobber a concurrent recalc's update.
1543 	 */
1544 	mutex_lock(&nf->nf_mark->nfm_recalc_mutex);
1545 
1546 	/* Set up notifications for any ignored delegation events */
1547 	lease_mask = inode_lease_ignore_mask(inode);
1548 
1549 	if (lease_mask & FL_IGN_DIR_CREATE)
1550 		set |= FS_CREATE | FS_MOVED_TO;
1551 	else
1552 		clear |= FS_CREATE | FS_MOVED_TO;
1553 
1554 	if (lease_mask & FL_IGN_DIR_DELETE)
1555 		set |= FS_DELETE | FS_MOVED_FROM;
1556 	else
1557 		clear |= FS_DELETE | FS_MOVED_FROM;
1558 
1559 	if (lease_mask & FL_IGN_DIR_RENAME)
1560 		set |= FS_RENAME;
1561 	else
1562 		clear |= FS_RENAME;
1563 
1564 	fsnotify_modify_mark_mask(mark, set, clear);
1565 	mutex_unlock(&nf->nf_mark->nfm_recalc_mutex);
1566 }
1567