2 * Copyright (c) 2013, 2014, 2015 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"
27 #include "fatal-signal.h"
30 #include "netdev-dpdk.h"
32 #include "poll-loop.h"
34 #include "socket-util.h"
38 /* Omit the definitions in this file because they are somewhat difficult to
39 * write without prompting "sparse" complaints, without ugliness or
40 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
41 * doesn't matter that we don't define them. */
43 #include "openvswitch/vlog.h"
45 VLOG_DEFINE_THIS_MODULE(ovs_thread);
47 /* If there is a reason that we cannot fork anymore (unless the fork will be
48 * immediately followed by an exec), then this points to a string that
50 static const char *must_not_fork;
52 /* True if we created any threads beyond the main initial thread. */
53 static bool multithreaded;
55 #define LOCK_FUNCTION(TYPE, FUN) \
57 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
59 OVS_NO_THREAD_SAFETY_ANALYSIS \
61 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
64 /* Verify that 'l' was initialized. */ \
65 if (OVS_UNLIKELY(!l->where)) { \
66 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
70 error = pthread_##TYPE##_##FUN(&l->lock); \
71 if (OVS_UNLIKELY(error)) { \
72 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
76 LOCK_FUNCTION(mutex, lock);
77 LOCK_FUNCTION(rwlock, rdlock);
78 LOCK_FUNCTION(rwlock, wrlock);
80 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
82 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
84 OVS_NO_THREAD_SAFETY_ANALYSIS \
86 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
89 /* Verify that 'l' was initialized. */ \
90 if (OVS_UNLIKELY(!l->where)) { \
91 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
95 error = pthread_##TYPE##_##FUN(&l->lock); \
96 if (OVS_UNLIKELY(error) && error != EBUSY) { \
97 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
104 TRY_LOCK_FUNCTION(mutex, trylock);
105 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
106 TRY_LOCK_FUNCTION(rwlock, trywrlock);
108 #define UNLOCK_FUNCTION(TYPE, FUN, WHERE) \
110 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
111 OVS_NO_THREAD_SAFETY_ANALYSIS \
113 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
116 /* Verify that 'l' was initialized. */ \
117 ovs_assert(l->where); \
120 error = pthread_##TYPE##_##FUN(&l->lock); \
121 if (OVS_UNLIKELY(error)) { \
122 ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
125 UNLOCK_FUNCTION(mutex, unlock, "<unlocked>");
126 UNLOCK_FUNCTION(mutex, destroy, NULL);
127 UNLOCK_FUNCTION(rwlock, unlock, "<unlocked>");
128 UNLOCK_FUNCTION(rwlock, destroy, NULL);
130 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
132 x##FUNCTION(PARAM1 arg1) \
134 int error = FUNCTION(arg1); \
135 if (OVS_UNLIKELY(error)) { \
136 ovs_abort(error, "%s failed", #FUNCTION); \
139 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
141 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
143 int error = FUNCTION(arg1, arg2); \
144 if (OVS_UNLIKELY(error)) { \
145 ovs_abort(error, "%s failed", #FUNCTION); \
148 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
150 x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3) \
152 int error = FUNCTION(arg1, arg2, arg3); \
153 if (OVS_UNLIKELY(error)) { \
154 ovs_abort(error, "%s failed", #FUNCTION); \
158 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
159 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
160 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
161 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
162 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
163 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
165 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
166 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
167 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
168 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
171 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
172 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
173 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
174 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
176 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
178 typedef void destructor_func(void *);
179 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
180 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
181 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
184 XPTHREAD_FUNC3(pthread_sigmask, int, const sigset_t *, sigset_t *);
188 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
190 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
191 pthread_mutexattr_t attr;
194 l->where = "<unlocked>";
195 xpthread_mutexattr_init(&attr);
196 xpthread_mutexattr_settype(&attr, type);
197 error = pthread_mutex_init(&l->lock, &attr);
198 if (OVS_UNLIKELY(error)) {
199 ovs_abort(error, "pthread_mutex_init failed");
201 xpthread_mutexattr_destroy(&attr);
204 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
206 ovs_mutex_init(const struct ovs_mutex *mutex)
208 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
211 /* Initializes 'mutex' as a recursive mutex. */
213 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
215 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
218 /* Initializes 'mutex' as a recursive mutex. */
220 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
222 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
223 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
225 ovs_mutex_init(mutex);
230 ovs_rwlock_init(const struct ovs_rwlock *l_)
232 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
233 pthread_rwlockattr_t attr;
236 l->where = "<unlocked>";
238 xpthread_rwlockattr_init(&attr);
239 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
240 xpthread_rwlockattr_setkind_np(
241 &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
243 error = pthread_rwlock_init(&l->lock, NULL);
244 if (OVS_UNLIKELY(error)) {
245 ovs_abort(error, "pthread_rwlock_init failed");
247 xpthread_rwlockattr_destroy(&attr);
251 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
253 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
256 ovsrcu_quiesce_start();
257 error = pthread_cond_wait(cond, &mutex->lock);
258 ovsrcu_quiesce_end();
260 if (OVS_UNLIKELY(error)) {
261 ovs_abort(error, "pthread_cond_wait failed");
265 /* Initializes the 'barrier'. 'size' is the number of threads
266 * expected to hit the barrier. */
268 ovs_barrier_init(struct ovs_barrier *barrier, uint32_t size)
270 barrier->size = size;
271 atomic_count_init(&barrier->count, 0);
272 barrier->seq = seq_create();
275 /* Destroys the 'barrier'. */
277 ovs_barrier_destroy(struct ovs_barrier *barrier)
279 seq_destroy(barrier->seq);
282 /* Makes the calling thread block on the 'barrier' until all
283 * 'barrier->size' threads hit the barrier.
284 * ovs_barrier provides the necessary acquire-release semantics to make
285 * the effects of prior memory accesses of all the participating threads
286 * visible on return and to prevent the following memory accesses to be
287 * reordered before the ovs_barrier_block(). */
289 ovs_barrier_block(struct ovs_barrier *barrier)
291 uint64_t seq = seq_read(barrier->seq);
294 orig = atomic_count_inc(&barrier->count);
295 if (orig + 1 == barrier->size) {
296 atomic_count_set(&barrier->count, 0);
297 /* seq_change() serves as a release barrier against the other threads,
298 * so the zeroed count is visible to them as they continue. */
299 seq_change(barrier->seq);
301 /* To prevent thread from waking up by other event,
302 * keeps waiting for the change of 'barrier->seq'. */
303 while (seq == seq_read(barrier->seq)) {
304 seq_wait(barrier->seq, seq);
310 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
312 struct ovsthread_aux {
313 void *(*start)(void *);
319 ovsthread_wrapper(void *aux_)
321 static atomic_count next_id = ATOMIC_COUNT_INIT(1);
323 struct ovsthread_aux *auxp = aux_;
324 struct ovsthread_aux aux;
327 id = atomic_count_inc(&next_id);
328 *ovsthread_id_get() = id;
333 /* The order of the following calls is important, because
334 * ovsrcu_quiesce_end() saves a copy of the thread name. */
335 char *subprogram_name = xasprintf("%s%u", aux.name, id);
336 set_subprogram_name(subprogram_name);
337 free(subprogram_name);
338 ovsrcu_quiesce_end();
340 return aux.start(aux.arg);
343 /* Starts a thread that calls 'start(arg)'. Sets the thread's name to 'name'
344 * (suffixed by its ovsthread_id()). Returns the new thread's pthread_t. */
346 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
348 struct ovsthread_aux *aux;
352 forbid_forking("multiple threads exist");
353 multithreaded = true;
354 ovsrcu_quiesce_end();
356 aux = xmalloc(sizeof *aux);
359 ovs_strlcpy(aux->name, name, sizeof aux->name);
361 error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
363 ovs_abort(error, "pthread_create failed");
369 ovsthread_once_start__(struct ovsthread_once *once)
371 ovs_mutex_lock(&once->mutex);
372 /* Mutex synchronizes memory, so we get the current value of 'done'. */
376 ovs_mutex_unlock(&once->mutex);
381 ovsthread_once_done(struct ovsthread_once *once)
383 /* We need release semantics here, so that the following store may not
384 * be moved ahead of any of the preceding initialization operations.
385 * A release atomic_thread_fence provides that prior memory accesses
386 * will not be reordered to take place after the following store. */
387 atomic_thread_fence(memory_order_release);
389 ovs_mutex_unlock(&once->mutex);
393 single_threaded(void)
395 return !multithreaded;
398 /* Asserts that the process has not yet created any threads (beyond the initial
401 * ('where' is used in logging. Commonly one would use
402 * assert_single_threaded() to automatically provide the caller's source file
403 * and line number for 'where'.) */
405 assert_single_threaded_at(const char *where)
408 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
414 /* Forks the current process (checking that this is allowed). Aborts with
415 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
416 * returned by fork().
418 * ('where' is used in logging. Commonly one would use xfork() to
419 * automatically provide the caller's source file and line number for
422 xfork_at(const char *where)
427 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
428 where, must_not_fork);
433 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
439 /* Notes that the process must not call fork() from now on, for the specified
440 * 'reason'. (The process may still fork() if it execs itself immediately
443 forbid_forking(const char *reason)
445 ovs_assert(reason != NULL);
446 must_not_fork = reason;
449 /* Returns true if the process is allowed to fork, false otherwise. */
453 return !must_not_fork;
456 /* ovsthread_stats. */
459 ovsthread_stats_init(struct ovsthread_stats *stats)
463 ovs_mutex_init(&stats->mutex);
464 for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
465 stats->buckets[i] = NULL;
470 ovsthread_stats_destroy(struct ovsthread_stats *stats)
472 ovs_mutex_destroy(&stats->mutex);
476 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
477 void *(*new_bucket)(void))
479 unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
480 void *bucket = stats->buckets[idx];
482 ovs_mutex_lock(&stats->mutex);
483 bucket = stats->buckets[idx];
485 bucket = stats->buckets[idx] = new_bucket();
487 ovs_mutex_unlock(&stats->mutex);
493 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
495 for (; i < ARRAY_SIZE(stats->buckets); i++) {
496 if (stats->buckets[i]) {
504 /* Parses /proc/cpuinfo for the total number of physical cores on this system
505 * across all CPU packages, not counting hyper-threads.
507 * Sets *n_cores to the total number of cores on this system, or 0 if the
508 * number cannot be determined. */
510 parse_cpuinfo(long int *n_cores)
512 static const char file_name[] = "/proc/cpuinfo";
514 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
518 stream = fopen(file_name, "r");
520 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
524 while (fgets(line, sizeof line, stream)) {
527 /* Find the next CPU package. */
528 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
530 VLOG_WARN("Counted over 64 CPU packages on this system. "
531 "Parsing %s for core count may be inaccurate.",
537 if (cpu & (1ULL << id)) {
538 /* We've already counted this package's cores. */
543 /* Find the number of cores for this package. */
544 while (fgets(line, sizeof line, stream)) {
547 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
559 /* Returns the total number of cores on this system, or 0 if the number cannot
562 * Tries not to count hyper-threads, but may be inaccurate - particularly on
563 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
564 * formatted different to the layout that parse_cpuinfo() expects. */
566 count_cpu_cores(void)
568 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
569 static long int n_cores;
571 if (ovsthread_once_start(&once)) {
573 parse_cpuinfo(&n_cores);
575 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
579 GetSystemInfo(&sysinfo);
580 n_cores = sysinfo.dwNumberOfProcessors;
582 ovsthread_once_done(&once);
585 return n_cores > 0 ? n_cores : 0;
588 /* Returns 'true' if current thread is PMD thread. */
592 const char *name = get_subprogram_name();
593 return !strncmp(name, "pmd", 3);
601 #define MAX_KEYS (L1_SIZE * L2_SIZE)
603 /* A piece of thread-specific data. */
604 struct ovsthread_key {
605 struct ovs_list list_node; /* In 'inuse_keys' or 'free_keys'. */
606 void (*destructor)(void *); /* Called at thread exit. */
608 /* Indexes into the per-thread array in struct ovsthread_key_slots.
609 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
613 /* Per-thread data structure. */
614 struct ovsthread_key_slots {
615 struct ovs_list list_node; /* In 'slots_list'. */
619 /* Contains "struct ovsthread_key_slots *". */
620 static pthread_key_t tsd_key;
622 /* Guards data structures below. */
623 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
625 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
628 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
629 * ready for reuse. (We keep them around only to be able to easily locate
632 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
633 * from 0 to n_keys - 1, inclusive. */
634 static struct ovs_list inuse_keys OVS_GUARDED_BY(key_mutex)
635 = OVS_LIST_INITIALIZER(&inuse_keys);
636 static struct ovs_list free_keys OVS_GUARDED_BY(key_mutex)
637 = OVS_LIST_INITIALIZER(&free_keys);
638 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
640 /* All existing struct ovsthread_key_slots. */
641 static struct ovs_list slots_list OVS_GUARDED_BY(key_mutex)
642 = OVS_LIST_INITIALIZER(&slots_list);
645 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
647 void **p2 = slots->p1[index / L2_SIZE];
649 void **valuep = &p2[index % L2_SIZE];
650 void *value = *valuep;
659 ovsthread_key_destruct__(void *slots_)
661 struct ovsthread_key_slots *slots = slots_;
662 struct ovsthread_key *key;
666 ovs_mutex_lock(&key_mutex);
667 list_remove(&slots->list_node);
668 LIST_FOR_EACH (key, list_node, &inuse_keys) {
669 void *value = clear_slot(slots, key->index);
670 if (value && key->destructor) {
671 key->destructor(value);
675 ovs_mutex_unlock(&key_mutex);
677 for (i = 0; i < DIV_ROUND_UP(n, L2_SIZE); i++) {
683 /* Cancels the callback to ovsthread_key_destruct__().
685 * Cancelling the call to the destructor during the main thread exit
686 * is needed while using pthreads-win32 library in Windows. It has been
687 * observed that in pthreads-win32, a call to the destructor during
688 * main thread exit causes undefined behavior. */
690 ovsthread_cancel_ovsthread_key_destruct__(void *aux OVS_UNUSED)
692 pthread_setspecific(tsd_key, NULL);
695 /* Initializes '*keyp' as a thread-specific data key. The data items are
696 * initially null in all threads.
698 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
699 * called passing the final data value as its argument. 'destructor' must not
700 * call any thread-specific data functions in this API.
702 * This function is similar to xpthread_key_create(). */
704 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
706 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
707 struct ovsthread_key *key;
709 if (ovsthread_once_start(&once)) {
710 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
711 fatal_signal_add_hook(ovsthread_cancel_ovsthread_key_destruct__,
713 ovsthread_once_done(&once);
716 ovs_mutex_lock(&key_mutex);
717 if (list_is_empty(&free_keys)) {
718 key = xmalloc(sizeof *key);
719 key->index = n_keys++;
720 if (key->index >= MAX_KEYS) {
724 key = CONTAINER_OF(list_pop_back(&free_keys),
725 struct ovsthread_key, list_node);
727 list_push_back(&inuse_keys, &key->list_node);
728 key->destructor = destructor;
729 ovs_mutex_unlock(&key_mutex);
734 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
737 * This function is similar to xpthread_key_delete(). */
739 ovsthread_key_delete(ovsthread_key_t key)
741 struct ovsthread_key_slots *slots;
743 ovs_mutex_lock(&key_mutex);
745 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
746 list_remove(&key->list_node);
747 list_push_back(&free_keys, &key->list_node);
749 /* Clear this slot in all threads. */
750 LIST_FOR_EACH (slots, list_node, &slots_list) {
751 clear_slot(slots, key->index);
754 ovs_mutex_unlock(&key_mutex);
758 ovsthread_key_lookup__(const struct ovsthread_key *key)
760 struct ovsthread_key_slots *slots;
763 slots = pthread_getspecific(tsd_key);
765 slots = xzalloc(sizeof *slots);
767 ovs_mutex_lock(&key_mutex);
768 pthread_setspecific(tsd_key, slots);
769 list_push_back(&slots_list, &slots->list_node);
770 ovs_mutex_unlock(&key_mutex);
773 p2 = slots->p1[key->index / L2_SIZE];
775 p2 = xzalloc(L2_SIZE * sizeof *p2);
776 slots->p1[key->index / L2_SIZE] = p2;
779 return &p2[key->index % L2_SIZE];
782 /* Sets the value of thread-specific data item 'key', in the current thread, to
785 * This function is similar to pthread_setspecific(). */
787 ovsthread_setspecific(ovsthread_key_t key, const void *value)
789 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
792 /* Returns the value of thread-specific data item 'key' in the current thread.
794 * This function is similar to pthread_getspecific(). */
796 ovsthread_getspecific(ovsthread_key_t key)
798 return *ovsthread_key_lookup__(key);