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"
29 struct OVS_LOCKABLE ovs_mutex {
31 const char *where; /* NULL if and only if uninitialized. */
34 /* Poll-block()-able barrier similar to pthread_barrier_t. */
36 uint32_t size; /* Number of threads to wait. */
37 atomic_uint32_t count; /* Number of threads already hit the barrier. */
41 /* "struct ovs_mutex" initializer. */
42 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
43 #define OVS_MUTEX_INITIALIZER { PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, \
46 #define OVS_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, "<unlocked>" }
49 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
50 #define OVS_ADAPTIVE_MUTEX_INITIALIZER \
51 { PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP, "<unlocked>" }
53 #define OVS_ADAPTIVE_MUTEX_INITIALIZER OVS_MUTEX_INITIALIZER
56 /* ovs_mutex functions analogous to pthread_mutex_*() functions.
58 * Most of these functions abort the process with an error message on any
59 * error. ovs_mutex_trylock() is an exception: it passes through a 0 or EBUSY
60 * return value to the caller and aborts on any other error. */
61 void ovs_mutex_init(const struct ovs_mutex *);
62 void ovs_mutex_init_recursive(const struct ovs_mutex *);
63 void ovs_mutex_init_adaptive(const struct ovs_mutex *);
64 void ovs_mutex_destroy(const struct ovs_mutex *);
65 void ovs_mutex_unlock(const struct ovs_mutex *mutex) OVS_RELEASES(mutex);
66 void ovs_mutex_lock_at(const struct ovs_mutex *mutex, const char *where)
68 #define ovs_mutex_lock(mutex) \
69 ovs_mutex_lock_at(mutex, SOURCE_LOCATOR)
71 int ovs_mutex_trylock_at(const struct ovs_mutex *mutex, const char *where)
72 OVS_TRY_LOCK(0, mutex);
73 #define ovs_mutex_trylock(mutex) \
74 ovs_mutex_trylock_at(mutex, SOURCE_LOCATOR)
76 void ovs_mutex_cond_wait(pthread_cond_t *, const struct ovs_mutex *);
78 /* Wrappers for pthread_mutex_*() that abort the process on any error.
79 * This is still needed when ovs-atomic-pthreads.h is used. */
80 void xpthread_mutex_lock(pthread_mutex_t *mutex);
81 void xpthread_mutex_unlock(pthread_mutex_t *mutex);
83 /* Wrappers for pthread_mutexattr_*() that abort the process on any error. */
84 void xpthread_mutexattr_init(pthread_mutexattr_t *);
85 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
86 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
87 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
91 * An ovs_rwlock does not support recursive readers, because POSIX allows
92 * taking the reader lock recursively to deadlock when a thread is waiting on
93 * the write-lock. (NetBSD does deadlock.) glibc rwlocks in their default
94 * configuration do not deadlock, but ovs_rwlock_init() initializes rwlocks as
95 * non-recursive (which will deadlock) for two reasons:
97 * - glibc only provides fairness to writers in this mode.
99 * - It's better to find bugs in the primary Open vSwitch target rather
100 * than exposing them only to porters. */
101 struct OVS_LOCKABLE ovs_rwlock {
102 pthread_rwlock_t lock;
103 const char *where; /* NULL if and only if uninitialized. */
107 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
108 #define OVS_RWLOCK_INITIALIZER \
109 { PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP, "<unlocked>" }
111 #define OVS_RWLOCK_INITIALIZER { PTHREAD_RWLOCK_INITIALIZER, "<unlocked>" }
114 /* ovs_rwlock functions analogous to pthread_rwlock_*() functions.
116 * Most of these functions abort the process with an error message on any
117 * error. The "trylock" functions are exception: they pass through a 0 or
118 * EBUSY return value to the caller and abort on any other error. */
119 void ovs_rwlock_init(const struct ovs_rwlock *);
120 void ovs_rwlock_destroy(const struct ovs_rwlock *);
121 void ovs_rwlock_unlock(const struct ovs_rwlock *rwlock) OVS_RELEASES(rwlock);
123 /* Wrappers for pthread_rwlockattr_*() that abort the process on any error. */
124 void xpthread_rwlockattr_init(pthread_rwlockattr_t *);
125 void xpthread_rwlockattr_destroy(pthread_rwlockattr_t *);
126 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
127 void xpthread_rwlockattr_setkind_np(pthread_rwlockattr_t *, int kind);
130 void ovs_rwlock_wrlock_at(const struct ovs_rwlock *rwlock, const char *where)
131 OVS_ACQ_WRLOCK(rwlock);
132 #define ovs_rwlock_wrlock(rwlock) \
133 ovs_rwlock_wrlock_at(rwlock, SOURCE_LOCATOR)
135 int ovs_rwlock_trywrlock_at(const struct ovs_rwlock *rwlock, const char *where)
136 OVS_TRY_WRLOCK(0, rwlock);
137 #define ovs_rwlock_trywrlock(rwlock) \
138 ovs_rwlock_trywrlock_at(rwlock, SOURCE_LOCATOR)
140 void ovs_rwlock_rdlock_at(const struct ovs_rwlock *rwlock, const char *where)
141 OVS_ACQ_RDLOCK(rwlock);
142 #define ovs_rwlock_rdlock(rwlock) \
143 ovs_rwlock_rdlock_at(rwlock, SOURCE_LOCATOR)
145 int ovs_rwlock_tryrdlock_at(const struct ovs_rwlock *rwlock, const char *where)
146 OVS_TRY_RDLOCK(0, rwlock);
147 #define ovs_rwlock_tryrdlock(rwlock) \
148 ovs_rwlock_tryrdlock_at(rwlock, SOURCE_LOCATOR)
150 /* ovs_barrier functions analogous to pthread_barrier_*() functions. */
151 void ovs_barrier_init(struct ovs_barrier *, uint32_t count);
152 void ovs_barrier_destroy(struct ovs_barrier *);
153 void ovs_barrier_block(struct ovs_barrier *);
155 /* Wrappers for xpthread_cond_*() that abort the process on any error.
157 * Use ovs_mutex_cond_wait() to wait for a condition. */
158 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
159 void xpthread_cond_destroy(pthread_cond_t *);
160 void xpthread_cond_signal(pthread_cond_t *);
161 void xpthread_cond_broadcast(pthread_cond_t *);
163 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
164 void xpthread_key_delete(pthread_key_t);
165 void xpthread_setspecific(pthread_key_t, const void *);
167 pthread_t ovs_thread_create(const char *name, void *(*)(void *), void *);
168 void xpthread_join(pthread_t, void **);
176 * Multiple forms of standard per-thread data exist, each with its own pluses
177 * and minuses. In general, if one of these forms is appropriate, then it's a
178 * good idea to use it:
180 * - POSIX per-thread data via pthread_key_t is portable to any pthreads
181 * implementation, and allows a destructor function to be defined. It
182 * only (directly) supports per-thread pointers, which are always
183 * initialized to NULL. It requires once-only allocation of a
184 * pthread_key_t value. It is relatively slow. Typically few
185 * "pthread_key_t"s are available (POSIX requires only at least 128,
186 * glibc supplies only 1024).
188 * - The thread_local feature newly defined in C11 <threads.h> works with
189 * any data type and initializer, and it is fast. thread_local does not
190 * require once-only initialization like pthread_key_t. C11 does not
191 * define what happens if one attempts to access a thread_local object
192 * from a thread other than the one to which that object belongs. There
193 * is no provision to call a user-specified destructor when a thread
194 * ends. Typical implementations allow for an arbitrary amount of
195 * thread_local storage, but statically allocated only.
197 * - The __thread keyword is a GCC extension similar to thread_local but
198 * with a longer history. __thread is not portable to every GCC version
199 * or environment. __thread does not restrict the use of a thread-local
200 * object outside its own thread.
202 * Here's a handy summary:
204 * pthread_key_t thread_local __thread
205 * ------------- ------------ -------------
206 * portability high low medium
207 * speed low high high
208 * supports destructors? yes no no
209 * needs key allocation? yes no no
210 * arbitrary initializer? no yes yes
211 * cross-thread access? yes no yes
212 * amount available? few arbitrary arbitrary
213 * dynamically allocated? yes no no
219 * OVS provides some extensions and wrappers:
221 * - In a situation where the performance of thread_local or __thread is
222 * desirable, but portability is required, DEFINE_STATIC_PER_THREAD_DATA
223 * and DECLARE_EXTERN_PER_THREAD_DATA/DEFINE_EXTERN_PER_THREAD_DATA may
224 * be appropriate (see below).
226 * - DEFINE_PER_THREAD_MALLOCED_DATA can be convenient for simple
227 * per-thread malloc()'d buffers.
229 * - struct ovs_tsd provides an alternative to pthread_key_t that isn't
230 * limited to a small number of keys.
233 /* For static data, use this macro in a source file:
235 * DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
237 * For global data, "declare" the data in the header and "define" it in
238 * the source file, with:
240 * DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME).
241 * DEFINE_EXTERN_PER_THREAD_DATA(NAME, INITIALIZER).
243 * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
244 * performance is acceptable, because of its portability (see the table above).
245 * This macro is an alternatives that takes advantage of thread_local (and
246 * __thread), for its performance, when it is available, and falls back to
247 * POSIX per-thread data otherwise.
249 * Defines per-thread variable NAME with the given TYPE, initialized to
250 * INITIALIZER (which must be valid as an initializer for a variable with
253 * The public interface to the variable is:
255 * TYPE *NAME_get(void)
256 * TYPE *NAME_get_unsafe(void)
258 * Returns the address of this thread's instance of NAME.
260 * Use NAME_get() in a context where this might be the first use of the
261 * per-thread variable in the program. Use NAME_get_unsafe(), which
262 * avoids a conditional test and is thus slightly faster, in a context
263 * where one knows that NAME_get() has already been called previously.
265 * There is no "NAME_set()" (or "NAME_set_unsafe()") function. To set the
266 * value of the per-thread variable, dereference the pointer returned by
267 * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
269 #if HAVE_THREAD_LOCAL || HAVE___THREAD
271 #if HAVE_THREAD_LOCAL
274 #define thread_local __thread
279 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
280 typedef TYPE NAME##_type; \
282 static NAME##_type * \
283 NAME##_get_unsafe(void) \
285 static thread_local NAME##_type var = __VA_ARGS__; \
289 static NAME##_type * \
292 return NAME##_get_unsafe(); \
294 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
295 typedef TYPE NAME##_type; \
296 extern thread_local NAME##_type NAME##_var; \
298 static inline NAME##_type * \
299 NAME##_get_unsafe(void) \
301 return &NAME##_var; \
304 static inline NAME##_type * \
307 return NAME##_get_unsafe(); \
309 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
310 thread_local NAME##_type NAME##_var = __VA_ARGS__;
311 #else /* no C implementation support for thread-local storage */
312 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
313 typedef TYPE NAME##_type; \
314 static pthread_key_t NAME##_key; \
316 static NAME##_type * \
317 NAME##_get_unsafe(void) \
319 return pthread_getspecific(NAME##_key); \
323 NAME##_once_init(void) \
325 if (pthread_key_create(&NAME##_key, free)) { \
330 static NAME##_type * \
333 static pthread_once_t once = PTHREAD_ONCE_INIT; \
334 NAME##_type *value; \
336 pthread_once(&once, NAME##_once_init); \
337 value = NAME##_get_unsafe(); \
339 static const NAME##_type initial_value = __VA_ARGS__; \
341 value = malloc(sizeof *value); \
342 if (value == NULL) { \
345 *value = initial_value; \
346 xpthread_setspecific(NAME##_key, value); \
350 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
351 typedef TYPE NAME##_type; \
352 static pthread_key_t NAME##_key; \
354 static inline NAME##_type * \
355 NAME##_get_unsafe(void) \
357 return pthread_getspecific(NAME##_key); \
360 NAME##_type *NAME##_get(void);
361 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
363 NAME##_once_init(void) \
365 if (pthread_key_create(&NAME##_key, free)) { \
373 static pthread_once_t once = PTHREAD_ONCE_INIT; \
374 NAME##_type *value; \
376 pthread_once(&once, NAME##_once_init); \
377 value = NAME##_get_unsafe(); \
379 static const NAME##_type initial_value = __VA_ARGS__; \
381 value = malloc(sizeof *value); \
382 if (value == NULL) { \
385 *value = initial_value; \
386 xpthread_setspecific(NAME##_key, value); \
392 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
394 * This is a simple wrapper around POSIX per-thread data primitives. It
395 * defines per-thread variable NAME with the given TYPE, which must be a
396 * pointer type. In each thread, the per-thread variable is initialized to
397 * NULL. When a thread terminates, the variable is freed with free().
399 * The public interface to the variable is:
401 * TYPE NAME_get(void)
402 * TYPE NAME_get_unsafe(void)
404 * Returns the value of per-thread variable NAME in this thread.
406 * Use NAME_get() in a context where this might be the first use of the
407 * per-thread variable in the program. Use NAME_get_unsafe(), which
408 * avoids a conditional test and is thus slightly faster, in a context
409 * where one knows that NAME_get() has already been called previously.
411 * TYPE NAME_set(TYPE new_value)
412 * TYPE NAME_set_unsafe(TYPE new_value)
414 * Sets the value of per-thread variable NAME to 'new_value' in this
415 * thread, and returns its previous value.
417 * Use NAME_set() in a context where this might be the first use of the
418 * per-thread variable in the program. Use NAME_set_unsafe(), which
419 * avoids a conditional test and is thus slightly faster, in a context
420 * where one knows that NAME_set() has already been called previously.
422 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME) \
423 static pthread_key_t NAME##_key; \
426 NAME##_once_init(void) \
428 if (pthread_key_create(&NAME##_key, free)) { \
436 static pthread_once_t once = PTHREAD_ONCE_INIT; \
437 pthread_once(&once, NAME##_once_init); \
441 NAME##_get_unsafe(void) \
443 return pthread_getspecific(NAME##_key); \
446 static OVS_UNUSED TYPE \
450 return NAME##_get_unsafe(); \
454 NAME##_set_unsafe(TYPE value) \
456 TYPE old_value = NAME##_get_unsafe(); \
457 xpthread_setspecific(NAME##_key, value); \
461 static OVS_UNUSED TYPE \
462 NAME##_set(TYPE value) \
465 return NAME##_set_unsafe(value); \
468 /* Dynamically allocated thread-specific data with lots of slots.
470 * pthread_key_t can provide as few as 128 pieces of thread-specific data (even
471 * glibc is limited to 1,024). Thus, one must be careful to allocate only a
472 * few keys globally. One cannot, for example, allocate a key for every
473 * instance of a data structure if there might be an arbitrary number of those
476 * This API is similar to the pthread one (simply search and replace pthread_
477 * by ovsthread_) but it a much larger limit that can be raised if necessary
478 * (by recompiling). Thus, one may more freely use this form of
479 * thread-specific data.
481 * ovsthread_key_t also differs from pthread_key_t in the following ways:
483 * - Destructors must not access thread-specific data (via ovsthread_key).
485 * - The pthread_key_t API allows concurrently exiting threads to start
486 * executing the destructor after pthread_key_delete() returns. The
487 * ovsthread_key_t API guarantees that, when ovsthread_key_delete()
488 * returns, all destructors have returned and no new ones will start
491 typedef struct ovsthread_key *ovsthread_key_t;
493 void ovsthread_key_create(ovsthread_key_t *, void (*destructor)(void *));
494 void ovsthread_key_delete(ovsthread_key_t);
496 void ovsthread_setspecific(ovsthread_key_t, const void *);
497 void *ovsthread_getspecific(ovsthread_key_t);
499 /* Convenient once-only execution.
505 * POSIX provides pthread_once_t and pthread_once() as primitives for running a
506 * set of code only once per process execution. They are used like this:
508 * static void run_once(void) { ...initialization... }
509 * static pthread_once_t once = PTHREAD_ONCE_INIT;
511 * pthread_once(&once, run_once);
513 * pthread_once() does not allow passing any parameters to the initialization
514 * function, which is often inconvenient, because it means that the function
515 * can only access data declared at file scope.
521 * Use ovsthread_once, like this, instead:
523 * static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
525 * if (ovsthread_once_start(&once)) {
526 * ...initialization...
527 * ovsthread_once_done(&once);
531 struct ovsthread_once {
533 struct ovs_mutex mutex;
536 #define OVSTHREAD_ONCE_INITIALIZER \
538 ATOMIC_VAR_INIT(false), \
539 OVS_MUTEX_INITIALIZER, \
542 static inline bool ovsthread_once_start(struct ovsthread_once *once)
543 OVS_TRY_LOCK(true, once->mutex);
544 void ovsthread_once_done(struct ovsthread_once *once)
545 OVS_RELEASES(once->mutex);
547 bool ovsthread_once_start__(struct ovsthread_once *once)
548 OVS_TRY_LOCK(false, once->mutex);
551 ovsthread_once_is_done__(struct ovsthread_once *once)
555 atomic_read_explicit(&once->done, &done, memory_order_relaxed);
559 /* Returns true if this is the first call to ovsthread_once_start() for
560 * 'once'. In this case, the caller should perform whatever initialization
561 * actions it needs to do, then call ovsthread_once_done() for 'once'.
563 * Returns false if this is not the first call to ovsthread_once_start() for
564 * 'once'. In this case, the call will not return until after
565 * ovsthread_once_done() has been called. */
567 ovsthread_once_start(struct ovsthread_once *once)
569 return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
570 && !ovsthread_once_start__(once));
575 * pthread_t isn't so nice for some purposes. Its size and representation are
576 * implementation dependent, which means that there is no way to hash it.
577 * This thread ID avoids the problem.
580 DECLARE_EXTERN_PER_THREAD_DATA(unsigned int, ovsthread_id);
582 /* Returns a per-thread identifier unique within the lifetime of the
584 static inline unsigned int
585 ovsthread_id_self(void)
587 return *ovsthread_id_get();
590 /* Simulated global counter.
592 * Incrementing such a counter is meant to be cheaper than incrementing a
593 * global counter protected by a lock. It is probably more expensive than
594 * incrementing a truly thread-local variable, but such a variable has no
595 * straightforward way to get the sum.
601 * Fully thread-safe. */
603 struct ovsthread_stats {
604 struct ovs_mutex mutex;
605 void *volatile buckets[16];
608 void ovsthread_stats_init(struct ovsthread_stats *);
609 void ovsthread_stats_destroy(struct ovsthread_stats *);
611 void *ovsthread_stats_bucket_get(struct ovsthread_stats *,
612 void *(*new_bucket)(void));
614 #define OVSTHREAD_STATS_FOR_EACH_BUCKET(BUCKET, IDX, STATS) \
615 for ((IDX) = ovs_thread_stats_next_bucket(STATS, 0); \
616 ((IDX) < ARRAY_SIZE((STATS)->buckets) \
617 ? ((BUCKET) = (STATS)->buckets[IDX], true) \
619 (IDX) = ovs_thread_stats_next_bucket(STATS, (IDX) + 1))
620 size_t ovs_thread_stats_next_bucket(const struct ovsthread_stats *, size_t);
622 bool single_threaded(void);
624 void assert_single_threaded_at(const char *where);
625 #define assert_single_threaded() assert_single_threaded_at(SOURCE_LOCATOR)
628 pid_t xfork_at(const char *where);
629 #define xfork() xfork_at(SOURCE_LOCATOR)
632 void forbid_forking(const char *reason);
635 /* Useful functions related to threading. */
637 int count_cpu_cores(void);
639 #endif /* ovs-thread.h */