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