fatal-signal: Make thread-safe.
[sliver-openvswitch.git] / lib / ovs-thread.h
1 /*
2  * Copyright (c) 2013 Nicira, Inc.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef OVS_THREAD_H
18 #define OVS_THREAD_H 1
19
20 #include <pthread.h>
21 #include <stddef.h>
22 #include <sys/types.h>
23 #include "ovs-atomic.h"
24 #include "util.h"
25
26 /* glibc has some non-portable mutex types and initializers:
27  *
28  *    - PTHREAD_MUTEX_ADAPTIVE_NP is a mutex type that works as a spinlock that
29  *      falls back to a mutex after spinning for some number of iterations.
30  *
31  *    - PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP is a non-portable initializer
32  *      for an error-checking mutex.
33  *
34  * We use these definitions to fall back to PTHREAD_MUTEX_NORMAL instead in
35  * these cases.
36  *
37  * (glibc has other non-portable initializers, but we can't reasonably
38  * substitute for them here.) */
39 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
40 #define PTHREAD_MUTEX_ADAPTIVE PTHREAD_MUTEX_ADAPTIVE_NP
41 #define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER \
42     PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
43 #else
44 #define PTHREAD_MUTEX_ADAPTIVE PTHREAD_MUTEX_NORMAL
45 #define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
46 #endif
47
48 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
49 #define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER \
50     PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
51 #else
52 #define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
53 #endif
54 \f
55 /* Simple wrappers for pthreads functions.  Most of these functions abort the
56  * process with an error message on any error.  The *_trylock() functions are
57  * exceptions: they pass through a 0 or EBUSY return value to the caller and
58  * abort on any other error. */
59
60 void xpthread_mutex_init(pthread_mutex_t *, pthread_mutexattr_t *);
61 void xpthread_mutex_lock(pthread_mutex_t *mutex) OVS_ACQUIRES(mutex);
62 void xpthread_mutex_unlock(pthread_mutex_t *mutex) OVS_RELEASES(mutex);
63 int xpthread_mutex_trylock(pthread_mutex_t *);
64
65 void xpthread_mutexattr_init(pthread_mutexattr_t *);
66 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
67 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
68 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
69
70 void xpthread_rwlock_init(pthread_rwlock_t *, pthread_rwlockattr_t *);
71 void xpthread_rwlock_rdlock(pthread_rwlock_t *rwlock) OVS_ACQUIRES(rwlock);
72 void xpthread_rwlock_wrlock(pthread_rwlock_t *rwlock) OVS_ACQUIRES(rwlock);
73 void xpthread_rwlock_unlock(pthread_rwlock_t *rwlock) OVS_RELEASES(rwlock);
74 int xpthread_rwlock_tryrdlock(pthread_rwlock_t *);
75 int xpthread_rwlock_trywrlock(pthread_rwlock_t *);
76
77 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
78 void xpthread_cond_signal(pthread_cond_t *);
79 void xpthread_cond_broadcast(pthread_cond_t *);
80 void xpthread_cond_wait(pthread_cond_t *, pthread_mutex_t *mutex)
81     OVS_MUST_HOLD(mutex);
82
83 #ifdef __CHECKER__
84 /* Replace these functions by the macros already defined in the <pthread.h>
85  * annotations, because the macro definitions have correct semantics for the
86  * conditional acquisition that can't be captured in a function annotation.
87  * The difference in semantics from pthread_*() to xpthread_*() does not matter
88  * because sparse is not a compiler. */
89 #define xpthread_mutex_trylock pthread_mutex_trylock
90 #define xpthread_rwlock_tryrdlock pthread_rwlock_tryrdlock
91 #define xpthread_rwlock_trywrlock pthread_rwlock_trywrlock
92 #endif
93
94 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
95
96 void xpthread_create(pthread_t *, pthread_attr_t *, void *(*)(void *), void *);
97 \f
98 /* Per-thread data.
99  *
100  * Multiple forms of per-thread data exist, each with its own pluses and
101  * minuses:
102  *
103  *     - POSIX per-thread data via pthread_key_t is portable to any pthreads
104  *       implementation, and allows a destructor function to be defined.  It
105  *       only (directly) supports per-thread pointers, which are always
106  *       initialized to NULL.  It requires once-only allocation of a
107  *       pthread_key_t value.  It is relatively slow.
108  *
109  *     - The thread_local feature newly defined in C11 <threads.h> works with
110  *       any data type and initializer, and it is fast.  thread_local does not
111  *       require once-only initialization like pthread_key_t.  C11 does not
112  *       define what happens if one attempts to access a thread_local object
113  *       from a thread other than the one to which that object belongs.  There
114  *       is no provision to call a user-specified destructor when a thread
115  *       ends.
116  *
117  *     - The __thread keyword is a GCC extension similar to thread_local but
118  *       with a longer history.  __thread is not portable to every GCC version
119  *       or environment.  __thread does not restrict the use of a thread-local
120  *       object outside its own thread.
121  *
122  * Here's a handy summary:
123  *
124  *                     pthread_key_t     thread_local       __thread
125  *                     -------------     ------------     -------------
126  * portability             high               low             medium
127  * speed                    low              high               high
128  * supports destructors?    yes                no                 no
129  * needs key allocation?    yes                no                 no
130  * arbitrary initializer?    no               yes                yes
131  * cross-thread access?     yes                no                yes
132  */
133
134 /* DEFINE_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
135  *
136  * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
137  * performance is acceptable, because of its portability (see the table above).
138  * This macro is an alternatives that takes advantage of thread_local (and
139  * __thread), for its performance, when it is available, and falls back to
140  * POSIX per-thread data otherwise.
141  *
142  * Defines per-thread variable NAME with the given TYPE, initialized to
143  * INITIALIZER (which must be valid as an initializer for a variable with
144  * static lifetime).
145  *
146  * The public interface to the variable is:
147  *
148  *    TYPE *NAME_get(void)
149  *    TYPE *NAME_get_unsafe(void)
150  *
151  *       Returns the address of this thread's instance of NAME.
152  *
153  *       Use NAME_get() in a context where this might be the first use of the
154  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
155  *       avoids a conditional test and is thus slightly faster, in a context
156  *       where one knows that NAME_get() has already been called previously.
157  *
158  * There is no "NAME_set()" (or "NAME_set_unsafe()") function.  To set the
159  * value of the per-thread variable, dereference the pointer returned by
160  * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
161  */
162 #if HAVE_THREAD_LOCAL || HAVE___THREAD
163
164 #if HAVE_THREAD_LOCAL
165 #include <threads.h>
166 #elif HAVE___THREAD
167 #define thread_local __thread
168 #else
169 #error
170 #endif
171
172 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...)                 \
173     typedef TYPE NAME##_type;                                   \
174     static thread_local NAME##_type NAME##_var = __VA_ARGS__;   \
175                                                                 \
176     static NAME##_type *                                        \
177     NAME##_get_unsafe(void)                                     \
178     {                                                           \
179         return &NAME##_var;                                     \
180     }                                                           \
181                                                                 \
182     static NAME##_type *                                        \
183     NAME##_get(void)                                            \
184     {                                                           \
185         return NAME##_get_unsafe();                             \
186     }
187 #else  /* no C implementation support for thread-local storage  */
188 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...)                         \
189     typedef TYPE NAME##_type;                                           \
190     static pthread_key_t NAME##_key;                                    \
191                                                                         \
192     static NAME##_type *                                                \
193     NAME##_get_unsafe(void)                                             \
194     {                                                                   \
195         return pthread_getspecific(NAME##_key);                         \
196     }                                                                   \
197                                                                         \
198     static void                                                         \
199     NAME##_once_init(void)                                              \
200     {                                                                   \
201         if (pthread_key_create(&NAME##_key, free)) {                    \
202             abort();                                                    \
203         }                                                               \
204     }                                                                   \
205                                                                         \
206     static NAME##_type *                                                \
207     NAME##_get(void)                                                    \
208     {                                                                   \
209         static pthread_once_t once = PTHREAD_ONCE_INIT;                 \
210         NAME##_type *value;                                             \
211                                                                         \
212         pthread_once(&once, NAME##_once_init);                          \
213         value = NAME##_get_unsafe();                                    \
214         if (!value) {                                                   \
215             static const NAME##_type initial_value = __VA_ARGS__;       \
216                                                                         \
217             value = xmalloc(sizeof *value);                             \
218             *value = initial_value;                                     \
219             pthread_setspecific(NAME##_key, value);                     \
220         }                                                               \
221         return value;                                                   \
222     }
223 #endif
224
225 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
226  *
227  * This is a simple wrapper around POSIX per-thread data primitives.  It
228  * defines per-thread variable NAME with the given TYPE, which must be a
229  * pointer type.  In each thread, the per-thread variable is initialized to
230  * NULL.  When a thread terminates, the variable is freed with free().
231  *
232  * The public interface to the variable is:
233  *
234  *    TYPE NAME_get(void)
235  *    TYPE NAME_get_unsafe(void)
236  *
237  *       Returns the value of per-thread variable NAME in this thread.
238  *
239  *       Use NAME_get() in a context where this might be the first use of the
240  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
241  *       avoids a conditional test and is thus slightly faster, in a context
242  *       where one knows that NAME_get() has already been called previously.
243  *
244  *    TYPE NAME_set(TYPE new_value)
245  *    TYPE NAME_set_unsafe(TYPE new_value)
246  *
247  *       Sets the value of per-thread variable NAME to 'new_value' in this
248  *       thread, and returns its previous value.
249  *
250  *       Use NAME_set() in a context where this might be the first use of the
251  *       per-thread variable in the program.  Use NAME_set_unsafe(), which
252  *       avoids a conditional test and is thus slightly faster, in a context
253  *       where one knows that NAME_set() has already been called previously.
254  */
255 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME)     \
256     static pthread_key_t NAME##_key;                    \
257                                                         \
258     static void                                         \
259     NAME##_once_init(void)                              \
260     {                                                   \
261         if (pthread_key_create(&NAME##_key, free)) {    \
262             abort();                                    \
263         }                                               \
264     }                                                   \
265                                                         \
266     static void                                         \
267     NAME##_init(void)                                   \
268     {                                                   \
269         static pthread_once_t once = PTHREAD_ONCE_INIT; \
270         pthread_once(&once, NAME##_once_init);          \
271     }                                                   \
272                                                         \
273     static TYPE                                         \
274     NAME##_get_unsafe(void)                             \
275     {                                                   \
276         return pthread_getspecific(NAME##_key);         \
277     }                                                   \
278                                                         \
279     static OVS_UNUSED TYPE                              \
280     NAME##_get(void)                                    \
281     {                                                   \
282         NAME##_init();                                  \
283         return NAME##_get_unsafe();                     \
284     }                                                   \
285                                                         \
286     static TYPE                                         \
287     NAME##_set_unsafe(TYPE value)                       \
288     {                                                   \
289         TYPE old_value = NAME##_get_unsafe();           \
290         pthread_setspecific(NAME##_key, value);         \
291         return old_value;                               \
292     }                                                   \
293                                                         \
294     static OVS_UNUSED TYPE                              \
295     NAME##_set(TYPE value)                              \
296     {                                                   \
297         NAME##_init();                                  \
298         return NAME##_set_unsafe(value);                \
299     }
300 \f
301 /* Convenient once-only execution.
302  *
303  *
304  * Problem
305  * =======
306  *
307  * POSIX provides pthread_once_t and pthread_once() as primitives for running a
308  * set of code only once per process execution.  They are used like this:
309  *
310  *     static void run_once(void) { ...initialization... }
311  *     static pthread_once_t once = PTHREAD_ONCE_INIT;
312  * ...
313  *     pthread_once(&once, run_once);
314  *
315  * pthread_once() does not allow passing any parameters to the initialization
316  * function, which is often inconvenient, because it means that the function
317  * can only access data declared at file scope.
318  *
319  *
320  * Solution
321  * ========
322  *
323  * Use ovsthread_once, like this, instead:
324  *
325  *     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
326  *
327  *     if (ovsthread_once_start(&once)) {
328  *         ...initialization...
329  *         ovsthread_once_done(&once);
330  *     }
331  */
332
333 struct ovsthread_once {
334     atomic_bool done;
335     pthread_mutex_t mutex;
336 };
337
338 #define OVSTHREAD_ONCE_INITIALIZER              \
339     {                                           \
340         ATOMIC_VAR_INIT(false),                 \
341         PTHREAD_ADAPTIVE_MUTEX_INITIALIZER,     \
342     }
343
344 static inline bool ovsthread_once_start(struct ovsthread_once *);
345 void ovsthread_once_done(struct ovsthread_once *once) OVS_RELEASES(once);
346
347 bool ovsthread_once_start__(struct ovsthread_once *);
348
349 static inline bool
350 ovsthread_once_is_done__(const struct ovsthread_once *once)
351 {
352     bool done;
353
354     atomic_read_explicit(&once->done, &done, memory_order_relaxed);
355     return done;
356 }
357
358 /* Returns true if this is the first call to ovsthread_once_start() for
359  * 'once'.  In this case, the caller should perform whatever initialization
360  * actions it needs to do, then call ovsthread_once_done() for 'once'.
361  *
362  * Returns false if this is not the first call to ovsthread_once_start() for
363  * 'once'.  In this case, the call will not return until after
364  * ovsthread_once_done() has been called. */
365 static inline bool
366 ovsthread_once_start(struct ovsthread_once *once)
367 {
368     return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
369                         && !ovsthread_once_start__(once));
370 }
371
372 #ifdef __CHECKER__
373 #define ovsthread_once_start(ONCE) \
374     ((ONCE)->done ? false : ({ OVS_ACQUIRE(ONCE); true; }))
375 #endif
376 \f
377 void assert_single_threaded(const char *where);
378 #define assert_single_threaded() assert_single_threaded(SOURCE_LOCATOR)
379
380 pid_t xfork(const char *where);
381 #define xfork() xfork(SOURCE_LOCATOR)
382
383 void forbid_forking(const char *reason);
384 bool may_fork(void);
385
386 #endif /* ovs-thread.h */