2 * Sleepable Read-Copy Update mechanism for mutual exclusion.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, you can access it online at
16 * http://www.gnu.org/licenses/gpl-2.0.html.
18 * Copyright (C) IBM Corporation, 2006
19 * Copyright (C) Fujitsu, 2012
21 * Author: Paul McKenney <paulmck@us.ibm.com>
22 * Lai Jiangshan <laijs@cn.fujitsu.com>
24 * For detailed explanation of Read-Copy Update mechanism see -
25 * Documentation/RCU/ *.txt
29 #include <linux/export.h>
30 #include <linux/mutex.h>
31 #include <linux/percpu.h>
32 #include <linux/preempt.h>
33 #include <linux/rcupdate_wait.h>
34 #include <linux/sched.h>
35 #include <linux/smp.h>
36 #include <linux/delay.h>
37 #include <linux/srcu.h>
42 * Initialize an rcu_batch structure to empty.
44 static inline void rcu_batch_init(struct rcu_batch *b)
51 * Enqueue a callback onto the tail of the specified rcu_batch structure.
53 static inline void rcu_batch_queue(struct rcu_batch *b, struct rcu_head *head)
56 b->tail = &head->next;
60 * Is the specified rcu_batch structure empty?
62 static inline bool rcu_batch_empty(struct rcu_batch *b)
64 return b->tail == &b->head;
68 * Remove the callback at the head of the specified rcu_batch structure
69 * and return a pointer to it, or return NULL if the structure is empty.
71 static inline struct rcu_head *rcu_batch_dequeue(struct rcu_batch *b)
73 struct rcu_head *head;
75 if (rcu_batch_empty(b))
80 if (b->tail == &head->next)
87 * Move all callbacks from the rcu_batch structure specified by "from" to
88 * the structure specified by "to".
90 static inline void rcu_batch_move(struct rcu_batch *to, struct rcu_batch *from)
92 if (!rcu_batch_empty(from)) {
93 *to->tail = from->head;
94 to->tail = from->tail;
99 static int init_srcu_struct_fields(struct srcu_struct *sp)
102 spin_lock_init(&sp->queue_lock);
104 rcu_batch_init(&sp->batch_queue);
105 rcu_batch_init(&sp->batch_check0);
106 rcu_batch_init(&sp->batch_check1);
107 rcu_batch_init(&sp->batch_done);
108 INIT_DELAYED_WORK(&sp->work, process_srcu);
109 sp->per_cpu_ref = alloc_percpu(struct srcu_array);
110 return sp->per_cpu_ref ? 0 : -ENOMEM;
113 #ifdef CONFIG_DEBUG_LOCK_ALLOC
115 int __init_srcu_struct(struct srcu_struct *sp, const char *name,
116 struct lock_class_key *key)
118 /* Don't re-initialize a lock while it is held. */
119 debug_check_no_locks_freed((void *)sp, sizeof(*sp));
120 lockdep_init_map(&sp->dep_map, name, key, 0);
121 return init_srcu_struct_fields(sp);
123 EXPORT_SYMBOL_GPL(__init_srcu_struct);
125 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
128 * init_srcu_struct - initialize a sleep-RCU structure
129 * @sp: structure to initialize.
131 * Must invoke this on a given srcu_struct before passing that srcu_struct
132 * to any other function. Each srcu_struct represents a separate domain
133 * of SRCU protection.
135 int init_srcu_struct(struct srcu_struct *sp)
137 return init_srcu_struct_fields(sp);
139 EXPORT_SYMBOL_GPL(init_srcu_struct);
141 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
144 * Returns approximate total of the readers' ->lock_count[] values for the
145 * rank of per-CPU counters specified by idx.
147 static unsigned long srcu_readers_lock_idx(struct srcu_struct *sp, int idx)
150 unsigned long sum = 0;
152 for_each_possible_cpu(cpu) {
153 struct srcu_array *cpuc = per_cpu_ptr(sp->per_cpu_ref, cpu);
155 sum += READ_ONCE(cpuc->lock_count[idx]);
161 * Returns approximate total of the readers' ->unlock_count[] values for the
162 * rank of per-CPU counters specified by idx.
164 static unsigned long srcu_readers_unlock_idx(struct srcu_struct *sp, int idx)
167 unsigned long sum = 0;
169 for_each_possible_cpu(cpu) {
170 struct srcu_array *cpuc = per_cpu_ptr(sp->per_cpu_ref, cpu);
172 sum += READ_ONCE(cpuc->unlock_count[idx]);
178 * Return true if the number of pre-existing readers is determined to
181 static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
183 unsigned long unlocks;
185 unlocks = srcu_readers_unlock_idx(sp, idx);
188 * Make sure that a lock is always counted if the corresponding unlock
189 * is counted. Needs to be a smp_mb() as the read side may contain a
190 * read from a variable that is written to before the synchronize_srcu()
191 * in the write side. In this case smp_mb()s A and B act like the store
194 * This smp_mb() also pairs with smp_mb() C to prevent accesses after the
195 * synchronize_srcu() from being executed before the grace period ends.
200 * If the locks are the same as the unlocks, then there must have
201 * been no readers on this index at some time in between. This does not
202 * mean that there are no more readers, as one could have read the
203 * current index but not have incremented the lock counter yet.
205 * Possible bug: There is no guarantee that there haven't been ULONG_MAX
206 * increments of ->lock_count[] since the unlocks were counted, meaning
207 * that this could return true even if there are still active readers.
208 * Since there are no memory barriers around srcu_flip(), the CPU is not
209 * required to increment ->completed before running
210 * srcu_readers_unlock_idx(), which means that there could be an
211 * arbitrarily large number of critical sections that execute after
212 * srcu_readers_unlock_idx() but use the old value of ->completed.
214 return srcu_readers_lock_idx(sp, idx) == unlocks;
218 * srcu_readers_active - returns true if there are readers. and false
220 * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
222 * Note that this is not an atomic primitive, and can therefore suffer
223 * severe errors when invoked on an active srcu_struct. That said, it
224 * can be useful as an error check at cleanup time.
226 static bool srcu_readers_active(struct srcu_struct *sp)
229 unsigned long sum = 0;
231 for_each_possible_cpu(cpu) {
232 struct srcu_array *cpuc = per_cpu_ptr(sp->per_cpu_ref, cpu);
234 sum += READ_ONCE(cpuc->lock_count[0]);
235 sum += READ_ONCE(cpuc->lock_count[1]);
236 sum -= READ_ONCE(cpuc->unlock_count[0]);
237 sum -= READ_ONCE(cpuc->unlock_count[1]);
243 * cleanup_srcu_struct - deconstruct a sleep-RCU structure
244 * @sp: structure to clean up.
246 * Must invoke this only after you are finished using a given srcu_struct
247 * that was initialized via init_srcu_struct(). This code does some
248 * probabalistic checking, spotting late uses of srcu_read_lock(),
249 * synchronize_srcu(), synchronize_srcu_expedited(), and call_srcu().
250 * If any such late uses are detected, the per-CPU memory associated with
251 * the srcu_struct is simply leaked and WARN_ON() is invoked. If the
252 * caller frees the srcu_struct itself, a use-after-free crash will likely
253 * ensue, but at least there will be a warning printed.
255 void cleanup_srcu_struct(struct srcu_struct *sp)
257 if (WARN_ON(srcu_readers_active(sp)))
258 return; /* Leakage unless caller handles error. */
259 free_percpu(sp->per_cpu_ref);
260 sp->per_cpu_ref = NULL;
262 EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
265 * Counts the new reader in the appropriate per-CPU element of the
267 * Returns an index that must be passed to the matching srcu_read_unlock().
269 int __srcu_read_lock(struct srcu_struct *sp)
273 idx = READ_ONCE(sp->completed) & 0x1;
274 this_cpu_inc(sp->per_cpu_ref->lock_count[idx]);
275 smp_mb(); /* B */ /* Avoid leaking the critical section. */
278 EXPORT_SYMBOL_GPL(__srcu_read_lock);
281 * Removes the count for the old reader from the appropriate per-CPU
282 * element of the srcu_struct. Note that this may well be a different
283 * CPU than that which was incremented by the corresponding srcu_read_lock().
285 void __srcu_read_unlock(struct srcu_struct *sp, int idx)
287 smp_mb(); /* C */ /* Avoid leaking the critical section. */
288 this_cpu_inc(sp->per_cpu_ref->unlock_count[idx]);
290 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
293 * We use an adaptive strategy for synchronize_srcu() and especially for
294 * synchronize_srcu_expedited(). We spin for a fixed time period
295 * (defined below) to allow SRCU readers to exit their read-side critical
296 * sections. If there are still some readers after 10 microseconds,
297 * we repeatedly block for 1-millisecond time periods. This approach
298 * has done well in testing, so there is no need for a config parameter.
300 #define SRCU_RETRY_CHECK_DELAY 5
301 #define SYNCHRONIZE_SRCU_TRYCOUNT 2
302 #define SYNCHRONIZE_SRCU_EXP_TRYCOUNT 12
305 * @@@ Wait until all pre-existing readers complete. Such readers
306 * will have used the index specified by "idx".
307 * the caller should ensures the ->completed is not changed while checking
308 * and idx = (->completed & 1) ^ 1
310 static bool try_check_zero(struct srcu_struct *sp, int idx, int trycount)
313 if (srcu_readers_active_idx_check(sp, idx))
317 udelay(SRCU_RETRY_CHECK_DELAY);
322 * Increment the ->completed counter so that future SRCU readers will
323 * use the other rank of the ->(un)lock_count[] arrays. This allows
324 * us to wait for pre-existing readers in a starvation-free manner.
326 static void srcu_flip(struct srcu_struct *sp)
328 WRITE_ONCE(sp->completed, sp->completed + 1);
331 * Ensure that if the updater misses an __srcu_read_unlock()
332 * increment, that task's next __srcu_read_lock() will see the
333 * above counter update. Note that both this memory barrier
334 * and the one in srcu_readers_active_idx_check() provide the
335 * guarantee for __srcu_read_lock().
337 smp_mb(); /* D */ /* Pairs with C. */
341 * Enqueue an SRCU callback on the specified srcu_struct structure,
342 * initiating grace-period processing if it is not already running.
344 * Note that all CPUs must agree that the grace period extended beyond
345 * all pre-existing SRCU read-side critical section. On systems with
346 * more than one CPU, this means that when "func()" is invoked, each CPU
347 * is guaranteed to have executed a full memory barrier since the end of
348 * its last corresponding SRCU read-side critical section whose beginning
349 * preceded the call to call_rcu(). It also means that each CPU executing
350 * an SRCU read-side critical section that continues beyond the start of
351 * "func()" must have executed a memory barrier after the call_rcu()
352 * but before the beginning of that SRCU read-side critical section.
353 * Note that these guarantees include CPUs that are offline, idle, or
354 * executing in user mode, as well as CPUs that are executing in the kernel.
356 * Furthermore, if CPU A invoked call_rcu() and CPU B invoked the
357 * resulting SRCU callback function "func()", then both CPU A and CPU
358 * B are guaranteed to execute a full memory barrier during the time
359 * interval between the call to call_rcu() and the invocation of "func()".
360 * This guarantee applies even if CPU A and CPU B are the same CPU (but
361 * again only if the system has more than one CPU).
363 * Of course, these guarantees apply only for invocations of call_srcu(),
364 * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
365 * srcu_struct structure.
367 void call_srcu(struct srcu_struct *sp, struct rcu_head *head,
374 spin_lock_irqsave(&sp->queue_lock, flags);
375 smp_mb__after_unlock_lock(); /* Caller's prior accesses before GP. */
376 rcu_batch_queue(&sp->batch_queue, head);
379 queue_delayed_work(system_power_efficient_wq, &sp->work, 0);
381 spin_unlock_irqrestore(&sp->queue_lock, flags);
383 EXPORT_SYMBOL_GPL(call_srcu);
385 static void srcu_advance_batches(struct srcu_struct *sp, int trycount);
386 static void srcu_reschedule(struct srcu_struct *sp);
389 * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
391 static void __synchronize_srcu(struct srcu_struct *sp, int trycount)
393 struct rcu_synchronize rcu;
394 struct rcu_head *head = &rcu.head;
397 RCU_LOCKDEP_WARN(lock_is_held(&sp->dep_map) ||
398 lock_is_held(&rcu_bh_lock_map) ||
399 lock_is_held(&rcu_lock_map) ||
400 lock_is_held(&rcu_sched_lock_map),
401 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
404 init_completion(&rcu.completion);
407 head->func = wakeme_after_rcu;
408 spin_lock_irq(&sp->queue_lock);
409 smp_mb__after_unlock_lock(); /* Caller's prior accesses before GP. */
411 /* steal the processing owner */
413 rcu_batch_queue(&sp->batch_check0, head);
414 spin_unlock_irq(&sp->queue_lock);
416 srcu_advance_batches(sp, trycount);
417 if (!rcu_batch_empty(&sp->batch_done)) {
418 BUG_ON(sp->batch_done.head != head);
419 rcu_batch_dequeue(&sp->batch_done);
422 /* give the processing owner to work_struct */
425 rcu_batch_queue(&sp->batch_queue, head);
426 spin_unlock_irq(&sp->queue_lock);
430 wait_for_completion(&rcu.completion);
431 smp_mb(); /* Caller's later accesses after GP. */
437 * synchronize_srcu - wait for prior SRCU read-side critical-section completion
438 * @sp: srcu_struct with which to synchronize.
440 * Wait for the count to drain to zero of both indexes. To avoid the
441 * possible starvation of synchronize_srcu(), it waits for the count of
442 * the index=((->completed & 1) ^ 1) to drain to zero at first,
443 * and then flip the completed and wait for the count of the other index.
445 * Can block; must be called from process context.
447 * Note that it is illegal to call synchronize_srcu() from the corresponding
448 * SRCU read-side critical section; doing so will result in deadlock.
449 * However, it is perfectly legal to call synchronize_srcu() on one
450 * srcu_struct from some other srcu_struct's read-side critical section,
451 * as long as the resulting graph of srcu_structs is acyclic.
453 * There are memory-ordering constraints implied by synchronize_srcu().
454 * On systems with more than one CPU, when synchronize_srcu() returns,
455 * each CPU is guaranteed to have executed a full memory barrier since
456 * the end of its last corresponding SRCU-sched read-side critical section
457 * whose beginning preceded the call to synchronize_srcu(). In addition,
458 * each CPU having an SRCU read-side critical section that extends beyond
459 * the return from synchronize_srcu() is guaranteed to have executed a
460 * full memory barrier after the beginning of synchronize_srcu() and before
461 * the beginning of that SRCU read-side critical section. Note that these
462 * guarantees include CPUs that are offline, idle, or executing in user mode,
463 * as well as CPUs that are executing in the kernel.
465 * Furthermore, if CPU A invoked synchronize_srcu(), which returned
466 * to its caller on CPU B, then both CPU A and CPU B are guaranteed
467 * to have executed a full memory barrier during the execution of
468 * synchronize_srcu(). This guarantee applies even if CPU A and CPU B
469 * are the same CPU, but again only if the system has more than one CPU.
471 * Of course, these memory-ordering guarantees apply only when
472 * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
473 * passed the same srcu_struct structure.
475 void synchronize_srcu(struct srcu_struct *sp)
477 __synchronize_srcu(sp, (rcu_gp_is_expedited() && !rcu_gp_is_normal())
478 ? SYNCHRONIZE_SRCU_EXP_TRYCOUNT
479 : SYNCHRONIZE_SRCU_TRYCOUNT);
481 EXPORT_SYMBOL_GPL(synchronize_srcu);
484 * synchronize_srcu_expedited - Brute-force SRCU grace period
485 * @sp: srcu_struct with which to synchronize.
487 * Wait for an SRCU grace period to elapse, but be more aggressive about
488 * spinning rather than blocking when waiting.
490 * Note that synchronize_srcu_expedited() has the same deadlock and
491 * memory-ordering properties as does synchronize_srcu().
493 void synchronize_srcu_expedited(struct srcu_struct *sp)
495 __synchronize_srcu(sp, SYNCHRONIZE_SRCU_EXP_TRYCOUNT);
497 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
500 * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
501 * @sp: srcu_struct on which to wait for in-flight callbacks.
503 void srcu_barrier(struct srcu_struct *sp)
505 synchronize_srcu(sp);
507 EXPORT_SYMBOL_GPL(srcu_barrier);
510 * srcu_batches_completed - return batches completed.
511 * @sp: srcu_struct on which to report batch completion.
513 * Report the number of batches, correlated with, but not necessarily
514 * precisely the same as, the number of grace periods that have elapsed.
516 unsigned long srcu_batches_completed(struct srcu_struct *sp)
518 return sp->completed;
520 EXPORT_SYMBOL_GPL(srcu_batches_completed);
522 #define SRCU_CALLBACK_BATCH 10
523 #define SRCU_INTERVAL 1
526 * Move any new SRCU callbacks to the first stage of the SRCU grace
529 static void srcu_collect_new(struct srcu_struct *sp)
531 if (!rcu_batch_empty(&sp->batch_queue)) {
532 spin_lock_irq(&sp->queue_lock);
533 rcu_batch_move(&sp->batch_check0, &sp->batch_queue);
534 spin_unlock_irq(&sp->queue_lock);
539 * Core SRCU state machine. Advance callbacks from ->batch_check0 to
540 * ->batch_check1 and then to ->batch_done as readers drain.
542 static void srcu_advance_batches(struct srcu_struct *sp, int trycount)
544 int idx = 1 ^ (sp->completed & 1);
547 * Because readers might be delayed for an extended period after
548 * fetching ->completed for their index, at any point in time there
549 * might well be readers using both idx=0 and idx=1. We therefore
550 * need to wait for readers to clear from both index values before
551 * invoking a callback.
554 if (rcu_batch_empty(&sp->batch_check0) &&
555 rcu_batch_empty(&sp->batch_check1))
556 return; /* no callbacks need to be advanced */
558 if (!try_check_zero(sp, idx, trycount))
559 return; /* failed to advance, will try after SRCU_INTERVAL */
562 * The callbacks in ->batch_check1 have already done with their
563 * first zero check and flip back when they were enqueued on
564 * ->batch_check0 in a previous invocation of srcu_advance_batches().
565 * (Presumably try_check_zero() returned false during that
566 * invocation, leaving the callbacks stranded on ->batch_check1.)
567 * They are therefore ready to invoke, so move them to ->batch_done.
569 rcu_batch_move(&sp->batch_done, &sp->batch_check1);
571 if (rcu_batch_empty(&sp->batch_check0))
572 return; /* no callbacks need to be advanced */
576 * The callbacks in ->batch_check0 just finished their
577 * first check zero and flip, so move them to ->batch_check1
578 * for future checking on the other idx.
580 rcu_batch_move(&sp->batch_check1, &sp->batch_check0);
583 * SRCU read-side critical sections are normally short, so check
584 * at least twice in quick succession after a flip.
586 trycount = trycount < 2 ? 2 : trycount;
587 if (!try_check_zero(sp, idx^1, trycount))
588 return; /* failed to advance, will try after SRCU_INTERVAL */
591 * The callbacks in ->batch_check1 have now waited for all
592 * pre-existing readers using both idx values. They are therefore
593 * ready to invoke, so move them to ->batch_done.
595 rcu_batch_move(&sp->batch_done, &sp->batch_check1);
599 * Invoke a limited number of SRCU callbacks that have passed through
600 * their grace period. If there are more to do, SRCU will reschedule
601 * the workqueue. Note that needed memory barriers have been executed
602 * in this task's context by srcu_readers_active_idx_check().
604 static void srcu_invoke_callbacks(struct srcu_struct *sp)
607 struct rcu_head *head;
609 for (i = 0; i < SRCU_CALLBACK_BATCH; i++) {
610 head = rcu_batch_dequeue(&sp->batch_done);
620 * Finished one round of SRCU grace period. Start another if there are
621 * more SRCU callbacks queued, otherwise put SRCU into not-running state.
623 static void srcu_reschedule(struct srcu_struct *sp)
627 if (rcu_batch_empty(&sp->batch_done) &&
628 rcu_batch_empty(&sp->batch_check1) &&
629 rcu_batch_empty(&sp->batch_check0) &&
630 rcu_batch_empty(&sp->batch_queue)) {
631 spin_lock_irq(&sp->queue_lock);
632 if (rcu_batch_empty(&sp->batch_done) &&
633 rcu_batch_empty(&sp->batch_check1) &&
634 rcu_batch_empty(&sp->batch_check0) &&
635 rcu_batch_empty(&sp->batch_queue)) {
639 spin_unlock_irq(&sp->queue_lock);
643 queue_delayed_work(system_power_efficient_wq,
644 &sp->work, SRCU_INTERVAL);
648 * This is the work-queue function that handles SRCU grace periods.
650 void process_srcu(struct work_struct *work)
652 struct srcu_struct *sp;
654 sp = container_of(work, struct srcu_struct, work.work);
656 srcu_collect_new(sp);
657 srcu_advance_batches(sp, 1);
658 srcu_invoke_callbacks(sp);
661 EXPORT_SYMBOL_GPL(process_srcu);