1394 lines · 44.7 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0+/* * Sleepable Read-Copy Update mechanism for mutual exclusion. * * Copyright (C) IBM Corporation, 2006 * Copyright (C) Fujitsu, 2012 * * Authors: Paul McKenney <paulmck@linux.ibm.com> *	   Lai Jiangshan <laijs@cn.fujitsu.com> * * For detailed explanation of Read-Copy Update mechanism see - *		Documentation/RCU/ *.txt * */ #define pr_fmt(fmt) "rcu: " fmt #include <linux/export.h>#include <linux/mutex.h>#include <linux/percpu.h>#include <linux/preempt.h>#include <linux/rcupdate_wait.h>#include <linux/sched.h>#include <linux/smp.h>#include <linux/delay.h>#include <linux/module.h>#include <linux/srcu.h> #include "rcu.h"#include "rcu_segcblist.h" #ifndef data_race#define data_race(expr)							\	({								\		expr;							\	})#endif#ifndef ASSERT_EXCLUSIVE_WRITER#define ASSERT_EXCLUSIVE_WRITER(var) do { } while (0)#endif#ifndef ASSERT_EXCLUSIVE_ACCESS#define ASSERT_EXCLUSIVE_ACCESS(var) do { } while (0)#endif /* Holdoff in nanoseconds for auto-expediting. */#define DEFAULT_SRCU_EXP_HOLDOFF (25 * 1000)static ulong exp_holdoff = DEFAULT_SRCU_EXP_HOLDOFF;module_param(exp_holdoff, ulong, 0444); /* Overflow-check frequency.  N bits roughly says every 2**N grace periods. */static ulong counter_wrap_check = (ULONG_MAX >> 2);module_param(counter_wrap_check, ulong, 0444); /* Early-boot callback-management, so early that no lock is required! */static LIST_HEAD(srcu_boot_list);static bool __read_mostly srcu_init_done; static void srcu_invoke_callbacks(struct work_struct *work);static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay);static void process_srcu(struct work_struct *work);static void srcu_delay_timer(struct timer_list *t); /* Wrappers for lock acquisition and release, see raw_spin_lock_rcu_node(). */#define spin_lock_rcu_node(p)					\do {									\	spin_lock(&ACCESS_PRIVATE(p, lock));			\	smp_mb__after_unlock_lock();					\} while (0) #define spin_unlock_rcu_node(p) spin_unlock(&ACCESS_PRIVATE(p, lock)) #define spin_lock_irq_rcu_node(p)					\do {									\	spin_lock_irq(&ACCESS_PRIVATE(p, lock));			\	smp_mb__after_unlock_lock();					\} while (0) #define spin_unlock_irq_rcu_node(p)					\	spin_unlock_irq(&ACCESS_PRIVATE(p, lock)) #define spin_lock_irqsave_rcu_node(p, flags)			\do {									\	spin_lock_irqsave(&ACCESS_PRIVATE(p, lock), flags);	\	smp_mb__after_unlock_lock();					\} while (0) #define spin_unlock_irqrestore_rcu_node(p, flags)			\	spin_unlock_irqrestore(&ACCESS_PRIVATE(p, lock), flags)	\ /* * Initialize SRCU combining tree.  Note that statically allocated * srcu_struct structures might already have srcu_read_lock() and * srcu_read_unlock() running against them.  So if the is_static parameter * is set, don't initialize ->srcu_lock_count[] and ->srcu_unlock_count[]. */static void init_srcu_struct_nodes(struct srcu_struct *ssp, bool is_static){	int cpu;	int i;	int level = 0;	int levelspread[RCU_NUM_LVLS];	struct srcu_data *sdp;	struct srcu_node *snp;	struct srcu_node *snp_first; 	/* Work out the overall tree geometry. */	ssp->level[0] = &ssp->node[0];	for (i = 1; i < rcu_num_lvls; i++)		ssp->level[i] = ssp->level[i - 1] + num_rcu_lvl[i - 1];	rcu_init_levelspread(levelspread, num_rcu_lvl); 	/* Each pass through this loop initializes one srcu_node structure. */	srcu_for_each_node_breadth_first(ssp, snp) {		spin_lock_init(&ACCESS_PRIVATE(snp, lock));		WARN_ON_ONCE(ARRAY_SIZE(snp->srcu_have_cbs) !=			     ARRAY_SIZE(snp->srcu_data_have_cbs));		for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++) {			snp->srcu_have_cbs[i] = 0;			snp->srcu_data_have_cbs[i] = 0;		}		snp->srcu_gp_seq_needed_exp = 0;		snp->grplo = -1;		snp->grphi = -1;		if (snp == &ssp->node[0]) {			/* Root node, special case. */			snp->srcu_parent = NULL;			continue;		} 		/* Non-root node. */		if (snp == ssp->level[level + 1])			level++;		snp->srcu_parent = ssp->level[level - 1] +				   (snp - ssp->level[level]) /				   levelspread[level - 1];	} 	/*	 * Initialize the per-CPU srcu_data array, which feeds into the	 * leaves of the srcu_node tree.	 */	WARN_ON_ONCE(ARRAY_SIZE(sdp->srcu_lock_count) !=		     ARRAY_SIZE(sdp->srcu_unlock_count));	level = rcu_num_lvls - 1;	snp_first = ssp->level[level];	for_each_possible_cpu(cpu) {		sdp = per_cpu_ptr(ssp->sda, cpu);		spin_lock_init(&ACCESS_PRIVATE(sdp, lock));		rcu_segcblist_init(&sdp->srcu_cblist);		sdp->srcu_cblist_invoking = false;		sdp->srcu_gp_seq_needed = ssp->srcu_gp_seq;		sdp->srcu_gp_seq_needed_exp = ssp->srcu_gp_seq;		sdp->mynode = &snp_first[cpu / levelspread[level]];		for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) {			if (snp->grplo < 0)				snp->grplo = cpu;			snp->grphi = cpu;		}		sdp->cpu = cpu;		INIT_WORK(&sdp->work, srcu_invoke_callbacks);		timer_setup(&sdp->delay_work, srcu_delay_timer, 0);		sdp->ssp = ssp;		sdp->grpmask = 1 << (cpu - sdp->mynode->grplo);		if (is_static)			continue; 		/* Dynamically allocated, better be no srcu_read_locks()! */		for (i = 0; i < ARRAY_SIZE(sdp->srcu_lock_count); i++) {			sdp->srcu_lock_count[i] = 0;			sdp->srcu_unlock_count[i] = 0;		}	}} /* * Initialize non-compile-time initialized fields, including the * associated srcu_node and srcu_data structures.  The is_static * parameter is passed through to init_srcu_struct_nodes(), and * also tells us that ->sda has already been wired up to srcu_data. */static int init_srcu_struct_fields(struct srcu_struct *ssp, bool is_static){	mutex_init(&ssp->srcu_cb_mutex);	mutex_init(&ssp->srcu_gp_mutex);	ssp->srcu_idx = 0;	ssp->srcu_gp_seq = 0;	ssp->srcu_barrier_seq = 0;	mutex_init(&ssp->srcu_barrier_mutex);	atomic_set(&ssp->srcu_barrier_cpu_cnt, 0);	INIT_DELAYED_WORK(&ssp->work, process_srcu);	if (!is_static)		ssp->sda = alloc_percpu(struct srcu_data);	init_srcu_struct_nodes(ssp, is_static);	ssp->srcu_gp_seq_needed_exp = 0;	ssp->srcu_last_gp_end = ktime_get_mono_fast_ns();	smp_store_release(&ssp->srcu_gp_seq_needed, 0); /* Init done. */	return ssp->sda ? 0 : -ENOMEM;} #ifdef CONFIG_DEBUG_LOCK_ALLOC int __init_srcu_struct(struct srcu_struct *ssp, const char *name,		       struct lock_class_key *key){	/* Don't re-initialize a lock while it is held. */	debug_check_no_locks_freed((void *)ssp, sizeof(*ssp));	lockdep_init_map(&ssp->dep_map, name, key, 0);	spin_lock_init(&ACCESS_PRIVATE(ssp, lock));	return init_srcu_struct_fields(ssp, false);}EXPORT_SYMBOL_GPL(__init_srcu_struct); #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */ /** * init_srcu_struct - initialize a sleep-RCU structure * @ssp: structure to initialize. * * Must invoke this on a given srcu_struct before passing that srcu_struct * to any other function.  Each srcu_struct represents a separate domain * of SRCU protection. */int init_srcu_struct(struct srcu_struct *ssp){	spin_lock_init(&ACCESS_PRIVATE(ssp, lock));	return init_srcu_struct_fields(ssp, false);}EXPORT_SYMBOL_GPL(init_srcu_struct); #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */ /* * First-use initialization of statically allocated srcu_struct * structure.  Wiring up the combining tree is more than can be * done with compile-time initialization, so this check is added * to each update-side SRCU primitive.  Use ssp->lock, which -is- * compile-time initialized, to resolve races involving multiple * CPUs trying to garner first-use privileges. */static void check_init_srcu_struct(struct srcu_struct *ssp){	unsigned long flags; 	/* The smp_load_acquire() pairs with the smp_store_release(). */	if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_gp_seq_needed))) /*^^^*/		return; /* Already initialized. */	spin_lock_irqsave_rcu_node(ssp, flags);	if (!rcu_seq_state(ssp->srcu_gp_seq_needed)) {		spin_unlock_irqrestore_rcu_node(ssp, flags);		return;	}	init_srcu_struct_fields(ssp, true);	spin_unlock_irqrestore_rcu_node(ssp, flags);} /* * Returns approximate total of the readers' ->srcu_lock_count[] values * for the rank of per-CPU counters specified by idx. */static unsigned long srcu_readers_lock_idx(struct srcu_struct *ssp, int idx){	int cpu;	unsigned long sum = 0; 	for_each_possible_cpu(cpu) {		struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu); 		sum += READ_ONCE(cpuc->srcu_lock_count[idx]);	}	return sum;} /* * Returns approximate total of the readers' ->srcu_unlock_count[] values * for the rank of per-CPU counters specified by idx. */static unsigned long srcu_readers_unlock_idx(struct srcu_struct *ssp, int idx){	int cpu;	unsigned long sum = 0; 	for_each_possible_cpu(cpu) {		struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu); 		sum += READ_ONCE(cpuc->srcu_unlock_count[idx]);	}	return sum;} /* * Return true if the number of pre-existing readers is determined to * be zero. */static bool srcu_readers_active_idx_check(struct srcu_struct *ssp, int idx){	unsigned long unlocks; 	unlocks = srcu_readers_unlock_idx(ssp, idx); 	/*	 * Make sure that a lock is always counted if the corresponding	 * unlock is counted. Needs to be a smp_mb() as the read side may	 * contain a read from a variable that is written to before the	 * synchronize_srcu() in the write side. In this case smp_mb()s	 * A and B act like the store buffering pattern.	 *	 * This smp_mb() also pairs with smp_mb() C to prevent accesses	 * after the synchronize_srcu() from being executed before the	 * grace period ends.	 */	smp_mb(); /* A */ 	/*	 * If the locks are the same as the unlocks, then there must have	 * been no readers on this index at some time in between. This does	 * not mean that there are no more readers, as one could have read	 * the current index but not have incremented the lock counter yet.	 *	 * So suppose that the updater is preempted here for so long	 * that more than ULONG_MAX non-nested readers come and go in	 * the meantime.  It turns out that this cannot result in overflow	 * because if a reader modifies its unlock count after we read it	 * above, then that reader's next load of ->srcu_idx is guaranteed	 * to get the new value, which will cause it to operate on the	 * other bank of counters, where it cannot contribute to the	 * overflow of these counters.  This means that there is a maximum	 * of 2*NR_CPUS increments, which cannot overflow given current	 * systems, especially not on 64-bit systems.	 *	 * OK, how about nesting?  This does impose a limit on nesting	 * of floor(ULONG_MAX/NR_CPUS/2), which should be sufficient,	 * especially on 64-bit systems.	 */	return srcu_readers_lock_idx(ssp, idx) == unlocks;} /** * srcu_readers_active - returns true if there are readers. and false *                       otherwise * @ssp: which srcu_struct to count active readers (holding srcu_read_lock). * * Note that this is not an atomic primitive, and can therefore suffer * severe errors when invoked on an active srcu_struct.  That said, it * can be useful as an error check at cleanup time. */static bool srcu_readers_active(struct srcu_struct *ssp){	int cpu;	unsigned long sum = 0; 	for_each_possible_cpu(cpu) {		struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu); 		sum += READ_ONCE(cpuc->srcu_lock_count[0]);		sum += READ_ONCE(cpuc->srcu_lock_count[1]);		sum -= READ_ONCE(cpuc->srcu_unlock_count[0]);		sum -= READ_ONCE(cpuc->srcu_unlock_count[1]);	}	return sum;} #define SRCU_INTERVAL		1 /* * Return grace-period delay, zero if there are expedited grace * periods pending, SRCU_INTERVAL otherwise. */static unsigned long srcu_get_delay(struct srcu_struct *ssp){	if (ULONG_CMP_LT(READ_ONCE(ssp->srcu_gp_seq),			 READ_ONCE(ssp->srcu_gp_seq_needed_exp)))		return 0;	return SRCU_INTERVAL;} /** * cleanup_srcu_struct - deconstruct a sleep-RCU structure * @ssp: structure to clean up. * * Must invoke this after you are finished using a given srcu_struct that * was initialized via init_srcu_struct(), else you leak memory. */void cleanup_srcu_struct(struct srcu_struct *ssp){	int cpu; 	if (WARN_ON(!srcu_get_delay(ssp)))		return; /* Just leak it! */	if (WARN_ON(srcu_readers_active(ssp)))		return; /* Just leak it! */	flush_delayed_work(&ssp->work);	for_each_possible_cpu(cpu) {		struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu); 		del_timer_sync(&sdp->delay_work);		flush_work(&sdp->work);		if (WARN_ON(rcu_segcblist_n_cbs(&sdp->srcu_cblist)))			return; /* Forgot srcu_barrier(), so just leak it! */	}	if (WARN_ON(rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)) != SRCU_STATE_IDLE) ||	    WARN_ON(srcu_readers_active(ssp))) {		pr_info("%s: Active srcu_struct %p state: %d\n",			__func__, ssp, rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)));		return; /* Caller forgot to stop doing call_srcu()? */	}	free_percpu(ssp->sda);	ssp->sda = NULL;}EXPORT_SYMBOL_GPL(cleanup_srcu_struct); /* * Counts the new reader in the appropriate per-CPU element of the * srcu_struct. * Returns an index that must be passed to the matching srcu_read_unlock(). */int __srcu_read_lock(struct srcu_struct *ssp){	int idx; 	idx = READ_ONCE(ssp->srcu_idx) & 0x1;	this_cpu_inc(ssp->sda->srcu_lock_count[idx]);	smp_mb(); /* B */  /* Avoid leaking the critical section. */	return idx;}EXPORT_SYMBOL_GPL(__srcu_read_lock); /* * Removes the count for the old reader from the appropriate per-CPU * element of the srcu_struct.  Note that this may well be a different * CPU than that which was incremented by the corresponding srcu_read_lock(). */void __srcu_read_unlock(struct srcu_struct *ssp, int idx){	smp_mb(); /* C */  /* Avoid leaking the critical section. */	this_cpu_inc(ssp->sda->srcu_unlock_count[idx]);}EXPORT_SYMBOL_GPL(__srcu_read_unlock); /* * We use an adaptive strategy for synchronize_srcu() and especially for * synchronize_srcu_expedited().  We spin for a fixed time period * (defined below) to allow SRCU readers to exit their read-side critical * sections.  If there are still some readers after a few microseconds, * we repeatedly block for 1-millisecond time periods. */#define SRCU_RETRY_CHECK_DELAY		5 /* * Start an SRCU grace period. */static void srcu_gp_start(struct srcu_struct *ssp){	struct srcu_data *sdp = this_cpu_ptr(ssp->sda);	int state; 	lockdep_assert_held(&ACCESS_PRIVATE(ssp, lock));	WARN_ON_ONCE(ULONG_CMP_GE(ssp->srcu_gp_seq, ssp->srcu_gp_seq_needed));	spin_lock_rcu_node(sdp);  /* Interrupts already disabled. */	rcu_segcblist_advance(&sdp->srcu_cblist,			      rcu_seq_current(&ssp->srcu_gp_seq));	(void)rcu_segcblist_accelerate(&sdp->srcu_cblist,				       rcu_seq_snap(&ssp->srcu_gp_seq));	spin_unlock_rcu_node(sdp);  /* Interrupts remain disabled. */	smp_mb(); /* Order prior store to ->srcu_gp_seq_needed vs. GP start. */	rcu_seq_start(&ssp->srcu_gp_seq);	state = rcu_seq_state(ssp->srcu_gp_seq);	WARN_ON_ONCE(state != SRCU_STATE_SCAN1);}  static void srcu_delay_timer(struct timer_list *t){	struct srcu_data *sdp = container_of(t, struct srcu_data, delay_work); 	queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);} static void srcu_queue_delayed_work_on(struct srcu_data *sdp,				       unsigned long delay){	if (!delay) {		queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);		return;	} 	timer_reduce(&sdp->delay_work, jiffies + delay);} /* * Schedule callback invocation for the specified srcu_data structure, * if possible, on the corresponding CPU. */static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay){	srcu_queue_delayed_work_on(sdp, delay);} /* * Schedule callback invocation for all srcu_data structures associated * with the specified srcu_node structure that have callbacks for the

Lines 1–500 of 1394.