ovs-thread: Get rid of obsolete sparse wrappers.
[sliver-openvswitch.git] / lib / ovs-thread.h
1 /*
2  * Copyright (c) 2013, 2014 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" initializer. */
34 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
35 #define OVS_MUTEX_INITIALIZER { PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, NULL }
36 #else
37 #define OVS_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, NULL }
38 #endif
39
40 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
41 #define OVS_ADAPTIVE_MUTEX_INITIALIZER                  \
42     { PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP, NULL }
43 #else
44 #define OVS_ADAPTIVE_MUTEX_INITIALIZER OVS_MUTEX_INITIALIZER
45 #endif
46
47 /* ovs_mutex functions analogous to pthread_mutex_*() functions.
48  *
49  * Most of these functions abort the process with an error message on any
50  * error.  ovs_mutex_trylock() is an exception: it passes through a 0 or EBUSY
51  * return value to the caller and aborts on any other error. */
52 void ovs_mutex_init(const struct ovs_mutex *);
53 void ovs_mutex_init_recursive(const struct ovs_mutex *);
54 void ovs_mutex_init_adaptive(const struct ovs_mutex *);
55 void ovs_mutex_destroy(const struct ovs_mutex *);
56 void ovs_mutex_unlock(const struct ovs_mutex *mutex) OVS_RELEASES(mutex);
57 void ovs_mutex_lock_at(const struct ovs_mutex *mutex, const char *where)
58     OVS_ACQUIRES(mutex);
59 #define ovs_mutex_lock(mutex) \
60         ovs_mutex_lock_at(mutex, SOURCE_LOCATOR)
61
62 int ovs_mutex_trylock_at(const struct ovs_mutex *mutex, const char *where)
63     OVS_TRY_LOCK(0, mutex);
64 #define ovs_mutex_trylock(mutex) \
65         ovs_mutex_trylock_at(mutex, SOURCE_LOCATOR)
66
67 void ovs_mutex_cond_wait(pthread_cond_t *, const struct ovs_mutex *);
68
69 /* Wrappers for pthread_mutex_*() that abort the process on any error.
70  * This is still needed when ovs-atomic-pthreads.h is used. */
71 void xpthread_mutex_lock(pthread_mutex_t *mutex);
72 void xpthread_mutex_unlock(pthread_mutex_t *mutex);
73
74 /* Wrappers for pthread_mutexattr_*() that abort the process on any error. */
75 void xpthread_mutexattr_init(pthread_mutexattr_t *);
76 void xpthread_mutexattr_destroy(pthread_mutexattr_t *);
77 void xpthread_mutexattr_settype(pthread_mutexattr_t *, int type);
78 void xpthread_mutexattr_gettype(pthread_mutexattr_t *, int *typep);
79
80 /* Read-write lock. */
81 struct OVS_LOCKABLE ovs_rwlock {
82     pthread_rwlock_t lock;
83     const char *where;
84 };
85
86 /* Initializer. */
87 #define OVS_RWLOCK_INITIALIZER { PTHREAD_RWLOCK_INITIALIZER, NULL }
88
89 /* ovs_rwlock functions analogous to pthread_rwlock_*() functions.
90  *
91  * Most of these functions abort the process with an error message on any
92  * error.  The "trylock" functions are exception: they pass through a 0 or
93  * EBUSY return value to the caller and abort on any other error. */
94 void ovs_rwlock_init(const struct ovs_rwlock *);
95 void ovs_rwlock_destroy(const struct ovs_rwlock *);
96 void ovs_rwlock_unlock(const struct ovs_rwlock *rwlock) OVS_RELEASES(rwlock);
97
98 void ovs_rwlock_wrlock_at(const struct ovs_rwlock *rwlock, const char *where)
99     OVS_ACQ_WRLOCK(rwlock);
100 #define ovs_rwlock_wrlock(rwlock) \
101         ovs_rwlock_wrlock_at(rwlock, SOURCE_LOCATOR)
102
103 int ovs_rwlock_trywrlock_at(const struct ovs_rwlock *rwlock, const char *where)
104     OVS_TRY_WRLOCK(0, rwlock);
105 #define ovs_rwlock_trywrlock(rwlock) \
106     ovs_rwlock_trywrlock_at(rwlock, SOURCE_LOCATOR)
107
108 void ovs_rwlock_rdlock_at(const struct ovs_rwlock *rwlock, const char *where)
109     OVS_ACQ_RDLOCK(rwlock);
110 #define ovs_rwlock_rdlock(rwlock) \
111         ovs_rwlock_rdlock_at(rwlock, SOURCE_LOCATOR)
112
113 int ovs_rwlock_tryrdlock_at(const struct ovs_rwlock *rwlock, const char *where)
114     OVS_TRY_RDLOCK(0, rwlock);
115 #define ovs_rwlock_tryrdlock(rwlock) \
116         ovs_rwlock_tryrdlock_at(rwlock, SOURCE_LOCATOR)
117
118 /* Wrappers for xpthread_cond_*() that abort the process on any error.
119  *
120  * Use ovs_mutex_cond_wait() to wait for a condition. */
121 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
122 void xpthread_cond_destroy(pthread_cond_t *);
123 void xpthread_cond_signal(pthread_cond_t *);
124 void xpthread_cond_broadcast(pthread_cond_t *);
125
126 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
127 void xpthread_key_delete(pthread_key_t);
128 void xpthread_setspecific(pthread_key_t, const void *);
129
130 void xpthread_create(pthread_t *, pthread_attr_t *, void *(*)(void *), void *);
131 void xpthread_join(pthread_t, void **);
132 \f
133 /* Per-thread data.
134  *
135  *
136  * Standard Forms
137  * ==============
138  *
139  * Multiple forms of standard per-thread data exist, each with its own pluses
140  * and minuses.  In general, if one of these forms is appropriate, then it's a
141  * good idea to use it:
142  *
143  *     - POSIX per-thread data via pthread_key_t is portable to any pthreads
144  *       implementation, and allows a destructor function to be defined.  It
145  *       only (directly) supports per-thread pointers, which are always
146  *       initialized to NULL.  It requires once-only allocation of a
147  *       pthread_key_t value.  It is relatively slow.  Typically few
148  *       "pthread_key_t"s are available (POSIX requires only at least 128,
149  *       glibc supplies only 1024).
150  *
151  *     - The thread_local feature newly defined in C11 <threads.h> works with
152  *       any data type and initializer, and it is fast.  thread_local does not
153  *       require once-only initialization like pthread_key_t.  C11 does not
154  *       define what happens if one attempts to access a thread_local object
155  *       from a thread other than the one to which that object belongs.  There
156  *       is no provision to call a user-specified destructor when a thread
157  *       ends.  Typical implementations allow for an arbitrary amount of
158  *       thread_local storage, but statically allocated only.
159  *
160  *     - The __thread keyword is a GCC extension similar to thread_local but
161  *       with a longer history.  __thread is not portable to every GCC version
162  *       or environment.  __thread does not restrict the use of a thread-local
163  *       object outside its own thread.
164  *
165  * Here's a handy summary:
166  *
167  *                     pthread_key_t     thread_local       __thread
168  *                     -------------     ------------     -------------
169  * portability             high               low             medium
170  * speed                    low              high               high
171  * supports destructors?    yes                no                 no
172  * needs key allocation?    yes                no                 no
173  * arbitrary initializer?    no               yes                yes
174  * cross-thread access?     yes                no                yes
175  * amount available?        few            arbitrary         arbitrary
176  * dynamically allocated?   yes                no                 no
177  *
178  *
179  * Extensions
180  * ==========
181  *
182  * OVS provides some extensions and wrappers:
183  *
184  *     - In a situation where the performance of thread_local or __thread is
185  *       desirable, but portability is required, DEFINE_STATIC_PER_THREAD_DATA
186  *       and DECLARE_EXTERN_PER_THREAD_DATA/DEFINE_EXTERN_PER_THREAD_DATA may
187  *       be appropriate (see below).
188  *
189  *     - DEFINE_PER_THREAD_MALLOCED_DATA can be convenient for simple
190  *       per-thread malloc()'d buffers.
191  *
192  *     - struct ovs_tsd provides an alternative to pthread_key_t that isn't
193  *       limited to a small number of keys.
194  */
195
196 /* For static data, use this macro in a source file:
197  *
198  *    DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
199  *
200  * For global data, "declare" the data in the header and "define" it in
201  * the source file, with:
202  *
203  *    DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME).
204  *    DEFINE_EXTERN_PER_THREAD_DATA(NAME, INITIALIZER).
205  *
206  * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
207  * performance is acceptable, because of its portability (see the table above).
208  * This macro is an alternatives that takes advantage of thread_local (and
209  * __thread), for its performance, when it is available, and falls back to
210  * POSIX per-thread data otherwise.
211  *
212  * Defines per-thread variable NAME with the given TYPE, initialized to
213  * INITIALIZER (which must be valid as an initializer for a variable with
214  * static lifetime).
215  *
216  * The public interface to the variable is:
217  *
218  *    TYPE *NAME_get(void)
219  *    TYPE *NAME_get_unsafe(void)
220  *
221  *       Returns the address of this thread's instance of NAME.
222  *
223  *       Use NAME_get() in a context where this might be the first use of the
224  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
225  *       avoids a conditional test and is thus slightly faster, in a context
226  *       where one knows that NAME_get() has already been called previously.
227  *
228  * There is no "NAME_set()" (or "NAME_set_unsafe()") function.  To set the
229  * value of the per-thread variable, dereference the pointer returned by
230  * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
231  */
232 #if HAVE_THREAD_LOCAL || HAVE___THREAD
233
234 #if HAVE_THREAD_LOCAL
235 #include <threads.h>
236 #elif HAVE___THREAD
237 #define thread_local __thread
238 #else
239 #error
240 #endif
241
242 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...)                  \
243     typedef TYPE NAME##_type;                                           \
244                                                                         \
245     static NAME##_type *                                                \
246     NAME##_get_unsafe(void)                                             \
247     {                                                                   \
248         static thread_local NAME##_type var = __VA_ARGS__;              \
249         return &var;                                                    \
250     }                                                                   \
251                                                                         \
252     static NAME##_type *                                                \
253     NAME##_get(void)                                                    \
254     {                                                                   \
255         return NAME##_get_unsafe();                                     \
256     }
257 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME)                      \
258     typedef TYPE NAME##_type;                                           \
259     extern thread_local NAME##_type NAME##_var;                         \
260                                                                         \
261     static inline NAME##_type *                                         \
262     NAME##_get_unsafe(void)                                             \
263     {                                                                   \
264         return &NAME##_var;                                             \
265     }                                                                   \
266                                                                         \
267     static inline NAME##_type *                                         \
268     NAME##_get(void)                                                    \
269     {                                                                   \
270         return NAME##_get_unsafe();                                     \
271     }
272 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...)         \
273     thread_local NAME##_type NAME##_var = __VA_ARGS__;
274 #else  /* no C implementation support for thread-local storage  */
275 #define DEFINE_STATIC_PER_THREAD_DATA(TYPE, NAME, ...)                  \
276     typedef TYPE NAME##_type;                                           \
277     static pthread_key_t NAME##_key;                                    \
278                                                                         \
279     static NAME##_type *                                                \
280     NAME##_get_unsafe(void)                                             \
281     {                                                                   \
282         return pthread_getspecific(NAME##_key);                         \
283     }                                                                   \
284                                                                         \
285     static void                                                         \
286     NAME##_once_init(void)                                              \
287     {                                                                   \
288         if (pthread_key_create(&NAME##_key, free)) {                    \
289             abort();                                                    \
290         }                                                               \
291     }                                                                   \
292                                                                         \
293     static NAME##_type *                                                \
294     NAME##_get(void)                                                    \
295     {                                                                   \
296         static pthread_once_t once = PTHREAD_ONCE_INIT;                 \
297         NAME##_type *value;                                             \
298                                                                         \
299         pthread_once(&once, NAME##_once_init);                          \
300         value = NAME##_get_unsafe();                                    \
301         if (!value) {                                                   \
302             static const NAME##_type initial_value = __VA_ARGS__;       \
303                                                                         \
304             value = malloc(sizeof *value);                              \
305             if (value == NULL) {                                        \
306                 out_of_memory();                                        \
307             }                                                           \
308             *value = initial_value;                                     \
309             xpthread_setspecific(NAME##_key, value);                    \
310         }                                                               \
311         return value;                                                   \
312     }
313 #define DECLARE_EXTERN_PER_THREAD_DATA(TYPE, NAME)                      \
314     typedef TYPE NAME##_type;                                           \
315     static pthread_key_t NAME##_key;                                    \
316                                                                         \
317     static inline NAME##_type *                                         \
318     NAME##_get_unsafe(void)                                             \
319     {                                                                   \
320         return pthread_getspecific(NAME##_key);                         \
321     }                                                                   \
322                                                                         \
323     NAME##_type *NAME##_get(void);
324 #define DEFINE_EXTERN_PER_THREAD_DATA(NAME, ...)                        \
325     static void                                                         \
326     NAME##_once_init(void)                                              \
327     {                                                                   \
328         if (pthread_key_create(&NAME##_key, free)) {                    \
329             abort();                                                    \
330         }                                                               \
331     }                                                                   \
332                                                                         \
333     NAME##_type *                                                       \
334     NAME##_get(void)                                                    \
335     {                                                                   \
336         static pthread_once_t once = PTHREAD_ONCE_INIT;                 \
337         NAME##_type *value;                                             \
338                                                                         \
339         pthread_once(&once, NAME##_once_init);                          \
340         value = NAME##_get_unsafe();                                    \
341         if (!value) {                                                   \
342             static const NAME##_type initial_value = __VA_ARGS__;       \
343                                                                         \
344             value = malloc(sizeof *value);                              \
345             if (value == NULL) {                                        \
346                 out_of_memory();                                        \
347             }                                                           \
348             *value = initial_value;                                     \
349             xpthread_setspecific(NAME##_key, value);                    \
350         }                                                               \
351         return value;                                                   \
352     }
353 #endif
354
355 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
356  *
357  * This is a simple wrapper around POSIX per-thread data primitives.  It
358  * defines per-thread variable NAME with the given TYPE, which must be a
359  * pointer type.  In each thread, the per-thread variable is initialized to
360  * NULL.  When a thread terminates, the variable is freed with free().
361  *
362  * The public interface to the variable is:
363  *
364  *    TYPE NAME_get(void)
365  *    TYPE NAME_get_unsafe(void)
366  *
367  *       Returns the value of per-thread variable NAME in this thread.
368  *
369  *       Use NAME_get() in a context where this might be the first use of the
370  *       per-thread variable in the program.  Use NAME_get_unsafe(), which
371  *       avoids a conditional test and is thus slightly faster, in a context
372  *       where one knows that NAME_get() has already been called previously.
373  *
374  *    TYPE NAME_set(TYPE new_value)
375  *    TYPE NAME_set_unsafe(TYPE new_value)
376  *
377  *       Sets the value of per-thread variable NAME to 'new_value' in this
378  *       thread, and returns its previous value.
379  *
380  *       Use NAME_set() in a context where this might be the first use of the
381  *       per-thread variable in the program.  Use NAME_set_unsafe(), which
382  *       avoids a conditional test and is thus slightly faster, in a context
383  *       where one knows that NAME_set() has already been called previously.
384  */
385 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME)     \
386     static pthread_key_t NAME##_key;                    \
387                                                         \
388     static void                                         \
389     NAME##_once_init(void)                              \
390     {                                                   \
391         if (pthread_key_create(&NAME##_key, free)) {    \
392             abort();                                    \
393         }                                               \
394     }                                                   \
395                                                         \
396     static void                                         \
397     NAME##_init(void)                                   \
398     {                                                   \
399         static pthread_once_t once = PTHREAD_ONCE_INIT; \
400         pthread_once(&once, NAME##_once_init);          \
401     }                                                   \
402                                                         \
403     static TYPE                                         \
404     NAME##_get_unsafe(void)                             \
405     {                                                   \
406         return pthread_getspecific(NAME##_key);         \
407     }                                                   \
408                                                         \
409     static OVS_UNUSED TYPE                              \
410     NAME##_get(void)                                    \
411     {                                                   \
412         NAME##_init();                                  \
413         return NAME##_get_unsafe();                     \
414     }                                                   \
415                                                         \
416     static TYPE                                         \
417     NAME##_set_unsafe(TYPE value)                       \
418     {                                                   \
419         TYPE old_value = NAME##_get_unsafe();           \
420         xpthread_setspecific(NAME##_key, value);        \
421         return old_value;                               \
422     }                                                   \
423                                                         \
424     static OVS_UNUSED TYPE                              \
425     NAME##_set(TYPE value)                              \
426     {                                                   \
427         NAME##_init();                                  \
428         return NAME##_set_unsafe(value);                \
429     }
430
431 /* Dynamically allocated thread-specific data with lots of slots.
432  *
433  * pthread_key_t can provide as few as 128 pieces of thread-specific data (even
434  * glibc is limited to 1,024).  Thus, one must be careful to allocate only a
435  * few keys globally.  One cannot, for example, allocate a key for every
436  * instance of a data structure if there might be an arbitrary number of those
437  * data structures.
438  *
439  * This API is similar to the pthread one (simply search and replace pthread_
440  * by ovsthread_) but it a much larger limit that can be raised if necessary
441  * (by recompiling).  Thus, one may more freely use this form of
442  * thread-specific data.
443  *
444  * ovsthread_key_t also differs from pthread_key_t in the following ways:
445  *
446  *    - Destructors must not access thread-specific data (via ovsthread_key).
447  *
448  *    - The pthread_key_t API allows concurrently exiting threads to start
449  *      executing the destructor after pthread_key_delete() returns.  The
450  *      ovsthread_key_t API guarantees that, when ovsthread_key_delete()
451  *      returns, all destructors have returned and no new ones will start
452  *      execution.
453  */
454 typedef struct ovsthread_key *ovsthread_key_t;
455
456 void ovsthread_key_create(ovsthread_key_t *, void (*destructor)(void *));
457 void ovsthread_key_delete(ovsthread_key_t);
458
459 void ovsthread_setspecific(ovsthread_key_t, const void *);
460 void *ovsthread_getspecific(ovsthread_key_t);
461 \f
462 /* Convenient once-only execution.
463  *
464  *
465  * Problem
466  * =======
467  *
468  * POSIX provides pthread_once_t and pthread_once() as primitives for running a
469  * set of code only once per process execution.  They are used like this:
470  *
471  *     static void run_once(void) { ...initialization... }
472  *     static pthread_once_t once = PTHREAD_ONCE_INIT;
473  * ...
474  *     pthread_once(&once, run_once);
475  *
476  * pthread_once() does not allow passing any parameters to the initialization
477  * function, which is often inconvenient, because it means that the function
478  * can only access data declared at file scope.
479  *
480  *
481  * Solution
482  * ========
483  *
484  * Use ovsthread_once, like this, instead:
485  *
486  *     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
487  *
488  *     if (ovsthread_once_start(&once)) {
489  *         ...initialization...
490  *         ovsthread_once_done(&once);
491  *     }
492  */
493
494 struct ovsthread_once {
495     atomic_bool done;
496     struct ovs_mutex mutex;
497 };
498
499 #define OVSTHREAD_ONCE_INITIALIZER              \
500     {                                           \
501         ATOMIC_VAR_INIT(false),                 \
502         OVS_MUTEX_INITIALIZER,                  \
503     }
504
505 static inline bool ovsthread_once_start(struct ovsthread_once *once)
506     OVS_TRY_LOCK(true, once->mutex);
507 void ovsthread_once_done(struct ovsthread_once *once)
508     OVS_RELEASES(once->mutex);
509
510 bool ovsthread_once_start__(struct ovsthread_once *once)
511     OVS_TRY_LOCK(false, once->mutex);
512
513 static inline bool
514 ovsthread_once_is_done__(struct ovsthread_once *once)
515 {
516     bool done;
517
518     atomic_read_explicit(&once->done, &done, memory_order_relaxed);
519     return done;
520 }
521
522 /* Returns true if this is the first call to ovsthread_once_start() for
523  * 'once'.  In this case, the caller should perform whatever initialization
524  * actions it needs to do, then call ovsthread_once_done() for 'once'.
525  *
526  * Returns false if this is not the first call to ovsthread_once_start() for
527  * 'once'.  In this case, the call will not return until after
528  * ovsthread_once_done() has been called. */
529 static inline bool
530 ovsthread_once_start(struct ovsthread_once *once)
531 {
532     return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
533                         && !ovsthread_once_start__(once));
534 }
535 \f
536 /* Thread ID.
537  *
538  * pthread_t isn't so nice for some purposes.  Its size and representation are
539  * implementation dependent, which means that there is no way to hash it.
540  * This thread ID avoids the problem.
541  */
542
543 DECLARE_EXTERN_PER_THREAD_DATA(unsigned int, ovsthread_id);
544
545 /* Returns a per-thread identifier unique within the lifetime of the
546  * process. */
547 static inline unsigned int
548 ovsthread_id_self(void)
549 {
550     return *ovsthread_id_get();
551 }
552 \f
553 /* Simulated global counter.
554  *
555  * Incrementing such a counter is meant to be cheaper than incrementing a
556  * global counter protected by a lock.  It is probably more expensive than
557  * incrementing a truly thread-local variable, but such a variable has no
558  * straightforward way to get the sum.
559  *
560  *
561  * Thread-safety
562  * =============
563  *
564  * Fully thread-safe. */
565
566 struct ovsthread_counter *ovsthread_counter_create(void);
567 void ovsthread_counter_destroy(struct ovsthread_counter *);
568 void ovsthread_counter_inc(struct ovsthread_counter *, unsigned long long int);
569 unsigned long long int ovsthread_counter_read(
570     const struct ovsthread_counter *);
571 \f
572 void assert_single_threaded_at(const char *where);
573 #define assert_single_threaded() assert_single_threaded_at(SOURCE_LOCATOR)
574
575 pid_t xfork_at(const char *where);
576 #define xfork() xfork_at(SOURCE_LOCATOR)
577
578 void forbid_forking(const char *reason);
579 bool may_fork(void);
580 \f
581 /* Useful functions related to threading. */
582
583 int count_cpu_cores(void);
584
585 #endif /* ovs-thread.h */