File Index
Files and directories
Sign in
FILE

cache.c

File preview with syntax highlighting.

linux-6.19.14/net/sunrpc/cache.c C
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * net/sunrpc/cache.c
   4 *
   5 * Generic code for various authentication-related caches
   6 * used by sunrpc clients and servers.
   7 *
   8 * Copyright (C) 2002 Neil Brown <neilb@cse.unsw.edu.au>
   9 */
  10
  11#include <linux/types.h>
  12#include <linux/fs.h>
  13#include <linux/file.h>
  14#include <linux/slab.h>
  15#include <linux/signal.h>
  16#include <linux/sched.h>
  17#include <linux/kmod.h>
  18#include <linux/list.h>
  19#include <linux/module.h>
  20#include <linux/ctype.h>
  21#include <linux/string_helpers.h>
  22#include <linux/uaccess.h>
  23#include <linux/poll.h>
  24#include <linux/seq_file.h>
  25#include <linux/proc_fs.h>
  26#include <linux/net.h>
  27#include <linux/workqueue.h>
  28#include <linux/mutex.h>
  29#include <linux/pagemap.h>
  30#include <asm/ioctls.h>
  31#include <linux/sunrpc/types.h>
  32#include <linux/sunrpc/cache.h>
  33#include <linux/sunrpc/stats.h>
  34#include <linux/sunrpc/rpc_pipe_fs.h>
  35#include <trace/events/sunrpc.h>
  36
  37#include "netns.h"
  38#include "fail.h"
  39
  40#define	 RPCDBG_FACILITY RPCDBG_CACHE
  41
  42static bool cache_defer_req(struct cache_req *req, struct cache_head *item);
  43static void cache_revisit_request(struct cache_head *item);
  44
  45static void cache_init(struct cache_head *h, struct cache_detail *detail)
  46{
  47	time64_t now = seconds_since_boot();
  48	INIT_HLIST_NODE(&h->cache_list);
  49	h->flags = 0;
  50	kref_init(&h->ref);
  51	h->expiry_time = now + CACHE_NEW_EXPIRY;
  52	if (now <= detail->flush_time)
  53		/* ensure it isn't already expired */
  54		now = detail->flush_time + 1;
  55	h->last_refresh = now;
  56}
  57
  58static void cache_fresh_unlocked(struct cache_head *head,
  59				struct cache_detail *detail);
  60
  61static struct cache_head *sunrpc_cache_find_rcu(struct cache_detail *detail,
  62						struct cache_head *key,
  63						int hash)
  64{
  65	struct hlist_head *head = &detail->hash_table[hash];
  66	struct cache_head *tmp;
  67
  68	rcu_read_lock();
  69	hlist_for_each_entry_rcu(tmp, head, cache_list) {
  70		if (!detail->match(tmp, key))
  71			continue;
  72		if (test_bit(CACHE_VALID, &tmp->flags) &&
  73		    cache_is_expired(detail, tmp))
  74			continue;
  75		tmp = cache_get_rcu(tmp);
  76		rcu_read_unlock();
  77		return tmp;
  78	}
  79	rcu_read_unlock();
  80	return NULL;
  81}
  82
  83static void sunrpc_begin_cache_remove_entry(struct cache_head *ch,
  84					    struct cache_detail *cd)
  85{
  86	/* Must be called under cd->hash_lock */
  87	hlist_del_init_rcu(&ch->cache_list);
  88	set_bit(CACHE_CLEANED, &ch->flags);
  89	cd->entries --;
  90}
  91
  92static void sunrpc_end_cache_remove_entry(struct cache_head *ch,
  93					  struct cache_detail *cd)
  94{
  95	cache_fresh_unlocked(ch, cd);
  96	cache_put(ch, cd);
  97}
  98
  99static struct cache_head *sunrpc_cache_add_entry(struct cache_detail *detail,
 100						 struct cache_head *key,
 101						 int hash)
 102{
 103	struct cache_head *new, *tmp, *freeme = NULL;
 104	struct hlist_head *head = &detail->hash_table[hash];
 105
 106	new = detail->alloc();
 107	if (!new)
 108		return NULL;
 109	/* must fully initialise 'new', else
 110	 * we might get lose if we need to
 111	 * cache_put it soon.
 112	 */
 113	cache_init(new, detail);
 114	detail->init(new, key);
 115
 116	spin_lock(&detail->hash_lock);
 117
 118	/* check if entry appeared while we slept */
 119	hlist_for_each_entry_rcu(tmp, head, cache_list,
 120				 lockdep_is_held(&detail->hash_lock)) {
 121		if (!detail->match(tmp, key))
 122			continue;
 123		if (test_bit(CACHE_VALID, &tmp->flags) &&
 124		    cache_is_expired(detail, tmp)) {
 125			sunrpc_begin_cache_remove_entry(tmp, detail);
 126			trace_cache_entry_expired(detail, tmp);
 127			freeme = tmp;
 128			break;
 129		}
 130		cache_get(tmp);
 131		spin_unlock(&detail->hash_lock);
 132		cache_put(new, detail);
 133		return tmp;
 134	}
 135
 136	hlist_add_head_rcu(&new->cache_list, head);
 137	detail->entries++;
 138	if (detail->nextcheck > new->expiry_time)
 139		detail->nextcheck = new->expiry_time + 1;
 140	cache_get(new);
 141	spin_unlock(&detail->hash_lock);
 142
 143	if (freeme)
 144		sunrpc_end_cache_remove_entry(freeme, detail);
 145	return new;
 146}
 147
 148struct cache_head *sunrpc_cache_lookup_rcu(struct cache_detail *detail,
 149					   struct cache_head *key, int hash)
 150{
 151	struct cache_head *ret;
 152
 153	ret = sunrpc_cache_find_rcu(detail, key, hash);
 154	if (ret)
 155		return ret;
 156	/* Didn't find anything, insert an empty entry */
 157	return sunrpc_cache_add_entry(detail, key, hash);
 158}
 159EXPORT_SYMBOL_GPL(sunrpc_cache_lookup_rcu);
 160
 161static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch);
 162
 163static void cache_fresh_locked(struct cache_head *head, time64_t expiry,
 164			       struct cache_detail *detail)
 165{
 166	time64_t now = seconds_since_boot();
 167	if (now <= detail->flush_time)
 168		/* ensure it isn't immediately treated as expired */
 169		now = detail->flush_time + 1;
 170	head->expiry_time = expiry;
 171	head->last_refresh = now;
 172	smp_wmb(); /* paired with smp_rmb() in cache_is_valid() */
 173	set_bit(CACHE_VALID, &head->flags);
 174}
 175
 176static void cache_fresh_unlocked(struct cache_head *head,
 177				 struct cache_detail *detail)
 178{
 179	if (test_and_clear_bit(CACHE_PENDING, &head->flags)) {
 180		cache_revisit_request(head);
 181		cache_dequeue(detail, head);
 182	}
 183}
 184
 185static void cache_make_negative(struct cache_detail *detail,
 186				struct cache_head *h)
 187{
 188	set_bit(CACHE_NEGATIVE, &h->flags);
 189	trace_cache_entry_make_negative(detail, h);
 190}
 191
 192static void cache_entry_update(struct cache_detail *detail,
 193			       struct cache_head *h,
 194			       struct cache_head *new)
 195{
 196	if (!test_bit(CACHE_NEGATIVE, &new->flags)) {
 197		detail->update(h, new);
 198		trace_cache_entry_update(detail, h);
 199	} else {
 200		cache_make_negative(detail, h);
 201	}
 202}
 203
 204struct cache_head *sunrpc_cache_update(struct cache_detail *detail,
 205				       struct cache_head *new, struct cache_head *old, int hash)
 206{
 207	/* The 'old' entry is to be replaced by 'new'.
 208	 * If 'old' is not VALID, we update it directly,
 209	 * otherwise we need to replace it
 210	 */
 211	struct cache_head *tmp;
 212
 213	if (!test_bit(CACHE_VALID, &old->flags)) {
 214		spin_lock(&detail->hash_lock);
 215		if (!test_bit(CACHE_VALID, &old->flags)) {
 216			cache_entry_update(detail, old, new);
 217			cache_fresh_locked(old, new->expiry_time, detail);
 218			spin_unlock(&detail->hash_lock);
 219			cache_fresh_unlocked(old, detail);
 220			return old;
 221		}
 222		spin_unlock(&detail->hash_lock);
 223	}
 224	/* We need to insert a new entry */
 225	tmp = detail->alloc();
 226	if (!tmp) {
 227		cache_put(old, detail);
 228		return NULL;
 229	}
 230	cache_init(tmp, detail);
 231	detail->init(tmp, old);
 232
 233	spin_lock(&detail->hash_lock);
 234	cache_entry_update(detail, tmp, new);
 235	hlist_add_head(&tmp->cache_list, &detail->hash_table[hash]);
 236	detail->entries++;
 237	cache_get(tmp);
 238	cache_fresh_locked(tmp, new->expiry_time, detail);
 239	cache_fresh_locked(old, 0, detail);
 240	spin_unlock(&detail->hash_lock);
 241	cache_fresh_unlocked(tmp, detail);
 242	cache_fresh_unlocked(old, detail);
 243	cache_put(old, detail);
 244	return tmp;
 245}
 246EXPORT_SYMBOL_GPL(sunrpc_cache_update);
 247
 248static inline int cache_is_valid(struct cache_head *h)
 249{
 250	if (!test_bit(CACHE_VALID, &h->flags))
 251		return -EAGAIN;
 252	else {
 253		/* entry is valid */
 254		if (test_bit(CACHE_NEGATIVE, &h->flags))
 255			return -ENOENT;
 256		else {
 257			/*
 258			 * In combination with write barrier in
 259			 * sunrpc_cache_update, ensures that anyone
 260			 * using the cache entry after this sees the
 261			 * updated contents:
 262			 */
 263			smp_rmb();
 264			return 0;
 265		}
 266	}
 267}
 268
 269static int try_to_negate_entry(struct cache_detail *detail, struct cache_head *h)
 270{
 271	int rv;
 272
 273	spin_lock(&detail->hash_lock);
 274	rv = cache_is_valid(h);
 275	if (rv == -EAGAIN) {
 276		cache_make_negative(detail, h);
 277		cache_fresh_locked(h, seconds_since_boot()+CACHE_NEW_EXPIRY,
 278				   detail);
 279		rv = -ENOENT;
 280	}
 281	spin_unlock(&detail->hash_lock);
 282	cache_fresh_unlocked(h, detail);
 283	return rv;
 284}
 285
 286int cache_check_rcu(struct cache_detail *detail,
 287		    struct cache_head *h, struct cache_req *rqstp)
 288{
 289	int rv;
 290	time64_t refresh_age, age;
 291
 292	/* First decide return status as best we can */
 293	rv = cache_is_valid(h);
 294
 295	/* now see if we want to start an upcall */
 296	refresh_age = (h->expiry_time - h->last_refresh);
 297	age = seconds_since_boot() - h->last_refresh;
 298
 299	if (rqstp == NULL) {
 300		if (rv == -EAGAIN)
 301			rv = -ENOENT;
 302	} else if (rv == -EAGAIN ||
 303		   (h->expiry_time != 0 && age > refresh_age/2)) {
 304		dprintk("RPC:       Want update, refage=%lld, age=%lld\n",
 305				refresh_age, age);
 306		switch (detail->cache_upcall(detail, h)) {
 307		case -EINVAL:
 308			rv = try_to_negate_entry(detail, h);
 309			break;
 310		case -EAGAIN:
 311			cache_fresh_unlocked(h, detail);
 312			break;
 313		}
 314	}
 315
 316	if (rv == -EAGAIN) {
 317		if (!cache_defer_req(rqstp, h)) {
 318			/*
 319			 * Request was not deferred; handle it as best
 320			 * we can ourselves:
 321			 */
 322			rv = cache_is_valid(h);
 323			if (rv == -EAGAIN)
 324				rv = -ETIMEDOUT;
 325		}
 326	}
 327
 328	return rv;
 329}
 330EXPORT_SYMBOL_GPL(cache_check_rcu);
 331
 332/*
 333 * This is the generic cache management routine for all
 334 * the authentication caches.
 335 * It checks the currency of a cache item and will (later)
 336 * initiate an upcall to fill it if needed.
 337 *
 338 *
 339 * Returns 0 if the cache_head can be used, or cache_puts it and returns
 340 * -EAGAIN if upcall is pending and request has been queued
 341 * -ETIMEDOUT if upcall failed or request could not be queue or
 342 *           upcall completed but item is still invalid (implying that
 343 *           the cache item has been replaced with a newer one).
 344 * -ENOENT if cache entry was negative
 345 */
 346int cache_check(struct cache_detail *detail,
 347		struct cache_head *h, struct cache_req *rqstp)
 348{
 349	int rv;
 350
 351	rv = cache_check_rcu(detail, h, rqstp);
 352	if (rv)
 353		cache_put(h, detail);
 354	return rv;
 355}
 356EXPORT_SYMBOL_GPL(cache_check);
 357
 358/*
 359 * caches need to be periodically cleaned.
 360 * For this we maintain a list of cache_detail and
 361 * a current pointer into that list and into the table
 362 * for that entry.
 363 *
 364 * Each time cache_clean is called it finds the next non-empty entry
 365 * in the current table and walks the list in that entry
 366 * looking for entries that can be removed.
 367 *
 368 * An entry gets removed if:
 369 * - The expiry is before current time
 370 * - The last_refresh time is before the flush_time for that cache
 371 *
 372 * later we might drop old entries with non-NEVER expiry if that table
 373 * is getting 'full' for some definition of 'full'
 374 *
 375 * The question of "how often to scan a table" is an interesting one
 376 * and is answered in part by the use of the "nextcheck" field in the
 377 * cache_detail.
 378 * When a scan of a table begins, the nextcheck field is set to a time
 379 * that is well into the future.
 380 * While scanning, if an expiry time is found that is earlier than the
 381 * current nextcheck time, nextcheck is set to that expiry time.
 382 * If the flush_time is ever set to a time earlier than the nextcheck
 383 * time, the nextcheck time is then set to that flush_time.
 384 *
 385 * A table is then only scanned if the current time is at least
 386 * the nextcheck time.
 387 *
 388 */
 389
 390static LIST_HEAD(cache_list);
 391static DEFINE_SPINLOCK(cache_list_lock);
 392static struct cache_detail *current_detail;
 393static int current_index;
 394
 395static void do_cache_clean(struct work_struct *work);
 396static struct delayed_work cache_cleaner;
 397
 398void sunrpc_init_cache_detail(struct cache_detail *cd)
 399{
 400	spin_lock_init(&cd->hash_lock);
 401	INIT_LIST_HEAD(&cd->queue);
 402	spin_lock(&cache_list_lock);
 403	cd->nextcheck = 0;
 404	cd->entries = 0;
 405	atomic_set(&cd->writers, 0);
 406	cd->last_close = 0;
 407	cd->last_warn = -1;
 408	list_add(&cd->others, &cache_list);
 409	spin_unlock(&cache_list_lock);
 410
 411	/* start the cleaning process */
 412	queue_delayed_work(system_power_efficient_wq, &cache_cleaner, 0);
 413}
 414EXPORT_SYMBOL_GPL(sunrpc_init_cache_detail);
 415
 416void sunrpc_destroy_cache_detail(struct cache_detail *cd)
 417{
 418	cache_purge(cd);
 419	spin_lock(&cache_list_lock);
 420	spin_lock(&cd->hash_lock);
 421	if (current_detail == cd)
 422		current_detail = NULL;
 423	list_del_init(&cd->others);
 424	spin_unlock(&cd->hash_lock);
 425	spin_unlock(&cache_list_lock);
 426	if (list_empty(&cache_list)) {
 427		/* module must be being unloaded so its safe to kill the worker */
 428		cancel_delayed_work_sync(&cache_cleaner);
 429	}
 430}
 431EXPORT_SYMBOL_GPL(sunrpc_destroy_cache_detail);
 432
 433/* clean cache tries to find something to clean
 434 * and cleans it.
 435 * It returns 1 if it cleaned something,
 436 *            0 if it didn't find anything this time
 437 *           -1 if it fell off the end of the list.
 438 */
 439static int cache_clean(void)
 440{
 441	int rv = 0;
 442	struct list_head *next;
 443
 444	spin_lock(&cache_list_lock);
 445
 446	/* find a suitable table if we don't already have one */
 447	while (current_detail == NULL ||
 448	    current_index >= current_detail->hash_size) {
 449		if (current_detail)
 450			next = current_detail->others.next;
 451		else
 452			next = cache_list.next;
 453		if (next == &cache_list) {
 454			current_detail = NULL;
 455			spin_unlock(&cache_list_lock);
 456			return -1;
 457		}
 458		current_detail = list_entry(next, struct cache_detail, others);
 459		if (current_detail->nextcheck > seconds_since_boot())
 460			current_index = current_detail->hash_size;
 461		else {
 462			current_index = 0;
 463			current_detail->nextcheck = seconds_since_boot()+30*60;
 464		}
 465	}
 466
 467	spin_lock(&current_detail->hash_lock);
 468
 469	/* find a non-empty bucket in the table */
 470	while (current_index < current_detail->hash_size &&
 471	       hlist_empty(&current_detail->hash_table[current_index]))
 472		current_index++;
 473
 474	/* find a cleanable entry in the bucket and clean it, or set to next bucket */
 475	if (current_index < current_detail->hash_size) {
 476		struct cache_head *ch = NULL;
 477		struct cache_detail *d;
 478		struct hlist_head *head;
 479		struct hlist_node *tmp;
 480
 481		/* Ok, now to clean this strand */
 482		head = &current_detail->hash_table[current_index];
 483		hlist_for_each_entry_safe(ch, tmp, head, cache_list) {
 484			if (current_detail->nextcheck > ch->expiry_time)
 485				current_detail->nextcheck = ch->expiry_time+1;
 486			if (!cache_is_expired(current_detail, ch))
 487				continue;
 488
 489			sunrpc_begin_cache_remove_entry(ch, current_detail);
 490			trace_cache_entry_expired(current_detail, ch);
 491			rv = 1;
 492			break;
 493		}
 494
 495		spin_unlock(&current_detail->hash_lock);
 496		d = current_detail;
 497		if (!ch)
 498			current_index ++;
 499		spin_unlock(&cache_list_lock);
 500		if (ch)
 501			sunrpc_end_cache_remove_entry(ch, d);
 502	} else {
 503		spin_unlock(&current_detail->hash_lock);
 504		spin_unlock(&cache_list_lock);
 505	}
 506
 507	return rv;
 508}
 509
 510/*
 511 * We want to regularly clean the cache, so we need to schedule some work ...
 512 */
 513static void do_cache_clean(struct work_struct *work)
 514{
 515	int delay;
 516
 517	if (list_empty(&cache_list))
 518		return;
 519
 520	if (cache_clean() == -1)
 521		delay = round_jiffies_relative(30*HZ);
 522	else
 523		delay = 5;
 524
 525	queue_delayed_work(system_power_efficient_wq, &cache_cleaner, delay);
 526}
 527
 528
 529/*
 530 * Clean all caches promptly.  This just calls cache_clean
 531 * repeatedly until we are sure that every cache has had a chance to
 532 * be fully cleaned
 533 */
 534void cache_flush(void)
 535{
 536	while (cache_clean() != -1)
 537		cond_resched();
 538	while (cache_clean() != -1)
 539		cond_resched();
 540}
 541EXPORT_SYMBOL_GPL(cache_flush);
 542
 543void cache_purge(struct cache_detail *detail)
 544{
 545	struct cache_head *ch = NULL;
 546	struct hlist_head *head = NULL;
 547	int i = 0;
 548
 549	spin_lock(&detail->hash_lock);
 550	if (!detail->entries) {
 551		spin_unlock(&detail->hash_lock);
 552		return;
 553	}
 554
 555	dprintk("RPC: %d entries in %s cache\n", detail->entries, detail->name);
 556	for (i = 0; i < detail->hash_size; i++) {
 557		head = &detail->hash_table[i];
 558		while (!hlist_empty(head)) {
 559			ch = hlist_entry(head->first, struct cache_head,
 560					 cache_list);
 561			sunrpc_begin_cache_remove_entry(ch, detail);
 562			spin_unlock(&detail->hash_lock);
 563			sunrpc_end_cache_remove_entry(ch, detail);
 564			spin_lock(&detail->hash_lock);
 565		}
 566	}
 567	spin_unlock(&detail->hash_lock);
 568}
 569EXPORT_SYMBOL_GPL(cache_purge);
 570
 571
 572/*
 573 * Deferral and Revisiting of Requests.
 574 *
 575 * If a cache lookup finds a pending entry, we
 576 * need to defer the request and revisit it later.
 577 * All deferred requests are stored in a hash table,
 578 * indexed by "struct cache_head *".
 579 * As it may be wasteful to store a whole request
 580 * structure, we allow the request to provide a
 581 * deferred form, which must contain a
 582 * 'struct cache_deferred_req'
 583 * This cache_deferred_req contains a method to allow
 584 * it to be revisited when cache info is available
 585 */
 586
 587#define	DFR_HASHSIZE	(PAGE_SIZE/sizeof(struct list_head))
 588#define	DFR_HASH(item)	((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)
 589
 590#define	DFR_MAX	300	/* ??? */
 591
 592static DEFINE_SPINLOCK(cache_defer_lock);
 593static LIST_HEAD(cache_defer_list);
 594static struct hlist_head cache_defer_hash[DFR_HASHSIZE];
 595static int cache_defer_cnt;
 596
 597static void __unhash_deferred_req(struct cache_deferred_req *dreq)
 598{
 599	hlist_del_init(&dreq->hash);
 600	if (!list_empty(&dreq->recent)) {
 601		list_del_init(&dreq->recent);
 602		cache_defer_cnt--;
 603	}
 604}
 605
 606static void __hash_deferred_req(struct cache_deferred_req *dreq, struct cache_head *item)
 607{
 608	int hash = DFR_HASH(item);
 609
 610	INIT_LIST_HEAD(&dreq->recent);
 611	hlist_add_head(&dreq->hash, &cache_defer_hash[hash]);
 612}
 613
 614static void setup_deferral(struct cache_deferred_req *dreq,
 615			   struct cache_head *item,
 616			   int count_me)
 617{
 618
 619	dreq->item = item;
 620
 621	spin_lock(&cache_defer_lock);
 622
 623	__hash_deferred_req(dreq, item);
 624
 625	if (count_me) {
 626		cache_defer_cnt++;
 627		list_add(&dreq->recent, &cache_defer_list);
 628	}
 629
 630	spin_unlock(&cache_defer_lock);
 631
 632}
 633
 634struct thread_deferred_req {
 635	struct cache_deferred_req handle;
 636	struct completion completion;
 637};
 638
 639static void cache_restart_thread(struct cache_deferred_req *dreq, int too_many)
 640{
 641	struct thread_deferred_req *dr =
 642		container_of(dreq, struct thread_deferred_req, handle);
 643	complete(&dr->completion);
 644}
 645
 646static void cache_wait_req(struct cache_req *req, struct cache_head *item)
 647{
 648	struct thread_deferred_req sleeper;
 649	struct cache_deferred_req *dreq = &sleeper.handle;
 650
 651	sleeper.completion = COMPLETION_INITIALIZER_ONSTACK(sleeper.completion);
 652	dreq->revisit = cache_restart_thread;
 653
 654	setup_deferral(dreq, item, 0);
 655
 656	if (!test_bit(CACHE_PENDING, &item->flags) ||
 657	    wait_for_completion_interruptible_timeout(
 658		    &sleeper.completion, req->thread_wait) <= 0) {
 659		/* The completion wasn't completed, so we need
 660		 * to clean up
 661		 */
 662		spin_lock(&cache_defer_lock);
 663		if (!hlist_unhashed(&sleeper.handle.hash)) {
 664			__unhash_deferred_req(&sleeper.handle);
 665			spin_unlock(&cache_defer_lock);
 666		} else {
 667			/* cache_revisit_request already removed
 668			 * this from the hash table, but hasn't
 669			 * called ->revisit yet.  It will very soon
 670			 * and we need to wait for it.
 671			 */
 672			spin_unlock(&cache_defer_lock);
 673			wait_for_completion(&sleeper.completion);
 674		}
 675	}
 676}
 677
 678static void cache_limit_defers(void)
 679{
 680	/* Make sure we haven't exceed the limit of allowed deferred
 681	 * requests.
 682	 */
 683	struct cache_deferred_req *discard = NULL;
 684
 685	if (cache_defer_cnt <= DFR_MAX)
 686		return;
 687
 688	spin_lock(&cache_defer_lock);
 689
 690	/* Consider removing either the first or the last */
 691	if (cache_defer_cnt > DFR_MAX) {
 692		if (get_random_u32_below(2))
 693			discard = list_entry(cache_defer_list.next,
 694					     struct cache_deferred_req, recent);
 695		else
 696			discard = list_entry(cache_defer_list.prev,
 697					     struct cache_deferred_req, recent);
 698		__unhash_deferred_req(discard);
 699	}
 700	spin_unlock(&cache_defer_lock);
 701	if (discard)
 702		discard->revisit(discard, 1);
 703}
 704
 705#if IS_ENABLED(CONFIG_FAIL_SUNRPC)
 706static inline bool cache_defer_immediately(void)
 707{
 708	return !fail_sunrpc.ignore_cache_wait &&
 709		should_fail(&fail_sunrpc.attr, 1);
 710}
 711#else
 712static inline bool cache_defer_immediately(void)
 713{
 714	return false;
 715}
 716#endif
 717
 718/* Return true if and only if a deferred request is queued. */
 719static bool cache_defer_req(struct cache_req *req, struct cache_head *item)
 720{
 721	struct cache_deferred_req *dreq;
 722
 723	if (!cache_defer_immediately()) {
 724		cache_wait_req(req, item);
 725		if (!test_bit(CACHE_PENDING, &item->flags))
 726			return false;
 727	}
 728
 729	dreq = req->defer(req);
 730	if (dreq == NULL)
 731		return false;
 732	setup_deferral(dreq, item, 1);
 733	if (!test_bit(CACHE_PENDING, &item->flags))
 734		/* Bit could have been cleared before we managed to
 735		 * set up the deferral, so need to revisit just in case
 736		 */
 737		cache_revisit_request(item);
 738
 739	cache_limit_defers();
 740	return true;
 741}
 742
 743static void cache_revisit_request(struct cache_head *item)
 744{
 745	struct cache_deferred_req *dreq;
 746	struct hlist_node *tmp;
 747	int hash = DFR_HASH(item);
 748	LIST_HEAD(pending);
 749
 750	spin_lock(&cache_defer_lock);
 751
 752	hlist_for_each_entry_safe(dreq, tmp, &cache_defer_hash[hash], hash)
 753		if (dreq->item == item) {
 754			__unhash_deferred_req(dreq);
 755			list_add(&dreq->recent, &pending);
 756		}
 757
 758	spin_unlock(&cache_defer_lock);
 759
 760	while (!list_empty(&pending)) {
 761		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
 762		list_del_init(&dreq->recent);
 763		dreq->revisit(dreq, 0);
 764	}
 765}
 766
 767void cache_clean_deferred(void *owner)
 768{
 769	struct cache_deferred_req *dreq, *tmp;
 770	LIST_HEAD(pending);
 771
 772	spin_lock(&cache_defer_lock);
 773
 774	list_for_each_entry_safe(dreq, tmp, &cache_defer_list, recent) {
 775		if (dreq->owner == owner) {
 776			__unhash_deferred_req(dreq);
 777			list_add(&dreq->recent, &pending);
 778		}
 779	}
 780	spin_unlock(&cache_defer_lock);
 781
 782	while (!list_empty(&pending)) {
 783		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
 784		list_del_init(&dreq->recent);
 785		dreq->revisit(dreq, 1);
 786	}
 787}
 788
 789/*
 790 * communicate with user-space
 791 *
 792 * We have a magic /proc file - /proc/net/rpc/<cachename>/channel.
 793 * On read, you get a full request, or block.
 794 * On write, an update request is processed.
 795 * Poll works if anything to read, and always allows write.
 796 *
 797 * Implemented by linked list of requests.  Each open file has
 798 * a ->private that also exists in this list.  New requests are added
 799 * to the end and may wakeup and preceding readers.
 800 * New readers are added to the head.  If, on read, an item is found with
 801 * CACHE_UPCALLING clear, we free it from the list.
 802 *
 803 */
 804
 805static DEFINE_SPINLOCK(queue_lock);
 806
 807struct cache_queue {
 808	struct list_head	list;
 809	int			reader;	/* if 0, then request */
 810};
 811struct cache_request {
 812	struct cache_queue	q;
 813	struct cache_head	*item;
 814	char			* buf;
 815	int			len;
 816	int			readers;
 817};
 818struct cache_reader {
 819	struct cache_queue	q;
 820	int			offset;	/* if non-0, we have a refcnt on next request */
 821};
 822
 823static int cache_request(struct cache_detail *detail,
 824			       struct cache_request *crq)
 825{
 826	char *bp = crq->buf;
 827	int len = PAGE_SIZE;
 828
 829	detail->cache_request(detail, crq->item, &bp, &len);
 830	if (len < 0)
 831		return -E2BIG;
 832	return PAGE_SIZE - len;
 833}
 834
 835static ssize_t cache_read(struct file *filp, char __user *buf, size_t count,
 836			  loff_t *ppos, struct cache_detail *cd)
 837{
 838	struct cache_reader *rp = filp->private_data;
 839	struct cache_request *rq;
 840	struct inode *inode = file_inode(filp);
 841	int err;
 842
 843	if (count == 0)
 844		return 0;
 845
 846	inode_lock(inode); /* protect against multiple concurrent
 847			      * readers on this file */
 848 again:
 849	spin_lock(&queue_lock);
 850	/* need to find next request */
 851	while (rp->q.list.next != &cd->queue &&
 852	       list_entry(rp->q.list.next, struct cache_queue, list)
 853	       ->reader) {
 854		struct list_head *next = rp->q.list.next;
 855		list_move(&rp->q.list, next);
 856	}
 857	if (rp->q.list.next == &cd->queue) {
 858		spin_unlock(&queue_lock);
 859		inode_unlock(inode);
 860		WARN_ON_ONCE(rp->offset);
 861		return 0;
 862	}
 863	rq = container_of(rp->q.list.next, struct cache_request, q.list);
 864	WARN_ON_ONCE(rq->q.reader);
 865	if (rp->offset == 0)
 866		rq->readers++;
 867	spin_unlock(&queue_lock);
 868
 869	if (rq->len == 0) {
 870		err = cache_request(cd, rq);
 871		if (err < 0)
 872			goto out;
 873		rq->len = err;
 874	}
 875
 876	if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
 877		err = -EAGAIN;
 878		spin_lock(&queue_lock);
 879		list_move(&rp->q.list, &rq->q.list);
 880		spin_unlock(&queue_lock);
 881	} else {
 882		if (rp->offset + count > rq->len)
 883			count = rq->len - rp->offset;
 884		err = -EFAULT;
 885		if (copy_to_user(buf, rq->buf + rp->offset, count))
 886			goto out;
 887		rp->offset += count;
 888		if (rp->offset >= rq->len) {
 889			rp->offset = 0;
 890			spin_lock(&queue_lock);
 891			list_move(&rp->q.list, &rq->q.list);
 892			spin_unlock(&queue_lock);
 893		}
 894		err = 0;
 895	}
 896 out:
 897	if (rp->offset == 0) {
 898		/* need to release rq */
 899		spin_lock(&queue_lock);
 900		rq->readers--;
 901		if (rq->readers == 0 &&
 902		    !test_bit(CACHE_PENDING, &rq->item->flags)) {
 903			list_del(&rq->q.list);
 904			spin_unlock(&queue_lock);
 905			cache_put(rq->item, cd);
 906			kfree(rq->buf);
 907			kfree(rq);
 908		} else
 909			spin_unlock(&queue_lock);
 910	}
 911	if (err == -EAGAIN)
 912		goto again;
 913	inode_unlock(inode);
 914	return err ? err :  count;
 915}
 916
 917static ssize_t cache_do_downcall(char *kaddr, const char __user *buf,
 918				 size_t count, struct cache_detail *cd)
 919{
 920	ssize_t ret;
 921
 922	if (count == 0)
 923		return -EINVAL;
 924	if (copy_from_user(kaddr, buf, count))
 925		return -EFAULT;
 926	kaddr[count] = '\0';
 927	ret = cd->cache_parse(cd, kaddr, count);
 928	if (!ret)
 929		ret = count;
 930	return ret;
 931}
 932
 933static ssize_t cache_downcall(struct address_space *mapping,
 934			      const char __user *buf,
 935			      size_t count, struct cache_detail *cd)
 936{
 937	char *write_buf;
 938	ssize_t ret = -ENOMEM;
 939
 940	if (count >= 32768) { /* 32k is max userland buffer, lets check anyway */
 941		ret = -EINVAL;
 942		goto out;
 943	}
 944
 945	write_buf = kvmalloc(count + 1, GFP_KERNEL);
 946	if (!write_buf)
 947		goto out;
 948
 949	ret = cache_do_downcall(write_buf, buf, count, cd);
 950	kvfree(write_buf);
 951out:
 952	return ret;
 953}
 954
 955static ssize_t cache_write(struct file *filp, const char __user *buf,
 956			   size_t count, loff_t *ppos,
 957			   struct cache_detail *cd)
 958{
 959	struct address_space *mapping = filp->f_mapping;
 960	struct inode *inode = file_inode(filp);
 961	ssize_t ret = -EINVAL;
 962
 963	if (!cd->cache_parse)
 964		goto out;
 965
 966	inode_lock(inode);
 967	ret = cache_downcall(mapping, buf, count, cd);
 968	inode_unlock(inode);
 969out:
 970	return ret;
 971}
 972
 973static DECLARE_WAIT_QUEUE_HEAD(queue_wait);
 974
 975static __poll_t cache_poll(struct file *filp, poll_table *wait,
 976			       struct cache_detail *cd)
 977{
 978	__poll_t mask;
 979	struct cache_reader *rp = filp->private_data;
 980	struct cache_queue *cq;
 981
 982	poll_wait(filp, &queue_wait, wait);
 983
 984	/* alway allow write */
 985	mask = EPOLLOUT | EPOLLWRNORM;
 986
 987	if (!rp)
 988		return mask;
 989
 990	spin_lock(&queue_lock);
 991
 992	for (cq= &rp->q; &cq->list != &cd->queue;
 993	     cq = list_entry(cq->list.next, struct cache_queue, list))
 994		if (!cq->reader) {
 995			mask |= EPOLLIN | EPOLLRDNORM;
 996			break;
 997		}
 998	spin_unlock(&queue_lock);
 999	return mask;
1000}
1001
1002static int cache_ioctl(struct inode *ino, struct file *filp,
1003		       unsigned int cmd, unsigned long arg,
1004		       struct cache_detail *cd)
1005{
1006	int len = 0;
1007	struct cache_reader *rp = filp->private_data;
1008	struct cache_queue *cq;
1009
1010	if (cmd != FIONREAD || !rp)
1011		return -EINVAL;
1012
1013	spin_lock(&queue_lock);
1014
1015	/* only find the length remaining in current request,
1016	 * or the length of the next request
1017	 */
1018	for (cq= &rp->q; &cq->list != &cd->queue;
1019	     cq = list_entry(cq->list.next, struct cache_queue, list))
1020		if (!cq->reader) {
1021			struct cache_request *cr =
1022				container_of(cq, struct cache_request, q);
1023			len = cr->len - rp->offset;
1024			break;
1025		}
1026	spin_unlock(&queue_lock);
1027
1028	return put_user(len, (int __user *)arg);
1029}
1030
1031static int cache_open(struct inode *inode, struct file *filp,
1032		      struct cache_detail *cd)
1033{
1034	struct cache_reader *rp = NULL;
1035
1036	if (!cd || !try_module_get(cd->owner))
1037		return -EACCES;
1038	nonseekable_open(inode, filp);
1039	if (filp->f_mode & FMODE_READ) {
1040		rp = kmalloc(sizeof(*rp), GFP_KERNEL);
1041		if (!rp) {
1042			module_put(cd->owner);
1043			return -ENOMEM;
1044		}
1045		rp->offset = 0;
1046		rp->q.reader = 1;
1047
1048		spin_lock(&queue_lock);
1049		list_add(&rp->q.list, &cd->queue);
1050		spin_unlock(&queue_lock);
1051	}
1052	if (filp->f_mode & FMODE_WRITE)
1053		atomic_inc(&cd->writers);
1054	filp->private_data = rp;
1055	return 0;
1056}
1057
1058static int cache_release(struct inode *inode, struct file *filp,
1059			 struct cache_detail *cd)
1060{
1061	struct cache_reader *rp = filp->private_data;
1062
1063	if (rp) {
1064		struct cache_request *rq = NULL;
1065
1066		spin_lock(&queue_lock);
1067		if (rp->offset) {
1068			struct cache_queue *cq;
1069			for (cq = &rp->q; &cq->list != &cd->queue;
1070			     cq = list_entry(cq->list.next,
1071					     struct cache_queue, list))
1072				if (!cq->reader) {
1073					struct cache_request *cr =
1074						container_of(cq,
1075						struct cache_request, q);
1076					cr->readers--;
1077					if (cr->readers == 0 &&
1078					    !test_bit(CACHE_PENDING,
1079						      &cr->item->flags)) {
1080						list_del(&cr->q.list);
1081						rq = cr;
1082					}
1083					break;
1084				}
1085			rp->offset = 0;
1086		}
1087		list_del(&rp->q.list);
1088		spin_unlock(&queue_lock);
1089
1090		if (rq) {
1091			cache_put(rq->item, cd);
1092			kfree(rq->buf);
1093			kfree(rq);
1094		}
1095
1096		filp->private_data = NULL;
1097		kfree(rp);
1098	}
1099	if (filp->f_mode & FMODE_WRITE) {
1100		atomic_dec(&cd->writers);
1101		cd->last_close = seconds_since_boot();
1102	}
1103	module_put(cd->owner);
1104	return 0;
1105}
1106
1107
1108
1109static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch)
1110{
1111	struct cache_queue *cq, *tmp;
1112	struct cache_request *cr;
1113	LIST_HEAD(dequeued);
1114
1115	spin_lock(&queue_lock);
1116	list_for_each_entry_safe(cq, tmp, &detail->queue, list)
1117		if (!cq->reader) {
1118			cr = container_of(cq, struct cache_request, q);
1119			if (cr->item != ch)
1120				continue;
1121			if (test_bit(CACHE_PENDING, &ch->flags))
1122				/* Lost a race and it is pending again */
1123				break;
1124			if (cr->readers != 0)
1125				continue;
1126			list_move(&cr->q.list, &dequeued);
1127		}
1128	spin_unlock(&queue_lock);
1129	while (!list_empty(&dequeued)) {
1130		cr = list_entry(dequeued.next, struct cache_request, q.list);
1131		list_del(&cr->q.list);
1132		cache_put(cr->item, detail);
1133		kfree(cr->buf);
1134		kfree(cr);
1135	}
1136}
1137
1138/*
1139 * Support routines for text-based upcalls.
1140 * Fields are separated by spaces.
1141 * Fields are either mangled to quote space tab newline slosh with slosh
1142 * or a hexified with a leading \x
1143 * Record is terminated with newline.
1144 *
1145 */
1146
1147void qword_add(char **bpp, int *lp, char *str)
1148{
1149	char *bp = *bpp;
1150	int len = *lp;
1151	int ret;
1152
1153	if (len < 0) return;
1154
1155	ret = string_escape_str(str, bp, len, ESCAPE_OCTAL, "\\ \n\t");
1156	if (ret >= len) {
1157		bp += len;
1158		len = -1;
1159	} else {
1160		bp += ret;
1161		len -= ret;
1162		*bp++ = ' ';
1163		len--;
1164	}
1165	*bpp = bp;
1166	*lp = len;
1167}
1168EXPORT_SYMBOL_GPL(qword_add);
1169
1170void qword_addhex(char **bpp, int *lp, char *buf, int blen)
1171{
1172	char *bp = *bpp;
1173	int len = *lp;
1174
1175	if (len < 0) return;
1176
1177	if (len > 2) {
1178		*bp++ = '\\';
1179		*bp++ = 'x';
1180		len -= 2;
1181		while (blen && len >= 2) {
1182			bp = hex_byte_pack(bp, *buf++);
1183			len -= 2;
1184			blen--;
1185		}
1186	}
1187	if (blen || len<1) len = -1;
1188	else {
1189		*bp++ = ' ';
1190		len--;
1191	}
1192	*bpp = bp;
1193	*lp = len;
1194}
1195EXPORT_SYMBOL_GPL(qword_addhex);
1196
1197static void warn_no_listener(struct cache_detail *detail)
1198{
1199	if (detail->last_warn != detail->last_close) {
1200		detail->last_warn = detail->last_close;
1201		if (detail->warn_no_listener)
1202			detail->warn_no_listener(detail, detail->last_close != 0);
1203	}
1204}
1205
1206static bool cache_listeners_exist(struct cache_detail *detail)
1207{
1208	if (atomic_read(&detail->writers))
1209		return true;
1210	if (detail->last_close == 0)
1211		/* This cache was never opened */
1212		return false;
1213	if (detail->last_close < seconds_since_boot() - 30)
1214		/*
1215		 * We allow for the possibility that someone might
1216		 * restart a userspace daemon without restarting the
1217		 * server; but after 30 seconds, we give up.
1218		 */
1219		 return false;
1220	return true;
1221}
1222
1223/*
1224 * register an upcall request to user-space and queue it up for read() by the
1225 * upcall daemon.
1226 *
1227 * Each request is at most one page long.
1228 */
1229static int cache_pipe_upcall(struct cache_detail *detail, struct cache_head *h)
1230{
1231	char *buf;
1232	struct cache_request *crq;
1233	int ret = 0;
1234
1235	if (test_bit(CACHE_CLEANED, &h->flags))
1236		/* Too late to make an upcall */
1237		return -EAGAIN;
1238
1239	buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1240	if (!buf)
1241		return -EAGAIN;
1242
1243	crq = kmalloc(sizeof (*crq), GFP_KERNEL);
1244	if (!crq) {
1245		kfree(buf);
1246		return -EAGAIN;
1247	}
1248
1249	crq->q.reader = 0;
1250	crq->buf = buf;
1251	crq->len = 0;
1252	crq->readers = 0;
1253	spin_lock(&queue_lock);
1254	if (test_bit(CACHE_PENDING, &h->flags)) {
1255		crq->item = cache_get(h);
1256		list_add_tail(&crq->q.list, &detail->queue);
1257		trace_cache_entry_upcall(detail, h);
1258	} else
1259		/* Lost a race, no longer PENDING, so don't enqueue */
1260		ret = -EAGAIN;
1261	spin_unlock(&queue_lock);
1262	wake_up(&queue_wait);
1263	if (ret == -EAGAIN) {
1264		kfree(buf);
1265		kfree(crq);
1266	}
1267	return ret;
1268}
1269
1270int sunrpc_cache_pipe_upcall(struct cache_detail *detail, struct cache_head *h)
1271{
1272	if (test_and_set_bit(CACHE_PENDING, &h->flags))
1273		return 0;
1274	return cache_pipe_upcall(detail, h);
1275}
1276EXPORT_SYMBOL_GPL(sunrpc_cache_pipe_upcall);
1277
1278int sunrpc_cache_pipe_upcall_timeout(struct cache_detail *detail,
1279				     struct cache_head *h)
1280{
1281	if (!cache_listeners_exist(detail)) {
1282		warn_no_listener(detail);
1283		trace_cache_entry_no_listener(detail, h);
1284		return -EINVAL;
1285	}
1286	return sunrpc_cache_pipe_upcall(detail, h);
1287}
1288EXPORT_SYMBOL_GPL(sunrpc_cache_pipe_upcall_timeout);
1289
1290/*
1291 * parse a message from user-space and pass it
1292 * to an appropriate cache
1293 * Messages are, like requests, separated into fields by
1294 * spaces and dequotes as \xHEXSTRING or embedded \nnn octal
1295 *
1296 * Message is
1297 *   reply cachename expiry key ... content....
1298 *
1299 * key and content are both parsed by cache
1300 */
1301
1302int qword_get(char **bpp, char *dest, int bufsize)
1303{
1304	/* return bytes copied, or -1 on error */
1305	char *bp = *bpp;
1306	int len = 0;
1307
1308	while (*bp == ' ') bp++;
1309
1310	if (bp[0] == '\\' && bp[1] == 'x') {
1311		/* HEX STRING */
1312		bp += 2;
1313		while (len < bufsize - 1) {
1314			int h, l;
1315
1316			h = hex_to_bin(bp[0]);
1317			if (h < 0)
1318				break;
1319
1320			l = hex_to_bin(bp[1]);
1321			if (l < 0)
1322				break;
1323
1324			*dest++ = (h << 4) | l;
1325			bp += 2;
1326			len++;
1327		}
1328	} else {
1329		/* text with \nnn octal quoting */
1330		while (*bp != ' ' && *bp != '\n' && *bp && len < bufsize-1) {
1331			if (*bp == '\\' &&
1332			    isodigit(bp[1]) && (bp[1] <= '3') &&
1333			    isodigit(bp[2]) &&
1334			    isodigit(bp[3])) {
1335				int byte = (*++bp -'0');
1336				bp++;
1337				byte = (byte << 3) | (*bp++ - '0');
1338				byte = (byte << 3) | (*bp++ - '0');
1339				*dest++ = byte;
1340				len++;
1341			} else {
1342				*dest++ = *bp++;
1343				len++;
1344			}
1345		}
1346	}
1347
1348	if (*bp != ' ' && *bp != '\n' && *bp != '\0')
1349		return -1;
1350	while (*bp == ' ') bp++;
1351	*bpp = bp;
1352	*dest = '\0';
1353	return len;
1354}
1355EXPORT_SYMBOL_GPL(qword_get);
1356
1357
1358/*
1359 * support /proc/net/rpc/$CACHENAME/content
1360 * as a seqfile.
1361 * We call ->cache_show passing NULL for the item to
1362 * get a header, then pass each real item in the cache
1363 */
1364
1365static void *__cache_seq_start(struct seq_file *m, loff_t *pos)
1366{
1367	loff_t n = *pos;
1368	unsigned int hash, entry;
1369	struct cache_head *ch;
1370	struct cache_detail *cd = m->private;
1371
1372	if (!n--)
1373		return SEQ_START_TOKEN;
1374	hash = n >> 32;
1375	entry = n & ((1LL<<32) - 1);
1376
1377	hlist_for_each_entry_rcu(ch, &cd->hash_table[hash], cache_list)
1378		if (!entry--)
1379			return ch;
1380	n &= ~((1LL<<32) - 1);
1381	do {
1382		hash++;
1383		n += 1LL<<32;
1384	} while(hash < cd->hash_size &&
1385		hlist_empty(&cd->hash_table[hash]));
1386	if (hash >= cd->hash_size)
1387		return NULL;
1388	*pos = n+1;
1389	return hlist_entry_safe(rcu_dereference_raw(
1390				hlist_first_rcu(&cd->hash_table[hash])),
1391				struct cache_head, cache_list);
1392}
1393
1394static void *cache_seq_next(struct seq_file *m, void *p, loff_t *pos)
1395{
1396	struct cache_head *ch = p;
1397	int hash = (*pos >> 32);
1398	struct cache_detail *cd = m->private;
1399
1400	if (p == SEQ_START_TOKEN)
1401		hash = 0;
1402	else if (ch->cache_list.next == NULL) {
1403		hash++;
1404		*pos += 1LL<<32;
1405	} else {
1406		++*pos;
1407		return hlist_entry_safe(rcu_dereference_raw(
1408					hlist_next_rcu(&ch->cache_list)),
1409					struct cache_head, cache_list);
1410	}
1411	*pos &= ~((1LL<<32) - 1);
1412	while (hash < cd->hash_size &&
1413	       hlist_empty(&cd->hash_table[hash])) {
1414		hash++;
1415		*pos += 1LL<<32;
1416	}
1417	if (hash >= cd->hash_size)
1418		return NULL;
1419	++*pos;
1420	return hlist_entry_safe(rcu_dereference_raw(
1421				hlist_first_rcu(&cd->hash_table[hash])),
1422				struct cache_head, cache_list);
1423}
1424
1425void *cache_seq_start_rcu(struct seq_file *m, loff_t *pos)
1426	__acquires(RCU)
1427{
1428	rcu_read_lock();
1429	return __cache_seq_start(m, pos);
1430}
1431EXPORT_SYMBOL_GPL(cache_seq_start_rcu);
1432
1433void *cache_seq_next_rcu(struct seq_file *file, void *p, loff_t *pos)
1434{
1435	return cache_seq_next(file, p, pos);
1436}
1437EXPORT_SYMBOL_GPL(cache_seq_next_rcu);
1438
1439void cache_seq_stop_rcu(struct seq_file *m, void *p)
1440	__releases(RCU)
1441{
1442	rcu_read_unlock();
1443}
1444EXPORT_SYMBOL_GPL(cache_seq_stop_rcu);
1445
1446static int c_show(struct seq_file *m, void *p)
1447{
1448	struct cache_head *cp = p;
1449	struct cache_detail *cd = m->private;
1450
1451	if (p == SEQ_START_TOKEN)
1452		return cd->cache_show(m, cd, NULL);
1453
1454	ifdebug(CACHE)
1455		seq_printf(m, "# expiry=%lld refcnt=%d flags=%lx\n",
1456			   convert_to_wallclock(cp->expiry_time),
1457			   kref_read(&cp->ref), cp->flags);
1458
1459	if (cache_check_rcu(cd, cp, NULL))
1460		seq_puts(m, "# ");
1461	else if (cache_is_expired(cd, cp))
1462		seq_puts(m, "# ");
1463
1464	return cd->cache_show(m, cd, cp);
1465}
1466
1467static const struct seq_operations cache_content_op = {
1468	.start	= cache_seq_start_rcu,
1469	.next	= cache_seq_next_rcu,
1470	.stop	= cache_seq_stop_rcu,
1471	.show	= c_show,
1472};
1473
1474static int content_open(struct inode *inode, struct file *file,
1475			struct cache_detail *cd)
1476{
1477	struct seq_file *seq;
1478	int err;
1479
1480	if (!cd || !try_module_get(cd->owner))
1481		return -EACCES;
1482
1483	err = seq_open(file, &cache_content_op);
1484	if (err) {
1485		module_put(cd->owner);
1486		return err;
1487	}
1488
1489	seq = file->private_data;
1490	seq->private = cd;
1491	return 0;
1492}
1493
1494static int content_release(struct inode *inode, struct file *file,
1495		struct cache_detail *cd)
1496{
1497	int ret = seq_release(inode, file);
1498	module_put(cd->owner);
1499	return ret;
1500}
1501
1502static int open_flush(struct inode *inode, struct file *file,
1503			struct cache_detail *cd)
1504{
1505	if (!cd || !try_module_get(cd->owner))
1506		return -EACCES;
1507	return nonseekable_open(inode, file);
1508}
1509
1510static int release_flush(struct inode *inode, struct file *file,
1511			struct cache_detail *cd)
1512{
1513	module_put(cd->owner);
1514	return 0;
1515}
1516
1517static ssize_t read_flush(struct file *file, char __user *buf,
1518			  size_t count, loff_t *ppos,
1519			  struct cache_detail *cd)
1520{
1521	char tbuf[22];
1522	size_t len;
1523
1524	len = snprintf(tbuf, sizeof(tbuf), "%llu\n",
1525			convert_to_wallclock(cd->flush_time));
1526	return simple_read_from_buffer(buf, count, ppos, tbuf, len);
1527}
1528
1529static ssize_t write_flush(struct file *file, const char __user *buf,
1530			   size_t count, loff_t *ppos,
1531			   struct cache_detail *cd)
1532{
1533	char tbuf[20];
1534	char *ep;
1535	time64_t now;
1536
1537	if (*ppos || count > sizeof(tbuf)-1)
1538		return -EINVAL;
1539	if (copy_from_user(tbuf, buf, count))
1540		return -EFAULT;
1541	tbuf[count] = 0;
1542	simple_strtoul(tbuf, &ep, 0);
1543	if (*ep && *ep != '\n')
1544		return -EINVAL;
1545	/* Note that while we check that 'buf' holds a valid number,
1546	 * we always ignore the value and just flush everything.
1547	 * Making use of the number leads to races.
1548	 */
1549
1550	now = seconds_since_boot();
1551	/* Always flush everything, so behave like cache_purge()
1552	 * Do this by advancing flush_time to the current time,
1553	 * or by one second if it has already reached the current time.
1554	 * Newly added cache entries will always have ->last_refresh greater
1555	 * that ->flush_time, so they don't get flushed prematurely.
1556	 */
1557
1558	if (cd->flush_time >= now)
1559		now = cd->flush_time + 1;
1560
1561	cd->flush_time = now;
1562	cd->nextcheck = now;
1563	cache_flush();
1564
1565	if (cd->flush)
1566		cd->flush();
1567
1568	*ppos += count;
1569	return count;
1570}
1571
1572static ssize_t cache_read_procfs(struct file *filp, char __user *buf,
1573				 size_t count, loff_t *ppos)
1574{
1575	struct cache_detail *cd = pde_data(file_inode(filp));
1576
1577	return cache_read(filp, buf, count, ppos, cd);
1578}
1579
1580static ssize_t cache_write_procfs(struct file *filp, const char __user *buf,
1581				  size_t count, loff_t *ppos)
1582{
1583	struct cache_detail *cd = pde_data(file_inode(filp));
1584
1585	return cache_write(filp, buf, count, ppos, cd);
1586}
1587
1588static __poll_t cache_poll_procfs(struct file *filp, poll_table *wait)
1589{
1590	struct cache_detail *cd = pde_data(file_inode(filp));
1591
1592	return cache_poll(filp, wait, cd);
1593}
1594
1595static long cache_ioctl_procfs(struct file *filp,
1596			       unsigned int cmd, unsigned long arg)
1597{
1598	struct inode *inode = file_inode(filp);
1599	struct cache_detail *cd = pde_data(inode);
1600
1601	return cache_ioctl(inode, filp, cmd, arg, cd);
1602}
1603
1604static int cache_open_procfs(struct inode *inode, struct file *filp)
1605{
1606	struct cache_detail *cd = pde_data(inode);
1607
1608	return cache_open(inode, filp, cd);
1609}
1610
1611static int cache_release_procfs(struct inode *inode, struct file *filp)
1612{
1613	struct cache_detail *cd = pde_data(inode);
1614
1615	return cache_release(inode, filp, cd);
1616}
1617
1618static const struct proc_ops cache_channel_proc_ops = {
1619	.proc_read	= cache_read_procfs,
1620	.proc_write	= cache_write_procfs,
1621	.proc_poll	= cache_poll_procfs,
1622	.proc_ioctl	= cache_ioctl_procfs, /* for FIONREAD */
1623	.proc_open	= cache_open_procfs,
1624	.proc_release	= cache_release_procfs,
1625};
1626
1627static int content_open_procfs(struct inode *inode, struct file *filp)
1628{
1629	struct cache_detail *cd = pde_data(inode);
1630
1631	return content_open(inode, filp, cd);
1632}
1633
1634static int content_release_procfs(struct inode *inode, struct file *filp)
1635{
1636	struct cache_detail *cd = pde_data(inode);
1637
1638	return content_release(inode, filp, cd);
1639}
1640
1641static const struct proc_ops content_proc_ops = {
1642	.proc_open	= content_open_procfs,
1643	.proc_read	= seq_read,
1644	.proc_lseek	= seq_lseek,
1645	.proc_release	= content_release_procfs,
1646};
1647
1648static int open_flush_procfs(struct inode *inode, struct file *filp)
1649{
1650	struct cache_detail *cd = pde_data(inode);
1651
1652	return open_flush(inode, filp, cd);
1653}
1654
1655static int release_flush_procfs(struct inode *inode, struct file *filp)
1656{
1657	struct cache_detail *cd = pde_data(inode);
1658
1659	return release_flush(inode, filp, cd);
1660}
1661
1662static ssize_t read_flush_procfs(struct file *filp, char __user *buf,
1663			    size_t count, loff_t *ppos)
1664{
1665	struct cache_detail *cd = pde_data(file_inode(filp));
1666
1667	return read_flush(filp, buf, count, ppos, cd);
1668}
1669
1670static ssize_t write_flush_procfs(struct file *filp,
1671				  const char __user *buf,
1672				  size_t count, loff_t *ppos)
1673{
1674	struct cache_detail *cd = pde_data(file_inode(filp));
1675
1676	return write_flush(filp, buf, count, ppos, cd);
1677}
1678
1679static const struct proc_ops cache_flush_proc_ops = {
1680	.proc_open	= open_flush_procfs,
1681	.proc_read	= read_flush_procfs,
1682	.proc_write	= write_flush_procfs,
1683	.proc_release	= release_flush_procfs,
1684};
1685
1686static void remove_cache_proc_entries(struct cache_detail *cd)
1687{
1688	if (cd->procfs) {
1689		proc_remove(cd->procfs);
1690		cd->procfs = NULL;
1691	}
1692}
1693
1694static int create_cache_proc_entries(struct cache_detail *cd, struct net *net)
1695{
1696	struct proc_dir_entry *p;
1697	struct sunrpc_net *sn;
1698
1699	if (!IS_ENABLED(CONFIG_PROC_FS))
1700		return 0;
1701
1702	sn = net_generic(net, sunrpc_net_id);
1703	cd->procfs = proc_mkdir(cd->name, sn->proc_net_rpc);
1704	if (cd->procfs == NULL)
1705		goto out_nomem;
1706
1707	p = proc_create_data("flush", S_IFREG | 0600,
1708			     cd->procfs, &cache_flush_proc_ops, cd);
1709	if (p == NULL)
1710		goto out_nomem;
1711
1712	if (cd->cache_request || cd->cache_parse) {
1713		p = proc_create_data("channel", S_IFREG | 0600, cd->procfs,
1714				     &cache_channel_proc_ops, cd);
1715		if (p == NULL)
1716			goto out_nomem;
1717	}
1718	if (cd->cache_show) {
1719		p = proc_create_data("content", S_IFREG | 0400, cd->procfs,
1720				     &content_proc_ops, cd);
1721		if (p == NULL)
1722			goto out_nomem;
1723	}
1724	return 0;
1725out_nomem:
1726	remove_cache_proc_entries(cd);
1727	return -ENOMEM;
1728}
1729
1730void __init cache_initialize(void)
1731{
1732	INIT_DEFERRABLE_WORK(&cache_cleaner, do_cache_clean);
1733}
1734
1735int cache_register_net(struct cache_detail *cd, struct net *net)
1736{
1737	int ret;
1738
1739	sunrpc_init_cache_detail(cd);
1740	ret = create_cache_proc_entries(cd, net);
1741	if (ret)
1742		sunrpc_destroy_cache_detail(cd);
1743	return ret;
1744}
1745EXPORT_SYMBOL_GPL(cache_register_net);
1746
1747void cache_unregister_net(struct cache_detail *cd, struct net *net)
1748{
1749	remove_cache_proc_entries(cd);
1750	sunrpc_destroy_cache_detail(cd);
1751}
1752EXPORT_SYMBOL_GPL(cache_unregister_net);
1753
1754struct cache_detail *cache_create_net(const struct cache_detail *tmpl, struct net *net)
1755{
1756	struct cache_detail *cd;
1757	int i;
1758
1759	cd = kmemdup(tmpl, sizeof(struct cache_detail), GFP_KERNEL);
1760	if (cd == NULL)
1761		return ERR_PTR(-ENOMEM);
1762
1763	cd->hash_table = kcalloc(cd->hash_size, sizeof(struct hlist_head),
1764				 GFP_KERNEL);
1765	if (cd->hash_table == NULL) {
1766		kfree(cd);
1767		return ERR_PTR(-ENOMEM);
1768	}
1769
1770	for (i = 0; i < cd->hash_size; i++)
1771		INIT_HLIST_HEAD(&cd->hash_table[i]);
1772	cd->net = net;
1773	return cd;
1774}
1775EXPORT_SYMBOL_GPL(cache_create_net);
1776
1777void cache_destroy_net(struct cache_detail *cd, struct net *net)
1778{
1779	kfree(cd->hash_table);
1780	kfree(cd);
1781}
1782EXPORT_SYMBOL_GPL(cache_destroy_net);
1783
1784static ssize_t cache_read_pipefs(struct file *filp, char __user *buf,
1785				 size_t count, loff_t *ppos)
1786{
1787	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1788
1789	return cache_read(filp, buf, count, ppos, cd);
1790}
1791
1792static ssize_t cache_write_pipefs(struct file *filp, const char __user *buf,
1793				  size_t count, loff_t *ppos)
1794{
1795	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1796
1797	return cache_write(filp, buf, count, ppos, cd);
1798}
1799
1800static __poll_t cache_poll_pipefs(struct file *filp, poll_table *wait)
1801{
1802	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1803
1804	return cache_poll(filp, wait, cd);
1805}
1806
1807static long cache_ioctl_pipefs(struct file *filp,
1808			      unsigned int cmd, unsigned long arg)
1809{
1810	struct inode *inode = file_inode(filp);
1811	struct cache_detail *cd = RPC_I(inode)->private;
1812
1813	return cache_ioctl(inode, filp, cmd, arg, cd);
1814}
1815
1816static int cache_open_pipefs(struct inode *inode, struct file *filp)
1817{
1818	struct cache_detail *cd = RPC_I(inode)->private;
1819
1820	return cache_open(inode, filp, cd);
1821}
1822
1823static int cache_release_pipefs(struct inode *inode, struct file *filp)
1824{
1825	struct cache_detail *cd = RPC_I(inode)->private;
1826
1827	return cache_release(inode, filp, cd);
1828}
1829
1830const struct file_operations cache_file_operations_pipefs = {
1831	.owner		= THIS_MODULE,
1832	.read		= cache_read_pipefs,
1833	.write		= cache_write_pipefs,
1834	.poll		= cache_poll_pipefs,
1835	.unlocked_ioctl	= cache_ioctl_pipefs, /* for FIONREAD */
1836	.open		= cache_open_pipefs,
1837	.release	= cache_release_pipefs,
1838};
1839
1840static int content_open_pipefs(struct inode *inode, struct file *filp)
1841{
1842	struct cache_detail *cd = RPC_I(inode)->private;
1843
1844	return content_open(inode, filp, cd);
1845}
1846
1847static int content_release_pipefs(struct inode *inode, struct file *filp)
1848{
1849	struct cache_detail *cd = RPC_I(inode)->private;
1850
1851	return content_release(inode, filp, cd);
1852}
1853
1854const struct file_operations content_file_operations_pipefs = {
1855	.open		= content_open_pipefs,
1856	.read		= seq_read,
1857	.llseek		= seq_lseek,
1858	.release	= content_release_pipefs,
1859};
1860
1861static int open_flush_pipefs(struct inode *inode, struct file *filp)
1862{
1863	struct cache_detail *cd = RPC_I(inode)->private;
1864
1865	return open_flush(inode, filp, cd);
1866}
1867
1868static int release_flush_pipefs(struct inode *inode, struct file *filp)
1869{
1870	struct cache_detail *cd = RPC_I(inode)->private;
1871
1872	return release_flush(inode, filp, cd);
1873}
1874
1875static ssize_t read_flush_pipefs(struct file *filp, char __user *buf,
1876			    size_t count, loff_t *ppos)
1877{
1878	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1879
1880	return read_flush(filp, buf, count, ppos, cd);
1881}
1882
1883static ssize_t write_flush_pipefs(struct file *filp,
1884				  const char __user *buf,
1885				  size_t count, loff_t *ppos)
1886{
1887	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1888
1889	return write_flush(filp, buf, count, ppos, cd);
1890}
1891
1892const struct file_operations cache_flush_operations_pipefs = {
1893	.open		= open_flush_pipefs,
1894	.read		= read_flush_pipefs,
1895	.write		= write_flush_pipefs,
1896	.release	= release_flush_pipefs,
1897};
1898
1899int sunrpc_cache_register_pipefs(struct dentry *parent,
1900				 const char *name, umode_t umode,
1901				 struct cache_detail *cd)
1902{
1903	struct dentry *dir = rpc_create_cache_dir(parent, name, umode, cd);
1904	if (IS_ERR(dir))
1905		return PTR_ERR(dir);
1906	cd->pipefs = dir;
1907	return 0;
1908}
1909EXPORT_SYMBOL_GPL(sunrpc_cache_register_pipefs);
1910
1911void sunrpc_cache_unregister_pipefs(struct cache_detail *cd)
1912{
1913	if (cd->pipefs) {
1914		rpc_remove_cache_dir(cd->pipefs);
1915		cd->pipefs = NULL;
1916	}
1917}
1918EXPORT_SYMBOL_GPL(sunrpc_cache_unregister_pipefs);
1919
1920void sunrpc_cache_unhash(struct cache_detail *cd, struct cache_head *h)
1921{
1922	spin_lock(&cd->hash_lock);
1923	if (!hlist_unhashed(&h->cache_list)){
1924		sunrpc_begin_cache_remove_entry(h, cd);
1925		spin_unlock(&cd->hash_lock);
1926		sunrpc_end_cache_remove_entry(h, cd);
1927	} else
1928		spin_unlock(&cd->hash_lock);
1929}
1930EXPORT_SYMBOL_GPL(sunrpc_cache_unhash);
~/ Read-only file preview.