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