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