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