2 * Copyright (c) 2013, 2014 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "ovs-thread.h"
26 #include "poll-loop.h"
28 #include "socket-util.h"
32 /* Omit the definitions in this file because they are somewhat difficult to
33 * write without prompting "sparse" complaints, without ugliness or
34 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
35 * doesn't matter that we don't define them. */
39 VLOG_DEFINE_THIS_MODULE(ovs_thread);
41 /* If there is a reason that we cannot fork anymore (unless the fork will be
42 * immediately followed by an exec), then this points to a string that
44 static const char *must_not_fork;
46 /* True if we created any threads beyond the main initial thread. */
47 static bool multithreaded;
49 #define LOCK_FUNCTION(TYPE, FUN) \
51 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
53 OVS_NO_THREAD_SAFETY_ANALYSIS \
55 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
58 /* Verify that 'l' was initialized. */ \
59 if (OVS_UNLIKELY(!l->where)) { \
60 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
64 error = pthread_##TYPE##_##FUN(&l->lock); \
65 if (OVS_UNLIKELY(error)) { \
66 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
70 LOCK_FUNCTION(mutex, lock);
71 LOCK_FUNCTION(rwlock, rdlock);
72 LOCK_FUNCTION(rwlock, wrlock);
74 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
76 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
78 OVS_NO_THREAD_SAFETY_ANALYSIS \
80 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
83 /* Verify that 'l' was initialized. */ \
84 if (OVS_UNLIKELY(!l->where)) { \
85 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
89 error = pthread_##TYPE##_##FUN(&l->lock); \
90 if (OVS_UNLIKELY(error) && error != EBUSY) { \
91 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
98 TRY_LOCK_FUNCTION(mutex, trylock);
99 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
100 TRY_LOCK_FUNCTION(rwlock, trywrlock);
102 #define UNLOCK_FUNCTION(TYPE, FUN, WHERE) \
104 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
105 OVS_NO_THREAD_SAFETY_ANALYSIS \
107 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
110 /* Verify that 'l' was initialized. */ \
111 ovs_assert(l->where); \
114 error = pthread_##TYPE##_##FUN(&l->lock); \
115 if (OVS_UNLIKELY(error)) { \
116 ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
119 UNLOCK_FUNCTION(mutex, unlock, "<unlocked>");
120 UNLOCK_FUNCTION(mutex, destroy, NULL);
121 UNLOCK_FUNCTION(rwlock, unlock, "<unlocked>");
122 UNLOCK_FUNCTION(rwlock, destroy, NULL);
124 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
126 x##FUNCTION(PARAM1 arg1) \
128 int error = FUNCTION(arg1); \
129 if (OVS_UNLIKELY(error)) { \
130 ovs_abort(error, "%s failed", #FUNCTION); \
133 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
135 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
137 int error = FUNCTION(arg1, arg2); \
138 if (OVS_UNLIKELY(error)) { \
139 ovs_abort(error, "%s failed", #FUNCTION); \
142 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
144 x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3) \
146 int error = FUNCTION(arg1, arg2, arg3); \
147 if (OVS_UNLIKELY(error)) { \
148 ovs_abort(error, "%s failed", #FUNCTION); \
152 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
153 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
154 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
155 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
156 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
157 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
159 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
160 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
161 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
162 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
165 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
166 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
167 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
168 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
170 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
172 typedef void destructor_func(void *);
173 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
174 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
175 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
178 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
180 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
181 pthread_mutexattr_t attr;
184 l->where = "<unlocked>";
185 xpthread_mutexattr_init(&attr);
186 xpthread_mutexattr_settype(&attr, type);
187 error = pthread_mutex_init(&l->lock, &attr);
188 if (OVS_UNLIKELY(error)) {
189 ovs_abort(error, "pthread_mutex_init failed");
191 xpthread_mutexattr_destroy(&attr);
194 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
196 ovs_mutex_init(const struct ovs_mutex *mutex)
198 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
201 /* Initializes 'mutex' as a recursive mutex. */
203 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
205 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
208 /* Initializes 'mutex' as a recursive mutex. */
210 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
212 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
213 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
215 ovs_mutex_init(mutex);
220 ovs_rwlock_init(const struct ovs_rwlock *l_)
222 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
223 pthread_rwlockattr_t attr;
226 l->where = "<unlocked>";
228 xpthread_rwlockattr_init(&attr);
229 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
230 xpthread_rwlockattr_setkind_np(
231 &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
233 error = pthread_rwlock_init(&l->lock, NULL);
234 if (OVS_UNLIKELY(error)) {
235 ovs_abort(error, "pthread_rwlock_init failed");
237 xpthread_rwlockattr_destroy(&attr);
241 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
243 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
246 ovsrcu_quiesce_start();
247 error = pthread_cond_wait(cond, &mutex->lock);
248 ovsrcu_quiesce_end();
250 if (OVS_UNLIKELY(error)) {
251 ovs_abort(error, "pthread_cond_wait failed");
255 /* Initializes the 'barrier'. 'size' is the number of threads
256 * expected to hit the barrier. */
258 ovs_barrier_init(struct ovs_barrier *barrier, uint32_t size)
260 barrier->size = size;
261 atomic_init(&barrier->count, 0);
262 barrier->seq = seq_create();
265 /* Destroys the 'barrier'. */
267 ovs_barrier_destroy(struct ovs_barrier *barrier)
269 seq_destroy(barrier->seq);
272 /* Makes the calling thread block on the 'barrier' until all
273 * 'barrier->size' threads hit the barrier. */
275 ovs_barrier_block(struct ovs_barrier *barrier)
277 uint64_t seq = seq_read(barrier->seq);
280 atomic_add(&barrier->count, 1, &orig);
281 if (orig + 1 == barrier->size) {
282 atomic_store(&barrier->count, 0);
283 seq_change(barrier->seq);
286 /* To prevent thread from waking up by other event,
287 * keeps waiting for the change of 'barrier->seq'. */
288 while (seq == seq_read(barrier->seq)) {
289 seq_wait(barrier->seq, seq);
294 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
296 struct ovsthread_aux {
297 void *(*start)(void *);
303 ovsthread_wrapper(void *aux_)
305 static atomic_uint next_id = ATOMIC_VAR_INIT(1);
307 struct ovsthread_aux *auxp = aux_;
308 struct ovsthread_aux aux;
311 atomic_add(&next_id, 1, &id);
312 *ovsthread_id_get() = id;
317 /* The order of the following calls is important, because
318 * ovsrcu_quiesce_end() saves a copy of the thread name. */
319 set_subprogram_name("%s%u", aux.name, id);
320 ovsrcu_quiesce_end();
322 return aux.start(aux.arg);
325 /* Starts a thread that calls 'start(arg)'. Sets the thread's name to 'name'
326 * (suffixed by its ovsthread_id()). Returns the new thread's pthread_t. */
328 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
330 struct ovsthread_aux *aux;
334 forbid_forking("multiple threads exist");
335 multithreaded = true;
336 ovsrcu_quiesce_end();
338 aux = xmalloc(sizeof *aux);
341 ovs_strlcpy(aux->name, name, sizeof aux->name);
343 error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
345 ovs_abort(error, "pthread_create failed");
351 ovsthread_once_start__(struct ovsthread_once *once)
353 ovs_mutex_lock(&once->mutex);
354 if (!ovsthread_once_is_done__(once)) {
357 ovs_mutex_unlock(&once->mutex);
362 ovsthread_once_done(struct ovsthread_once *once)
364 atomic_store(&once->done, true);
365 ovs_mutex_unlock(&once->mutex);
369 single_threaded(void)
371 return !multithreaded;
374 /* Asserts that the process has not yet created any threads (beyond the initial
377 * ('where' is used in logging. Commonly one would use
378 * assert_single_threaded() to automatically provide the caller's source file
379 * and line number for 'where'.) */
381 assert_single_threaded_at(const char *where)
384 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
390 /* Forks the current process (checking that this is allowed). Aborts with
391 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
392 * returned by fork().
394 * ('where' is used in logging. Commonly one would use xfork() to
395 * automatically provide the caller's source file and line number for
398 xfork_at(const char *where)
403 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
404 where, must_not_fork);
409 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
415 /* Notes that the process must not call fork() from now on, for the specified
416 * 'reason'. (The process may still fork() if it execs itself immediately
419 forbid_forking(const char *reason)
421 ovs_assert(reason != NULL);
422 must_not_fork = reason;
425 /* Returns true if the process is allowed to fork, false otherwise. */
429 return !must_not_fork;
432 /* ovsthread_stats. */
435 ovsthread_stats_init(struct ovsthread_stats *stats)
439 ovs_mutex_init(&stats->mutex);
440 for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
441 stats->buckets[i] = NULL;
446 ovsthread_stats_destroy(struct ovsthread_stats *stats)
448 ovs_mutex_destroy(&stats->mutex);
452 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
453 void *(*new_bucket)(void))
455 unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
456 void *bucket = stats->buckets[idx];
458 ovs_mutex_lock(&stats->mutex);
459 bucket = stats->buckets[idx];
461 bucket = stats->buckets[idx] = new_bucket();
463 ovs_mutex_unlock(&stats->mutex);
469 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
471 for (; i < ARRAY_SIZE(stats->buckets); i++) {
472 if (stats->buckets[i]) {
480 /* Parses /proc/cpuinfo for the total number of physical cores on this system
481 * across all CPU packages, not counting hyper-threads.
483 * Sets *n_cores to the total number of cores on this system, or 0 if the
484 * number cannot be determined. */
486 parse_cpuinfo(long int *n_cores)
488 static const char file_name[] = "/proc/cpuinfo";
490 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
494 stream = fopen(file_name, "r");
496 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
500 while (fgets(line, sizeof line, stream)) {
503 /* Find the next CPU package. */
504 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
506 VLOG_WARN("Counted over 64 CPU packages on this system. "
507 "Parsing %s for core count may be inaccurate.",
513 if (cpu & (1ULL << id)) {
514 /* We've already counted this package's cores. */
519 /* Find the number of cores for this package. */
520 while (fgets(line, sizeof line, stream)) {
523 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
535 /* Returns the total number of cores on this system, or 0 if the number cannot
538 * Tries not to count hyper-threads, but may be inaccurate - particularly on
539 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
540 * formatted different to the layout that parse_cpuinfo() expects. */
542 count_cpu_cores(void)
544 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
545 static long int n_cores;
547 if (ovsthread_once_start(&once)) {
549 parse_cpuinfo(&n_cores);
551 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
555 GetSystemInfo(&sysinfo);
556 n_cores = sysinfo.dwNumberOfProcessors;
558 ovsthread_once_done(&once);
561 return n_cores > 0 ? n_cores : 0;
568 #define MAX_KEYS (L1_SIZE * L2_SIZE)
570 /* A piece of thread-specific data. */
571 struct ovsthread_key {
572 struct list list_node; /* In 'inuse_keys' or 'free_keys'. */
573 void (*destructor)(void *); /* Called at thread exit. */
575 /* Indexes into the per-thread array in struct ovsthread_key_slots.
576 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
580 /* Per-thread data structure. */
581 struct ovsthread_key_slots {
582 struct list list_node; /* In 'slots_list'. */
586 /* Contains "struct ovsthread_key_slots *". */
587 static pthread_key_t tsd_key;
589 /* Guards data structures below. */
590 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
592 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
595 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
596 * ready for reuse. (We keep them around only to be able to easily locate
599 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
600 * from 0 to n_keys - 1, inclusive. */
601 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
602 = LIST_INITIALIZER(&inuse_keys);
603 static struct list free_keys OVS_GUARDED_BY(key_mutex)
604 = LIST_INITIALIZER(&free_keys);
605 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
607 /* All existing struct ovsthread_key_slots. */
608 static struct list slots_list OVS_GUARDED_BY(key_mutex)
609 = LIST_INITIALIZER(&slots_list);
612 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
614 void **p2 = slots->p1[index / L2_SIZE];
616 void **valuep = &p2[index % L2_SIZE];
617 void *value = *valuep;
626 ovsthread_key_destruct__(void *slots_)
628 struct ovsthread_key_slots *slots = slots_;
629 struct ovsthread_key *key;
633 ovs_mutex_lock(&key_mutex);
634 list_remove(&slots->list_node);
635 LIST_FOR_EACH (key, list_node, &inuse_keys) {
636 void *value = clear_slot(slots, key->index);
637 if (value && key->destructor) {
638 key->destructor(value);
642 ovs_mutex_unlock(&key_mutex);
644 for (i = 0; i < n / L2_SIZE; i++) {
650 /* Initializes '*keyp' as a thread-specific data key. The data items are
651 * initially null in all threads.
653 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
654 * called passing the final data value as its argument. 'destructor' must not
655 * call any thread-specific data functions in this API.
657 * This function is similar to xpthread_key_create(). */
659 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
661 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
662 struct ovsthread_key *key;
664 if (ovsthread_once_start(&once)) {
665 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
666 ovsthread_once_done(&once);
669 ovs_mutex_lock(&key_mutex);
670 if (list_is_empty(&free_keys)) {
671 key = xmalloc(sizeof *key);
672 key->index = n_keys++;
673 if (key->index >= MAX_KEYS) {
677 key = CONTAINER_OF(list_pop_back(&free_keys),
678 struct ovsthread_key, list_node);
680 list_push_back(&inuse_keys, &key->list_node);
681 key->destructor = destructor;
682 ovs_mutex_unlock(&key_mutex);
687 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
690 * This function is similar to xpthread_key_delete(). */
692 ovsthread_key_delete(ovsthread_key_t key)
694 struct ovsthread_key_slots *slots;
696 ovs_mutex_lock(&key_mutex);
698 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
699 list_remove(&key->list_node);
700 list_push_back(&free_keys, &key->list_node);
702 /* Clear this slot in all threads. */
703 LIST_FOR_EACH (slots, list_node, &slots_list) {
704 clear_slot(slots, key->index);
707 ovs_mutex_unlock(&key_mutex);
711 ovsthread_key_lookup__(const struct ovsthread_key *key)
713 struct ovsthread_key_slots *slots;
716 slots = pthread_getspecific(tsd_key);
718 slots = xzalloc(sizeof *slots);
720 ovs_mutex_lock(&key_mutex);
721 pthread_setspecific(tsd_key, slots);
722 list_push_back(&slots_list, &slots->list_node);
723 ovs_mutex_unlock(&key_mutex);
726 p2 = slots->p1[key->index / L2_SIZE];
728 p2 = xzalloc(L2_SIZE * sizeof *p2);
729 slots->p1[key->index / L2_SIZE] = p2;
732 return &p2[key->index % L2_SIZE];
735 /* Sets the value of thread-specific data item 'key', in the current thread, to
738 * This function is similar to pthread_setspecific(). */
740 ovsthread_setspecific(ovsthread_key_t key, const void *value)
742 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
745 /* Returns the value of thread-specific data item 'key' in the current thread.
747 * This function is similar to pthread_getspecific(). */
749 ovsthread_getspecific(ovsthread_key_t key)
751 return *ovsthread_key_lookup__(key);