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.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_struct_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' ->seq[] values for the
145 * rank of per-CPU counters specified by idx.
147 static unsigned long srcu_readers_seq_idx(struct srcu_struct
*sp
, int idx
)
150 unsigned long sum
= 0;
153 for_each_possible_cpu(cpu
) {
154 t
= READ_ONCE(per_cpu_ptr(sp
->per_cpu_ref
, cpu
)->seq
[idx
]);
161 * Returns approximate number of readers active on the specified rank
162 * of the per-CPU ->c[] counters.
164 static unsigned long srcu_readers_active_idx(struct srcu_struct
*sp
, int idx
)
167 unsigned long sum
= 0;
170 for_each_possible_cpu(cpu
) {
171 t
= READ_ONCE(per_cpu_ptr(sp
->per_cpu_ref
, cpu
)->c
[idx
]);
178 * Return true if the number of pre-existing readers is determined to
179 * be stably zero. An example unstable zero can occur if the call
180 * to srcu_readers_active_idx() misses an __srcu_read_lock() increment,
181 * but due to task migration, sees the corresponding __srcu_read_unlock()
182 * decrement. This can happen because srcu_readers_active_idx() takes
183 * time to sum the array, and might in fact be interrupted or preempted
184 * partway through the summation.
186 static bool srcu_readers_active_idx_check(struct srcu_struct
*sp
, int idx
)
190 seq
= srcu_readers_seq_idx(sp
, idx
);
193 * The following smp_mb() A pairs with the smp_mb() B located in
194 * __srcu_read_lock(). This pairing ensures that if an
195 * __srcu_read_lock() increments its counter after the summation
196 * in srcu_readers_active_idx(), then the corresponding SRCU read-side
197 * critical section will see any changes made prior to the start
198 * of the current SRCU grace period.
200 * Also, if the above call to srcu_readers_seq_idx() saw the
201 * increment of ->seq[], then the call to srcu_readers_active_idx()
202 * must see the increment of ->c[].
207 * Note that srcu_readers_active_idx() can incorrectly return
208 * zero even though there is a pre-existing reader throughout.
209 * To see this, suppose that task A is in a very long SRCU
210 * read-side critical section that started on CPU 0, and that
211 * no other reader exists, so that the sum of the counters
212 * is equal to one. Then suppose that task B starts executing
213 * srcu_readers_active_idx(), summing up to CPU 1, and then that
214 * task C starts reading on CPU 0, so that its increment is not
215 * summed, but finishes reading on CPU 2, so that its decrement
216 * -is- summed. Then when task B completes its sum, it will
217 * incorrectly get zero, despite the fact that task A has been
218 * in its SRCU read-side critical section the whole time.
220 * We therefore do a validation step should srcu_readers_active_idx()
223 if (srcu_readers_active_idx(sp
, idx
) != 0)
227 * The remainder of this function is the validation step.
228 * The following smp_mb() D pairs with the smp_mb() C in
229 * __srcu_read_unlock(). If the __srcu_read_unlock() was seen
230 * by srcu_readers_active_idx() above, then any destructive
231 * operation performed after the grace period will happen after
232 * the corresponding SRCU read-side critical section.
234 * Note that there can be at most NR_CPUS worth of readers using
235 * the old index, which is not enough to overflow even a 32-bit
236 * integer. (Yes, this does mean that systems having more than
237 * a billion or so CPUs need to be 64-bit systems.) Therefore,
238 * the sum of the ->seq[] counters cannot possibly overflow.
239 * Therefore, the only way that the return values of the two
240 * calls to srcu_readers_seq_idx() can be equal is if there were
241 * no increments of the corresponding rank of ->seq[] counts
242 * in the interim. But the missed-increment scenario laid out
243 * above includes an increment of the ->seq[] counter by
244 * the corresponding __srcu_read_lock(). Therefore, if this
245 * scenario occurs, the return values from the two calls to
246 * srcu_readers_seq_idx() will differ, and thus the validation
247 * step below suffices.
251 return srcu_readers_seq_idx(sp
, idx
) == seq
;
255 * srcu_readers_active - returns true if there are readers. and false
257 * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
259 * Note that this is not an atomic primitive, and can therefore suffer
260 * severe errors when invoked on an active srcu_struct. That said, it
261 * can be useful as an error check at cleanup time.
263 static bool srcu_readers_active(struct srcu_struct
*sp
)
266 unsigned long sum
= 0;
268 for_each_possible_cpu(cpu
) {
269 sum
+= READ_ONCE(per_cpu_ptr(sp
->per_cpu_ref
, cpu
)->c
[0]);
270 sum
+= READ_ONCE(per_cpu_ptr(sp
->per_cpu_ref
, cpu
)->c
[1]);
276 * cleanup_srcu_struct - deconstruct a sleep-RCU structure
277 * @sp: structure to clean up.
279 * Must invoke this after you are finished using a given srcu_struct that
280 * was initialized via init_srcu_struct(), else you leak memory.
282 void cleanup_srcu_struct(struct srcu_struct
*sp
)
284 if (WARN_ON(srcu_readers_active(sp
)))
285 return; /* Leakage unless caller handles error. */
286 free_percpu(sp
->per_cpu_ref
);
287 sp
->per_cpu_ref
= NULL
;
289 EXPORT_SYMBOL_GPL(cleanup_srcu_struct
);
292 * Counts the new reader in the appropriate per-CPU element of the
293 * srcu_struct. Must be called from process context.
294 * Returns an index that must be passed to the matching srcu_read_unlock().
296 int __srcu_read_lock(struct srcu_struct
*sp
)
300 idx
= READ_ONCE(sp
->completed
) & 0x1;
301 __this_cpu_inc(sp
->per_cpu_ref
->c
[idx
]);
302 smp_mb(); /* B */ /* Avoid leaking the critical section. */
303 __this_cpu_inc(sp
->per_cpu_ref
->seq
[idx
]);
306 EXPORT_SYMBOL_GPL(__srcu_read_lock
);
309 * Removes the count for the old reader from the appropriate per-CPU
310 * element of the srcu_struct. Note that this may well be a different
311 * CPU than that which was incremented by the corresponding srcu_read_lock().
312 * Must be called from process context.
314 void __srcu_read_unlock(struct srcu_struct
*sp
, int idx
)
316 smp_mb(); /* C */ /* Avoid leaking the critical section. */
317 this_cpu_dec(sp
->per_cpu_ref
->c
[idx
]);
319 EXPORT_SYMBOL_GPL(__srcu_read_unlock
);
322 * We use an adaptive strategy for synchronize_srcu() and especially for
323 * synchronize_srcu_expedited(). We spin for a fixed time period
324 * (defined below) to allow SRCU readers to exit their read-side critical
325 * sections. If there are still some readers after 10 microseconds,
326 * we repeatedly block for 1-millisecond time periods. This approach
327 * has done well in testing, so there is no need for a config parameter.
329 #define SRCU_RETRY_CHECK_DELAY 5
330 #define SYNCHRONIZE_SRCU_TRYCOUNT 2
331 #define SYNCHRONIZE_SRCU_EXP_TRYCOUNT 12
334 * @@@ Wait until all pre-existing readers complete. Such readers
335 * will have used the index specified by "idx".
336 * the caller should ensures the ->completed is not changed while checking
337 * and idx = (->completed & 1) ^ 1
339 static bool try_check_zero(struct srcu_struct
*sp
, int idx
, int trycount
)
342 if (srcu_readers_active_idx_check(sp
, idx
))
346 udelay(SRCU_RETRY_CHECK_DELAY
);
351 * Increment the ->completed counter so that future SRCU readers will
352 * use the other rank of the ->c[] and ->seq[] arrays. This allows
353 * us to wait for pre-existing readers in a starvation-free manner.
355 static void srcu_flip(struct srcu_struct
*sp
)
361 * Enqueue an SRCU callback on the specified srcu_struct structure,
362 * initiating grace-period processing if it is not already running.
364 * Note that all CPUs must agree that the grace period extended beyond
365 * all pre-existing SRCU read-side critical section. On systems with
366 * more than one CPU, this means that when "func()" is invoked, each CPU
367 * is guaranteed to have executed a full memory barrier since the end of
368 * its last corresponding SRCU read-side critical section whose beginning
369 * preceded the call to call_rcu(). It also means that each CPU executing
370 * an SRCU read-side critical section that continues beyond the start of
371 * "func()" must have executed a memory barrier after the call_rcu()
372 * but before the beginning of that SRCU read-side critical section.
373 * Note that these guarantees include CPUs that are offline, idle, or
374 * executing in user mode, as well as CPUs that are executing in the kernel.
376 * Furthermore, if CPU A invoked call_rcu() and CPU B invoked the
377 * resulting SRCU callback function "func()", then both CPU A and CPU
378 * B are guaranteed to execute a full memory barrier during the time
379 * interval between the call to call_rcu() and the invocation of "func()".
380 * This guarantee applies even if CPU A and CPU B are the same CPU (but
381 * again only if the system has more than one CPU).
383 * Of course, these guarantees apply only for invocations of call_srcu(),
384 * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
385 * srcu_struct structure.
387 void call_srcu(struct srcu_struct
*sp
, struct rcu_head
*head
,
394 spin_lock_irqsave(&sp
->queue_lock
, flags
);
395 rcu_batch_queue(&sp
->batch_queue
, head
);
398 queue_delayed_work(system_power_efficient_wq
, &sp
->work
, 0);
400 spin_unlock_irqrestore(&sp
->queue_lock
, flags
);
402 EXPORT_SYMBOL_GPL(call_srcu
);
404 static void srcu_advance_batches(struct srcu_struct
*sp
, int trycount
);
405 static void srcu_reschedule(struct srcu_struct
*sp
);
408 * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
410 static void __synchronize_srcu(struct srcu_struct
*sp
, int trycount
)
412 struct rcu_synchronize rcu
;
413 struct rcu_head
*head
= &rcu
.head
;
416 RCU_LOCKDEP_WARN(lock_is_held(&sp
->dep_map
) ||
417 lock_is_held(&rcu_bh_lock_map
) ||
418 lock_is_held(&rcu_lock_map
) ||
419 lock_is_held(&rcu_sched_lock_map
),
420 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
423 init_completion(&rcu
.completion
);
426 head
->func
= wakeme_after_rcu
;
427 spin_lock_irq(&sp
->queue_lock
);
429 /* steal the processing owner */
431 rcu_batch_queue(&sp
->batch_check0
, head
);
432 spin_unlock_irq(&sp
->queue_lock
);
434 srcu_advance_batches(sp
, trycount
);
435 if (!rcu_batch_empty(&sp
->batch_done
)) {
436 BUG_ON(sp
->batch_done
.head
!= head
);
437 rcu_batch_dequeue(&sp
->batch_done
);
440 /* give the processing owner to work_struct */
443 rcu_batch_queue(&sp
->batch_queue
, head
);
444 spin_unlock_irq(&sp
->queue_lock
);
448 wait_for_completion(&rcu
.completion
);
452 * synchronize_srcu - wait for prior SRCU read-side critical-section completion
453 * @sp: srcu_struct with which to synchronize.
455 * Wait for the count to drain to zero of both indexes. To avoid the
456 * possible starvation of synchronize_srcu(), it waits for the count of
457 * the index=((->completed & 1) ^ 1) to drain to zero at first,
458 * and then flip the completed and wait for the count of the other index.
460 * Can block; must be called from process context.
462 * Note that it is illegal to call synchronize_srcu() from the corresponding
463 * SRCU read-side critical section; doing so will result in deadlock.
464 * However, it is perfectly legal to call synchronize_srcu() on one
465 * srcu_struct from some other srcu_struct's read-side critical section,
466 * as long as the resulting graph of srcu_structs is acyclic.
468 * There are memory-ordering constraints implied by synchronize_srcu().
469 * On systems with more than one CPU, when synchronize_srcu() returns,
470 * each CPU is guaranteed to have executed a full memory barrier since
471 * the end of its last corresponding SRCU-sched read-side critical section
472 * whose beginning preceded the call to synchronize_srcu(). In addition,
473 * each CPU having an SRCU read-side critical section that extends beyond
474 * the return from synchronize_srcu() is guaranteed to have executed a
475 * full memory barrier after the beginning of synchronize_srcu() and before
476 * the beginning of that SRCU read-side critical section. Note that these
477 * guarantees include CPUs that are offline, idle, or executing in user mode,
478 * as well as CPUs that are executing in the kernel.
480 * Furthermore, if CPU A invoked synchronize_srcu(), which returned
481 * to its caller on CPU B, then both CPU A and CPU B are guaranteed
482 * to have executed a full memory barrier during the execution of
483 * synchronize_srcu(). This guarantee applies even if CPU A and CPU B
484 * are the same CPU, but again only if the system has more than one CPU.
486 * Of course, these memory-ordering guarantees apply only when
487 * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
488 * passed the same srcu_struct structure.
490 void synchronize_srcu(struct srcu_struct
*sp
)
492 __synchronize_srcu(sp
, (rcu_gp_is_expedited() && !rcu_gp_is_normal())
493 ? SYNCHRONIZE_SRCU_EXP_TRYCOUNT
494 : SYNCHRONIZE_SRCU_TRYCOUNT
);
496 EXPORT_SYMBOL_GPL(synchronize_srcu
);
499 * synchronize_srcu_expedited - Brute-force SRCU grace period
500 * @sp: srcu_struct with which to synchronize.
502 * Wait for an SRCU grace period to elapse, but be more aggressive about
503 * spinning rather than blocking when waiting.
505 * Note that synchronize_srcu_expedited() has the same deadlock and
506 * memory-ordering properties as does synchronize_srcu().
508 void synchronize_srcu_expedited(struct srcu_struct
*sp
)
510 __synchronize_srcu(sp
, SYNCHRONIZE_SRCU_EXP_TRYCOUNT
);
512 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited
);
515 * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
516 * @sp: srcu_struct on which to wait for in-flight callbacks.
518 void srcu_barrier(struct srcu_struct
*sp
)
520 synchronize_srcu(sp
);
522 EXPORT_SYMBOL_GPL(srcu_barrier
);
525 * srcu_batches_completed - return batches completed.
526 * @sp: srcu_struct on which to report batch completion.
528 * Report the number of batches, correlated with, but not necessarily
529 * precisely the same as, the number of grace periods that have elapsed.
531 unsigned long srcu_batches_completed(struct srcu_struct
*sp
)
533 return sp
->completed
;
535 EXPORT_SYMBOL_GPL(srcu_batches_completed
);
537 #define SRCU_CALLBACK_BATCH 10
538 #define SRCU_INTERVAL 1
541 * Move any new SRCU callbacks to the first stage of the SRCU grace
544 static void srcu_collect_new(struct srcu_struct
*sp
)
546 if (!rcu_batch_empty(&sp
->batch_queue
)) {
547 spin_lock_irq(&sp
->queue_lock
);
548 rcu_batch_move(&sp
->batch_check0
, &sp
->batch_queue
);
549 spin_unlock_irq(&sp
->queue_lock
);
554 * Core SRCU state machine. Advance callbacks from ->batch_check0 to
555 * ->batch_check1 and then to ->batch_done as readers drain.
557 static void srcu_advance_batches(struct srcu_struct
*sp
, int trycount
)
559 int idx
= 1 ^ (sp
->completed
& 1);
562 * Because readers might be delayed for an extended period after
563 * fetching ->completed for their index, at any point in time there
564 * might well be readers using both idx=0 and idx=1. We therefore
565 * need to wait for readers to clear from both index values before
566 * invoking a callback.
569 if (rcu_batch_empty(&sp
->batch_check0
) &&
570 rcu_batch_empty(&sp
->batch_check1
))
571 return; /* no callbacks need to be advanced */
573 if (!try_check_zero(sp
, idx
, trycount
))
574 return; /* failed to advance, will try after SRCU_INTERVAL */
577 * The callbacks in ->batch_check1 have already done with their
578 * first zero check and flip back when they were enqueued on
579 * ->batch_check0 in a previous invocation of srcu_advance_batches().
580 * (Presumably try_check_zero() returned false during that
581 * invocation, leaving the callbacks stranded on ->batch_check1.)
582 * They are therefore ready to invoke, so move them to ->batch_done.
584 rcu_batch_move(&sp
->batch_done
, &sp
->batch_check1
);
586 if (rcu_batch_empty(&sp
->batch_check0
))
587 return; /* no callbacks need to be advanced */
591 * The callbacks in ->batch_check0 just finished their
592 * first check zero and flip, so move them to ->batch_check1
593 * for future checking on the other idx.
595 rcu_batch_move(&sp
->batch_check1
, &sp
->batch_check0
);
598 * SRCU read-side critical sections are normally short, so check
599 * at least twice in quick succession after a flip.
601 trycount
= trycount
< 2 ? 2 : trycount
;
602 if (!try_check_zero(sp
, idx
^1, trycount
))
603 return; /* failed to advance, will try after SRCU_INTERVAL */
606 * The callbacks in ->batch_check1 have now waited for all
607 * pre-existing readers using both idx values. They are therefore
608 * ready to invoke, so move them to ->batch_done.
610 rcu_batch_move(&sp
->batch_done
, &sp
->batch_check1
);
614 * Invoke a limited number of SRCU callbacks that have passed through
615 * their grace period. If there are more to do, SRCU will reschedule
618 static void srcu_invoke_callbacks(struct srcu_struct
*sp
)
621 struct rcu_head
*head
;
623 for (i
= 0; i
< SRCU_CALLBACK_BATCH
; i
++) {
624 head
= rcu_batch_dequeue(&sp
->batch_done
);
634 * Finished one round of SRCU grace period. Start another if there are
635 * more SRCU callbacks queued, otherwise put SRCU into not-running state.
637 static void srcu_reschedule(struct srcu_struct
*sp
)
641 if (rcu_batch_empty(&sp
->batch_done
) &&
642 rcu_batch_empty(&sp
->batch_check1
) &&
643 rcu_batch_empty(&sp
->batch_check0
) &&
644 rcu_batch_empty(&sp
->batch_queue
)) {
645 spin_lock_irq(&sp
->queue_lock
);
646 if (rcu_batch_empty(&sp
->batch_done
) &&
647 rcu_batch_empty(&sp
->batch_check1
) &&
648 rcu_batch_empty(&sp
->batch_check0
) &&
649 rcu_batch_empty(&sp
->batch_queue
)) {
653 spin_unlock_irq(&sp
->queue_lock
);
657 queue_delayed_work(system_power_efficient_wq
,
658 &sp
->work
, SRCU_INTERVAL
);
662 * This is the work-queue function that handles SRCU grace periods.
664 void process_srcu(struct work_struct
*work
)
666 struct srcu_struct
*sp
;
668 sp
= container_of(work
, struct srcu_struct
, work
.work
);
670 srcu_collect_new(sp
);
671 srcu_advance_batches(sp
, 1);
672 srcu_invoke_callbacks(sp
);
675 EXPORT_SYMBOL_GPL(process_srcu
);