source: mainline/kernel/generic/src/synch/rcu.c@ 618d02a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 618d02a was fbe6b65, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

rcu: Gave a high-level overview/description of the rcu algorithms.

  • Property mode set to 100644
File size: 55.3 KB
Line 
1/*
2 * Copyright (c) 2012 Adam Hraska
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29
30/** @addtogroup sync
31 * @{
32 */
33
34/**
35 * @file
36 * @brief Preemptible read-copy update. Usable from interrupt handlers.
37 *
38 * @par Podzimek-preempt-RCU (RCU_PREEMPT_PODZIMEK)
39 *
40 * Podzimek-preempt-RCU is a preemptible variant of Podzimek's non-preemptible
41 * RCU algorithm [1, 2]. Grace period (GP) detection is centralized into a
42 * single detector thread. The detector requests that each cpu announces
43 * that it passed a quiescent state (QS), ie a state when the cpu is
44 * outside of an rcu reader section (CS). Cpus check for QSs during context
45 * switches and when entering and exiting rcu reader sections. Once all
46 * cpus announce a QS and if there were no threads preempted in a CS, the
47 * GP ends.
48 *
49 * The detector increments the global GP counter, _rcu_cur_gp, in order
50 * to start a new GP. Readers notice the new GP by comparing the changed
51 * _rcu_cur_gp to a locally stored value last_seen_gp which denotes the
52 * the last GP number for which the cpu noted an explicit QS (and issued
53 * a memory barrier). Readers check for the change in the outer-most
54 * (ie not nested) rcu_read_lock()/unlock() as these functions represent
55 * a QS. The reader first executes a memory barrier (MB) in order to contain
56 * memory references within a CS (and to make changes made by writers
57 * visible in the CS following rcu_read_lock()). Next, the reader notes
58 * that it reached a QS by updating the cpu local last_seen_gp to the
59 * global GP counter, _rcu_cur_gp. Cache coherency eventually makes
60 * the updated last_seen_gp visible to the detector cpu, much like it
61 * delivered the changed _rcu_cur_gp to all cpus.
62 *
63 * The detector waits a while after starting a GP and then reads each
64 * cpu's last_seen_gp to see if it reached a QS. If a cpu did not record
65 * a QS (might be a long running thread without an RCU reader CS; or cache
66 * coherency has yet to make the most current last_seen_gp visible to
67 * the detector; or the cpu is still in a CS) the cpu is interrupted
68 * via an IPI. If the IPI handler finds the cpu still in a CS, it instructs
69 * the cpu to notify the detector that it had exited the CS via a semaphore.
70 * The detector then waits on the semaphore for any cpus to exit their
71 * CSs. Lastly, it waits for the last reader preempted in a CS to
72 * exit its CS if there were any and signals the end of the GP to
73 * separate reclaimer threads wired to each cpu. Reclaimers then
74 * execute the callbacks queued on each of the cpus.
75 *
76 *
77 * @par A-RCU algorithm (RCU_PREEMPT_A)
78 *
79 * A-RCU is based on the user space rcu algorithm in [3] utilizing signals
80 * (urcu) and Podzimek's rcu [1]. Like in Podzimek's rcu, callbacks are
81 * executed by cpu-bound reclaimer threads. There is however no dedicated
82 * detector thread and the reclaimers take on the responsibilities of the
83 * detector when they need to start a new GP. A new GP is again announced
84 * and acknowledged with _rcu_cur_gp and the cpu local last_seen_gp. Unlike
85 * Podzimek's rcu, cpus check explicitly for QS only during context switches.
86 * Like in urcu, rcu_read_lock()/unlock() only maintain the nesting count
87 * and never issue any memory barriers. This makes rcu_read_lock()/unlock()
88 * simple and fast.
89 *
90 * If a new callback is queued for a reclaimer and no GP is in progress,
91 * the reclaimer takes on the role of a detector. The detector increments
92 * _rcu_cur_gp in order to start a new GP. It waits a while to give cpus
93 * a chance to switch a context (a natural QS). Then, it examines each
94 * non-idle cpu that has yet to pass a QS via an IPI. The IPI handler
95 * sees the most current _rcu_cur_gp and last_seen_gp and notes a QS
96 * with a memory barrier and an update to last_seen_gp. If the handler
97 * finds the cpu in a CS it does nothing and let the detector poll/interrupt
98 * the cpu again after a short sleep.
99 *
100 * @par Caveats
101 *
102 * last_seen_gp and _rcu_cur_gp are always 64bit variables and they
103 * are read non-atomically on 32bit machines. Reading a clobbered
104 * value of last_seen_gp or _rcu_cur_gp or writing a clobbered value
105 * of _rcu_cur_gp to last_seen_gp will at worst force the detector
106 * to unnecessarily interrupt a cpu. Interrupting a cpu makes the
107 * correct value of _rcu_cur_gp visible to the cpu and correctly
108 * resets last_seen_gp in both algorithms.
109 *
110 *
111 *
112 * [1] Read-copy-update for opensolaris,
113 * 2010, Podzimek
114 * https://andrej.podzimek.org/thesis.pdf
115 *
116 * [2] (podzimek-rcu) implementation file "rcu.patch"
117 * http://d3s.mff.cuni.cz/projects/operating_systems/rcu/rcu.patch
118 *
119 * [3] User-level implementations of read-copy update,
120 * 2012, appendix
121 * http://www.rdrop.com/users/paulmck/RCU/urcu-supp-accepted.2011.08.30a.pdf
122 *
123 */
124
125#include <synch/rcu.h>
126#include <synch/condvar.h>
127#include <synch/semaphore.h>
128#include <synch/spinlock.h>
129#include <synch/mutex.h>
130#include <proc/thread.h>
131#include <cpu/cpu_mask.h>
132#include <cpu.h>
133#include <smp/smp_call.h>
134#include <compiler/barrier.h>
135#include <atomic.h>
136#include <arch.h>
137#include <macros.h>
138
139/*
140 * Number of milliseconds to give to preexisting readers to finish
141 * when non-expedited grace period detection is in progress.
142 */
143#define DETECT_SLEEP_MS 10
144/*
145 * Max number of pending callbacks in the local cpu's queue before
146 * aggressively expediting the current grace period
147 */
148#define EXPEDITE_THRESHOLD 2000
149/*
150 * Max number of callbacks to execute in one go with preemption
151 * enabled. If there are more callbacks to be executed they will
152 * be run with preemption disabled in order to prolong reclaimer's
153 * time slice and give it a chance to catch up with callback producers.
154 */
155#define CRITICAL_THRESHOLD 30000
156/* Half the number of values a uint32 can hold. */
157#define UINT32_MAX_HALF 2147483648U
158
159/**
160 * The current grace period number. Increases monotonically.
161 * Lock rcu.gp_lock or rcu.preempt_lock to get a current value.
162 */
163rcu_gp_t _rcu_cur_gp;
164
165/** Global RCU data. */
166typedef struct rcu_data {
167 /** Detector uses so signal reclaimers that a grace period ended. */
168 condvar_t gp_ended;
169 /** Reclaimers use to notify the detector to accelerate GP detection. */
170 condvar_t expedite_now;
171 /**
172 * Protects: req_gp_end_cnt, req_expedited_cnt, completed_gp, _rcu_cur_gp;
173 * or: completed_gp, _rcu_cur_gp
174 */
175 SPINLOCK_DECLARE(gp_lock);
176 /**
177 * The number of the most recently completed grace period. At most
178 * one behind _rcu_cur_gp. If equal to _rcu_cur_gp, a grace period
179 * detection is not in progress and the detector is idle.
180 */
181 rcu_gp_t completed_gp;
182
183 /** Protects the following 3 fields. */
184 IRQ_SPINLOCK_DECLARE(preempt_lock);
185 /** Preexisting readers that have been preempted. */
186 list_t cur_preempted;
187 /** Reader that have been preempted and might delay the next grace period.*/
188 list_t next_preempted;
189 /**
190 * The detector is waiting for the last preempted reader
191 * in cur_preempted to announce that it exited its reader
192 * section by up()ing remaining_readers.
193 */
194 bool preempt_blocking_det;
195
196#ifdef RCU_PREEMPT_A
197
198 /**
199 * The detector waits on this semaphore for any preempted readers
200 * delaying the grace period once all cpus pass a quiescent state.
201 */
202 semaphore_t remaining_readers;
203
204#elif defined(RCU_PREEMPT_PODZIMEK)
205
206 /** Reclaimers notify the detector when they request more grace periods.*/
207 condvar_t req_gp_changed;
208 /** Number of grace period ends the detector was requested to announce. */
209 size_t req_gp_end_cnt;
210 /** Number of consecutive grace periods to detect quickly and aggressively.*/
211 size_t req_expedited_cnt;
212 /**
213 * Number of cpus with readers that are delaying the current GP.
214 * They will up() remaining_readers.
215 */
216 atomic_t delaying_cpu_cnt;
217 /**
218 * The detector waits on this semaphore for any readers delaying the GP.
219 *
220 * Each of the cpus with readers that are delaying the current GP
221 * must up() this sema once they reach a quiescent state. If there
222 * are any readers in cur_preempted (ie preempted preexisting) and
223 * they are already delaying GP detection, the last to unlock its
224 * reader section must up() this sema once.
225 */
226 semaphore_t remaining_readers;
227#endif
228
229 /** Excludes simultaneous rcu_barrier() calls. */
230 mutex_t barrier_mtx;
231 /** Number of cpus that we are waiting for to complete rcu_barrier(). */
232 atomic_t barrier_wait_cnt;
233 /** rcu_barrier() waits for the completion of barrier callbacks on this wq.*/
234 waitq_t barrier_wq;
235
236 /** Interruptible attached detector thread pointer. */
237 thread_t *detector_thr;
238
239 /* Some statistics. */
240 size_t stat_expedited_cnt;
241 size_t stat_delayed_cnt;
242 size_t stat_preempt_blocking_cnt;
243 /* Does not contain self/local calls. */
244 size_t stat_smp_call_cnt;
245} rcu_data_t;
246
247
248static rcu_data_t rcu;
249
250static void start_reclaimers(void);
251static void synch_complete(rcu_item_t *rcu_item);
252static inline void rcu_call_impl(bool expedite, rcu_item_t *rcu_item,
253 rcu_func_t func);
254static void add_barrier_cb(void *arg);
255static void barrier_complete(rcu_item_t *barrier_item);
256static bool arriving_cbs_empty(void);
257static bool next_cbs_empty(void);
258static bool cur_cbs_empty(void);
259static bool all_cbs_empty(void);
260static void reclaimer(void *arg);
261static bool wait_for_pending_cbs(void);
262static bool advance_cbs(void);
263static void exec_completed_cbs(rcu_gp_t last_completed_gp);
264static void exec_cbs(rcu_item_t **phead);
265static bool wait_for_cur_cbs_gp_end(bool expedite, rcu_gp_t *last_completed_gp);
266static void upd_missed_gp_in_wait(rcu_gp_t completed_gp);
267
268#ifdef RCU_PREEMPT_PODZIMEK
269static void start_detector(void);
270static void read_unlock_impl(size_t *pnesting_cnt);
271static void req_detection(size_t req_cnt);
272static bool cv_wait_for_gp(rcu_gp_t wait_on_gp);
273static void detector(void *);
274static bool wait_for_detect_req(void);
275static void end_cur_gp(void);
276static bool wait_for_readers(void);
277static bool gp_sleep(void);
278static void interrupt_delaying_cpus(cpu_mask_t *cpu_mask);
279static bool wait_for_delaying_cpus(void);
280#elif defined(RCU_PREEMPT_A)
281static bool wait_for_readers(bool expedite);
282static bool gp_sleep(bool *expedite);
283#endif
284
285static void start_new_gp(void);
286static void rm_quiescent_cpus(cpu_mask_t *cpu_mask);
287static void sample_cpus(cpu_mask_t *reader_cpus, void *arg);
288static void sample_local_cpu(void *);
289static bool wait_for_preempt_reader(void);
290static void note_preempted_reader(void);
291static void rm_preempted_reader(void);
292static void upd_max_cbs_in_slice(void);
293
294
295
296/** Initializes global RCU structures. */
297void rcu_init(void)
298{
299 condvar_initialize(&rcu.gp_ended);
300 condvar_initialize(&rcu.expedite_now);
301
302 spinlock_initialize(&rcu.gp_lock, "rcu.gp_lock");
303 _rcu_cur_gp = 0;
304 rcu.completed_gp = 0;
305
306 irq_spinlock_initialize(&rcu.preempt_lock, "rcu.preempt_lock");
307 list_initialize(&rcu.cur_preempted);
308 list_initialize(&rcu.next_preempted);
309 rcu.preempt_blocking_det = false;
310
311 mutex_initialize(&rcu.barrier_mtx, MUTEX_PASSIVE);
312 atomic_set(&rcu.barrier_wait_cnt, 0);
313 waitq_initialize(&rcu.barrier_wq);
314
315 semaphore_initialize(&rcu.remaining_readers, 0);
316
317#ifdef RCU_PREEMPT_PODZIMEK
318 condvar_initialize(&rcu.req_gp_changed);
319
320 rcu.req_gp_end_cnt = 0;
321 rcu.req_expedited_cnt = 0;
322 atomic_set(&rcu.delaying_cpu_cnt, 0);
323#endif
324
325 rcu.detector_thr = NULL;
326
327 rcu.stat_expedited_cnt = 0;
328 rcu.stat_delayed_cnt = 0;
329 rcu.stat_preempt_blocking_cnt = 0;
330 rcu.stat_smp_call_cnt = 0;
331}
332
333/** Initializes per-CPU RCU data. If on the boot cpu inits global data too.*/
334void rcu_cpu_init(void)
335{
336 if (config.cpu_active == 1) {
337 rcu_init();
338 }
339
340 CPU->rcu.last_seen_gp = 0;
341
342#ifdef RCU_PREEMPT_PODZIMEK
343 CPU->rcu.nesting_cnt = 0;
344 CPU->rcu.is_delaying_gp = false;
345 CPU->rcu.signal_unlock = false;
346#endif
347
348 CPU->rcu.cur_cbs = NULL;
349 CPU->rcu.cur_cbs_cnt = 0;
350 CPU->rcu.next_cbs = NULL;
351 CPU->rcu.next_cbs_cnt = 0;
352 CPU->rcu.arriving_cbs = NULL;
353 CPU->rcu.parriving_cbs_tail = &CPU->rcu.arriving_cbs;
354 CPU->rcu.arriving_cbs_cnt = 0;
355
356 CPU->rcu.cur_cbs_gp = 0;
357 CPU->rcu.next_cbs_gp = 0;
358
359 semaphore_initialize(&CPU->rcu.arrived_flag, 0);
360
361 /* BSP creates reclaimer threads before AP's rcu_cpu_init() runs. */
362 if (config.cpu_active == 1)
363 CPU->rcu.reclaimer_thr = NULL;
364
365 CPU->rcu.stat_max_cbs = 0;
366 CPU->rcu.stat_avg_cbs = 0;
367 CPU->rcu.stat_missed_gps = 0;
368 CPU->rcu.stat_missed_gp_in_wait = 0;
369 CPU->rcu.stat_max_slice_cbs = 0;
370 CPU->rcu.last_arriving_cnt = 0;
371}
372
373/** Completes RCU init. Creates and runs the detector and reclaimer threads.*/
374void rcu_kinit_init(void)
375{
376#ifdef RCU_PREEMPT_PODZIMEK
377 start_detector();
378#endif
379
380 start_reclaimers();
381}
382
383/** Initializes any per-thread RCU structures. */
384void rcu_thread_init(thread_t *thread)
385{
386 thread->rcu.nesting_cnt = 0;
387
388#ifdef RCU_PREEMPT_PODZIMEK
389 thread->rcu.was_preempted = false;
390#endif
391
392 link_initialize(&thread->rcu.preempt_link);
393}
394
395
396/** Cleans up global RCU resources and stops dispatching callbacks.
397 *
398 * Call when shutting down the kernel. Outstanding callbacks will
399 * not be processed. Instead they will linger forever.
400 */
401void rcu_stop(void)
402{
403 /* Stop and wait for reclaimers. */
404 for (unsigned int cpu_id = 0; cpu_id < config.cpu_active; ++cpu_id) {
405 ASSERT(cpus[cpu_id].rcu.reclaimer_thr != NULL);
406
407 if (cpus[cpu_id].rcu.reclaimer_thr) {
408 thread_interrupt(cpus[cpu_id].rcu.reclaimer_thr);
409 thread_join(cpus[cpu_id].rcu.reclaimer_thr);
410 thread_detach(cpus[cpu_id].rcu.reclaimer_thr);
411 cpus[cpu_id].rcu.reclaimer_thr = NULL;
412 }
413 }
414
415#ifdef RCU_PREEMPT_PODZIMEK
416 /* Stop the detector and wait. */
417 if (rcu.detector_thr) {
418 thread_interrupt(rcu.detector_thr);
419 thread_join(rcu.detector_thr);
420 thread_detach(rcu.detector_thr);
421 rcu.detector_thr = NULL;
422 }
423#endif
424}
425
426/** Returns the number of elapsed grace periods since boot. */
427uint64_t rcu_completed_gps(void)
428{
429 spinlock_lock(&rcu.gp_lock);
430 uint64_t completed = rcu.completed_gp;
431 spinlock_unlock(&rcu.gp_lock);
432
433 return completed;
434}
435
436/** Creates and runs cpu-bound reclaimer threads. */
437static void start_reclaimers(void)
438{
439 for (unsigned int cpu_id = 0; cpu_id < config.cpu_count; ++cpu_id) {
440 char name[THREAD_NAME_BUFLEN] = {0};
441
442 snprintf(name, THREAD_NAME_BUFLEN - 1, "rcu-rec/%u", cpu_id);
443
444 cpus[cpu_id].rcu.reclaimer_thr =
445 thread_create(reclaimer, NULL, TASK, THREAD_FLAG_NONE, name);
446
447 if (!cpus[cpu_id].rcu.reclaimer_thr)
448 panic("Failed to create RCU reclaimer thread on cpu%u.", cpu_id);
449
450 thread_wire(cpus[cpu_id].rcu.reclaimer_thr, &cpus[cpu_id]);
451 thread_ready(cpus[cpu_id].rcu.reclaimer_thr);
452 }
453}
454
455#ifdef RCU_PREEMPT_PODZIMEK
456
457/** Starts the detector thread. */
458static void start_detector(void)
459{
460 rcu.detector_thr =
461 thread_create(detector, NULL, TASK, THREAD_FLAG_NONE, "rcu-det");
462
463 if (!rcu.detector_thr)
464 panic("Failed to create RCU detector thread.");
465
466 thread_ready(rcu.detector_thr);
467}
468
469/** Returns true if in an rcu reader section. */
470bool rcu_read_locked(void)
471{
472 preemption_disable();
473 bool locked = 0 < CPU->rcu.nesting_cnt;
474 preemption_enable();
475
476 return locked;
477}
478
479/** Unlocks the local reader section using the given nesting count.
480 *
481 * Preemption or interrupts must be disabled.
482 *
483 * @param pnesting_cnt Either &CPU->rcu.tmp_nesting_cnt or
484 * THREAD->rcu.nesting_cnt.
485 */
486static void read_unlock_impl(size_t *pnesting_cnt)
487{
488 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
489
490 if (0 == --(*pnesting_cnt)) {
491 _rcu_record_qs();
492
493 /*
494 * The thread was preempted while in a critical section or
495 * the detector is eagerly waiting for this cpu's reader
496 * to finish.
497 *
498 * Note that THREAD may be NULL in scheduler() and not just during boot.
499 */
500 if ((THREAD && THREAD->rcu.was_preempted) || CPU->rcu.is_delaying_gp) {
501 /* Rechecks with disabled interrupts. */
502 _rcu_signal_read_unlock();
503 }
504 }
505}
506
507/** If necessary, signals the detector that we exited a reader section. */
508void _rcu_signal_read_unlock(void)
509{
510 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
511
512 /* todo: make NMI safe with cpu-local atomic ops. */
513
514 /*
515 * We have to disable interrupts in order to make checking
516 * and resetting was_preempted and is_delaying_gp atomic
517 * with respect to local interrupt handlers. Otherwise
518 * an interrupt could beat us to calling semaphore_up()
519 * before we reset the appropriate flag.
520 */
521 ipl_t ipl = interrupts_disable();
522
523 /*
524 * If the detector is eagerly waiting for this cpu's reader to unlock,
525 * notify it that the reader did so.
526 */
527 if (CPU->rcu.is_delaying_gp) {
528 CPU->rcu.is_delaying_gp = false;
529 semaphore_up(&rcu.remaining_readers);
530 }
531
532 /*
533 * This reader was preempted while in a reader section.
534 * We might be holding up the current GP. Notify the
535 * detector if so.
536 */
537 if (THREAD && THREAD->rcu.was_preempted) {
538 ASSERT(link_used(&THREAD->rcu.preempt_link));
539 THREAD->rcu.was_preempted = false;
540
541 rm_preempted_reader();
542 }
543
544 /* If there was something to signal to the detector we have done so. */
545 CPU->rcu.signal_unlock = false;
546
547 interrupts_restore(ipl);
548}
549
550#endif /* RCU_PREEMPT_PODZIMEK */
551
552typedef struct synch_item {
553 waitq_t wq;
554 rcu_item_t rcu_item;
555} synch_item_t;
556
557/** Blocks until all preexisting readers exit their critical sections. */
558void rcu_synchronize(void)
559{
560 _rcu_synchronize(false);
561}
562
563/** Blocks until all preexisting readers exit their critical sections. */
564void rcu_synchronize_expedite(void)
565{
566 _rcu_synchronize(true);
567}
568
569/** Blocks until all preexisting readers exit their critical sections. */
570void _rcu_synchronize(bool expedite)
571{
572 /* Calling from a reader section will deadlock. */
573 ASSERT(!rcu_read_locked());
574
575 synch_item_t completion;
576
577 waitq_initialize(&completion.wq);
578 _rcu_call(expedite, &completion.rcu_item, synch_complete);
579 waitq_sleep(&completion.wq);
580}
581
582/** rcu_synchronize's callback. */
583static void synch_complete(rcu_item_t *rcu_item)
584{
585 synch_item_t *completion = member_to_inst(rcu_item, synch_item_t, rcu_item);
586 ASSERT(completion);
587 waitq_wakeup(&completion->wq, WAKEUP_FIRST);
588}
589
590/** Waits for all outstanding rcu calls to complete. */
591void rcu_barrier(void)
592{
593 /*
594 * Serialize rcu_barrier() calls so we don't overwrite cpu.barrier_item
595 * currently in use by rcu_barrier().
596 */
597 mutex_lock(&rcu.barrier_mtx);
598
599 /*
600 * Ensure we queue a barrier callback on all cpus before the already
601 * enqueued barrier callbacks start signaling completion.
602 */
603 atomic_set(&rcu.barrier_wait_cnt, 1);
604
605 DEFINE_CPU_MASK(cpu_mask);
606 cpu_mask_active(cpu_mask);
607
608 cpu_mask_for_each(*cpu_mask, cpu_id) {
609 smp_call(cpu_id, add_barrier_cb, NULL);
610 }
611
612 if (0 < atomic_predec(&rcu.barrier_wait_cnt)) {
613 waitq_sleep(&rcu.barrier_wq);
614 }
615
616 mutex_unlock(&rcu.barrier_mtx);
617}
618
619/** Issues a rcu_barrier() callback on the local cpu.
620 *
621 * Executed with interrupts disabled.
622 */
623static void add_barrier_cb(void *arg)
624{
625 ASSERT(interrupts_disabled() || PREEMPTION_DISABLED);
626 atomic_inc(&rcu.barrier_wait_cnt);
627 rcu_call(&CPU->rcu.barrier_item, barrier_complete);
628}
629
630/** Local cpu's rcu_barrier() completion callback. */
631static void barrier_complete(rcu_item_t *barrier_item)
632{
633 /* Is this the last barrier callback completed? */
634 if (0 == atomic_predec(&rcu.barrier_wait_cnt)) {
635 /* Notify rcu_barrier() that we're done. */
636 waitq_wakeup(&rcu.barrier_wq, WAKEUP_FIRST);
637 }
638}
639
640/** Adds a callback to invoke after all preexisting readers finish.
641 *
642 * May be called from within interrupt handlers or RCU reader sections.
643 *
644 * @param rcu_item Used by RCU to track the call. Must remain
645 * until the user callback function is entered.
646 * @param func User callback function that will be invoked once a full
647 * grace period elapsed, ie at a time when all preexisting
648 * readers have finished. The callback should be short and must
649 * not block. If you must sleep, enqueue your work in the system
650 * work queue from the callback (ie workq_global_enqueue()).
651 */
652void rcu_call(rcu_item_t *rcu_item, rcu_func_t func)
653{
654 rcu_call_impl(false, rcu_item, func);
655}
656
657/** rcu_call() implementation. See rcu_call() for comments. */
658void _rcu_call(bool expedite, rcu_item_t *rcu_item, rcu_func_t func)
659{
660 rcu_call_impl(expedite, rcu_item, func);
661}
662
663/** rcu_call() inline-able implementation. See rcu_call() for comments. */
664static inline void rcu_call_impl(bool expedite, rcu_item_t *rcu_item,
665 rcu_func_t func)
666{
667 ASSERT(rcu_item);
668
669 rcu_item->func = func;
670 rcu_item->next = NULL;
671
672 preemption_disable();
673
674 ipl_t ipl = interrupts_disable();
675
676 rcu_cpu_data_t *r = &CPU->rcu;
677 *r->parriving_cbs_tail = rcu_item;
678 r->parriving_cbs_tail = &rcu_item->next;
679
680 size_t cnt = ++r->arriving_cbs_cnt;
681 interrupts_restore(ipl);
682
683 if (expedite) {
684 r->expedite_arriving = true;
685 }
686
687 /* Added first callback - notify the reclaimer. */
688 if (cnt == 1 && !semaphore_count_get(&r->arrived_flag)) {
689 semaphore_up(&r->arrived_flag);
690 }
691
692 preemption_enable();
693}
694
695static bool cur_cbs_empty(void)
696{
697 ASSERT(THREAD && THREAD->wired);
698 return NULL == CPU->rcu.cur_cbs;
699}
700
701static bool next_cbs_empty(void)
702{
703 ASSERT(THREAD && THREAD->wired);
704 return NULL == CPU->rcu.next_cbs;
705}
706
707/** Disable interrupts to get an up-to-date result. */
708static bool arriving_cbs_empty(void)
709{
710 ASSERT(THREAD && THREAD->wired);
711 /*
712 * Accessing with interrupts enabled may at worst lead to
713 * a false negative if we race with a local interrupt handler.
714 */
715 return NULL == CPU->rcu.arriving_cbs;
716}
717
718static bool all_cbs_empty(void)
719{
720 return cur_cbs_empty() && next_cbs_empty() && arriving_cbs_empty();
721}
722
723
724/** Reclaimer thread dispatches locally queued callbacks once a GP ends. */
725static void reclaimer(void *arg)
726{
727 ASSERT(THREAD && THREAD->wired);
728 ASSERT(THREAD == CPU->rcu.reclaimer_thr);
729
730 rcu_gp_t last_compl_gp = 0;
731 bool ok = true;
732
733 while (ok && wait_for_pending_cbs()) {
734 ASSERT(CPU->rcu.reclaimer_thr == THREAD);
735
736 exec_completed_cbs(last_compl_gp);
737
738 bool expedite = advance_cbs();
739
740 ok = wait_for_cur_cbs_gp_end(expedite, &last_compl_gp);
741 }
742}
743
744/** Waits until there are callbacks waiting to be dispatched. */
745static bool wait_for_pending_cbs(void)
746{
747 if (!all_cbs_empty())
748 return true;
749
750 bool ok = true;
751
752 while (arriving_cbs_empty() && ok) {
753 ok = semaphore_down_interruptable(&CPU->rcu.arrived_flag);
754 }
755
756 return ok;
757}
758
759static void upd_stat_missed_gp(rcu_gp_t compl)
760{
761 if (CPU->rcu.cur_cbs_gp < compl) {
762 CPU->rcu.stat_missed_gps += (size_t)(compl - CPU->rcu.cur_cbs_gp);
763 }
764}
765
766/** Executes all callbacks for the given completed grace period. */
767static void exec_completed_cbs(rcu_gp_t last_completed_gp)
768{
769 upd_stat_missed_gp(last_completed_gp);
770
771 /* Both next_cbs and cur_cbs GP elapsed. */
772 if (CPU->rcu.next_cbs_gp <= last_completed_gp) {
773 ASSERT(CPU->rcu.cur_cbs_gp <= CPU->rcu.next_cbs_gp);
774
775 size_t exec_cnt = CPU->rcu.cur_cbs_cnt + CPU->rcu.next_cbs_cnt;
776
777 if (exec_cnt < CRITICAL_THRESHOLD) {
778 exec_cbs(&CPU->rcu.cur_cbs);
779 exec_cbs(&CPU->rcu.next_cbs);
780 } else {
781 /*
782 * Getting overwhelmed with too many callbacks to run.
783 * Disable preemption in order to prolong our time slice
784 * and catch up with updaters posting new callbacks.
785 */
786 preemption_disable();
787 exec_cbs(&CPU->rcu.cur_cbs);
788 exec_cbs(&CPU->rcu.next_cbs);
789 preemption_enable();
790 }
791
792 CPU->rcu.cur_cbs_cnt = 0;
793 CPU->rcu.next_cbs_cnt = 0;
794 } else if (CPU->rcu.cur_cbs_gp <= last_completed_gp) {
795
796 if (CPU->rcu.cur_cbs_cnt < CRITICAL_THRESHOLD) {
797 exec_cbs(&CPU->rcu.cur_cbs);
798 } else {
799 /*
800 * Getting overwhelmed with too many callbacks to run.
801 * Disable preemption in order to prolong our time slice
802 * and catch up with updaters posting new callbacks.
803 */
804 preemption_disable();
805 exec_cbs(&CPU->rcu.cur_cbs);
806 preemption_enable();
807 }
808
809 CPU->rcu.cur_cbs_cnt = 0;
810 }
811}
812
813/** Executes callbacks in the single-linked list. The list is left empty. */
814static void exec_cbs(rcu_item_t **phead)
815{
816 rcu_item_t *rcu_item = *phead;
817
818 while (rcu_item) {
819 /* func() may free rcu_item. Get a local copy. */
820 rcu_item_t *next = rcu_item->next;
821 rcu_func_t func = rcu_item->func;
822
823 func(rcu_item);
824
825 rcu_item = next;
826 }
827
828 *phead = NULL;
829}
830
831static void upd_stat_cb_cnts(size_t arriving_cnt)
832{
833 CPU->rcu.stat_max_cbs = max(arriving_cnt, CPU->rcu.stat_max_cbs);
834 if (0 < arriving_cnt) {
835 CPU->rcu.stat_avg_cbs =
836 (99 * CPU->rcu.stat_avg_cbs + 1 * arriving_cnt) / 100;
837 }
838}
839
840/** Prepares another batch of callbacks to dispatch at the nest grace period.
841 *
842 * @return True if the next batch of callbacks must be expedited quickly.
843 */
844static bool advance_cbs(void)
845{
846 /* Move next_cbs to cur_cbs. */
847 CPU->rcu.cur_cbs = CPU->rcu.next_cbs;
848 CPU->rcu.cur_cbs_cnt = CPU->rcu.next_cbs_cnt;
849 CPU->rcu.cur_cbs_gp = CPU->rcu.next_cbs_gp;
850
851 /* Move arriving_cbs to next_cbs. Empties arriving_cbs. */
852 ipl_t ipl = interrupts_disable();
853
854 /*
855 * Too many callbacks queued. Better speed up the detection
856 * or risk exhausting all system memory.
857 */
858 bool expedite = (EXPEDITE_THRESHOLD < CPU->rcu.arriving_cbs_cnt)
859 || CPU->rcu.expedite_arriving;
860
861 CPU->rcu.expedite_arriving = false;
862
863 CPU->rcu.next_cbs = CPU->rcu.arriving_cbs;
864 CPU->rcu.next_cbs_cnt = CPU->rcu.arriving_cbs_cnt;
865
866 CPU->rcu.arriving_cbs = NULL;
867 CPU->rcu.parriving_cbs_tail = &CPU->rcu.arriving_cbs;
868 CPU->rcu.arriving_cbs_cnt = 0;
869
870 interrupts_restore(ipl);
871
872 /* Update statistics of arrived callbacks. */
873 upd_stat_cb_cnts(CPU->rcu.next_cbs_cnt);
874
875 /*
876 * Make changes prior to queuing next_cbs visible to readers.
877 * See comment in wait_for_readers().
878 */
879 memory_barrier(); /* MB A, B */
880
881 /* At the end of next_cbs_gp, exec next_cbs. Determine what GP that is. */
882
883 if (!next_cbs_empty()) {
884 spinlock_lock(&rcu.gp_lock);
885
886 /* Exec next_cbs at the end of the next GP. */
887 CPU->rcu.next_cbs_gp = _rcu_cur_gp + 1;
888
889 /*
890 * There are no callbacks to invoke before next_cbs. Instruct
891 * wait_for_cur_cbs_gp() to notify us of the nearest GP end.
892 * That could be sooner than next_cbs_gp (if the current GP
893 * had not yet completed), so we'll create a shorter batch
894 * of callbacks next time around.
895 */
896 if (cur_cbs_empty()) {
897 CPU->rcu.cur_cbs_gp = rcu.completed_gp + 1;
898 }
899
900 spinlock_unlock(&rcu.gp_lock);
901 } else {
902 CPU->rcu.next_cbs_gp = CPU->rcu.cur_cbs_gp;
903 }
904
905 ASSERT(CPU->rcu.cur_cbs_gp <= CPU->rcu.next_cbs_gp);
906
907 return expedite;
908}
909
910
911#ifdef RCU_PREEMPT_A
912
913/** Waits for the grace period associated with callbacks cub_cbs to elapse.
914 *
915 * @param expedite Instructs the detector to aggressively speed up grace
916 * period detection without any delay.
917 * @param completed_gp Returns the most recent completed grace period
918 * number.
919 * @return false if the thread was interrupted and should stop.
920 */
921static bool wait_for_cur_cbs_gp_end(bool expedite, rcu_gp_t *completed_gp)
922{
923 spinlock_lock(&rcu.gp_lock);
924
925 ASSERT(CPU->rcu.cur_cbs_gp <= CPU->rcu.next_cbs_gp);
926 ASSERT(CPU->rcu.cur_cbs_gp <= _rcu_cur_gp + 1);
927
928 while (rcu.completed_gp < CPU->rcu.cur_cbs_gp) {
929 /* GP has not yet started - start a new one. */
930 if (rcu.completed_gp == _rcu_cur_gp) {
931 start_new_gp();
932 spinlock_unlock(&rcu.gp_lock);
933
934 if (!wait_for_readers(expedite))
935 return false;
936
937 spinlock_lock(&rcu.gp_lock);
938 /* Notify any reclaimers this GP had ended. */
939 rcu.completed_gp = _rcu_cur_gp;
940 condvar_broadcast(&rcu.gp_ended);
941 } else {
942 /* GP detection is in progress.*/
943
944 if (expedite)
945 condvar_signal(&rcu.expedite_now);
946
947 /* Wait for the GP to complete. */
948 int ret = _condvar_wait_timeout_spinlock(&rcu.gp_ended, &rcu.gp_lock,
949 SYNCH_NO_TIMEOUT, SYNCH_FLAGS_INTERRUPTIBLE);
950
951 if (ret == ESYNCH_INTERRUPTED) {
952 spinlock_unlock(&rcu.gp_lock);
953 return false;
954 }
955 }
956 }
957
958 upd_missed_gp_in_wait(rcu.completed_gp);
959
960 *completed_gp = rcu.completed_gp;
961 spinlock_unlock(&rcu.gp_lock);
962
963 return true;
964}
965
966static bool wait_for_readers(bool expedite)
967{
968 DEFINE_CPU_MASK(reader_cpus);
969
970 cpu_mask_active(reader_cpus);
971 rm_quiescent_cpus(reader_cpus);
972
973 while (!cpu_mask_is_none(reader_cpus)) {
974 /* Give cpus a chance to context switch (a QS) and batch callbacks. */
975 if(!gp_sleep(&expedite))
976 return false;
977
978 rm_quiescent_cpus(reader_cpus);
979 sample_cpus(reader_cpus, reader_cpus);
980 }
981
982 /* Update statistic. */
983 if (expedite) {
984 ++rcu.stat_expedited_cnt;
985 }
986
987 /*
988 * All cpus have passed through a QS and see the most recent _rcu_cur_gp.
989 * As a result newly preempted readers will associate with next_preempted
990 * and the number of old readers in cur_preempted will monotonically
991 * decrease. Wait for those old/preexisting readers.
992 */
993 return wait_for_preempt_reader();
994}
995
996static bool gp_sleep(bool *expedite)
997{
998 if (*expedite) {
999 scheduler();
1000 return true;
1001 } else {
1002 spinlock_lock(&rcu.gp_lock);
1003
1004 int ret = 0;
1005 ret = _condvar_wait_timeout_spinlock(&rcu.expedite_now, &rcu.gp_lock,
1006 DETECT_SLEEP_MS * 1000, SYNCH_FLAGS_INTERRUPTIBLE);
1007
1008 /* rcu.expedite_now was signaled. */
1009 if (ret == ESYNCH_OK_BLOCKED) {
1010 *expedite = true;
1011 }
1012
1013 spinlock_unlock(&rcu.gp_lock);
1014
1015 return (ret != ESYNCH_INTERRUPTED);
1016 }
1017}
1018
1019static void sample_local_cpu(void *arg)
1020{
1021 ASSERT(interrupts_disabled());
1022 cpu_mask_t *reader_cpus = (cpu_mask_t *)arg;
1023
1024 bool locked = RCU_CNT_INC <= THE->rcu_nesting;
1025 /* smp_call machinery makes the most current _rcu_cur_gp visible. */
1026 bool passed_qs = (CPU->rcu.last_seen_gp == _rcu_cur_gp);
1027
1028 if (locked && !passed_qs) {
1029 /*
1030 * This cpu has not yet passed a quiescent state during this grace
1031 * period and it is currently in a reader section. We'll have to
1032 * try to sample this cpu again later.
1033 */
1034 } else {
1035 /* Either not in a reader section or already passed a QS. */
1036 cpu_mask_reset(reader_cpus, CPU->id);
1037 /* Contain new reader sections and make prior changes visible to them.*/
1038 memory_barrier();
1039 CPU->rcu.last_seen_gp = _rcu_cur_gp;
1040 }
1041}
1042
1043/** Called by the scheduler() when switching away from the current thread. */
1044void rcu_after_thread_ran(void)
1045{
1046 ASSERT(interrupts_disabled());
1047
1048 /*
1049 * In order not to worry about NMI seeing rcu_nesting change work
1050 * with a local copy.
1051 */
1052 size_t nesting_cnt = ACCESS_ONCE(THE->rcu_nesting);
1053
1054 /* Preempted a reader critical section for the first time. */
1055 if (RCU_CNT_INC <= nesting_cnt && !(nesting_cnt & RCU_WAS_PREEMPTED)) {
1056 nesting_cnt |= RCU_WAS_PREEMPTED;
1057 note_preempted_reader();
1058 }
1059
1060 /* Save the thread's nesting count when it is not running. */
1061 THREAD->rcu.nesting_cnt = nesting_cnt;
1062 ACCESS_ONCE(THE->rcu_nesting) = 0;
1063
1064 if (CPU->rcu.last_seen_gp != _rcu_cur_gp) {
1065 /*
1066 * Contain any memory accesses of old readers before announcing a QS.
1067 * Also make changes from the previous GP visible to this cpu.
1068 * Moreover it separates writing to last_seen_gp from
1069 * note_preempted_reader().
1070 */
1071 memory_barrier();
1072 /*
1073 * The preempted reader has been noted globally. There are therefore
1074 * no readers running on this cpu so this is a quiescent state.
1075 *
1076 * Reading the multiword _rcu_cur_gp non-atomically is benign.
1077 * At worst, the read value will be different from the actual value.
1078 * As a result, both the detector and this cpu will believe
1079 * this cpu has not yet passed a QS although it really did.
1080 *
1081 * Reloading _rcu_cur_gp is benign, because it cannot change
1082 * until this cpu acknowledges it passed a QS by writing to
1083 * last_seen_gp. Since interrupts are disabled, only this
1084 * code may to so (IPIs won't get through).
1085 */
1086 CPU->rcu.last_seen_gp = _rcu_cur_gp;
1087 }
1088
1089 /*
1090 * Forcefully associate the reclaimer with the highest priority
1091 * even if preempted due to its time slice running out.
1092 */
1093 if (THREAD == CPU->rcu.reclaimer_thr) {
1094 THREAD->priority = -1;
1095 }
1096
1097 upd_max_cbs_in_slice();
1098}
1099
1100/** Called by the scheduler() when switching to a newly scheduled thread. */
1101void rcu_before_thread_runs(void)
1102{
1103 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
1104 ASSERT(!rcu_read_locked());
1105
1106 /* Load the thread's saved nesting count from before it was preempted. */
1107 THE->rcu_nesting = THREAD->rcu.nesting_cnt;
1108}
1109
1110/** Called from scheduler() when exiting the current thread.
1111 *
1112 * Preemption or interrupts are disabled and the scheduler() already
1113 * switched away from the current thread, calling rcu_after_thread_ran().
1114 */
1115void rcu_thread_exiting(void)
1116{
1117 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
1118 /*
1119 * The thread forgot to exit its reader critical section.
1120 * It is a bug, but rather than letting the entire system lock up
1121 * forcefully leave the reader section. The thread is not holding
1122 * any references anyway since it is exiting so it is safe.
1123 */
1124 if (RCU_CNT_INC <= THREAD->rcu.nesting_cnt) {
1125 /* Emulate _rcu_preempted_unlock() with the proper nesting count. */
1126 if (THREAD->rcu.nesting_cnt & RCU_WAS_PREEMPTED) {
1127 ipl_t ipl = interrupts_disable();
1128 rm_preempted_reader();
1129 interrupts_restore(ipl);
1130 }
1131
1132 printf("Bug: thread (id %" PRIu64 " \"%s\") exited while in RCU read"
1133 " section.\n", THREAD->tid, THREAD->name);
1134 }
1135}
1136
1137/** Returns true if in an rcu reader section. */
1138bool rcu_read_locked(void)
1139{
1140 return RCU_CNT_INC <= THE->rcu_nesting;
1141}
1142
1143/** Invoked when a preempted reader finally exits its reader section. */
1144void _rcu_preempted_unlock(void)
1145{
1146 ipl_t ipl = interrupts_disable();
1147
1148 /* todo: Replace with cpu-local atomics to be NMI-safe */
1149 if (THE->rcu_nesting == RCU_WAS_PREEMPTED) {
1150 THE->rcu_nesting = 0;
1151 /*
1152 * NMI handlers are never preempted but may call rm_preempted_reader()
1153 * if a NMI occurred in _rcu_preempted_unlock() of a preempted thread.
1154 * rm_preempted_reader() will not deadlock because none of the locks
1155 * it uses are locked in this case.
1156 */
1157 rm_preempted_reader();
1158 }
1159
1160 interrupts_restore(ipl);
1161}
1162
1163#elif defined(RCU_PREEMPT_PODZIMEK)
1164
1165/** Waits for the grace period associated with callbacks cub_cbs to elapse.
1166 *
1167 * @param expedite Instructs the detector to aggressively speed up grace
1168 * period detection without any delay.
1169 * @param completed_gp Returns the most recent completed grace period
1170 * number.
1171 * @return false if the thread was interrupted and should stop.
1172 */
1173static bool wait_for_cur_cbs_gp_end(bool expedite, rcu_gp_t *completed_gp)
1174{
1175 /*
1176 * Use a possibly outdated version of completed_gp to bypass checking
1177 * with the lock.
1178 *
1179 * Note that loading and storing rcu.completed_gp is not atomic
1180 * (it is 64bit wide). Reading a clobbered value that is less than
1181 * rcu.completed_gp is harmless - we'll recheck with a lock. The
1182 * only way to read a clobbered value that is greater than the actual
1183 * value is if the detector increases the higher-order word first and
1184 * then decreases the lower-order word (or we see stores in that order),
1185 * eg when incrementing from 2^32 - 1 to 2^32. The loaded value
1186 * suddenly jumps by 2^32. It would take hours for such an increase
1187 * to occur so it is safe to discard the value. We allow increases
1188 * of up to half the maximum to generously accommodate for loading an
1189 * outdated lower word.
1190 */
1191 rcu_gp_t compl_gp = ACCESS_ONCE(rcu.completed_gp);
1192 if (CPU->rcu.cur_cbs_gp <= compl_gp
1193 && compl_gp <= CPU->rcu.cur_cbs_gp + UINT32_MAX_HALF) {
1194 *completed_gp = compl_gp;
1195 return true;
1196 }
1197
1198 spinlock_lock(&rcu.gp_lock);
1199
1200 if (CPU->rcu.cur_cbs_gp <= rcu.completed_gp) {
1201 *completed_gp = rcu.completed_gp;
1202 spinlock_unlock(&rcu.gp_lock);
1203 return true;
1204 }
1205
1206 ASSERT(CPU->rcu.cur_cbs_gp <= CPU->rcu.next_cbs_gp);
1207 ASSERT(_rcu_cur_gp <= CPU->rcu.cur_cbs_gp);
1208
1209 /*
1210 * Notify the detector of how many GP ends we intend to wait for, so
1211 * it can avoid going to sleep unnecessarily. Optimistically assume
1212 * new callbacks will arrive while we're waiting; hence +1.
1213 */
1214 size_t remaining_gp_ends = (size_t) (CPU->rcu.next_cbs_gp - _rcu_cur_gp);
1215 req_detection(remaining_gp_ends + (arriving_cbs_empty() ? 0 : 1));
1216
1217 /*
1218 * Ask the detector to speed up GP detection if there are too many
1219 * pending callbacks and other reclaimers have not already done so.
1220 */
1221 if (expedite) {
1222 if(0 == rcu.req_expedited_cnt)
1223 condvar_signal(&rcu.expedite_now);
1224
1225 /*
1226 * Expedite only cub_cbs. If there really is a surge of callbacks
1227 * the arriving batch will expedite the GP for the huge number
1228 * of callbacks currently in next_cbs
1229 */
1230 rcu.req_expedited_cnt = 1;
1231 }
1232
1233 /* Wait for cur_cbs_gp to end. */
1234 bool interrupted = cv_wait_for_gp(CPU->rcu.cur_cbs_gp);
1235
1236 *completed_gp = rcu.completed_gp;
1237 spinlock_unlock(&rcu.gp_lock);
1238
1239 if (!interrupted)
1240 upd_missed_gp_in_wait(*completed_gp);
1241
1242 return !interrupted;
1243}
1244
1245/** Waits for an announcement of the end of the grace period wait_on_gp. */
1246static bool cv_wait_for_gp(rcu_gp_t wait_on_gp)
1247{
1248 ASSERT(spinlock_locked(&rcu.gp_lock));
1249
1250 bool interrupted = false;
1251
1252 /* Wait until wait_on_gp ends. */
1253 while (rcu.completed_gp < wait_on_gp && !interrupted) {
1254 int ret = _condvar_wait_timeout_spinlock(&rcu.gp_ended, &rcu.gp_lock,
1255 SYNCH_NO_TIMEOUT, SYNCH_FLAGS_INTERRUPTIBLE);
1256 interrupted = (ret == ESYNCH_INTERRUPTED);
1257 }
1258
1259 return interrupted;
1260}
1261
1262/** Requests the detector to detect at least req_cnt consecutive grace periods.*/
1263static void req_detection(size_t req_cnt)
1264{
1265 if (rcu.req_gp_end_cnt < req_cnt) {
1266 bool detector_idle = (0 == rcu.req_gp_end_cnt);
1267 rcu.req_gp_end_cnt = req_cnt;
1268
1269 if (detector_idle) {
1270 ASSERT(_rcu_cur_gp == rcu.completed_gp);
1271 condvar_signal(&rcu.req_gp_changed);
1272 }
1273 }
1274}
1275
1276
1277/** The detector thread detects and notifies reclaimers of grace period ends. */
1278static void detector(void *arg)
1279{
1280 spinlock_lock(&rcu.gp_lock);
1281
1282 while (wait_for_detect_req()) {
1283 /*
1284 * Announce new GP started. Readers start lazily acknowledging that
1285 * they passed a QS.
1286 */
1287 start_new_gp();
1288
1289 spinlock_unlock(&rcu.gp_lock);
1290
1291 if (!wait_for_readers())
1292 goto unlocked_out;
1293
1294 spinlock_lock(&rcu.gp_lock);
1295
1296 /* Notify reclaimers that they may now invoke queued callbacks. */
1297 end_cur_gp();
1298 }
1299
1300 spinlock_unlock(&rcu.gp_lock);
1301
1302unlocked_out:
1303 return;
1304}
1305
1306/** Waits for a request from a reclaimer thread to detect a grace period. */
1307static bool wait_for_detect_req(void)
1308{
1309 ASSERT(spinlock_locked(&rcu.gp_lock));
1310
1311 bool interrupted = false;
1312
1313 while (0 == rcu.req_gp_end_cnt && !interrupted) {
1314 int ret = _condvar_wait_timeout_spinlock(&rcu.req_gp_changed,
1315 &rcu.gp_lock, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_INTERRUPTIBLE);
1316
1317 interrupted = (ret == ESYNCH_INTERRUPTED);
1318 }
1319
1320 return !interrupted;
1321}
1322
1323
1324static void end_cur_gp(void)
1325{
1326 ASSERT(spinlock_locked(&rcu.gp_lock));
1327
1328 rcu.completed_gp = _rcu_cur_gp;
1329 --rcu.req_gp_end_cnt;
1330
1331 condvar_broadcast(&rcu.gp_ended);
1332}
1333
1334/** Waits for readers that started before the current GP started to finish. */
1335static bool wait_for_readers(void)
1336{
1337 DEFINE_CPU_MASK(reading_cpus);
1338
1339 /* All running cpus have potential readers. */
1340 cpu_mask_active(reading_cpus);
1341
1342 /*
1343 * Give readers time to pass through a QS. Also, batch arriving
1344 * callbacks in order to amortize detection overhead.
1345 */
1346 if (!gp_sleep())
1347 return false;
1348
1349 /* Non-intrusively determine which cpus have yet to pass a QS. */
1350 rm_quiescent_cpus(reading_cpus);
1351
1352 /* Actively interrupt cpus delaying the current GP and demand a QS. */
1353 interrupt_delaying_cpus(reading_cpus);
1354
1355 /* Wait for the interrupted cpus to notify us that they reached a QS. */
1356 if (!wait_for_delaying_cpus())
1357 return false;
1358 /*
1359 * All cpus recorded a QS or are still idle. Any new readers will be added
1360 * to next_preempt if preempted, ie the number of readers in cur_preempted
1361 * monotonically descreases.
1362 */
1363
1364 /* Wait for the last reader in cur_preempted to notify us it is done. */
1365 if (!wait_for_preempt_reader())
1366 return false;
1367
1368 return true;
1369}
1370
1371/** Sleeps a while if the current grace period is not to be expedited. */
1372static bool gp_sleep(void)
1373{
1374 spinlock_lock(&rcu.gp_lock);
1375
1376 int ret = 0;
1377 while (0 == rcu.req_expedited_cnt && 0 == ret) {
1378 /* minor bug: sleeps for the same duration if woken up spuriously. */
1379 ret = _condvar_wait_timeout_spinlock(&rcu.expedite_now, &rcu.gp_lock,
1380 DETECT_SLEEP_MS * 1000, SYNCH_FLAGS_INTERRUPTIBLE);
1381 }
1382
1383 if (0 < rcu.req_expedited_cnt) {
1384 --rcu.req_expedited_cnt;
1385 /* Update statistic. */
1386 ++rcu.stat_expedited_cnt;
1387 }
1388
1389 spinlock_unlock(&rcu.gp_lock);
1390
1391 return (ret != ESYNCH_INTERRUPTED);
1392}
1393
1394/** Actively interrupts and checks the offending cpus for quiescent states. */
1395static void interrupt_delaying_cpus(cpu_mask_t *cpu_mask)
1396{
1397 atomic_set(&rcu.delaying_cpu_cnt, 0);
1398
1399 sample_cpus(cpu_mask, NULL);
1400}
1401
1402/** Invoked on a cpu delaying grace period detection.
1403 *
1404 * Induces a quiescent state for the cpu or it instructs remaining
1405 * readers to notify the detector once they finish.
1406 */
1407static void sample_local_cpu(void *arg)
1408{
1409 ASSERT(interrupts_disabled());
1410 ASSERT(!CPU->rcu.is_delaying_gp);
1411
1412 /* Cpu did not pass a quiescent state yet. */
1413 if (CPU->rcu.last_seen_gp != _rcu_cur_gp) {
1414 /* Interrupted a reader in a reader critical section. */
1415 if (0 < CPU->rcu.nesting_cnt) {
1416 ASSERT(!CPU->idle);
1417 /* Note to notify the detector from rcu_read_unlock(). */
1418 CPU->rcu.is_delaying_gp = true;
1419 /*
1420 * Set signal_unlock only after setting is_delaying_gp so
1421 * that NMI handlers do not accidentally clear it in unlock()
1422 * before seeing and acting upon is_delaying_gp.
1423 */
1424 compiler_barrier();
1425 CPU->rcu.signal_unlock = true;
1426
1427 atomic_inc(&rcu.delaying_cpu_cnt);
1428 } else {
1429 /*
1430 * The cpu did not enter any rcu reader sections since
1431 * the start of the current GP. Record a quiescent state.
1432 *
1433 * Or, we interrupted rcu_read_unlock_impl() right before
1434 * it recorded a QS. Record a QS for it. The memory barrier
1435 * contains the reader section's mem accesses before
1436 * updating last_seen_gp.
1437 *
1438 * Or, we interrupted rcu_read_lock() right after it recorded
1439 * a QS for the previous GP but before it got a chance to
1440 * increment its nesting count. The memory barrier again
1441 * stops the CS code from spilling out of the CS.
1442 */
1443 memory_barrier();
1444 CPU->rcu.last_seen_gp = _rcu_cur_gp;
1445 }
1446 } else {
1447 /*
1448 * This cpu already acknowledged that it had passed through
1449 * a quiescent state since the start of cur_gp.
1450 */
1451 }
1452
1453 /*
1454 * smp_call() makes sure any changes propagate back to the caller.
1455 * In particular, it makes the most current last_seen_gp visible
1456 * to the detector.
1457 */
1458}
1459
1460/** Waits for cpus delaying the current grace period if there are any. */
1461static bool wait_for_delaying_cpus(void)
1462{
1463 int delaying_cpu_cnt = atomic_get(&rcu.delaying_cpu_cnt);
1464
1465 for (int i = 0; i < delaying_cpu_cnt; ++i){
1466 if (!semaphore_down_interruptable(&rcu.remaining_readers))
1467 return false;
1468 }
1469
1470 /* Update statistic. */
1471 rcu.stat_delayed_cnt += delaying_cpu_cnt;
1472
1473 return true;
1474}
1475
1476/** Called by the scheduler() when switching away from the current thread. */
1477void rcu_after_thread_ran(void)
1478{
1479 ASSERT(interrupts_disabled());
1480 /* todo: make is_delaying_gp and was_preempted NMI safe via local atomics.*/
1481
1482 /*
1483 * Prevent NMI handlers from interfering. The detector will be notified
1484 * here if CPU->rcu.is_delaying_gp and the current thread is no longer
1485 * running so there is nothing to signal to the detector.
1486 */
1487 CPU->rcu.signal_unlock = false;
1488 /* Separates clearing of .signal_unlock from CPU->rcu.nesting_cnt = 0. */
1489 compiler_barrier();
1490
1491 /* Save the thread's nesting count when it is not running. */
1492 THREAD->rcu.nesting_cnt = CPU->rcu.nesting_cnt;
1493 /* Interrupt handlers might use RCU while idle in scheduler(). */
1494 CPU->rcu.nesting_cnt = 0;
1495
1496 /* Preempted a reader critical section for the first time. */
1497 if (0 < THREAD->rcu.nesting_cnt && !THREAD->rcu.was_preempted) {
1498 THREAD->rcu.was_preempted = true;
1499 note_preempted_reader();
1500 }
1501
1502 /*
1503 * The preempted reader has been noted globally. There are therefore
1504 * no readers running on this cpu so this is a quiescent state.
1505 */
1506 _rcu_record_qs();
1507
1508 /*
1509 * This cpu is holding up the current GP. Let the detector know
1510 * it has just passed a quiescent state.
1511 *
1512 * The detector waits separately for preempted readers, so we have
1513 * to notify the detector even if we have just preempted a reader.
1514 */
1515 if (CPU->rcu.is_delaying_gp) {
1516 CPU->rcu.is_delaying_gp = false;
1517 semaphore_up(&rcu.remaining_readers);
1518 }
1519
1520 /*
1521 * Forcefully associate the detector with the highest priority
1522 * even if preempted due to its time slice running out.
1523 *
1524 * todo: Replace with strict scheduler priority classes.
1525 */
1526 if (THREAD == rcu.detector_thr) {
1527 THREAD->priority = -1;
1528 }
1529 else if (THREAD == CPU->rcu.reclaimer_thr) {
1530 THREAD->priority = -1;
1531 }
1532
1533 upd_max_cbs_in_slice();
1534}
1535
1536/** Called by the scheduler() when switching to a newly scheduled thread. */
1537void rcu_before_thread_runs(void)
1538{
1539 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
1540 ASSERT(0 == CPU->rcu.nesting_cnt);
1541
1542 /* Load the thread's saved nesting count from before it was preempted. */
1543 CPU->rcu.nesting_cnt = THREAD->rcu.nesting_cnt;
1544 /*
1545 * In the unlikely event that a NMI occurs between the loading of the
1546 * variables and setting signal_unlock, the NMI handler may invoke
1547 * rcu_read_unlock() and clear signal_unlock. In that case we will
1548 * incorrectly overwrite signal_unlock from false to true. This event
1549 * situation benign and the next rcu_read_unlock() will at worst
1550 * needlessly invoke _rcu_signal_unlock().
1551 */
1552 CPU->rcu.signal_unlock = THREAD->rcu.was_preempted || CPU->rcu.is_delaying_gp;
1553}
1554
1555/** Called from scheduler() when exiting the current thread.
1556 *
1557 * Preemption or interrupts are disabled and the scheduler() already
1558 * switched away from the current thread, calling rcu_after_thread_ran().
1559 */
1560void rcu_thread_exiting(void)
1561{
1562 ASSERT(THREAD != NULL);
1563 ASSERT(THREAD->state == Exiting);
1564 ASSERT(PREEMPTION_DISABLED || interrupts_disabled());
1565
1566 /*
1567 * The thread forgot to exit its reader critical section.
1568 * It is a bug, but rather than letting the entire system lock up
1569 * forcefully leave the reader section. The thread is not holding
1570 * any references anyway since it is exiting so it is safe.
1571 */
1572 if (0 < THREAD->rcu.nesting_cnt) {
1573 THREAD->rcu.nesting_cnt = 1;
1574 read_unlock_impl(&THREAD->rcu.nesting_cnt);
1575
1576 printf("Bug: thread (id %" PRIu64 " \"%s\") exited while in RCU read"
1577 " section.\n", THREAD->tid, THREAD->name);
1578 }
1579}
1580
1581
1582#endif /* RCU_PREEMPT_PODZIMEK */
1583
1584/** Announces the start of a new grace period for preexisting readers to ack. */
1585static void start_new_gp(void)
1586{
1587 ASSERT(spinlock_locked(&rcu.gp_lock));
1588
1589 irq_spinlock_lock(&rcu.preempt_lock, true);
1590
1591 /* Start a new GP. Announce to readers that a quiescent state is needed. */
1592 ++_rcu_cur_gp;
1593
1594 /*
1595 * Readers preempted before the start of this GP (next_preempted)
1596 * are preexisting readers now that a GP started and will hold up
1597 * the current GP until they exit their reader sections.
1598 *
1599 * Preempted readers from the previous GP have finished so
1600 * cur_preempted is empty, but see comment in _rcu_record_qs().
1601 */
1602 list_concat(&rcu.cur_preempted, &rcu.next_preempted);
1603
1604 irq_spinlock_unlock(&rcu.preempt_lock, true);
1605}
1606
1607/** Remove those cpus from the mask that have already passed a quiescent
1608 * state since the start of the current grace period.
1609 */
1610static void rm_quiescent_cpus(cpu_mask_t *cpu_mask)
1611{
1612 /*
1613 * Ensure the announcement of the start of a new GP (ie up-to-date
1614 * cur_gp) propagates to cpus that are just coming out of idle
1615 * mode before we sample their idle state flag.
1616 *
1617 * Cpus guarantee that after they set CPU->idle = true they will not
1618 * execute any RCU reader sections without first setting idle to
1619 * false and issuing a memory barrier. Therefore, if rm_quiescent_cpus()
1620 * later on sees an idle cpu, but the cpu is just exiting its idle mode,
1621 * the cpu must not have yet executed its memory barrier (otherwise
1622 * it would pair up with this mem barrier and we would see idle == false).
1623 * That memory barrier will pair up with the one below and ensure
1624 * that a reader on the now-non-idle cpu will see the most current
1625 * cur_gp. As a result, such a reader will never attempt to semaphore_up(
1626 * pending_readers) during this GP, which allows the detector to
1627 * ignore that cpu (the detector thinks it is idle). Moreover, any
1628 * changes made by RCU updaters will have propagated to readers
1629 * on the previously idle cpu -- again thanks to issuing a memory
1630 * barrier after returning from idle mode.
1631 *
1632 * idle -> non-idle cpu | detector | reclaimer
1633 * ------------------------------------------------------
1634 * rcu reader 1 | | rcu_call()
1635 * MB X | |
1636 * idle = true | | rcu_call()
1637 * (no rcu readers allowed ) | | MB A in advance_cbs()
1638 * MB Y | (...) | (...)
1639 * (no rcu readers allowed) | | MB B in advance_cbs()
1640 * idle = false | ++cur_gp |
1641 * (no rcu readers allowed) | MB C |
1642 * MB Z | signal gp_end |
1643 * rcu reader 2 | | exec_cur_cbs()
1644 *
1645 *
1646 * MB Y orders visibility of changes to idle for detector's sake.
1647 *
1648 * MB Z pairs up with MB C. The cpu making a transition from idle
1649 * will see the most current value of cur_gp and will not attempt
1650 * to notify the detector even if preempted during this GP.
1651 *
1652 * MB Z pairs up with MB A from the previous batch. Updaters' changes
1653 * are visible to reader 2 even when the detector thinks the cpu is idle
1654 * but it is not anymore.
1655 *
1656 * MB X pairs up with MB B. Late mem accesses of reader 1 are contained
1657 * and visible before idling and before any callbacks are executed
1658 * by reclaimers.
1659 *
1660 * In summary, the detector does not know of or wait for reader 2, but
1661 * it does not have to since it is a new reader that will not access
1662 * data from previous GPs and will see any changes.
1663 */
1664 memory_barrier(); /* MB C */
1665
1666 cpu_mask_for_each(*cpu_mask, cpu_id) {
1667 /*
1668 * The cpu already checked for and passed through a quiescent
1669 * state since the beginning of this GP.
1670 *
1671 * _rcu_cur_gp is modified by local detector thread only.
1672 * Therefore, it is up-to-date even without a lock.
1673 *
1674 * cpu.last_seen_gp may not be up-to-date. At worst, we will
1675 * unnecessarily sample its last_seen_gp with a smp_call.
1676 */
1677 bool cpu_acked_gp = (cpus[cpu_id].rcu.last_seen_gp == _rcu_cur_gp);
1678
1679 /*
1680 * Either the cpu is idle or it is exiting away from idle mode
1681 * and already sees the most current _rcu_cur_gp. See comment
1682 * in wait_for_readers().
1683 */
1684 bool cpu_idle = cpus[cpu_id].idle;
1685
1686 if (cpu_acked_gp || cpu_idle) {
1687 cpu_mask_reset(cpu_mask, cpu_id);
1688 }
1689 }
1690}
1691
1692/** Serially invokes sample_local_cpu(arg) on each cpu of reader_cpus. */
1693static void sample_cpus(cpu_mask_t *reader_cpus, void *arg)
1694{
1695 cpu_mask_for_each(*reader_cpus, cpu_id) {
1696 smp_call(cpu_id, sample_local_cpu, arg);
1697
1698 /* Update statistic. */
1699 if (CPU->id != cpu_id)
1700 ++rcu.stat_smp_call_cnt;
1701 }
1702}
1703
1704static void upd_missed_gp_in_wait(rcu_gp_t completed_gp)
1705{
1706 ASSERT(CPU->rcu.cur_cbs_gp <= completed_gp);
1707
1708 size_t delta = (size_t)(completed_gp - CPU->rcu.cur_cbs_gp);
1709 CPU->rcu.stat_missed_gp_in_wait += delta;
1710}
1711
1712/** Globally note that the current thread was preempted in a reader section. */
1713static void note_preempted_reader(void)
1714{
1715 irq_spinlock_lock(&rcu.preempt_lock, false);
1716
1717 if (CPU->rcu.last_seen_gp != _rcu_cur_gp) {
1718 /* The reader started before the GP started - we must wait for it.*/
1719 list_append(&THREAD->rcu.preempt_link, &rcu.cur_preempted);
1720 } else {
1721 /*
1722 * The reader started after the GP started and this cpu
1723 * already noted a quiescent state. We might block the next GP.
1724 */
1725 list_append(&THREAD->rcu.preempt_link, &rcu.next_preempted);
1726 }
1727
1728 irq_spinlock_unlock(&rcu.preempt_lock, false);
1729}
1730
1731/** Remove the current thread from the global list of preempted readers. */
1732static void rm_preempted_reader(void)
1733{
1734 irq_spinlock_lock(&rcu.preempt_lock, false);
1735
1736 ASSERT(link_used(&THREAD->rcu.preempt_link));
1737
1738 bool prev_empty = list_empty(&rcu.cur_preempted);
1739 list_remove(&THREAD->rcu.preempt_link);
1740 bool now_empty = list_empty(&rcu.cur_preempted);
1741
1742 /* This was the last reader in cur_preempted. */
1743 bool last_removed = now_empty && !prev_empty;
1744
1745 /*
1746 * Preempted readers are blocking the detector and
1747 * this was the last reader blocking the current GP.
1748 */
1749 if (last_removed && rcu.preempt_blocking_det) {
1750 rcu.preempt_blocking_det = false;
1751 semaphore_up(&rcu.remaining_readers);
1752 }
1753
1754 irq_spinlock_unlock(&rcu.preempt_lock, false);
1755}
1756
1757/** Waits for any preempted readers blocking this grace period to finish.*/
1758static bool wait_for_preempt_reader(void)
1759{
1760 irq_spinlock_lock(&rcu.preempt_lock, true);
1761
1762 bool reader_exists = !list_empty(&rcu.cur_preempted);
1763 rcu.preempt_blocking_det = reader_exists;
1764
1765 irq_spinlock_unlock(&rcu.preempt_lock, true);
1766
1767 if (reader_exists) {
1768 /* Update statistic. */
1769 ++rcu.stat_preempt_blocking_cnt;
1770
1771 return semaphore_down_interruptable(&rcu.remaining_readers);
1772 }
1773
1774 return true;
1775}
1776
1777static void upd_max_cbs_in_slice(void)
1778{
1779 rcu_cpu_data_t *cr = &CPU->rcu;
1780
1781 if (cr->arriving_cbs_cnt > cr->last_arriving_cnt) {
1782 size_t arrived_cnt = cr->arriving_cbs_cnt - cr->last_arriving_cnt;
1783 cr->stat_max_slice_cbs = max(arrived_cnt, cr->stat_max_slice_cbs);
1784 }
1785
1786 cr->last_arriving_cnt = cr->arriving_cbs_cnt;
1787}
1788
1789/** Prints RCU run-time statistics. */
1790void rcu_print_stat(void)
1791{
1792 /*
1793 * Don't take locks. Worst case is we get out-dated values.
1794 * CPU local values are updated without any locks, so there
1795 * are no locks to lock in order to get up-to-date values.
1796 */
1797
1798#ifdef RCU_PREEMPT_PODZIMEK
1799 const char *algo = "podzimek-preempt-rcu";
1800#elif defined(RCU_PREEMPT_A)
1801 const char *algo = "a-preempt-rcu";
1802#endif
1803
1804 printf("Config: expedite_threshold=%d, critical_threshold=%d,"
1805 " detect_sleep=%dms, %s\n",
1806 EXPEDITE_THRESHOLD, CRITICAL_THRESHOLD, DETECT_SLEEP_MS, algo);
1807 printf("Completed GPs: %" PRIu64 "\n", rcu.completed_gp);
1808 printf("Expedited GPs: %zu\n", rcu.stat_expedited_cnt);
1809 printf("Delayed GPs: %zu (cpus w/ still running readers after gp sleep)\n",
1810 rcu.stat_delayed_cnt);
1811 printf("Preempt blocked GPs: %zu (waited for preempted readers; "
1812 "running or not)\n", rcu.stat_preempt_blocking_cnt);
1813 printf("Smp calls: %zu\n", rcu.stat_smp_call_cnt);
1814
1815 printf("Max arrived callbacks per GP and CPU:\n");
1816 for (unsigned int i = 0; i < config.cpu_count; ++i) {
1817 printf(" %zu", cpus[i].rcu.stat_max_cbs);
1818 }
1819
1820 printf("\nAvg arrived callbacks per GP and CPU (nonempty batches only):\n");
1821 for (unsigned int i = 0; i < config.cpu_count; ++i) {
1822 printf(" %zu", cpus[i].rcu.stat_avg_cbs);
1823 }
1824
1825 printf("\nMax arrived callbacks per time slice and CPU:\n");
1826 for (unsigned int i = 0; i < config.cpu_count; ++i) {
1827 printf(" %zu", cpus[i].rcu.stat_max_slice_cbs);
1828 }
1829
1830 printf("\nMissed GP notifications per CPU:\n");
1831 for (unsigned int i = 0; i < config.cpu_count; ++i) {
1832 printf(" %zu", cpus[i].rcu.stat_missed_gps);
1833 }
1834
1835 printf("\nMissed GP notifications per CPU while waking up:\n");
1836 for (unsigned int i = 0; i < config.cpu_count; ++i) {
1837 printf(" %zu", cpus[i].rcu.stat_missed_gp_in_wait);
1838 }
1839 printf("\n");
1840}
1841
1842/** @}
1843 */
Note: See TracBrowser for help on using the repository browser.