clang: Add annotations for thread safety check.
[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
27 /* Mutex. */
28 struct OVS_LOCKABLE ovs_mutex {
29     pthread_mutex_t lock;
30     const char *where;
31 };
32
33 /* "struct ovs_mutex" initializers:
34  *
35  *    - OVS_MUTEX_INITIALIZER: common case.
36  *
37  *    - OVS_ADAPTIVE_MUTEX_INITIALIZER for a mutex that spins briefly then goes
38  *      to sleeps after some number of iterations.
39  *
40  *    - OVS_ERRORCHECK_MUTEX_INITIALIZER for a mutex that is used for
41  *      error-checking. */
42 #define OVS_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, NULL }
43 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
44 #define OVS_ADAPTIVE_MUTEX_INITIALIZER \
45     { PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP, NULL }
46 #else
47 #define OVS_ADAPTIVE_MUTEX_INITIALIZER OVS_MUTEX_INITIALIZER
48 #endif
49 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
50 #define OVS_ERRORCHECK_MUTEX_INITIALIZER \
51     { PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, NULL }
52 #else
53 #define OVS_ERRORCHECK_MUTEX_INITIALIZER OVS_MUTEX_INITIALIZER
54 #endif
55 \f
56 /* Mutex types, suitable for use with pthread_mutexattr_settype().
57  * There is only one nonstandard type:
58  *
59  *    - PTHREAD_MUTEX_ADAPTIVE_NP, the type used for
60  *      OVS_ADAPTIVE_MUTEX_INITIALIZER. */
61 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
62 #define OVS_MUTEX_ADAPTIVE PTHREAD_MUTEX_ADAPTIVE_NP
63 #else
64 #define OVS_MUTEX_ADAPTIVE PTHREAD_MUTEX_NORMAL
65 #endif
66
67 /* ovs_mutex functions analogous to pthread_mutex_*() functions.
68  *
69  * Most of these functions abort the process with an error message on any
70  * error.  ovs_mutex_trylock() is an exception: it passes through a 0 or EBUSY
71  * return value to the caller and aborts on any other error. */
72 void ovs_mutex_init(const struct ovs_mutex *, int type);
73 void ovs_mutex_destroy(const struct ovs_mutex *);
74 void ovs_mutex_unlock(const struct ovs_mutex *mutex) OVS_RELEASES(mutex);
75 void ovs_mutex_lock_at(const struct ovs_mutex *mutex, const char *where)
76     OVS_ACQUIRES(mutex);
77 #define ovs_mutex_lock(mutex) \
78         ovs_mutex_lock_at(mutex, SOURCE_LOCATOR)
79
80 int ovs_mutex_trylock_at(const struct ovs_mutex *mutex, const char *where)
81     OVS_TRY_LOCK(0, mutex);
82 #define ovs_mutex_trylock(mutex) \
83         ovs_mutex_trylock_at(mutex, SOURCE_LOCATOR)
84
85 void ovs_mutex_cond_wait(pthread_cond_t *, const struct ovs_mutex *);
86
87 /* Wrappers for pthread_mutexattr_*() that abort the process on any error. */
88 void xpthread_mutexattr_init(pthread_mutexattr_t *);
89 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
90 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
91 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
92
93 /* Read-write lock. */
94 struct OVS_LOCKABLE ovs_rwlock {
95     pthread_rwlock_t lock;
96     const char *where;
97 };
98
99 /* Initializer. */
100 #define OVS_RWLOCK_INITIALIZER { PTHREAD_RWLOCK_INITIALIZER, NULL }
101
102 /* ovs_rwlock functions analogous to pthread_rwlock_*() functions.
103  *
104  * Most of these functions abort the process with an error message on any
105  * error.  The "trylock" functions are exception: they pass through a 0 or
106  * EBUSY return value to the caller and abort on any other error. */
107 void ovs_rwlock_init(const struct ovs_rwlock *);
108 void ovs_rwlock_destroy(const struct ovs_rwlock *);
109 void ovs_rwlock_unlock(const struct ovs_rwlock *rwlock) OVS_RELEASES(rwlock);
110
111 void ovs_rwlock_wrlock_at(const struct ovs_rwlock *rwlock, const char *where)
112     OVS_ACQ_WRLOCK(rwlock);
113 #define ovs_rwlock_wrlock(rwlock) \
114         ovs_rwlock_wrlock_at(rwlock, SOURCE_LOCATOR);
115
116 int ovs_rwlock_trywrlock_at(const struct ovs_rwlock *rwlock, const char *where)
117     OVS_TRY_WRLOCK(0, rwlock);
118 #define ovs_rwlock_trywrlock(rwlock) \
119     ovs_rwlock_trywrlock_at(rwlock, SOURCE_LOCATOR)
120
121 void ovs_rwlock_rdlock_at(const struct ovs_rwlock *rwlock, const char *where)
122     OVS_ACQ_RDLOCK(rwlock);
123 #define ovs_rwlock_rdlock(rwlock) \
124         ovs_rwlock_rdlock_at(rwlock, SOURCE_LOCATOR);
125
126 int ovs_rwlock_tryrdlock_at(const struct ovs_rwlock *rwlock, const char *where)
127     OVS_TRY_RDLOCK(0, rwlock);
128 #define ovs_rwlock_tryrdlock(rwlock) \
129         ovs_rwlock_tryrdlock_at(rwlock, SOURCE_LOCATOR)
130
131 /* Wrappers for xpthread_cond_*() that abort the process on any error.
132  *
133  * Use ovs_mutex_cond_wait() to wait for a condition. */
134 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
135 void xpthread_cond_destroy(pthread_cond_t *);
136 void xpthread_cond_signal(pthread_cond_t *);
137 void xpthread_cond_broadcast(pthread_cond_t *);
138
139 #ifdef __CHECKER__
140 /* Replace these functions by the macros already defined in the <pthread.h>
141  * annotations, because the macro definitions have correct semantics for the
142  * conditional acquisition that can't be captured in a function annotation.
143  * The difference in semantics from pthread_*() to xpthread_*() does not matter
144  * because sparse is not a compiler. */
145 #define xpthread_mutex_trylock pthread_mutex_trylock
146 #define xpthread_rwlock_tryrdlock pthread_rwlock_tryrdlock
147 #define xpthread_rwlock_trywrlock pthread_rwlock_trywrlock
148 #endif
149
150 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
151
152 void xpthread_create(pthread_t *, pthread_attr_t *, void *(*)(void *), void *);
153 \f
154 /* Per-thread data.
155  *
156  * Multiple forms of per-thread data exist, each with its own pluses and
157  * minuses:
158  *
159  *     - POSIX per-thread data via pthread_key_t is portable to any pthreads
160  *       implementation, and allows a destructor function to be defined.  It
161  *       only (directly) supports per-thread pointers, which are always
162  *       initialized to NULL.  It requires once-only allocation of a
163  *       pthread_key_t value.  It is relatively slow.
164  *
165  *     - The thread_local feature newly defined in C11 <threads.h> works with
166  *       any data type and initializer, and it is fast.  thread_local does not
167  *       require once-only initialization like pthread_key_t.  C11 does not
168  *       define what happens if one attempts to access a thread_local object
169  *       from a thread other than the one to which that object belongs.  There
170  *       is no provision to call a user-specified destructor when a thread
171  *       ends.
172  *
173  *     - The __thread keyword is a GCC extension similar to thread_local but
174  *       with a longer history.  __thread is not portable to every GCC version
175  *       or environment.  __thread does not restrict the use of a thread-local
176  *       object outside its own thread.
177  *
178  * Here's a handy summary:
179  *
180  *                     pthread_key_t     thread_local       __thread
181  *                     -------------     ------------     -------------
182  * portability             high               low             medium
183  * speed                    low              high               high
184  * supports destructors?    yes                no                 no
185  * needs key allocation?    yes                no                 no
186  * arbitrary initializer?    no               yes                yes
187  * cross-thread access?     yes                no                yes
188  */
189
190 /* DEFINE_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
191  *
192  * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
193  * performance is acceptable, because of its portability (see the table above).
194  * This macro is an alternatives that takes advantage of thread_local (and
195  * __thread), for its performance, when it is available, and falls back to
196  * POSIX per-thread data otherwise.
197  *
198  * Defines per-thread variable NAME with the given TYPE, initialized to
199  * INITIALIZER (which must be valid as an initializer for a variable with
200  * static lifetime).
201  *
202  * The public interface to the variable is:
203  *
204  *    TYPE *NAME_get(void)
205  *    TYPE *NAME_get_unsafe(void)
206  *
207  *       Returns the address of this thread's instance of NAME.
208  *
209  *       Use NAME_get() in a context where this might be the first use of the
210  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
211  *       avoids a conditional test and is thus slightly faster, in a context
212  *       where one knows that NAME_get() has already been called previously.
213  *
214  * There is no "NAME_set()" (or "NAME_set_unsafe()") function.  To set the
215  * value of the per-thread variable, dereference the pointer returned by
216  * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
217  */
218 #if HAVE_THREAD_LOCAL || HAVE___THREAD
219
220 #if HAVE_THREAD_LOCAL
221 #include <threads.h>
222 #elif HAVE___THREAD
223 #define thread_local __thread
224 #else
225 #error
226 #endif
227
228 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...)                 \
229     typedef TYPE NAME##_type;                                   \
230     static thread_local NAME##_type NAME##_var = __VA_ARGS__;   \
231                                                                 \
232     static NAME##_type *                                        \
233     NAME##_get_unsafe(void)                                     \
234     {                                                           \
235         return &NAME##_var;                                     \
236     }                                                           \
237                                                                 \
238     static NAME##_type *                                        \
239     NAME##_get(void)                                            \
240     {                                                           \
241         return NAME##_get_unsafe();                             \
242     }
243 #else  /* no C implementation support for thread-local storage  */
244 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...)                         \
245     typedef TYPE NAME##_type;                                           \
246     static pthread_key_t NAME##_key;                                    \
247                                                                         \
248     static NAME##_type *                                                \
249     NAME##_get_unsafe(void)                                             \
250     {                                                                   \
251         return pthread_getspecific(NAME##_key);                         \
252     }                                                                   \
253                                                                         \
254     static void                                                         \
255     NAME##_once_init(void)                                              \
256     {                                                                   \
257         if (pthread_key_create(&NAME##_key, free)) {                    \
258             abort();                                                    \
259         }                                                               \
260     }                                                                   \
261                                                                         \
262     static NAME##_type *                                                \
263     NAME##_get(void)                                                    \
264     {                                                                   \
265         static pthread_once_t once = PTHREAD_ONCE_INIT;                 \
266         NAME##_type *value;                                             \
267                                                                         \
268         pthread_once(&once, NAME##_once_init);                          \
269         value = NAME##_get_unsafe();                                    \
270         if (!value) {                                                   \
271             static const NAME##_type initial_value = __VA_ARGS__;       \
272                                                                         \
273             value = xmalloc(sizeof *value);                             \
274             *value = initial_value;                                     \
275             pthread_setspecific(NAME##_key, value);                     \
276         }                                                               \
277         return value;                                                   \
278     }
279 #endif
280
281 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
282  *
283  * This is a simple wrapper around POSIX per-thread data primitives.  It
284  * defines per-thread variable NAME with the given TYPE, which must be a
285  * pointer type.  In each thread, the per-thread variable is initialized to
286  * NULL.  When a thread terminates, the variable is freed with free().
287  *
288  * The public interface to the variable is:
289  *
290  *    TYPE NAME_get(void)
291  *    TYPE NAME_get_unsafe(void)
292  *
293  *       Returns the value of per-thread variable NAME in this thread.
294  *
295  *       Use NAME_get() in a context where this might be the first use of the
296  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
297  *       avoids a conditional test and is thus slightly faster, in a context
298  *       where one knows that NAME_get() has already been called previously.
299  *
300  *    TYPE NAME_set(TYPE new_value)
301  *    TYPE NAME_set_unsafe(TYPE new_value)
302  *
303  *       Sets the value of per-thread variable NAME to 'new_value' in this
304  *       thread, and returns its previous value.
305  *
306  *       Use NAME_set() in a context where this might be the first use of the
307  *       per-thread variable in the program.  Use NAME_set_unsafe(), which
308  *       avoids a conditional test and is thus slightly faster, in a context
309  *       where one knows that NAME_set() has already been called previously.
310  */
311 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME)     \
312     static pthread_key_t NAME##_key;                    \
313                                                         \
314     static void                                         \
315     NAME##_once_init(void)                              \
316     {                                                   \
317         if (pthread_key_create(&NAME##_key, free)) {    \
318             abort();                                    \
319         }                                               \
320     }                                                   \
321                                                         \
322     static void                                         \
323     NAME##_init(void)                                   \
324     {                                                   \
325         static pthread_once_t once = PTHREAD_ONCE_INIT; \
326         pthread_once(&once, NAME##_once_init);          \
327     }                                                   \
328                                                         \
329     static TYPE                                         \
330     NAME##_get_unsafe(void)                             \
331     {                                                   \
332         return pthread_getspecific(NAME##_key);         \
333     }                                                   \
334                                                         \
335     static OVS_UNUSED TYPE                              \
336     NAME##_get(void)                                    \
337     {                                                   \
338         NAME##_init();                                  \
339         return NAME##_get_unsafe();                     \
340     }                                                   \
341                                                         \
342     static TYPE                                         \
343     NAME##_set_unsafe(TYPE value)                       \
344     {                                                   \
345         TYPE old_value = NAME##_get_unsafe();           \
346         pthread_setspecific(NAME##_key, value);         \
347         return old_value;                               \
348     }                                                   \
349                                                         \
350     static OVS_UNUSED TYPE                              \
351     NAME##_set(TYPE value)                              \
352     {                                                   \
353         NAME##_init();                                  \
354         return NAME##_set_unsafe(value);                \
355     }
356 \f
357 /* Convenient once-only execution.
358  *
359  *
360  * Problem
361  * =======
362  *
363  * POSIX provides pthread_once_t and pthread_once() as primitives for running a
364  * set of code only once per process execution.  They are used like this:
365  *
366  *     static void run_once(void) { ...initialization... }
367  *     static pthread_once_t once = PTHREAD_ONCE_INIT;
368  * ...
369  *     pthread_once(&once, run_once);
370  *
371  * pthread_once() does not allow passing any parameters to the initialization
372  * function, which is often inconvenient, because it means that the function
373  * can only access data declared at file scope.
374  *
375  *
376  * Solution
377  * ========
378  *
379  * Use ovsthread_once, like this, instead:
380  *
381  *     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
382  *
383  *     if (ovsthread_once_start(&once)) {
384  *         ...initialization...
385  *         ovsthread_once_done(&once);
386  *     }
387  */
388
389 struct ovsthread_once {
390     atomic_bool done;
391     struct ovs_mutex mutex;
392 };
393
394 #define OVSTHREAD_ONCE_INITIALIZER              \
395     {                                           \
396         ATOMIC_VAR_INIT(false),                 \
397         OVS_ADAPTIVE_MUTEX_INITIALIZER,         \
398     }
399
400 static inline bool ovsthread_once_start(struct ovsthread_once *once)
401     OVS_TRY_LOCK(true, &once->mutex);
402 void ovsthread_once_done(struct ovsthread_once *once)
403     OVS_RELEASES(&once->mutex);
404
405 bool ovsthread_once_start__(struct ovsthread_once *once)
406     OVS_TRY_LOCK(false, &once->mutex);
407
408 static inline bool
409 ovsthread_once_is_done__(const struct ovsthread_once *once)
410 {
411     bool done;
412
413     atomic_read_explicit(&once->done, &done, memory_order_relaxed);
414     return done;
415 }
416
417 /* Returns true if this is the first call to ovsthread_once_start() for
418  * 'once'.  In this case, the caller should perform whatever initialization
419  * actions it needs to do, then call ovsthread_once_done() for 'once'.
420  *
421  * Returns false if this is not the first call to ovsthread_once_start() for
422  * 'once'.  In this case, the call will not return until after
423  * ovsthread_once_done() has been called. */
424 static inline bool
425 ovsthread_once_start(struct ovsthread_once *once)
426 {
427     return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
428                         && !ovsthread_once_start__(once));
429 }
430
431 #ifdef __CHECKER__
432 #define ovsthread_once_start(ONCE) \
433     ((ONCE)->done ? false : ({ OVS_MACRO_LOCK((&ONCE->mutex)); true; }))
434 #endif
435 \f
436 void assert_single_threaded_at(const char *where);
437 #define assert_single_threaded() assert_single_threaded_at(SOURCE_LOCATOR)
438
439 pid_t xfork_at(const char *where);
440 #define xfork() xfork_at(SOURCE_LOCATOR)
441
442 void forbid_forking(const char *reason);
443 bool may_fork(void);
444
445 #endif /* ovs-thread.h */