source: mainline/kernel/generic/src/synch/rcu.c@ 09ab0a9a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 09ab0a9a was 09ab0a9a, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Fix vertical spacing with new Ccheck revision.

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