2 * Copyright (c) 2013 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 {
33 /* "struct ovs_mutex" initializer. */
34 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
35 #define OVS_MUTEX_INITIALIZER { PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, NULL }
37 #define OVS_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, NULL }
40 /* ovs_mutex functions analogous to pthread_mutex_*() functions.
42 * Most of these functions abort the process with an error message on any
43 * error. ovs_mutex_trylock() is an exception: it passes through a 0 or EBUSY
44 * return value to the caller and aborts on any other error. */
45 void ovs_mutex_init(const struct ovs_mutex *);
46 void ovs_mutex_init_recursive(const struct ovs_mutex *);
47 void ovs_mutex_destroy(const struct ovs_mutex *);
48 void ovs_mutex_unlock(const struct ovs_mutex *mutex) OVS_RELEASES(mutex);
49 void ovs_mutex_lock_at(const struct ovs_mutex *mutex, const char *where)
51 #define ovs_mutex_lock(mutex) \
52 ovs_mutex_lock_at(mutex, SOURCE_LOCATOR)
54 int ovs_mutex_trylock_at(const struct ovs_mutex *mutex, const char *where)
55 OVS_TRY_LOCK(0, mutex);
56 #define ovs_mutex_trylock(mutex) \
57 ovs_mutex_trylock_at(mutex, SOURCE_LOCATOR)
59 void ovs_mutex_cond_wait(pthread_cond_t *, const struct ovs_mutex *);
61 /* Wrappers for pthread_mutex_*() that abort the process on any error.
62 * This is still needed when ovs-atomic-pthreads.h is used. */
63 void xpthread_mutex_lock(pthread_mutex_t *mutex);
64 void xpthread_mutex_unlock(pthread_mutex_t *mutex);
66 /* Wrappers for pthread_mutexattr_*() that abort the process on any error. */
67 void xpthread_mutexattr_init(pthread_mutexattr_t *);
68 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
69 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
70 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
72 /* Read-write lock. */
73 struct OVS_LOCKABLE ovs_rwlock {
74 pthread_rwlock_t lock;
79 #define OVS_RWLOCK_INITIALIZER { PTHREAD_RWLOCK_INITIALIZER, NULL }
81 /* ovs_rwlock functions analogous to pthread_rwlock_*() functions.
83 * Most of these functions abort the process with an error message on any
84 * error. The "trylock" functions are exception: they pass through a 0 or
85 * EBUSY return value to the caller and abort on any other error. */
86 void ovs_rwlock_init(const struct ovs_rwlock *);
87 void ovs_rwlock_destroy(const struct ovs_rwlock *);
88 void ovs_rwlock_unlock(const struct ovs_rwlock *rwlock) OVS_RELEASES(rwlock);
90 void ovs_rwlock_wrlock_at(const struct ovs_rwlock *rwlock, const char *where)
91 OVS_ACQ_WRLOCK(rwlock);
92 #define ovs_rwlock_wrlock(rwlock) \
93 ovs_rwlock_wrlock_at(rwlock, SOURCE_LOCATOR)
95 int ovs_rwlock_trywrlock_at(const struct ovs_rwlock *rwlock, const char *where)
96 OVS_TRY_WRLOCK(0, rwlock);
97 #define ovs_rwlock_trywrlock(rwlock) \
98 ovs_rwlock_trywrlock_at(rwlock, SOURCE_LOCATOR)
100 void ovs_rwlock_rdlock_at(const struct ovs_rwlock *rwlock, const char *where)
101 OVS_ACQ_RDLOCK(rwlock);
102 #define ovs_rwlock_rdlock(rwlock) \
103 ovs_rwlock_rdlock_at(rwlock, SOURCE_LOCATOR)
105 int ovs_rwlock_tryrdlock_at(const struct ovs_rwlock *rwlock, const char *where)
106 OVS_TRY_RDLOCK(0, rwlock);
107 #define ovs_rwlock_tryrdlock(rwlock) \
108 ovs_rwlock_tryrdlock_at(rwlock, SOURCE_LOCATOR)
110 /* Wrappers for xpthread_cond_*() that abort the process on any error.
112 * Use ovs_mutex_cond_wait() to wait for a condition. */
113 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
114 void xpthread_cond_destroy(pthread_cond_t *);
115 void xpthread_cond_signal(pthread_cond_t *);
116 void xpthread_cond_broadcast(pthread_cond_t *);
119 /* Replace these functions by the macros already defined in the <pthread.h>
120 * annotations, because the macro definitions have correct semantics for the
121 * conditional acquisition that can't be captured in a function annotation.
122 * The difference in semantics from pthread_*() to xpthread_*() does not matter
123 * because sparse is not a compiler. */
124 #define xpthread_mutex_trylock pthread_mutex_trylock
125 #define xpthread_rwlock_tryrdlock pthread_rwlock_tryrdlock
126 #define xpthread_rwlock_trywrlock pthread_rwlock_trywrlock
129 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
130 void xpthread_setspecific(pthread_key_t, const void *);
132 void xpthread_create(pthread_t *, pthread_attr_t *, void *(*)(void *), void *);
133 void xpthread_join(pthread_t, void **);
137 * Multiple forms of per-thread data exist, each with its own pluses and
140 * - POSIX per-thread data via pthread_key_t is portable to any pthreads
141 * implementation, and allows a destructor function to be defined. It
142 * only (directly) supports per-thread pointers, which are always
143 * initialized to NULL. It requires once-only allocation of a
144 * pthread_key_t value. It is relatively slow.
146 * - The thread_local feature newly defined in C11 <threads.h> works with
147 * any data type and initializer, and it is fast. thread_local does not
148 * require once-only initialization like pthread_key_t. C11 does not
149 * define what happens if one attempts to access a thread_local object
150 * from a thread other than the one to which that object belongs. There
151 * is no provision to call a user-specified destructor when a thread
154 * - The __thread keyword is a GCC extension similar to thread_local but
155 * with a longer history. __thread is not portable to every GCC version
156 * or environment. __thread does not restrict the use of a thread-local
157 * object outside its own thread.
159 * Here's a handy summary:
161 * pthread_key_t thread_local __thread
162 * ------------- ------------ -------------
163 * portability high low medium
164 * speed low high high
165 * supports destructors? yes no no
166 * needs key allocation? yes no no
167 * arbitrary initializer? no yes yes
168 * cross-thread access? yes no yes
171 /* For static data, use this macro in a source file:
173 * DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
175 * For global data, "declare" the data in the header and "define" it in
176 * the source file, with:
178 * DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME).
179 * DEFINE_EXTERN_PER_THREAD_DATA(NAME, INITIALIZER).
181 * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
182 * performance is acceptable, because of its portability (see the table above).
183 * This macro is an alternatives that takes advantage of thread_local (and
184 * __thread), for its performance, when it is available, and falls back to
185 * POSIX per-thread data otherwise.
187 * Defines per-thread variable NAME with the given TYPE, initialized to
188 * INITIALIZER (which must be valid as an initializer for a variable with
191 * The public interface to the variable is:
193 * TYPE *NAME_get(void)
194 * TYPE *NAME_get_unsafe(void)
196 * Returns the address of this thread's instance of NAME.
198 * Use NAME_get() in a context where this might be the first use of the
199 * per-thread variable in the program. Use NAME_get_unsafe(), which
200 * avoids a conditional test and is thus slightly faster, in a context
201 * where one knows that NAME_get() has already been called previously.
203 * There is no "NAME_set()" (or "NAME_set_unsafe()") function. To set the
204 * value of the per-thread variable, dereference the pointer returned by
205 * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
207 #if HAVE_THREAD_LOCAL || HAVE___THREAD
209 #if HAVE_THREAD_LOCAL
212 #define thread_local __thread
217 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
218 typedef TYPE NAME##_type; \
220 static NAME##_type * \
221 NAME##_get_unsafe(void) \
223 static thread_local NAME##_type var = __VA_ARGS__; \
227 static NAME##_type * \
230 return NAME##_get_unsafe(); \
232 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
233 typedef TYPE NAME##_type; \
234 extern thread_local NAME##_type NAME##_var; \
236 static inline NAME##_type * \
237 NAME##_get_unsafe(void) \
239 return &NAME##_var; \
242 static inline NAME##_type * \
245 return NAME##_get_unsafe(); \
247 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
248 thread_local NAME##_type NAME##_var = __VA_ARGS__;
249 #else /* no C implementation support for thread-local storage */
250 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...) \
251 typedef TYPE NAME##_type; \
252 static pthread_key_t NAME##_key; \
254 static NAME##_type * \
255 NAME##_get_unsafe(void) \
257 return pthread_getspecific(NAME##_key); \
261 NAME##_once_init(void) \
263 if (pthread_key_create(&NAME##_key, free)) { \
268 static NAME##_type * \
271 static pthread_once_t once = PTHREAD_ONCE_INIT; \
272 NAME##_type *value; \
274 pthread_once(&once, NAME##_once_init); \
275 value = NAME##_get_unsafe(); \
277 static const NAME##_type initial_value = __VA_ARGS__; \
279 value = malloc(sizeof *value); \
280 if (value == NULL) { \
283 *value = initial_value; \
284 xpthread_setspecific(NAME##_key, value); \
288 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME) \
289 typedef TYPE NAME##_type; \
290 static pthread_key_t NAME##_key; \
292 static inline NAME##_type * \
293 NAME##_get_unsafe(void) \
295 return pthread_getspecific(NAME##_key); \
298 NAME##_type *NAME##_get(void);
299 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...) \
301 NAME##_once_init(void) \
303 if (pthread_key_create(&NAME##_key, free)) { \
311 static pthread_once_t once = PTHREAD_ONCE_INIT; \
312 NAME##_type *value; \
314 pthread_once(&once, NAME##_once_init); \
315 value = NAME##_get_unsafe(); \
317 static const NAME##_type initial_value = __VA_ARGS__; \
319 value = malloc(sizeof *value); \
320 if (value == NULL) { \
323 *value = initial_value; \
324 xpthread_setspecific(NAME##_key, value); \
330 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
332 * This is a simple wrapper around POSIX per-thread data primitives. It
333 * defines per-thread variable NAME with the given TYPE, which must be a
334 * pointer type. In each thread, the per-thread variable is initialized to
335 * NULL. When a thread terminates, the variable is freed with free().
337 * The public interface to the variable is:
339 * TYPE NAME_get(void)
340 * TYPE NAME_get_unsafe(void)
342 * Returns the value of per-thread variable NAME in this thread.
344 * Use NAME_get() in a context where this might be the first use of the
345 * per-thread variable in the program. Use NAME_get_unsafe(), which
346 * avoids a conditional test and is thus slightly faster, in a context
347 * where one knows that NAME_get() has already been called previously.
349 * TYPE NAME_set(TYPE new_value)
350 * TYPE NAME_set_unsafe(TYPE new_value)
352 * Sets the value of per-thread variable NAME to 'new_value' in this
353 * thread, and returns its previous value.
355 * Use NAME_set() in a context where this might be the first use of the
356 * per-thread variable in the program. Use NAME_set_unsafe(), which
357 * avoids a conditional test and is thus slightly faster, in a context
358 * where one knows that NAME_set() has already been called previously.
360 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME) \
361 static pthread_key_t NAME##_key; \
364 NAME##_once_init(void) \
366 if (pthread_key_create(&NAME##_key, free)) { \
374 static pthread_once_t once = PTHREAD_ONCE_INIT; \
375 pthread_once(&once, NAME##_once_init); \
379 NAME##_get_unsafe(void) \
381 return pthread_getspecific(NAME##_key); \
384 static OVS_UNUSED TYPE \
388 return NAME##_get_unsafe(); \
392 NAME##_set_unsafe(TYPE value) \
394 TYPE old_value = NAME##_get_unsafe(); \
395 xpthread_setspecific(NAME##_key, value); \
399 static OVS_UNUSED TYPE \
400 NAME##_set(TYPE value) \
403 return NAME##_set_unsafe(value); \
406 /* Convenient once-only execution.
412 * POSIX provides pthread_once_t and pthread_once() as primitives for running a
413 * set of code only once per process execution. They are used like this:
415 * static void run_once(void) { ...initialization... }
416 * static pthread_once_t once = PTHREAD_ONCE_INIT;
418 * pthread_once(&once, run_once);
420 * pthread_once() does not allow passing any parameters to the initialization
421 * function, which is often inconvenient, because it means that the function
422 * can only access data declared at file scope.
428 * Use ovsthread_once, like this, instead:
430 * static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
432 * if (ovsthread_once_start(&once)) {
433 * ...initialization...
434 * ovsthread_once_done(&once);
438 struct ovsthread_once {
440 struct ovs_mutex mutex;
443 #define OVSTHREAD_ONCE_INITIALIZER \
445 ATOMIC_VAR_INIT(false), \
446 OVS_MUTEX_INITIALIZER, \
449 static inline bool ovsthread_once_start(struct ovsthread_once *once)
450 OVS_TRY_LOCK(true, once->mutex);
451 void ovsthread_once_done(struct ovsthread_once *once)
452 OVS_RELEASES(once->mutex);
454 bool ovsthread_once_start__(struct ovsthread_once *once)
455 OVS_TRY_LOCK(false, once->mutex);
458 ovsthread_once_is_done__(struct ovsthread_once *once)
462 atomic_read_explicit(&once->done, &done, memory_order_relaxed);
466 /* Returns true if this is the first call to ovsthread_once_start() for
467 * 'once'. In this case, the caller should perform whatever initialization
468 * actions it needs to do, then call ovsthread_once_done() for 'once'.
470 * Returns false if this is not the first call to ovsthread_once_start() for
471 * 'once'. In this case, the call will not return until after
472 * ovsthread_once_done() has been called. */
474 ovsthread_once_start(struct ovsthread_once *once)
476 return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
477 && !ovsthread_once_start__(once));
482 * pthread_t isn't so nice for some purposes. Its size and representation are
483 * implementation dependent, which means that there is no way to hash it.
484 * This thread ID avoids the problem.
487 DECLARE_EXTERN_PER_THREAD_DATA(unsigned int, ovsthread_id);
489 /* Returns a per-thread identifier unique within the lifetime of the
491 static inline unsigned int
492 ovsthread_id_self(void)
494 return *ovsthread_id_get();
497 void assert_single_threaded_at(const char *where);
498 #define assert_single_threaded() assert_single_threaded_at(SOURCE_LOCATOR)
500 pid_t xfork_at(const char *where);
501 #define xfork() xfork_at(SOURCE_LOCATOR)
503 void forbid_forking(const char *reason);
506 /* Useful functions related to threading. */
508 int count_cpu_cores(void);
510 #endif /* ovs-thread.h */