2 * Copyright (c) 2013, 2014 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #define OVS_THREAD_H 1
22 #include <sys/types.h>
23 #include "ovs-atomic.h"
28 struct OVS_LOCKABLE ovs_mutex {
30 const char *where; /* NULL if and only if uninitialized. */
33 /* "struct ovs_mutex" initializer. */
34 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
35 #define OVS_MUTEX_INITIALIZER { PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, \
38 #define OVS_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, "<unlocked>" }
41 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
42 #define OVS_ADAPTIVE_MUTEX_INITIALIZER \
43 { PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP, NULL }
45 #define OVS_ADAPTIVE_MUTEX_INITIALIZER OVS_MUTEX_INITIALIZER
48 /* ovs_mutex functions analogous to pthread_mutex_*() functions.
50 * Most of these functions abort the process with an error message on any
51 * error. ovs_mutex_trylock() is an exception: it passes through a 0 or EBUSY
52 * return value to the caller and aborts on any other error. */
53 void ovs_mutex_init(const struct ovs_mutex *);
54 void ovs_mutex_init_recursive(const struct ovs_mutex *);
55 void ovs_mutex_init_adaptive(const struct ovs_mutex *);
56 void ovs_mutex_destroy(const struct ovs_mutex *);
57 void ovs_mutex_unlock(const struct ovs_mutex *mutex) OVS_RELEASES(mutex);
58 void ovs_mutex_lock_at(const struct ovs_mutex *mutex, const char *where)
60 #define ovs_mutex_lock(mutex) \
61 ovs_mutex_lock_at(mutex, SOURCE_LOCATOR)
63 int ovs_mutex_trylock_at(const struct ovs_mutex *mutex, const char *where)
64 OVS_TRY_LOCK(0, mutex);
65 #define ovs_mutex_trylock(mutex) \
66 ovs_mutex_trylock_at(mutex, SOURCE_LOCATOR)
68 void ovs_mutex_cond_wait(pthread_cond_t *, const struct ovs_mutex *);
70 /* Wrappers for pthread_mutex_*() that abort the process on any error.
71 * This is still needed when ovs-atomic-pthreads.h is used. */
72 void xpthread_mutex_lock(pthread_mutex_t *mutex);
73 void xpthread_mutex_unlock(pthread_mutex_t *mutex);
75 /* Wrappers for pthread_mutexattr_*() that abort the process on any error. */
76 void xpthread_mutexattr_init(pthread_mutexattr_t *);
77 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
78 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
79 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
83 * An ovs_rwlock does not support recursive readers, because POSIX allows
84 * taking the reader lock recursively to deadlock when a thread is waiting on
85 * the write-lock. (NetBSD does deadlock.) glibc rwlocks in their default
86 * configuration do not deadlock, but ovs_rwlock_init() initializes rwlocks as
87 * non-recursive (which will deadlock) for two reasons:
89 * - glibc only provides fairness to writers in this mode.
91 * - It's better to find bugs in the primary Open vSwitch target rather
92 * than exposing them only to porters. */
93 struct OVS_LOCKABLE ovs_rwlock {
94 pthread_rwlock_t lock;
95 const char *where; /* NULL if and only if uninitialized. */
99 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
100 #define OVS_RWLOCK_INITIALIZER \
101 { PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP, "<unlocked>" }
103 #define OVS_RWLOCK_INITIALIZER { PTHREAD_RWLOCK_INITIALIZER, "<unlocked>" }
106 /* ovs_rwlock functions analogous to pthread_rwlock_*() functions.
108 * Most of these functions abort the process with an error message on any
109 * error. The "trylock" functions are exception: they pass through a 0 or
110 * EBUSY return value to the caller and abort on any other error. */
111 void ovs_rwlock_init(const struct ovs_rwlock *);
112 void ovs_rwlock_destroy(const struct ovs_rwlock *);
113 void ovs_rwlock_unlock(const struct ovs_rwlock *rwlock) OVS_RELEASES(rwlock);
115 /* Wrappers for pthread_rwlockattr_*() that abort the process on any error. */
116 void xpthread_rwlockattr_init(pthread_rwlockattr_t *);
117 void xpthread_rwlockattr_destroy(pthread_rwlockattr_t *);
118 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
119 void xpthread_rwlockattr_setkind_np(pthread_rwlockattr_t *, int kind);
122 void ovs_rwlock_wrlock_at(const struct ovs_rwlock *rwlock, const char *where)
123 OVS_ACQ_WRLOCK(rwlock);
124 #define ovs_rwlock_wrlock(rwlock) \
125 ovs_rwlock_wrlock_at(rwlock, SOURCE_LOCATOR)
127 int ovs_rwlock_trywrlock_at(const struct ovs_rwlock *rwlock, const char *where)
128 OVS_TRY_WRLOCK(0, rwlock);
129 #define ovs_rwlock_trywrlock(rwlock) \
130 ovs_rwlock_trywrlock_at(rwlock, SOURCE_LOCATOR)
132 void ovs_rwlock_rdlock_at(const struct ovs_rwlock *rwlock, const char *where)
133 OVS_ACQ_RDLOCK(rwlock);
134 #define ovs_rwlock_rdlock(rwlock) \
135 ovs_rwlock_rdlock_at(rwlock, SOURCE_LOCATOR)
137 int ovs_rwlock_tryrdlock_at(const struct ovs_rwlock *rwlock, const char *where)
138 OVS_TRY_RDLOCK(0, rwlock);
139 #define ovs_rwlock_tryrdlock(rwlock) \
140 ovs_rwlock_tryrdlock_at(rwlock, SOURCE_LOCATOR)
142 /* Wrappers for xpthread_cond_*() that abort the process on any error.
144 * Use ovs_mutex_cond_wait() to wait for a condition. */
145 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
146 void xpthread_cond_destroy(pthread_cond_t *);
147 void xpthread_cond_signal(pthread_cond_t *);
148 void xpthread_cond_broadcast(pthread_cond_t *);
150 /* Wrappers for pthread_barrier_*() that abort the process on any error. */
151 void xpthread_barrier_init(pthread_barrier_t *, pthread_barrierattr_t *,
153 int xpthread_barrier_wait(pthread_barrier_t *);
154 void xpthread_barrier_destroy(pthread_barrier_t *);
156 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
157 void xpthread_key_delete(pthread_key_t);
158 void xpthread_setspecific(pthread_key_t, const void *);
160 pthread_t ovs_thread_create(const char *name, void *(*)(void *), void *);
161 void xpthread_join(pthread_t, void **);
169 * Multiple forms of standard per-thread data exist, each with its own pluses
170 * and minuses. In general, if one of these forms is appropriate, then it's a
171 * good idea to use it:
173 * - POSIX per-thread data via pthread_key_t is portable to any pthreads
174 * implementation, and allows a destructor function to be defined. It
175 * only (directly) supports per-thread pointers, which are always
176 * initialized to NULL. It requires once-only allocation of a
177 * pthread_key_t value. It is relatively slow. Typically few
178 * "pthread_key_t"s are available (POSIX requires only at least 128,
179 * glibc supplies only 1024).
181 * - The thread_local feature newly defined in C11 <threads.h> works with
182 * any data type and initializer, and it is fast. thread_local does not
183 * require once-only initialization like pthread_key_t. C11 does not
184 * define what happens if one attempts to access a thread_local object
185 * from a thread other than the one to which that object belongs. There
186 * is no provision to call a user-specified destructor when a thread
187 * ends. Typical implementations allow for an arbitrary amount of
188 * thread_local storage, but statically allocated only.
190 * - The __thread keyword is a GCC extension similar to thread_local but
191 * with a longer history. __thread is not portable to every GCC version
192 * or environment. __thread does not restrict the use of a thread-local
193 * object outside its own thread.
195 * Here's a handy summary:
197 * pthread_key_t thread_local __thread
198 * ------------- ------------ -------------
199 * portability high low medium
200 * speed low high high
201 * supports destructors? yes no no
202 * needs key allocation? yes no no
203 * arbitrary initializer? no yes yes
204 * cross-thread access? yes no yes
205 * amount available? few arbitrary arbitrary
206 * dynamically allocated? yes no no
212 * OVS provides some extensions and wrappers:
214 * - In a situation where the performance of thread_local or __thread is
215 * desirable, but portability is required, DEFINE_STATIC_PER_THREAD_DATA
216 * and DECLARE_EXTERN_PER_THREAD_DATA/DEFINE_EXTERN_PER_THREAD_DATA may
217 * be appropriate (see below).
219 * - DEFINE_PER_THREAD_MALLOCED_DATA can be convenient for simple
220 * per-thread malloc()'d buffers.
222 * - struct ovs_tsd provides an alternative to pthread_key_t that isn't
223 * limited to a small number of keys.
226 /* For static data, use this macro in a source file:
228 * DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
230 * For global data, "declare" the data in the header and "define" it in
231 * the source file, with:
233 * DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME).
234 * DEFINE_EXTERN_PER_THREAD_DATA(NAME, INITIALIZER).
236 * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
237 * performance is acceptable, because of its portability (see the table above).
238 * This macro is an alternatives that takes advantage of thread_local (and
239 * __thread), for its performance, when it is available, and falls back to
240 * POSIX per-thread data otherwise.
242 * Defines per-thread variable NAME with the given TYPE, initialized to
243 * INITIALIZER (which must be valid as an initializer for a variable with
246 * The public interface to the variable is:
248 * TYPE *NAME_get(void)
249 * TYPE *NAME_get_unsafe(void)
251 * Returns the address of this thread's instance of NAME.
253 * Use NAME_get() in a context where this might be the first use of the
254 * per-thread variable in the program. Use NAME_get_unsafe(), which
255 * avoids a conditional test and is thus slightly faster, in a context
256 * where one knows that NAME_get() has already been called previously.
258 * There is no "NAME_set()" (or "NAME_set_unsafe()") function. To set the
259 * value of the per-thread variable, dereference the pointer returned by
260 * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
262 #if HAVE_THREAD_LOCAL || HAVE___THREAD
264 #if HAVE_THREAD_LOCAL
267 #define thread_local __thread
272 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
273 typedef TYPE NAME##_type; \
275 static NAME##_type * \
276 NAME##_get_unsafe(void) \
278 static thread_local NAME##_type var = __VA_ARGS__; \
282 static NAME##_type * \
285 return NAME##_get_unsafe(); \
287 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
288 typedef TYPE NAME##_type; \
289 extern thread_local NAME##_type NAME##_var; \
291 static inline NAME##_type * \
292 NAME##_get_unsafe(void) \
294 return &NAME##_var; \
297 static inline NAME##_type * \
300 return NAME##_get_unsafe(); \
302 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
303 thread_local NAME##_type NAME##_var = __VA_ARGS__;
304 #else /* no C implementation support for thread-local storage */
305 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
306 typedef TYPE NAME##_type; \
307 static pthread_key_t NAME##_key; \
309 static NAME##_type * \
310 NAME##_get_unsafe(void) \
312 return pthread_getspecific(NAME##_key); \
316 NAME##_once_init(void) \
318 if (pthread_key_create(&NAME##_key, free)) { \
323 static NAME##_type * \
326 static pthread_once_t once = PTHREAD_ONCE_INIT; \
327 NAME##_type *value; \
329 pthread_once(&once, NAME##_once_init); \
330 value = NAME##_get_unsafe(); \
332 static const NAME##_type initial_value = __VA_ARGS__; \
334 value = malloc(sizeof *value); \
335 if (value == NULL) { \
338 *value = initial_value; \
339 xpthread_setspecific(NAME##_key, value); \
343 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
344 typedef TYPE NAME##_type; \
345 static pthread_key_t NAME##_key; \
347 static inline NAME##_type * \
348 NAME##_get_unsafe(void) \
350 return pthread_getspecific(NAME##_key); \
353 NAME##_type *NAME##_get(void);
354 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
356 NAME##_once_init(void) \
358 if (pthread_key_create(&NAME##_key, free)) { \
366 static pthread_once_t once = PTHREAD_ONCE_INIT; \
367 NAME##_type *value; \
369 pthread_once(&once, NAME##_once_init); \
370 value = NAME##_get_unsafe(); \
372 static const NAME##_type initial_value = __VA_ARGS__; \
374 value = malloc(sizeof *value); \
375 if (value == NULL) { \
378 *value = initial_value; \
379 xpthread_setspecific(NAME##_key, value); \
385 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
387 * This is a simple wrapper around POSIX per-thread data primitives. It
388 * defines per-thread variable NAME with the given TYPE, which must be a
389 * pointer type. In each thread, the per-thread variable is initialized to
390 * NULL. When a thread terminates, the variable is freed with free().
392 * The public interface to the variable is:
394 * TYPE NAME_get(void)
395 * TYPE NAME_get_unsafe(void)
397 * Returns the value of per-thread variable NAME in this thread.
399 * Use NAME_get() in a context where this might be the first use of the
400 * per-thread variable in the program. Use NAME_get_unsafe(), which
401 * avoids a conditional test and is thus slightly faster, in a context
402 * where one knows that NAME_get() has already been called previously.
404 * TYPE NAME_set(TYPE new_value)
405 * TYPE NAME_set_unsafe(TYPE new_value)
407 * Sets the value of per-thread variable NAME to 'new_value' in this
408 * thread, and returns its previous value.
410 * Use NAME_set() in a context where this might be the first use of the
411 * per-thread variable in the program. Use NAME_set_unsafe(), which
412 * avoids a conditional test and is thus slightly faster, in a context
413 * where one knows that NAME_set() has already been called previously.
415 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME) \
416 static pthread_key_t NAME##_key; \
419 NAME##_once_init(void) \
421 if (pthread_key_create(&NAME##_key, free)) { \
429 static pthread_once_t once = PTHREAD_ONCE_INIT; \
430 pthread_once(&once, NAME##_once_init); \
434 NAME##_get_unsafe(void) \
436 return pthread_getspecific(NAME##_key); \
439 static OVS_UNUSED TYPE \
443 return NAME##_get_unsafe(); \
447 NAME##_set_unsafe(TYPE value) \
449 TYPE old_value = NAME##_get_unsafe(); \
450 xpthread_setspecific(NAME##_key, value); \
454 static OVS_UNUSED TYPE \
455 NAME##_set(TYPE value) \
458 return NAME##_set_unsafe(value); \
461 /* Dynamically allocated thread-specific data with lots of slots.
463 * pthread_key_t can provide as few as 128 pieces of thread-specific data (even
464 * glibc is limited to 1,024). Thus, one must be careful to allocate only a
465 * few keys globally. One cannot, for example, allocate a key for every
466 * instance of a data structure if there might be an arbitrary number of those
469 * This API is similar to the pthread one (simply search and replace pthread_
470 * by ovsthread_) but it a much larger limit that can be raised if necessary
471 * (by recompiling). Thus, one may more freely use this form of
472 * thread-specific data.
474 * ovsthread_key_t also differs from pthread_key_t in the following ways:
476 * - Destructors must not access thread-specific data (via ovsthread_key).
478 * - The pthread_key_t API allows concurrently exiting threads to start
479 * executing the destructor after pthread_key_delete() returns. The
480 * ovsthread_key_t API guarantees that, when ovsthread_key_delete()
481 * returns, all destructors have returned and no new ones will start
484 typedef struct ovsthread_key *ovsthread_key_t;
486 void ovsthread_key_create(ovsthread_key_t *, void (*destructor)(void *));
487 void ovsthread_key_delete(ovsthread_key_t);
489 void ovsthread_setspecific(ovsthread_key_t, const void *);
490 void *ovsthread_getspecific(ovsthread_key_t);
492 /* Convenient once-only execution.
498 * POSIX provides pthread_once_t and pthread_once() as primitives for running a
499 * set of code only once per process execution. They are used like this:
501 * static void run_once(void) { ...initialization... }
502 * static pthread_once_t once = PTHREAD_ONCE_INIT;
504 * pthread_once(&once, run_once);
506 * pthread_once() does not allow passing any parameters to the initialization
507 * function, which is often inconvenient, because it means that the function
508 * can only access data declared at file scope.
514 * Use ovsthread_once, like this, instead:
516 * static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
518 * if (ovsthread_once_start(&once)) {
519 * ...initialization...
520 * ovsthread_once_done(&once);
524 struct ovsthread_once {
526 struct ovs_mutex mutex;
529 #define OVSTHREAD_ONCE_INITIALIZER \
531 ATOMIC_VAR_INIT(false), \
532 OVS_MUTEX_INITIALIZER, \
535 static inline bool ovsthread_once_start(struct ovsthread_once *once)
536 OVS_TRY_LOCK(true, once->mutex);
537 void ovsthread_once_done(struct ovsthread_once *once)
538 OVS_RELEASES(once->mutex);
540 bool ovsthread_once_start__(struct ovsthread_once *once)
541 OVS_TRY_LOCK(false, once->mutex);
544 ovsthread_once_is_done__(struct ovsthread_once *once)
548 atomic_read_explicit(&once->done, &done, memory_order_relaxed);
552 /* Returns true if this is the first call to ovsthread_once_start() for
553 * 'once'. In this case, the caller should perform whatever initialization
554 * actions it needs to do, then call ovsthread_once_done() for 'once'.
556 * Returns false if this is not the first call to ovsthread_once_start() for
557 * 'once'. In this case, the call will not return until after
558 * ovsthread_once_done() has been called. */
560 ovsthread_once_start(struct ovsthread_once *once)
562 return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
563 && !ovsthread_once_start__(once));
568 * pthread_t isn't so nice for some purposes. Its size and representation are
569 * implementation dependent, which means that there is no way to hash it.
570 * This thread ID avoids the problem.
573 DECLARE_EXTERN_PER_THREAD_DATA(unsigned int, ovsthread_id);
575 /* Returns a per-thread identifier unique within the lifetime of the
577 static inline unsigned int
578 ovsthread_id_self(void)
580 return *ovsthread_id_get();
583 /* Simulated global counter.
585 * Incrementing such a counter is meant to be cheaper than incrementing a
586 * global counter protected by a lock. It is probably more expensive than
587 * incrementing a truly thread-local variable, but such a variable has no
588 * straightforward way to get the sum.
594 * Fully thread-safe. */
596 struct ovsthread_stats {
597 struct ovs_mutex mutex;
598 void *volatile buckets[16];
601 void ovsthread_stats_init(struct ovsthread_stats *);
602 void ovsthread_stats_destroy(struct ovsthread_stats *);
604 void *ovsthread_stats_bucket_get(struct ovsthread_stats *,
605 void *(*new_bucket)(void));
607 #define OVSTHREAD_STATS_FOR_EACH_BUCKET(BUCKET, IDX, STATS) \
608 for ((IDX) = ovs_thread_stats_next_bucket(STATS, 0); \
609 ((IDX) < ARRAY_SIZE((STATS)->buckets) \
610 ? ((BUCKET) = (STATS)->buckets[IDX], true) \
612 (IDX) = ovs_thread_stats_next_bucket(STATS, (IDX) + 1))
613 size_t ovs_thread_stats_next_bucket(const struct ovsthread_stats *, size_t);
615 bool single_threaded(void);
617 void assert_single_threaded_at(const char *where);
618 #define assert_single_threaded() assert_single_threaded_at(SOURCE_LOCATOR)
621 pid_t xfork_at(const char *where);
622 #define xfork() xfork_at(SOURCE_LOCATOR)
625 void forbid_forking(const char *reason);
628 /* Useful functions related to threading. */
630 int count_cpu_cores(void);
632 #endif /* ovs-thread.h */