Linux 6.14-rc1
[linux.git] / fs / nfsd / filecache.c
blob0e552d873eaaa2ce0656b3521d2cd333b2226929
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * The NFSD open file cache.
5 * (c) 2015 - Jeff Layton <jeff.layton@primarydata.com>
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
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:
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.
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.
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>
44 #include "vfs.h"
45 #include "nfsd.h"
46 #include "nfsfh.h"
47 #include "netns.h"
48 #include "filecache.h"
49 #include "trace.h"
51 #define NFSD_LAUNDRETTE_DELAY (2 * HZ)
53 #define NFSD_FILE_CACHE_UP (0)
55 /* We only care about NFSD_MAY_READ/WRITE for this cache */
56 #define NFSD_FILE_MAY_MASK (NFSD_MAY_READ|NFSD_MAY_WRITE|NFSD_MAY_LOCALIO)
58 static DEFINE_PER_CPU(unsigned long, nfsd_file_cache_hits);
59 static DEFINE_PER_CPU(unsigned long, nfsd_file_acquisitions);
60 static DEFINE_PER_CPU(unsigned long, nfsd_file_allocations);
61 static DEFINE_PER_CPU(unsigned long, nfsd_file_releases);
62 static DEFINE_PER_CPU(unsigned long, nfsd_file_total_age);
63 static DEFINE_PER_CPU(unsigned long, nfsd_file_evictions);
65 struct nfsd_fcache_disposal {
66 spinlock_t lock;
67 struct list_head freeme;
70 static struct kmem_cache *nfsd_file_slab;
71 static struct kmem_cache *nfsd_file_mark_slab;
72 static struct list_lru nfsd_file_lru;
73 static unsigned long nfsd_file_flags;
74 static struct fsnotify_group *nfsd_file_fsnotify_group;
75 static struct delayed_work nfsd_filecache_laundrette;
76 static struct rhltable nfsd_file_rhltable
77 ____cacheline_aligned_in_smp;
79 static bool
80 nfsd_match_cred(const struct cred *c1, const struct cred *c2)
82 int i;
84 if (!uid_eq(c1->fsuid, c2->fsuid))
85 return false;
86 if (!gid_eq(c1->fsgid, c2->fsgid))
87 return false;
88 if (c1->group_info == NULL || c2->group_info == NULL)
89 return c1->group_info == c2->group_info;
90 if (c1->group_info->ngroups != c2->group_info->ngroups)
91 return false;
92 for (i = 0; i < c1->group_info->ngroups; i++) {
93 if (!gid_eq(c1->group_info->gid[i], c2->group_info->gid[i]))
94 return false;
96 return true;
99 static const struct rhashtable_params nfsd_file_rhash_params = {
100 .key_len = sizeof_field(struct nfsd_file, nf_inode),
101 .key_offset = offsetof(struct nfsd_file, nf_inode),
102 .head_offset = offsetof(struct nfsd_file, nf_rlist),
105 * Start with a single page hash table to reduce resizing churn
106 * on light workloads.
108 .min_size = 256,
109 .automatic_shrinking = true,
112 static void
113 nfsd_file_schedule_laundrette(void)
115 if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags))
116 queue_delayed_work(system_unbound_wq, &nfsd_filecache_laundrette,
117 NFSD_LAUNDRETTE_DELAY);
120 static void
121 nfsd_file_slab_free(struct rcu_head *rcu)
123 struct nfsd_file *nf = container_of(rcu, struct nfsd_file, nf_rcu);
125 put_cred(nf->nf_cred);
126 kmem_cache_free(nfsd_file_slab, nf);
129 static void
130 nfsd_file_mark_free(struct fsnotify_mark *mark)
132 struct nfsd_file_mark *nfm = container_of(mark, struct nfsd_file_mark,
133 nfm_mark);
135 kmem_cache_free(nfsd_file_mark_slab, nfm);
138 static struct nfsd_file_mark *
139 nfsd_file_mark_get(struct nfsd_file_mark *nfm)
141 if (!refcount_inc_not_zero(&nfm->nfm_ref))
142 return NULL;
143 return nfm;
146 static void
147 nfsd_file_mark_put(struct nfsd_file_mark *nfm)
149 if (refcount_dec_and_test(&nfm->nfm_ref)) {
150 fsnotify_destroy_mark(&nfm->nfm_mark, nfsd_file_fsnotify_group);
151 fsnotify_put_mark(&nfm->nfm_mark);
155 static struct nfsd_file_mark *
156 nfsd_file_mark_find_or_create(struct inode *inode)
158 int err;
159 struct fsnotify_mark *mark;
160 struct nfsd_file_mark *nfm = NULL, *new;
162 do {
163 fsnotify_group_lock(nfsd_file_fsnotify_group);
164 mark = fsnotify_find_inode_mark(inode,
165 nfsd_file_fsnotify_group);
166 if (mark) {
167 nfm = nfsd_file_mark_get(container_of(mark,
168 struct nfsd_file_mark,
169 nfm_mark));
170 fsnotify_group_unlock(nfsd_file_fsnotify_group);
171 if (nfm) {
172 fsnotify_put_mark(mark);
173 break;
175 /* Avoid soft lockup race with nfsd_file_mark_put() */
176 fsnotify_destroy_mark(mark, nfsd_file_fsnotify_group);
177 fsnotify_put_mark(mark);
178 } else {
179 fsnotify_group_unlock(nfsd_file_fsnotify_group);
182 /* allocate a new nfm */
183 new = kmem_cache_alloc(nfsd_file_mark_slab, GFP_KERNEL);
184 if (!new)
185 return NULL;
186 fsnotify_init_mark(&new->nfm_mark, nfsd_file_fsnotify_group);
187 new->nfm_mark.mask = FS_ATTRIB|FS_DELETE_SELF;
188 refcount_set(&new->nfm_ref, 1);
190 err = fsnotify_add_inode_mark(&new->nfm_mark, inode, 0);
193 * If the add was successful, then return the object.
194 * Otherwise, we need to put the reference we hold on the
195 * nfm_mark. The fsnotify code will take a reference and put
196 * it on failure, so we can't just free it directly. It's also
197 * not safe to call fsnotify_destroy_mark on it as the
198 * mark->group will be NULL. Thus, we can't let the nfm_ref
199 * counter drive the destruction at this point.
201 if (likely(!err))
202 nfm = new;
203 else
204 fsnotify_put_mark(&new->nfm_mark);
205 } while (unlikely(err == -EEXIST));
207 return nfm;
210 static struct nfsd_file *
211 nfsd_file_alloc(struct net *net, struct inode *inode, unsigned char need,
212 bool want_gc)
214 struct nfsd_file *nf;
216 nf = kmem_cache_alloc(nfsd_file_slab, GFP_KERNEL);
217 if (unlikely(!nf))
218 return NULL;
220 this_cpu_inc(nfsd_file_allocations);
221 INIT_LIST_HEAD(&nf->nf_lru);
222 INIT_LIST_HEAD(&nf->nf_gc);
223 nf->nf_birthtime = ktime_get();
224 nf->nf_file = NULL;
225 nf->nf_cred = get_current_cred();
226 nf->nf_net = net;
227 nf->nf_flags = want_gc ?
228 BIT(NFSD_FILE_HASHED) | BIT(NFSD_FILE_PENDING) | BIT(NFSD_FILE_GC) :
229 BIT(NFSD_FILE_HASHED) | BIT(NFSD_FILE_PENDING);
230 nf->nf_inode = inode;
231 refcount_set(&nf->nf_ref, 1);
232 nf->nf_may = need;
233 nf->nf_mark = NULL;
234 return nf;
238 * nfsd_file_check_write_error - check for writeback errors on a file
239 * @nf: nfsd_file to check for writeback errors
241 * Check whether a nfsd_file has an unseen error. Reset the write
242 * verifier if so.
244 static void
245 nfsd_file_check_write_error(struct nfsd_file *nf)
247 struct file *file = nf->nf_file;
249 if ((file->f_mode & FMODE_WRITE) &&
250 filemap_check_wb_err(file->f_mapping, READ_ONCE(file->f_wb_err)))
251 nfsd_reset_write_verifier(net_generic(nf->nf_net, nfsd_net_id));
254 static void
255 nfsd_file_hash_remove(struct nfsd_file *nf)
257 trace_nfsd_file_unhash(nf);
258 rhltable_remove(&nfsd_file_rhltable, &nf->nf_rlist,
259 nfsd_file_rhash_params);
262 static bool
263 nfsd_file_unhash(struct nfsd_file *nf)
265 if (test_and_clear_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
266 nfsd_file_hash_remove(nf);
267 return true;
269 return false;
272 static void
273 nfsd_file_free(struct nfsd_file *nf)
275 s64 age = ktime_to_ms(ktime_sub(ktime_get(), nf->nf_birthtime));
277 trace_nfsd_file_free(nf);
279 this_cpu_inc(nfsd_file_releases);
280 this_cpu_add(nfsd_file_total_age, age);
282 nfsd_file_unhash(nf);
283 if (nf->nf_mark)
284 nfsd_file_mark_put(nf->nf_mark);
285 if (nf->nf_file) {
286 nfsd_file_check_write_error(nf);
287 nfsd_filp_close(nf->nf_file);
291 * If this item is still linked via nf_lru, that's a bug.
292 * WARN and leak it to preserve system stability.
294 if (WARN_ON_ONCE(!list_empty(&nf->nf_lru)))
295 return;
297 call_rcu(&nf->nf_rcu, nfsd_file_slab_free);
300 static bool
301 nfsd_file_check_writeback(struct nfsd_file *nf)
303 struct file *file = nf->nf_file;
304 struct address_space *mapping;
306 /* File not open for write? */
307 if (!(file->f_mode & FMODE_WRITE))
308 return false;
311 * Some filesystems (e.g. NFS) flush all dirty data on close.
312 * On others, there is no need to wait for writeback.
314 if (!(file_inode(file)->i_sb->s_export_op->flags & EXPORT_OP_FLUSH_ON_CLOSE))
315 return false;
317 mapping = file->f_mapping;
318 return mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) ||
319 mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK);
323 static bool nfsd_file_lru_add(struct nfsd_file *nf)
325 set_bit(NFSD_FILE_REFERENCED, &nf->nf_flags);
326 if (list_lru_add_obj(&nfsd_file_lru, &nf->nf_lru)) {
327 trace_nfsd_file_lru_add(nf);
328 return true;
330 return false;
333 static bool nfsd_file_lru_remove(struct nfsd_file *nf)
335 if (list_lru_del_obj(&nfsd_file_lru, &nf->nf_lru)) {
336 trace_nfsd_file_lru_del(nf);
337 return true;
339 return false;
342 struct nfsd_file *
343 nfsd_file_get(struct nfsd_file *nf)
345 if (nf && refcount_inc_not_zero(&nf->nf_ref))
346 return nf;
347 return NULL;
351 * nfsd_file_put - put the reference to a nfsd_file
352 * @nf: nfsd_file of which to put the reference
354 * Put a reference to a nfsd_file. In the non-GC case, we just put the
355 * reference immediately. In the GC case, if the reference would be
356 * the last one, the put it on the LRU instead to be cleaned up later.
358 void
359 nfsd_file_put(struct nfsd_file *nf)
361 might_sleep();
362 trace_nfsd_file_put(nf);
364 if (test_bit(NFSD_FILE_GC, &nf->nf_flags) &&
365 test_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
367 * If this is the last reference (nf_ref == 1), then try to
368 * transfer it to the LRU.
370 if (refcount_dec_not_one(&nf->nf_ref))
371 return;
373 /* Try to add it to the LRU. If that fails, decrement. */
374 if (nfsd_file_lru_add(nf)) {
375 /* If it's still hashed, we're done */
376 if (test_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
377 nfsd_file_schedule_laundrette();
378 return;
382 * We're racing with unhashing, so try to remove it from
383 * the LRU. If removal fails, then someone else already
384 * has our reference.
386 if (!nfsd_file_lru_remove(nf))
387 return;
390 if (refcount_dec_and_test(&nf->nf_ref))
391 nfsd_file_free(nf);
395 * nfsd_file_put_local - put nfsd_file reference and arm nfsd_net_put in caller
396 * @nf: nfsd_file of which to put the reference
398 * First save the associated net to return to caller, then put
399 * the reference of the nfsd_file.
401 struct net *
402 nfsd_file_put_local(struct nfsd_file *nf)
404 struct net *net = nf->nf_net;
406 nfsd_file_put(nf);
407 return net;
411 * nfsd_file_file - get the backing file of an nfsd_file
412 * @nf: nfsd_file of which to access the backing file.
414 * Return backing file for @nf.
416 struct file *
417 nfsd_file_file(struct nfsd_file *nf)
419 return nf->nf_file;
422 static void
423 nfsd_file_dispose_list(struct list_head *dispose)
425 struct nfsd_file *nf;
427 while (!list_empty(dispose)) {
428 nf = list_first_entry(dispose, struct nfsd_file, nf_gc);
429 list_del_init(&nf->nf_gc);
430 nfsd_file_free(nf);
435 * nfsd_file_dispose_list_delayed - move list of dead files to net's freeme list
436 * @dispose: list of nfsd_files to be disposed
438 * Transfers each file to the "freeme" list for its nfsd_net, to eventually
439 * be disposed of by the per-net garbage collector.
441 static void
442 nfsd_file_dispose_list_delayed(struct list_head *dispose)
444 while(!list_empty(dispose)) {
445 struct nfsd_file *nf = list_first_entry(dispose,
446 struct nfsd_file, nf_gc);
447 struct nfsd_net *nn = net_generic(nf->nf_net, nfsd_net_id);
448 struct nfsd_fcache_disposal *l = nn->fcache_disposal;
450 spin_lock(&l->lock);
451 list_move_tail(&nf->nf_gc, &l->freeme);
452 spin_unlock(&l->lock);
453 svc_wake_up(nn->nfsd_serv);
458 * nfsd_file_net_dispose - deal with nfsd_files waiting to be disposed.
459 * @nn: nfsd_net in which to find files to be disposed.
461 * When files held open for nfsv3 are removed from the filecache, whether
462 * due to memory pressure or garbage collection, they are queued to
463 * a per-net-ns queue. This function completes the disposal, either
464 * directly or by waking another nfsd thread to help with the work.
466 void nfsd_file_net_dispose(struct nfsd_net *nn)
468 struct nfsd_fcache_disposal *l = nn->fcache_disposal;
470 if (!list_empty(&l->freeme)) {
471 LIST_HEAD(dispose);
472 int i;
474 spin_lock(&l->lock);
475 for (i = 0; i < 8 && !list_empty(&l->freeme); i++)
476 list_move(l->freeme.next, &dispose);
477 spin_unlock(&l->lock);
478 if (!list_empty(&l->freeme))
479 /* Wake up another thread to share the work
480 * *before* doing any actual disposing.
482 svc_wake_up(nn->nfsd_serv);
483 nfsd_file_dispose_list(&dispose);
488 * nfsd_file_lru_cb - Examine an entry on the LRU list
489 * @item: LRU entry to examine
490 * @lru: controlling LRU
491 * @arg: dispose list
493 * Return values:
494 * %LRU_REMOVED: @item was removed from the LRU
495 * %LRU_ROTATE: @item is to be moved to the LRU tail
496 * %LRU_SKIP: @item cannot be evicted
498 static enum lru_status
499 nfsd_file_lru_cb(struct list_head *item, struct list_lru_one *lru,
500 void *arg)
502 struct list_head *head = arg;
503 struct nfsd_file *nf = list_entry(item, struct nfsd_file, nf_lru);
505 /* We should only be dealing with GC entries here */
506 WARN_ON_ONCE(!test_bit(NFSD_FILE_GC, &nf->nf_flags));
509 * Don't throw out files that are still undergoing I/O or
510 * that have uncleared errors pending.
512 if (nfsd_file_check_writeback(nf)) {
513 trace_nfsd_file_gc_writeback(nf);
514 return LRU_SKIP;
517 /* If it was recently added to the list, skip it */
518 if (test_and_clear_bit(NFSD_FILE_REFERENCED, &nf->nf_flags)) {
519 trace_nfsd_file_gc_referenced(nf);
520 return LRU_ROTATE;
524 * Put the reference held on behalf of the LRU. If it wasn't the last
525 * one, then just remove it from the LRU and ignore it.
527 if (!refcount_dec_and_test(&nf->nf_ref)) {
528 trace_nfsd_file_gc_in_use(nf);
529 list_lru_isolate(lru, &nf->nf_lru);
530 return LRU_REMOVED;
533 /* Refcount went to zero. Unhash it and queue it to the dispose list */
534 nfsd_file_unhash(nf);
535 list_lru_isolate(lru, &nf->nf_lru);
536 list_add(&nf->nf_gc, head);
537 this_cpu_inc(nfsd_file_evictions);
538 trace_nfsd_file_gc_disposed(nf);
539 return LRU_REMOVED;
542 static void
543 nfsd_file_gc(void)
545 LIST_HEAD(dispose);
546 unsigned long ret;
548 ret = list_lru_walk(&nfsd_file_lru, nfsd_file_lru_cb,
549 &dispose, list_lru_count(&nfsd_file_lru));
550 trace_nfsd_file_gc_removed(ret, list_lru_count(&nfsd_file_lru));
551 nfsd_file_dispose_list_delayed(&dispose);
554 static void
555 nfsd_file_gc_worker(struct work_struct *work)
557 nfsd_file_gc();
558 if (list_lru_count(&nfsd_file_lru))
559 nfsd_file_schedule_laundrette();
562 static unsigned long
563 nfsd_file_lru_count(struct shrinker *s, struct shrink_control *sc)
565 return list_lru_count(&nfsd_file_lru);
568 static unsigned long
569 nfsd_file_lru_scan(struct shrinker *s, struct shrink_control *sc)
571 LIST_HEAD(dispose);
572 unsigned long ret;
574 ret = list_lru_shrink_walk(&nfsd_file_lru, sc,
575 nfsd_file_lru_cb, &dispose);
576 trace_nfsd_file_shrinker_removed(ret, list_lru_count(&nfsd_file_lru));
577 nfsd_file_dispose_list_delayed(&dispose);
578 return ret;
581 static struct shrinker *nfsd_file_shrinker;
584 * nfsd_file_cond_queue - conditionally unhash and queue a nfsd_file
585 * @nf: nfsd_file to attempt to queue
586 * @dispose: private list to queue successfully-put objects
588 * Unhash an nfsd_file, try to get a reference to it, and then put that
589 * reference. If it's the last reference, queue it to the dispose list.
591 static void
592 nfsd_file_cond_queue(struct nfsd_file *nf, struct list_head *dispose)
593 __must_hold(RCU)
595 int decrement = 1;
597 /* If we raced with someone else unhashing, ignore it */
598 if (!nfsd_file_unhash(nf))
599 return;
601 /* If we can't get a reference, ignore it */
602 if (!nfsd_file_get(nf))
603 return;
605 /* Extra decrement if we remove from the LRU */
606 if (nfsd_file_lru_remove(nf))
607 ++decrement;
609 /* If refcount goes to 0, then put on the dispose list */
610 if (refcount_sub_and_test(decrement, &nf->nf_ref)) {
611 list_add(&nf->nf_gc, dispose);
612 trace_nfsd_file_closing(nf);
617 * nfsd_file_queue_for_close: try to close out any open nfsd_files for an inode
618 * @inode: inode on which to close out nfsd_files
619 * @dispose: list on which to gather nfsd_files to close out
621 * An nfsd_file represents a struct file being held open on behalf of nfsd.
622 * An open file however can block other activity (such as leases), or cause
623 * undesirable behavior (e.g. spurious silly-renames when reexporting NFS).
625 * This function is intended to find open nfsd_files when this sort of
626 * conflicting access occurs and then attempt to close those files out.
628 * Populates the dispose list with entries that have already had their
629 * refcounts go to zero. The actual free of an nfsd_file can be expensive,
630 * so we leave it up to the caller whether it wants to wait or not.
632 static void
633 nfsd_file_queue_for_close(struct inode *inode, struct list_head *dispose)
635 struct rhlist_head *tmp, *list;
636 struct nfsd_file *nf;
638 rcu_read_lock();
639 list = rhltable_lookup(&nfsd_file_rhltable, &inode,
640 nfsd_file_rhash_params);
641 rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist) {
642 if (!test_bit(NFSD_FILE_GC, &nf->nf_flags))
643 continue;
644 nfsd_file_cond_queue(nf, dispose);
646 rcu_read_unlock();
650 * nfsd_file_close_inode - attempt a delayed close of a nfsd_file
651 * @inode: inode of the file to attempt to remove
653 * Close out any open nfsd_files that can be reaped for @inode. The
654 * actual freeing is deferred to the dispose_list_delayed infrastructure.
656 * This is used by the fsnotify callbacks and setlease notifier.
658 static void
659 nfsd_file_close_inode(struct inode *inode)
661 LIST_HEAD(dispose);
663 nfsd_file_queue_for_close(inode, &dispose);
664 nfsd_file_dispose_list_delayed(&dispose);
668 * nfsd_file_close_inode_sync - attempt to forcibly close a nfsd_file
669 * @inode: inode of the file to attempt to remove
671 * Close out any open nfsd_files that can be reaped for @inode. The
672 * nfsd_files are closed out synchronously.
674 * This is called from nfsd_rename and nfsd_unlink to avoid silly-renames
675 * when reexporting NFS.
677 void
678 nfsd_file_close_inode_sync(struct inode *inode)
680 struct nfsd_file *nf;
681 LIST_HEAD(dispose);
683 trace_nfsd_file_close(inode);
685 nfsd_file_queue_for_close(inode, &dispose);
686 while (!list_empty(&dispose)) {
687 nf = list_first_entry(&dispose, struct nfsd_file, nf_gc);
688 list_del_init(&nf->nf_gc);
689 nfsd_file_free(nf);
693 static int
694 nfsd_file_lease_notifier_call(struct notifier_block *nb, unsigned long arg,
695 void *data)
697 struct file_lease *fl = data;
699 /* Only close files for F_SETLEASE leases */
700 if (fl->c.flc_flags & FL_LEASE)
701 nfsd_file_close_inode(file_inode(fl->c.flc_file));
702 return 0;
705 static struct notifier_block nfsd_file_lease_notifier = {
706 .notifier_call = nfsd_file_lease_notifier_call,
709 static int
710 nfsd_file_fsnotify_handle_event(struct fsnotify_mark *mark, u32 mask,
711 struct inode *inode, struct inode *dir,
712 const struct qstr *name, u32 cookie)
714 if (WARN_ON_ONCE(!inode))
715 return 0;
717 trace_nfsd_file_fsnotify_handle_event(inode, mask);
719 /* Should be no marks on non-regular files */
720 if (!S_ISREG(inode->i_mode)) {
721 WARN_ON_ONCE(1);
722 return 0;
725 /* don't close files if this was not the last link */
726 if (mask & FS_ATTRIB) {
727 if (inode->i_nlink)
728 return 0;
731 nfsd_file_close_inode(inode);
732 return 0;
736 static const struct fsnotify_ops nfsd_file_fsnotify_ops = {
737 .handle_inode_event = nfsd_file_fsnotify_handle_event,
738 .free_mark = nfsd_file_mark_free,
742 nfsd_file_cache_init(void)
744 int ret;
746 lockdep_assert_held(&nfsd_mutex);
747 if (test_and_set_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
748 return 0;
750 ret = rhltable_init(&nfsd_file_rhltable, &nfsd_file_rhash_params);
751 if (ret)
752 goto out;
754 ret = -ENOMEM;
755 nfsd_file_slab = KMEM_CACHE(nfsd_file, 0);
756 if (!nfsd_file_slab) {
757 pr_err("nfsd: unable to create nfsd_file_slab\n");
758 goto out_err;
761 nfsd_file_mark_slab = KMEM_CACHE(nfsd_file_mark, 0);
762 if (!nfsd_file_mark_slab) {
763 pr_err("nfsd: unable to create nfsd_file_mark_slab\n");
764 goto out_err;
767 ret = list_lru_init(&nfsd_file_lru);
768 if (ret) {
769 pr_err("nfsd: failed to init nfsd_file_lru: %d\n", ret);
770 goto out_err;
773 nfsd_file_shrinker = shrinker_alloc(0, "nfsd-filecache");
774 if (!nfsd_file_shrinker) {
775 ret = -ENOMEM;
776 pr_err("nfsd: failed to allocate nfsd_file_shrinker\n");
777 goto out_lru;
780 nfsd_file_shrinker->count_objects = nfsd_file_lru_count;
781 nfsd_file_shrinker->scan_objects = nfsd_file_lru_scan;
782 nfsd_file_shrinker->seeks = 1;
784 shrinker_register(nfsd_file_shrinker);
786 ret = lease_register_notifier(&nfsd_file_lease_notifier);
787 if (ret) {
788 pr_err("nfsd: unable to register lease notifier: %d\n", ret);
789 goto out_shrinker;
792 nfsd_file_fsnotify_group = fsnotify_alloc_group(&nfsd_file_fsnotify_ops,
794 if (IS_ERR(nfsd_file_fsnotify_group)) {
795 pr_err("nfsd: unable to create fsnotify group: %ld\n",
796 PTR_ERR(nfsd_file_fsnotify_group));
797 ret = PTR_ERR(nfsd_file_fsnotify_group);
798 nfsd_file_fsnotify_group = NULL;
799 goto out_notifier;
802 INIT_DELAYED_WORK(&nfsd_filecache_laundrette, nfsd_file_gc_worker);
803 out:
804 if (ret)
805 clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags);
806 return ret;
807 out_notifier:
808 lease_unregister_notifier(&nfsd_file_lease_notifier);
809 out_shrinker:
810 shrinker_free(nfsd_file_shrinker);
811 out_lru:
812 list_lru_destroy(&nfsd_file_lru);
813 out_err:
814 kmem_cache_destroy(nfsd_file_slab);
815 nfsd_file_slab = NULL;
816 kmem_cache_destroy(nfsd_file_mark_slab);
817 nfsd_file_mark_slab = NULL;
818 rhltable_destroy(&nfsd_file_rhltable);
819 goto out;
823 * __nfsd_file_cache_purge: clean out the cache for shutdown
824 * @net: net-namespace to shut down the cache (may be NULL)
826 * Walk the nfsd_file cache and close out any that match @net. If @net is NULL,
827 * then close out everything. Called when an nfsd instance is being shut down,
828 * and when the exports table is flushed.
830 static void
831 __nfsd_file_cache_purge(struct net *net)
833 struct rhashtable_iter iter;
834 struct nfsd_file *nf;
835 LIST_HEAD(dispose);
837 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
838 if (net) {
839 struct nfsd_net *nn = net_generic(net, nfsd_net_id);
840 nfs_localio_invalidate_clients(&nn->local_clients,
841 &nn->local_clients_lock);
843 #endif
845 rhltable_walk_enter(&nfsd_file_rhltable, &iter);
846 do {
847 rhashtable_walk_start(&iter);
849 nf = rhashtable_walk_next(&iter);
850 while (!IS_ERR_OR_NULL(nf)) {
851 if (!net || nf->nf_net == net)
852 nfsd_file_cond_queue(nf, &dispose);
853 nf = rhashtable_walk_next(&iter);
856 rhashtable_walk_stop(&iter);
857 } while (nf == ERR_PTR(-EAGAIN));
858 rhashtable_walk_exit(&iter);
860 nfsd_file_dispose_list(&dispose);
863 static struct nfsd_fcache_disposal *
864 nfsd_alloc_fcache_disposal(void)
866 struct nfsd_fcache_disposal *l;
868 l = kmalloc(sizeof(*l), GFP_KERNEL);
869 if (!l)
870 return NULL;
871 spin_lock_init(&l->lock);
872 INIT_LIST_HEAD(&l->freeme);
873 return l;
876 static void
877 nfsd_free_fcache_disposal(struct nfsd_fcache_disposal *l)
879 nfsd_file_dispose_list(&l->freeme);
880 kfree(l);
883 static void
884 nfsd_free_fcache_disposal_net(struct net *net)
886 struct nfsd_net *nn = net_generic(net, nfsd_net_id);
887 struct nfsd_fcache_disposal *l = nn->fcache_disposal;
889 nfsd_free_fcache_disposal(l);
893 nfsd_file_cache_start_net(struct net *net)
895 struct nfsd_net *nn = net_generic(net, nfsd_net_id);
897 nn->fcache_disposal = nfsd_alloc_fcache_disposal();
898 return nn->fcache_disposal ? 0 : -ENOMEM;
902 * nfsd_file_cache_purge - Remove all cache items associated with @net
903 * @net: target net namespace
906 void
907 nfsd_file_cache_purge(struct net *net)
909 lockdep_assert_held(&nfsd_mutex);
910 if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
911 __nfsd_file_cache_purge(net);
914 void
915 nfsd_file_cache_shutdown_net(struct net *net)
917 nfsd_file_cache_purge(net);
918 nfsd_free_fcache_disposal_net(net);
921 void
922 nfsd_file_cache_shutdown(void)
924 int i;
926 lockdep_assert_held(&nfsd_mutex);
927 if (test_and_clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 0)
928 return;
930 lease_unregister_notifier(&nfsd_file_lease_notifier);
931 shrinker_free(nfsd_file_shrinker);
933 * make sure all callers of nfsd_file_lru_cb are done before
934 * calling nfsd_file_cache_purge
936 cancel_delayed_work_sync(&nfsd_filecache_laundrette);
937 __nfsd_file_cache_purge(NULL);
938 list_lru_destroy(&nfsd_file_lru);
939 rcu_barrier();
940 fsnotify_put_group(nfsd_file_fsnotify_group);
941 nfsd_file_fsnotify_group = NULL;
942 kmem_cache_destroy(nfsd_file_slab);
943 nfsd_file_slab = NULL;
944 fsnotify_wait_marks_destroyed();
945 kmem_cache_destroy(nfsd_file_mark_slab);
946 nfsd_file_mark_slab = NULL;
947 rhltable_destroy(&nfsd_file_rhltable);
949 for_each_possible_cpu(i) {
950 per_cpu(nfsd_file_cache_hits, i) = 0;
951 per_cpu(nfsd_file_acquisitions, i) = 0;
952 per_cpu(nfsd_file_allocations, i) = 0;
953 per_cpu(nfsd_file_releases, i) = 0;
954 per_cpu(nfsd_file_total_age, i) = 0;
955 per_cpu(nfsd_file_evictions, i) = 0;
959 static struct nfsd_file *
960 nfsd_file_lookup_locked(const struct net *net, const struct cred *cred,
961 struct inode *inode, unsigned char need,
962 bool want_gc)
964 struct rhlist_head *tmp, *list;
965 struct nfsd_file *nf;
967 list = rhltable_lookup(&nfsd_file_rhltable, &inode,
968 nfsd_file_rhash_params);
969 rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist) {
970 if (nf->nf_may != need)
971 continue;
972 if (nf->nf_net != net)
973 continue;
974 if (!nfsd_match_cred(nf->nf_cred, cred))
975 continue;
976 if (test_bit(NFSD_FILE_GC, &nf->nf_flags) != want_gc)
977 continue;
978 if (test_bit(NFSD_FILE_HASHED, &nf->nf_flags) == 0)
979 continue;
981 if (!nfsd_file_get(nf))
982 continue;
983 return nf;
985 return NULL;
989 * nfsd_file_is_cached - are there any cached open files for this inode?
990 * @inode: inode to check
992 * The lookup matches inodes in all net namespaces and is atomic wrt
993 * nfsd_file_acquire().
995 * Return values:
996 * %true: filecache contains at least one file matching this inode
997 * %false: filecache contains no files matching this inode
999 bool
1000 nfsd_file_is_cached(struct inode *inode)
1002 struct rhlist_head *tmp, *list;
1003 struct nfsd_file *nf;
1004 bool ret = false;
1006 rcu_read_lock();
1007 list = rhltable_lookup(&nfsd_file_rhltable, &inode,
1008 nfsd_file_rhash_params);
1009 rhl_for_each_entry_rcu(nf, tmp, list, nf_rlist)
1010 if (test_bit(NFSD_FILE_GC, &nf->nf_flags)) {
1011 ret = true;
1012 break;
1014 rcu_read_unlock();
1016 trace_nfsd_file_is_cached(inode, (int)ret);
1017 return ret;
1020 static __be32
1021 nfsd_file_do_acquire(struct svc_rqst *rqstp, struct net *net,
1022 struct svc_cred *cred,
1023 struct auth_domain *client,
1024 struct svc_fh *fhp,
1025 unsigned int may_flags, struct file *file,
1026 struct nfsd_file **pnf, bool want_gc)
1028 unsigned char need = may_flags & NFSD_FILE_MAY_MASK;
1029 struct nfsd_file *new, *nf;
1030 bool stale_retry = true;
1031 bool open_retry = true;
1032 struct inode *inode;
1033 __be32 status;
1034 int ret;
1036 retry:
1037 if (rqstp) {
1038 status = fh_verify(rqstp, fhp, S_IFREG,
1039 may_flags|NFSD_MAY_OWNER_OVERRIDE);
1040 } else {
1041 status = fh_verify_local(net, cred, client, fhp, S_IFREG,
1042 may_flags|NFSD_MAY_OWNER_OVERRIDE);
1044 if (status != nfs_ok)
1045 return status;
1046 inode = d_inode(fhp->fh_dentry);
1048 rcu_read_lock();
1049 nf = nfsd_file_lookup_locked(net, current_cred(), inode, need, want_gc);
1050 rcu_read_unlock();
1052 if (nf) {
1054 * If the nf is on the LRU then it holds an extra reference
1055 * that must be put if it's removed. It had better not be
1056 * the last one however, since we should hold another.
1058 if (nfsd_file_lru_remove(nf))
1059 refcount_dec(&nf->nf_ref);
1060 goto wait_for_construction;
1063 new = nfsd_file_alloc(net, inode, need, want_gc);
1064 if (!new) {
1065 status = nfserr_jukebox;
1066 goto out;
1069 rcu_read_lock();
1070 spin_lock(&inode->i_lock);
1071 nf = nfsd_file_lookup_locked(net, current_cred(), inode, need, want_gc);
1072 if (unlikely(nf)) {
1073 spin_unlock(&inode->i_lock);
1074 rcu_read_unlock();
1075 nfsd_file_free(new);
1076 goto wait_for_construction;
1078 nf = new;
1079 ret = rhltable_insert(&nfsd_file_rhltable, &nf->nf_rlist,
1080 nfsd_file_rhash_params);
1081 spin_unlock(&inode->i_lock);
1082 rcu_read_unlock();
1083 if (likely(ret == 0))
1084 goto open_file;
1086 trace_nfsd_file_insert_err(rqstp, inode, may_flags, ret);
1087 status = nfserr_jukebox;
1088 goto construction_err;
1090 wait_for_construction:
1091 wait_on_bit(&nf->nf_flags, NFSD_FILE_PENDING, TASK_UNINTERRUPTIBLE);
1093 /* Did construction of this file fail? */
1094 if (!test_bit(NFSD_FILE_HASHED, &nf->nf_flags)) {
1095 trace_nfsd_file_cons_err(rqstp, inode, may_flags, nf);
1096 if (!open_retry) {
1097 status = nfserr_jukebox;
1098 goto construction_err;
1100 nfsd_file_put(nf);
1101 open_retry = false;
1102 fh_put(fhp);
1103 goto retry;
1105 this_cpu_inc(nfsd_file_cache_hits);
1107 status = nfserrno(nfsd_open_break_lease(file_inode(nf->nf_file), may_flags));
1108 if (status != nfs_ok) {
1109 nfsd_file_put(nf);
1110 nf = NULL;
1113 out:
1114 if (status == nfs_ok) {
1115 this_cpu_inc(nfsd_file_acquisitions);
1116 nfsd_file_check_write_error(nf);
1117 *pnf = nf;
1119 trace_nfsd_file_acquire(rqstp, inode, may_flags, nf, status);
1120 return status;
1122 open_file:
1123 trace_nfsd_file_alloc(nf);
1124 nf->nf_mark = nfsd_file_mark_find_or_create(inode);
1125 if (nf->nf_mark) {
1126 if (file) {
1127 get_file(file);
1128 nf->nf_file = file;
1129 status = nfs_ok;
1130 trace_nfsd_file_opened(nf, status);
1131 } else {
1132 ret = nfsd_open_verified(fhp, may_flags, &nf->nf_file);
1133 if (ret == -EOPENSTALE && stale_retry) {
1134 stale_retry = false;
1135 nfsd_file_unhash(nf);
1136 clear_and_wake_up_bit(NFSD_FILE_PENDING,
1137 &nf->nf_flags);
1138 if (refcount_dec_and_test(&nf->nf_ref))
1139 nfsd_file_free(nf);
1140 nf = NULL;
1141 fh_put(fhp);
1142 goto retry;
1144 status = nfserrno(ret);
1145 trace_nfsd_file_open(nf, status);
1147 } else
1148 status = nfserr_jukebox;
1150 * If construction failed, or we raced with a call to unlink()
1151 * then unhash.
1153 if (status != nfs_ok || inode->i_nlink == 0)
1154 nfsd_file_unhash(nf);
1155 clear_and_wake_up_bit(NFSD_FILE_PENDING, &nf->nf_flags);
1156 if (status == nfs_ok)
1157 goto out;
1159 construction_err:
1160 if (refcount_dec_and_test(&nf->nf_ref))
1161 nfsd_file_free(nf);
1162 nf = NULL;
1163 goto out;
1167 * nfsd_file_acquire_gc - Get a struct nfsd_file with an open file
1168 * @rqstp: the RPC transaction being executed
1169 * @fhp: the NFS filehandle of the file to be opened
1170 * @may_flags: NFSD_MAY_ settings for the file
1171 * @pnf: OUT: new or found "struct nfsd_file" object
1173 * The nfsd_file object returned by this API is reference-counted
1174 * and garbage-collected. The object is retained for a few
1175 * seconds after the final nfsd_file_put() in case the caller
1176 * wants to re-use it.
1178 * Return values:
1179 * %nfs_ok - @pnf points to an nfsd_file with its reference
1180 * count boosted.
1182 * On error, an nfsstat value in network byte order is returned.
1184 __be32
1185 nfsd_file_acquire_gc(struct svc_rqst *rqstp, struct svc_fh *fhp,
1186 unsigned int may_flags, struct nfsd_file **pnf)
1188 return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1189 fhp, may_flags, NULL, pnf, true);
1193 * nfsd_file_acquire - Get a struct nfsd_file with an open file
1194 * @rqstp: the RPC transaction being executed
1195 * @fhp: the NFS filehandle of the file to be opened
1196 * @may_flags: NFSD_MAY_ settings for the file
1197 * @pnf: OUT: new or found "struct nfsd_file" object
1199 * The nfsd_file_object returned by this API is reference-counted
1200 * but not garbage-collected. The object is unhashed after the
1201 * final nfsd_file_put().
1203 * Return values:
1204 * %nfs_ok - @pnf points to an nfsd_file with its reference
1205 * count boosted.
1207 * On error, an nfsstat value in network byte order is returned.
1209 __be32
1210 nfsd_file_acquire(struct svc_rqst *rqstp, struct svc_fh *fhp,
1211 unsigned int may_flags, struct nfsd_file **pnf)
1213 return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1214 fhp, may_flags, NULL, pnf, false);
1218 * nfsd_file_acquire_local - Get a struct nfsd_file with an open file for localio
1219 * @net: The network namespace in which to perform a lookup
1220 * @cred: the user credential with which to validate access
1221 * @client: the auth_domain for LOCALIO lookup
1222 * @fhp: the NFS filehandle of the file to be opened
1223 * @may_flags: NFSD_MAY_ settings for the file
1224 * @pnf: OUT: new or found "struct nfsd_file" object
1226 * This file lookup interface provide access to a file given the
1227 * filehandle and credential. No connection-based authorisation
1228 * is performed and in that way it is quite different to other
1229 * file access mediated by nfsd. It allows a kernel module such as the NFS
1230 * client to reach across network and filesystem namespaces to access
1231 * a file. The security implications of this should be carefully
1232 * considered before use.
1234 * The nfsd_file_object returned by this API is reference-counted
1235 * but not garbage-collected. The object is unhashed after the
1236 * final nfsd_file_put().
1238 * Return values:
1239 * %nfs_ok - @pnf points to an nfsd_file with its reference
1240 * count boosted.
1242 * On error, an nfsstat value in network byte order is returned.
1244 __be32
1245 nfsd_file_acquire_local(struct net *net, struct svc_cred *cred,
1246 struct auth_domain *client, struct svc_fh *fhp,
1247 unsigned int may_flags, struct nfsd_file **pnf)
1250 * Save creds before calling nfsd_file_do_acquire() (which calls
1251 * nfsd_setuser). Important because caller (LOCALIO) is from
1252 * client context.
1254 const struct cred *save_cred = get_current_cred();
1255 __be32 beres;
1257 beres = nfsd_file_do_acquire(NULL, net, cred, client,
1258 fhp, may_flags, NULL, pnf, false);
1259 put_cred(revert_creds(save_cred));
1260 return beres;
1264 * nfsd_file_acquire_opened - Get a struct nfsd_file using existing open file
1265 * @rqstp: the RPC transaction being executed
1266 * @fhp: the NFS filehandle of the file just created
1267 * @may_flags: NFSD_MAY_ settings for the file
1268 * @file: cached, already-open file (may be NULL)
1269 * @pnf: OUT: new or found "struct nfsd_file" object
1271 * Acquire a nfsd_file object that is not GC'ed. If one doesn't already exist,
1272 * and @file is non-NULL, use it to instantiate a new nfsd_file instead of
1273 * opening a new one.
1275 * Return values:
1276 * %nfs_ok - @pnf points to an nfsd_file with its reference
1277 * count boosted.
1279 * On error, an nfsstat value in network byte order is returned.
1281 __be32
1282 nfsd_file_acquire_opened(struct svc_rqst *rqstp, struct svc_fh *fhp,
1283 unsigned int may_flags, struct file *file,
1284 struct nfsd_file **pnf)
1286 return nfsd_file_do_acquire(rqstp, SVC_NET(rqstp), NULL, NULL,
1287 fhp, may_flags, file, pnf, false);
1291 * Note that fields may be added, removed or reordered in the future. Programs
1292 * scraping this file for info should test the labels to ensure they're
1293 * getting the correct field.
1295 int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
1297 unsigned long allocations = 0, releases = 0, evictions = 0;
1298 unsigned long hits = 0, acquisitions = 0;
1299 unsigned int i, count = 0, buckets = 0;
1300 unsigned long lru = 0, total_age = 0;
1302 /* Serialize with server shutdown */
1303 mutex_lock(&nfsd_mutex);
1304 if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1) {
1305 struct bucket_table *tbl;
1306 struct rhashtable *ht;
1308 lru = list_lru_count(&nfsd_file_lru);
1310 rcu_read_lock();
1311 ht = &nfsd_file_rhltable.ht;
1312 count = atomic_read(&ht->nelems);
1313 tbl = rht_dereference_rcu(ht->tbl, ht);
1314 buckets = tbl->size;
1315 rcu_read_unlock();
1317 mutex_unlock(&nfsd_mutex);
1319 for_each_possible_cpu(i) {
1320 hits += per_cpu(nfsd_file_cache_hits, i);
1321 acquisitions += per_cpu(nfsd_file_acquisitions, i);
1322 allocations += per_cpu(nfsd_file_allocations, i);
1323 releases += per_cpu(nfsd_file_releases, i);
1324 total_age += per_cpu(nfsd_file_total_age, i);
1325 evictions += per_cpu(nfsd_file_evictions, i);
1328 seq_printf(m, "total inodes: %u\n", count);
1329 seq_printf(m, "hash buckets: %u\n", buckets);
1330 seq_printf(m, "lru entries: %lu\n", lru);
1331 seq_printf(m, "cache hits: %lu\n", hits);
1332 seq_printf(m, "acquisitions: %lu\n", acquisitions);
1333 seq_printf(m, "allocations: %lu\n", allocations);
1334 seq_printf(m, "releases: %lu\n", releases);
1335 seq_printf(m, "evictions: %lu\n", evictions);
1336 if (releases)
1337 seq_printf(m, "mean age (ms): %ld\n", total_age / releases);
1338 else
1339 seq_printf(m, "mean age (ms): -\n");
1340 return 0;