4702ba9aea4c1bc55f180b658c28bc56c03dec96
[urcu.git] / urcu.c
1 /*
2 * urcu.c
3 *
4 * Userspace RCU library
5 *
6 * Copyright (c) 2009 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * Copyright (c) 2009 Paul E. McKenney, IBM Corporation.
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 *
23 * IBM's contributions to this file may be relicensed under LGPLv2 or later.
24 */
25
26 #define _BSD_SOURCE
27 #define _GNU_SOURCE
28 #define _LGPL_SOURCE
29 #define _DEFAULT_SOURCE
30 #include <stdio.h>
31 #include <pthread.h>
32 #include <signal.h>
33 #include <assert.h>
34 #include <stdlib.h>
35 #include <stdint.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <poll.h>
39
40 #include "urcu/wfcqueue.h"
41 #include "urcu/map/urcu.h"
42 #include "urcu/static/urcu.h"
43 #include "urcu-pointer.h"
44 #include "urcu/tls-compat.h"
45
46 #include "urcu-die.h"
47 #include "urcu-wait.h"
48
49 /* Do not #define _LGPL_SOURCE to ensure we can emit the wrapper symbols */
50 #undef _LGPL_SOURCE
51 #include "urcu.h"
52 #define _LGPL_SOURCE
53
54 /*
55 * If a reader is really non-cooperative and refuses to commit its
56 * rcu_active_readers count to memory (there is no barrier in the reader
57 * per-se), kick it after 10 loops waiting for it.
58 */
59 #define KICK_READER_LOOPS 10
60
61 /*
62 * Active attempts to check for reader Q.S. before calling futex().
63 */
64 #define RCU_QS_ACTIVE_ATTEMPTS 100
65
66 /*
67 * RCU_MEMBARRIER is only possibly available on Linux.
68 */
69 #if defined(RCU_MEMBARRIER) && defined(__linux__)
70 #include <urcu/syscall-compat.h>
71 #endif
72
73 /* If the headers do not support SYS_membarrier, fall back on RCU_MB */
74 #ifdef SYS_membarrier
75 # define membarrier(...) syscall(SYS_membarrier, __VA_ARGS__)
76 #else
77 # define membarrier(...) -ENOSYS
78 #endif
79
80 enum membarrier_cmd {
81 MEMBARRIER_CMD_QUERY = 0,
82 MEMBARRIER_CMD_SHARED = (1 << 0),
83 };
84
85 #ifdef RCU_MEMBARRIER
86 static int init_done;
87 int rcu_has_sys_membarrier;
88
89 void __attribute__((constructor)) rcu_init(void);
90 #endif
91
92 #ifdef RCU_MB
93 void rcu_init(void)
94 {
95 }
96 #endif
97
98 #ifdef RCU_SIGNAL
99 static int init_done;
100
101 void __attribute__((constructor)) rcu_init(void);
102 void __attribute__((destructor)) rcu_exit(void);
103 #endif
104
105 /*
106 * rcu_gp_lock ensures mutual exclusion between threads calling
107 * synchronize_rcu().
108 */
109 static pthread_mutex_t rcu_gp_lock = PTHREAD_MUTEX_INITIALIZER;
110 /*
111 * rcu_registry_lock ensures mutual exclusion between threads
112 * registering and unregistering themselves to/from the registry, and
113 * with threads reading that registry from synchronize_rcu(). However,
114 * this lock is not held all the way through the completion of awaiting
115 * for the grace period. It is sporadically released between iterations
116 * on the registry.
117 * rcu_registry_lock may nest inside rcu_gp_lock.
118 */
119 static pthread_mutex_t rcu_registry_lock = PTHREAD_MUTEX_INITIALIZER;
120 struct rcu_gp rcu_gp = { .ctr = RCU_GP_COUNT };
121
122 /*
123 * Written to only by each individual reader. Read by both the reader and the
124 * writers.
125 */
126 DEFINE_URCU_TLS(struct rcu_reader, rcu_reader);
127
128 static CDS_LIST_HEAD(registry);
129
130 /*
131 * Queue keeping threads awaiting to wait for a grace period. Contains
132 * struct gp_waiters_thread objects.
133 */
134 static DEFINE_URCU_WAIT_QUEUE(gp_waiters);
135
136 static void mutex_lock(pthread_mutex_t *mutex)
137 {
138 int ret;
139
140 #ifndef DISTRUST_SIGNALS_EXTREME
141 ret = pthread_mutex_lock(mutex);
142 if (ret)
143 urcu_die(ret);
144 #else /* #ifndef DISTRUST_SIGNALS_EXTREME */
145 while ((ret = pthread_mutex_trylock(mutex)) != 0) {
146 if (ret != EBUSY && ret != EINTR)
147 urcu_die(ret);
148 if (CMM_LOAD_SHARED(URCU_TLS(rcu_reader).need_mb)) {
149 cmm_smp_mb();
150 _CMM_STORE_SHARED(URCU_TLS(rcu_reader).need_mb, 0);
151 cmm_smp_mb();
152 }
153 (void) poll(NULL, 0, 10);
154 }
155 #endif /* #else #ifndef DISTRUST_SIGNALS_EXTREME */
156 }
157
158 static void mutex_unlock(pthread_mutex_t *mutex)
159 {
160 int ret;
161
162 ret = pthread_mutex_unlock(mutex);
163 if (ret)
164 urcu_die(ret);
165 }
166
167 #ifdef RCU_MEMBARRIER
168 static void smp_mb_master(int group)
169 {
170 if (caa_likely(rcu_has_sys_membarrier))
171 (void) membarrier(MEMBARRIER_CMD_SHARED, 0);
172 else
173 cmm_smp_mb();
174 }
175 #endif
176
177 #ifdef RCU_MB
178 static void smp_mb_master(int group)
179 {
180 cmm_smp_mb();
181 }
182 #endif
183
184 #ifdef RCU_SIGNAL
185 static void force_mb_all_readers(void)
186 {
187 struct rcu_reader *index;
188
189 /*
190 * Ask for each threads to execute a cmm_smp_mb() so we can consider the
191 * compiler barriers around rcu read lock as real memory barriers.
192 */
193 if (cds_list_empty(&registry))
194 return;
195 /*
196 * pthread_kill has a cmm_smp_mb(). But beware, we assume it performs
197 * a cache flush on architectures with non-coherent cache. Let's play
198 * safe and don't assume anything : we use cmm_smp_mc() to make sure the
199 * cache flush is enforced.
200 */
201 cds_list_for_each_entry(index, &registry, node) {
202 CMM_STORE_SHARED(index->need_mb, 1);
203 pthread_kill(index->tid, SIGRCU);
204 }
205 /*
206 * Wait for sighandler (and thus mb()) to execute on every thread.
207 *
208 * Note that the pthread_kill() will never be executed on systems
209 * that correctly deliver signals in a timely manner. However, it
210 * is not uncommon for kernels to have bugs that can result in
211 * lost or unduly delayed signals.
212 *
213 * If you are seeing the below pthread_kill() executing much at
214 * all, we suggest testing the underlying kernel and filing the
215 * relevant bug report. For Linux kernels, we recommend getting
216 * the Linux Test Project (LTP).
217 */
218 cds_list_for_each_entry(index, &registry, node) {
219 while (CMM_LOAD_SHARED(index->need_mb)) {
220 pthread_kill(index->tid, SIGRCU);
221 (void) poll(NULL, 0, 1);
222 }
223 }
224 cmm_smp_mb(); /* read ->need_mb before ending the barrier */
225 }
226
227 static void smp_mb_master(int group)
228 {
229 force_mb_all_readers();
230 }
231 #endif /* #ifdef RCU_SIGNAL */
232
233 /*
234 * synchronize_rcu() waiting. Single thread.
235 */
236 static void wait_gp(void)
237 {
238 /* Read reader_gp before read futex */
239 smp_mb_master(RCU_MB_GROUP);
240 if (uatomic_read(&rcu_gp.futex) != -1)
241 return;
242 while (futex_async(&rcu_gp.futex, FUTEX_WAIT, -1,
243 NULL, NULL, 0)) {
244 switch (errno) {
245 case EWOULDBLOCK:
246 /* Value already changed. */
247 return;
248 case EINTR:
249 /* Retry if interrupted by signal. */
250 break; /* Get out of switch. */
251 default:
252 /* Unexpected error. */
253 urcu_die(errno);
254 }
255 }
256 }
257
258 /*
259 * Always called with rcu_registry lock held. Releases this lock between
260 * iterations and grabs it again. Holds the lock when it returns.
261 */
262 static void wait_for_readers(struct cds_list_head *input_readers,
263 struct cds_list_head *cur_snap_readers,
264 struct cds_list_head *qsreaders)
265 {
266 unsigned int wait_loops = 0;
267 struct rcu_reader *index, *tmp;
268 #ifdef HAS_INCOHERENT_CACHES
269 unsigned int wait_gp_loops = 0;
270 #endif /* HAS_INCOHERENT_CACHES */
271
272 /*
273 * Wait for each thread URCU_TLS(rcu_reader).ctr to either
274 * indicate quiescence (not nested), or observe the current
275 * rcu_gp.ctr value.
276 */
277 for (;;) {
278 if (wait_loops < RCU_QS_ACTIVE_ATTEMPTS)
279 wait_loops++;
280 if (wait_loops >= RCU_QS_ACTIVE_ATTEMPTS) {
281 uatomic_dec(&rcu_gp.futex);
282 /* Write futex before read reader_gp */
283 smp_mb_master(RCU_MB_GROUP);
284 }
285
286 cds_list_for_each_entry_safe(index, tmp, input_readers, node) {
287 switch (rcu_reader_state(&index->ctr)) {
288 case RCU_READER_ACTIVE_CURRENT:
289 if (cur_snap_readers) {
290 cds_list_move(&index->node,
291 cur_snap_readers);
292 break;
293 }
294 /* Fall-through */
295 case RCU_READER_INACTIVE:
296 cds_list_move(&index->node, qsreaders);
297 break;
298 case RCU_READER_ACTIVE_OLD:
299 /*
300 * Old snapshot. Leaving node in
301 * input_readers will make us busy-loop
302 * until the snapshot becomes current or
303 * the reader becomes inactive.
304 */
305 break;
306 }
307 }
308
309 #ifndef HAS_INCOHERENT_CACHES
310 if (cds_list_empty(input_readers)) {
311 if (wait_loops >= RCU_QS_ACTIVE_ATTEMPTS) {
312 /* Read reader_gp before write futex */
313 smp_mb_master(RCU_MB_GROUP);
314 uatomic_set(&rcu_gp.futex, 0);
315 }
316 break;
317 } else {
318 /* Temporarily unlock the registry lock. */
319 mutex_unlock(&rcu_registry_lock);
320 if (wait_loops >= RCU_QS_ACTIVE_ATTEMPTS)
321 wait_gp();
322 else
323 caa_cpu_relax();
324 /* Re-lock the registry lock before the next loop. */
325 mutex_lock(&rcu_registry_lock);
326 }
327 #else /* #ifndef HAS_INCOHERENT_CACHES */
328 /*
329 * BUSY-LOOP. Force the reader thread to commit its
330 * URCU_TLS(rcu_reader).ctr update to memory if we wait
331 * for too long.
332 */
333 if (cds_list_empty(input_readers)) {
334 if (wait_loops >= RCU_QS_ACTIVE_ATTEMPTS) {
335 /* Read reader_gp before write futex */
336 smp_mb_master(RCU_MB_GROUP);
337 uatomic_set(&rcu_gp.futex, 0);
338 }
339 break;
340 } else {
341 if (wait_gp_loops == KICK_READER_LOOPS) {
342 smp_mb_master(RCU_MB_GROUP);
343 wait_gp_loops = 0;
344 }
345 /* Temporarily unlock the registry lock. */
346 mutex_unlock(&rcu_registry_lock);
347 if (wait_loops >= RCU_QS_ACTIVE_ATTEMPTS) {
348 wait_gp();
349 wait_gp_loops++;
350 } else {
351 caa_cpu_relax();
352 }
353 /* Re-lock the registry lock before the next loop. */
354 mutex_lock(&rcu_registry_lock);
355 }
356 #endif /* #else #ifndef HAS_INCOHERENT_CACHES */
357 }
358 }
359
360 void synchronize_rcu(void)
361 {
362 CDS_LIST_HEAD(cur_snap_readers);
363 CDS_LIST_HEAD(qsreaders);
364 DEFINE_URCU_WAIT_NODE(wait, URCU_WAIT_WAITING);
365 struct urcu_waiters waiters;
366
367 /*
368 * Add ourself to gp_waiters queue of threads awaiting to wait
369 * for a grace period. Proceed to perform the grace period only
370 * if we are the first thread added into the queue.
371 * The implicit memory barrier before urcu_wait_add()
372 * orders prior memory accesses of threads put into the wait
373 * queue before their insertion into the wait queue.
374 */
375 if (urcu_wait_add(&gp_waiters, &wait) != 0) {
376 /* Not first in queue: will be awakened by another thread. */
377 urcu_adaptative_busy_wait(&wait);
378 /* Order following memory accesses after grace period. */
379 cmm_smp_mb();
380 return;
381 }
382 /* We won't need to wake ourself up */
383 urcu_wait_set_state(&wait, URCU_WAIT_RUNNING);
384
385 mutex_lock(&rcu_gp_lock);
386
387 /*
388 * Move all waiters into our local queue.
389 */
390 urcu_move_waiters(&waiters, &gp_waiters);
391
392 mutex_lock(&rcu_registry_lock);
393
394 if (cds_list_empty(&registry))
395 goto out;
396
397 /*
398 * All threads should read qparity before accessing data structure
399 * where new ptr points to. Must be done within rcu_registry_lock
400 * because it iterates on reader threads.
401 */
402 /* Write new ptr before changing the qparity */
403 smp_mb_master(RCU_MB_GROUP);
404
405 /*
406 * Wait for readers to observe original parity or be quiescent.
407 * wait_for_readers() can release and grab again rcu_registry_lock
408 * interally.
409 */
410 wait_for_readers(&registry, &cur_snap_readers, &qsreaders);
411
412 /*
413 * Must finish waiting for quiescent state for original parity before
414 * committing next rcu_gp.ctr update to memory. Failure to do so could
415 * result in the writer waiting forever while new readers are always
416 * accessing data (no progress). Enforce compiler-order of load
417 * URCU_TLS(rcu_reader).ctr before store to rcu_gp.ctr.
418 */
419 cmm_barrier();
420
421 /*
422 * Adding a cmm_smp_mb() which is _not_ formally required, but makes the
423 * model easier to understand. It does not have a big performance impact
424 * anyway, given this is the write-side.
425 */
426 cmm_smp_mb();
427
428 /* Switch parity: 0 -> 1, 1 -> 0 */
429 CMM_STORE_SHARED(rcu_gp.ctr, rcu_gp.ctr ^ RCU_GP_CTR_PHASE);
430
431 /*
432 * Must commit rcu_gp.ctr update to memory before waiting for quiescent
433 * state. Failure to do so could result in the writer waiting forever
434 * while new readers are always accessing data (no progress). Enforce
435 * compiler-order of store to rcu_gp.ctr before load rcu_reader ctr.
436 */
437 cmm_barrier();
438
439 /*
440 *
441 * Adding a cmm_smp_mb() which is _not_ formally required, but makes the
442 * model easier to understand. It does not have a big performance impact
443 * anyway, given this is the write-side.
444 */
445 cmm_smp_mb();
446
447 /*
448 * Wait for readers to observe new parity or be quiescent.
449 * wait_for_readers() can release and grab again rcu_registry_lock
450 * interally.
451 */
452 wait_for_readers(&cur_snap_readers, NULL, &qsreaders);
453
454 /*
455 * Put quiescent reader list back into registry.
456 */
457 cds_list_splice(&qsreaders, &registry);
458
459 /*
460 * Finish waiting for reader threads before letting the old ptr
461 * being freed. Must be done within rcu_registry_lock because it
462 * iterates on reader threads.
463 */
464 smp_mb_master(RCU_MB_GROUP);
465 out:
466 mutex_unlock(&rcu_registry_lock);
467 mutex_unlock(&rcu_gp_lock);
468
469 /*
470 * Wakeup waiters only after we have completed the grace period
471 * and have ensured the memory barriers at the end of the grace
472 * period have been issued.
473 */
474 urcu_wake_all_waiters(&waiters);
475 }
476
477 /*
478 * library wrappers to be used by non-LGPL compatible source code.
479 */
480
481 void rcu_read_lock(void)
482 {
483 _rcu_read_lock();
484 }
485
486 void rcu_read_unlock(void)
487 {
488 _rcu_read_unlock();
489 }
490
491 int rcu_read_ongoing(void)
492 {
493 return _rcu_read_ongoing();
494 }
495
496 void rcu_register_thread(void)
497 {
498 URCU_TLS(rcu_reader).tid = pthread_self();
499 assert(URCU_TLS(rcu_reader).need_mb == 0);
500 assert(!(URCU_TLS(rcu_reader).ctr & RCU_GP_CTR_NEST_MASK));
501
502 mutex_lock(&rcu_registry_lock);
503 assert(!URCU_TLS(rcu_reader).registered);
504 URCU_TLS(rcu_reader).registered = 1;
505 rcu_init(); /* In case gcc does not support constructor attribute */
506 cds_list_add(&URCU_TLS(rcu_reader).node, &registry);
507 mutex_unlock(&rcu_registry_lock);
508 }
509
510 void rcu_unregister_thread(void)
511 {
512 mutex_lock(&rcu_registry_lock);
513 assert(URCU_TLS(rcu_reader).registered);
514 URCU_TLS(rcu_reader).registered = 0;
515 cds_list_del(&URCU_TLS(rcu_reader).node);
516 mutex_unlock(&rcu_registry_lock);
517 }
518
519 #ifdef RCU_MEMBARRIER
520 void rcu_init(void)
521 {
522 int ret;
523
524 if (init_done)
525 return;
526 init_done = 1;
527 ret = membarrier(MEMBARRIER_CMD_QUERY, 0);
528 if (ret >= 0 && (ret & MEMBARRIER_CMD_SHARED)) {
529 rcu_has_sys_membarrier = 1;
530 }
531 }
532 #endif
533
534 #ifdef RCU_SIGNAL
535 static void sigrcu_handler(int signo, siginfo_t *siginfo, void *context)
536 {
537 /*
538 * Executing this cmm_smp_mb() is the only purpose of this signal handler.
539 * It punctually promotes cmm_barrier() into cmm_smp_mb() on every thread it is
540 * executed on.
541 */
542 cmm_smp_mb();
543 _CMM_STORE_SHARED(URCU_TLS(rcu_reader).need_mb, 0);
544 cmm_smp_mb();
545 }
546
547 /*
548 * rcu_init constructor. Called when the library is linked, but also when
549 * reader threads are calling rcu_register_thread().
550 * Should only be called by a single thread at a given time. This is ensured by
551 * holing the rcu_registry_lock from rcu_register_thread() or by running
552 * at library load time, which should not be executed by multiple
553 * threads nor concurrently with rcu_register_thread() anyway.
554 */
555 void rcu_init(void)
556 {
557 struct sigaction act;
558 int ret;
559
560 if (init_done)
561 return;
562 init_done = 1;
563
564 act.sa_sigaction = sigrcu_handler;
565 act.sa_flags = SA_SIGINFO | SA_RESTART;
566 sigemptyset(&act.sa_mask);
567 ret = sigaction(SIGRCU, &act, NULL);
568 if (ret)
569 urcu_die(errno);
570 }
571
572 void rcu_exit(void)
573 {
574 /*
575 * Don't unregister the SIGRCU signal handler anymore, because
576 * call_rcu threads could still be using it shortly before the
577 * application exits.
578 * Assertion disabled because call_rcu threads are now rcu
579 * readers, and left running at exit.
580 * assert(cds_list_empty(&registry));
581 */
582 }
583
584 #endif /* #ifdef RCU_SIGNAL */
585
586 DEFINE_RCU_FLAVOR(rcu_flavor);
587
588 #include "urcu-call-rcu-impl.h"
589 #include "urcu-defer-impl.h"
This page took 0.0941 seconds and 3 git commands to generate.