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