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"
28 #include "netdev-dpdk.h"
30 #include "poll-loop.h"
32 #include "socket-util.h"
36 /* Omit the definitions in this file because they are somewhat difficult to
37 * write without prompting "sparse" complaints, without ugliness or
38 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
39 * doesn't matter that we don't define them. */
43 VLOG_DEFINE_THIS_MODULE(ovs_thread);
45 /* If there is a reason that we cannot fork anymore (unless the fork will be
46 * immediately followed by an exec), then this points to a string that
48 static const char *must_not_fork;
50 /* True if we created any threads beyond the main initial thread. */
51 static bool multithreaded;
53 #define LOCK_FUNCTION(TYPE, FUN) \
55 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
57 OVS_NO_THREAD_SAFETY_ANALYSIS \
59 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
62 /* Verify that 'l' was initialized. */ \
63 if (OVS_UNLIKELY(!l->where)) { \
64 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
68 error = pthread_##TYPE##_##FUN(&l->lock); \
69 if (OVS_UNLIKELY(error)) { \
70 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
74 LOCK_FUNCTION(mutex, lock);
75 LOCK_FUNCTION(rwlock, rdlock);
76 LOCK_FUNCTION(rwlock, wrlock);
78 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
80 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
82 OVS_NO_THREAD_SAFETY_ANALYSIS \
84 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
87 /* Verify that 'l' was initialized. */ \
88 if (OVS_UNLIKELY(!l->where)) { \
89 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
93 error = pthread_##TYPE##_##FUN(&l->lock); \
94 if (OVS_UNLIKELY(error) && error != EBUSY) { \
95 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
102 TRY_LOCK_FUNCTION(mutex, trylock);
103 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
104 TRY_LOCK_FUNCTION(rwlock, trywrlock);
106 #define UNLOCK_FUNCTION(TYPE, FUN, WHERE) \
108 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
109 OVS_NO_THREAD_SAFETY_ANALYSIS \
111 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
114 /* Verify that 'l' was initialized. */ \
115 ovs_assert(l->where); \
118 error = pthread_##TYPE##_##FUN(&l->lock); \
119 if (OVS_UNLIKELY(error)) { \
120 ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
123 UNLOCK_FUNCTION(mutex, unlock, "<unlocked>");
124 UNLOCK_FUNCTION(mutex, destroy, NULL);
125 UNLOCK_FUNCTION(rwlock, unlock, "<unlocked>");
126 UNLOCK_FUNCTION(rwlock, destroy, NULL);
128 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
130 x##FUNCTION(PARAM1 arg1) \
132 int error = FUNCTION(arg1); \
133 if (OVS_UNLIKELY(error)) { \
134 ovs_abort(error, "%s failed", #FUNCTION); \
137 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
139 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
141 int error = FUNCTION(arg1, arg2); \
142 if (OVS_UNLIKELY(error)) { \
143 ovs_abort(error, "%s failed", #FUNCTION); \
146 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
148 x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3) \
150 int error = FUNCTION(arg1, arg2, arg3); \
151 if (OVS_UNLIKELY(error)) { \
152 ovs_abort(error, "%s failed", #FUNCTION); \
156 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
157 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
158 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
159 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
160 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
161 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
163 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
164 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
165 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
166 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
169 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
170 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
171 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
172 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
174 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
176 typedef void destructor_func(void *);
177 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
178 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
179 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
182 XPTHREAD_FUNC3(pthread_sigmask, int, const sigset_t *, sigset_t *);
186 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
188 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
189 pthread_mutexattr_t attr;
192 l->where = "<unlocked>";
193 xpthread_mutexattr_init(&attr);
194 xpthread_mutexattr_settype(&attr, type);
195 error = pthread_mutex_init(&l->lock, &attr);
196 if (OVS_UNLIKELY(error)) {
197 ovs_abort(error, "pthread_mutex_init failed");
199 xpthread_mutexattr_destroy(&attr);
202 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
204 ovs_mutex_init(const struct ovs_mutex *mutex)
206 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
209 /* Initializes 'mutex' as a recursive mutex. */
211 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
213 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
216 /* Initializes 'mutex' as a recursive mutex. */
218 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
220 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
221 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
223 ovs_mutex_init(mutex);
228 ovs_rwlock_init(const struct ovs_rwlock *l_)
230 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
231 pthread_rwlockattr_t attr;
234 l->where = "<unlocked>";
236 xpthread_rwlockattr_init(&attr);
237 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
238 xpthread_rwlockattr_setkind_np(
239 &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
241 error = pthread_rwlock_init(&l->lock, NULL);
242 if (OVS_UNLIKELY(error)) {
243 ovs_abort(error, "pthread_rwlock_init failed");
245 xpthread_rwlockattr_destroy(&attr);
249 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
251 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
254 ovsrcu_quiesce_start();
255 error = pthread_cond_wait(cond, &mutex->lock);
256 ovsrcu_quiesce_end();
258 if (OVS_UNLIKELY(error)) {
259 ovs_abort(error, "pthread_cond_wait failed");
263 /* Initializes the 'barrier'. 'size' is the number of threads
264 * expected to hit the barrier. */
266 ovs_barrier_init(struct ovs_barrier *barrier, uint32_t size)
268 barrier->size = size;
269 atomic_count_init(&barrier->count, 0);
270 barrier->seq = seq_create();
273 /* Destroys the 'barrier'. */
275 ovs_barrier_destroy(struct ovs_barrier *barrier)
277 seq_destroy(barrier->seq);
280 /* Makes the calling thread block on the 'barrier' until all
281 * 'barrier->size' threads hit the barrier.
282 * ovs_barrier provides the necessary acquire-release semantics to make
283 * the effects of prior memory accesses of all the participating threads
284 * visible on return and to prevent the following memory accesses to be
285 * reordered before the ovs_barrier_block(). */
287 ovs_barrier_block(struct ovs_barrier *barrier)
289 uint64_t seq = seq_read(barrier->seq);
292 orig = atomic_count_inc(&barrier->count);
293 if (orig + 1 == barrier->size) {
294 atomic_count_set(&barrier->count, 0);
295 /* seq_change() serves as a release barrier against the other threads,
296 * so the zeroed count is visible to them as they continue. */
297 seq_change(barrier->seq);
299 /* To prevent thread from waking up by other event,
300 * keeps waiting for the change of 'barrier->seq'. */
301 while (seq == seq_read(barrier->seq)) {
302 seq_wait(barrier->seq, seq);
308 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
310 struct ovsthread_aux {
311 void *(*start)(void *);
317 ovsthread_wrapper(void *aux_)
319 static atomic_count next_id = ATOMIC_COUNT_INIT(1);
321 struct ovsthread_aux *auxp = aux_;
322 struct ovsthread_aux aux;
325 id = atomic_count_inc(&next_id);
326 *ovsthread_id_get() = id;
331 /* The order of the following calls is important, because
332 * ovsrcu_quiesce_end() saves a copy of the thread name. */
333 set_subprogram_name("%s%u", aux.name, id);
334 ovsrcu_quiesce_end();
338 return aux.start(aux.arg);
341 /* Starts a thread that calls 'start(arg)'. Sets the thread's name to 'name'
342 * (suffixed by its ovsthread_id()). Returns the new thread's pthread_t. */
344 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
346 struct ovsthread_aux *aux;
350 forbid_forking("multiple threads exist");
351 multithreaded = true;
352 ovsrcu_quiesce_end();
354 aux = xmalloc(sizeof *aux);
357 ovs_strlcpy(aux->name, name, sizeof aux->name);
359 error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
361 ovs_abort(error, "pthread_create failed");
367 ovsthread_once_start__(struct ovsthread_once *once)
369 ovs_mutex_lock(&once->mutex);
370 /* Mutex synchronizes memory, so we get the current value of 'done'. */
374 ovs_mutex_unlock(&once->mutex);
379 ovsthread_once_done(struct ovsthread_once *once)
381 /* We need release semantics here, so that the following store may not
382 * be moved ahead of any of the preceding initialization operations.
383 * A release atomic_thread_fence provides that prior memory accesses
384 * will not be reordered to take place after the following store. */
385 atomic_thread_fence(memory_order_release);
387 ovs_mutex_unlock(&once->mutex);
391 single_threaded(void)
393 return !multithreaded;
396 /* Asserts that the process has not yet created any threads (beyond the initial
399 * ('where' is used in logging. Commonly one would use
400 * assert_single_threaded() to automatically provide the caller's source file
401 * and line number for 'where'.) */
403 assert_single_threaded_at(const char *where)
406 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
412 /* Forks the current process (checking that this is allowed). Aborts with
413 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
414 * returned by fork().
416 * ('where' is used in logging. Commonly one would use xfork() to
417 * automatically provide the caller's source file and line number for
420 xfork_at(const char *where)
425 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
426 where, must_not_fork);
431 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
437 /* Notes that the process must not call fork() from now on, for the specified
438 * 'reason'. (The process may still fork() if it execs itself immediately
441 forbid_forking(const char *reason)
443 ovs_assert(reason != NULL);
444 must_not_fork = reason;
447 /* Returns true if the process is allowed to fork, false otherwise. */
451 return !must_not_fork;
454 /* ovsthread_stats. */
457 ovsthread_stats_init(struct ovsthread_stats *stats)
461 ovs_mutex_init(&stats->mutex);
462 for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
463 stats->buckets[i] = NULL;
468 ovsthread_stats_destroy(struct ovsthread_stats *stats)
470 ovs_mutex_destroy(&stats->mutex);
474 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
475 void *(*new_bucket)(void))
477 unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
478 void *bucket = stats->buckets[idx];
480 ovs_mutex_lock(&stats->mutex);
481 bucket = stats->buckets[idx];
483 bucket = stats->buckets[idx] = new_bucket();
485 ovs_mutex_unlock(&stats->mutex);
491 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
493 for (; i < ARRAY_SIZE(stats->buckets); i++) {
494 if (stats->buckets[i]) {
502 /* Parses /proc/cpuinfo for the total number of physical cores on this system
503 * across all CPU packages, not counting hyper-threads.
505 * Sets *n_cores to the total number of cores on this system, or 0 if the
506 * number cannot be determined. */
508 parse_cpuinfo(long int *n_cores)
510 static const char file_name[] = "/proc/cpuinfo";
512 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
516 stream = fopen(file_name, "r");
518 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
522 while (fgets(line, sizeof line, stream)) {
525 /* Find the next CPU package. */
526 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
528 VLOG_WARN("Counted over 64 CPU packages on this system. "
529 "Parsing %s for core count may be inaccurate.",
535 if (cpu & (1ULL << id)) {
536 /* We've already counted this package's cores. */
541 /* Find the number of cores for this package. */
542 while (fgets(line, sizeof line, stream)) {
545 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
557 /* Returns the total number of cores on this system, or 0 if the number cannot
560 * Tries not to count hyper-threads, but may be inaccurate - particularly on
561 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
562 * formatted different to the layout that parse_cpuinfo() expects. */
564 count_cpu_cores(void)
566 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
567 static long int n_cores;
569 if (ovsthread_once_start(&once)) {
571 parse_cpuinfo(&n_cores);
573 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
577 GetSystemInfo(&sysinfo);
578 n_cores = sysinfo.dwNumberOfProcessors;
580 ovsthread_once_done(&once);
583 return n_cores > 0 ? n_cores : 0;
590 #define MAX_KEYS (L1_SIZE * L2_SIZE)
592 /* A piece of thread-specific data. */
593 struct ovsthread_key {
594 struct list list_node; /* In 'inuse_keys' or 'free_keys'. */
595 void (*destructor)(void *); /* Called at thread exit. */
597 /* Indexes into the per-thread array in struct ovsthread_key_slots.
598 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
602 /* Per-thread data structure. */
603 struct ovsthread_key_slots {
604 struct list list_node; /* In 'slots_list'. */
608 /* Contains "struct ovsthread_key_slots *". */
609 static pthread_key_t tsd_key;
611 /* Guards data structures below. */
612 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
614 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
617 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
618 * ready for reuse. (We keep them around only to be able to easily locate
621 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
622 * from 0 to n_keys - 1, inclusive. */
623 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
624 = LIST_INITIALIZER(&inuse_keys);
625 static struct list free_keys OVS_GUARDED_BY(key_mutex)
626 = LIST_INITIALIZER(&free_keys);
627 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
629 /* All existing struct ovsthread_key_slots. */
630 static struct list slots_list OVS_GUARDED_BY(key_mutex)
631 = LIST_INITIALIZER(&slots_list);
634 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
636 void **p2 = slots->p1[index / L2_SIZE];
638 void **valuep = &p2[index % L2_SIZE];
639 void *value = *valuep;
648 ovsthread_key_destruct__(void *slots_)
650 struct ovsthread_key_slots *slots = slots_;
651 struct ovsthread_key *key;
655 ovs_mutex_lock(&key_mutex);
656 list_remove(&slots->list_node);
657 LIST_FOR_EACH (key, list_node, &inuse_keys) {
658 void *value = clear_slot(slots, key->index);
659 if (value && key->destructor) {
660 key->destructor(value);
664 ovs_mutex_unlock(&key_mutex);
666 for (i = 0; i < n / L2_SIZE; i++) {
672 /* Initializes '*keyp' as a thread-specific data key. The data items are
673 * initially null in all threads.
675 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
676 * called passing the final data value as its argument. 'destructor' must not
677 * call any thread-specific data functions in this API.
679 * This function is similar to xpthread_key_create(). */
681 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
683 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
684 struct ovsthread_key *key;
686 if (ovsthread_once_start(&once)) {
687 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
688 ovsthread_once_done(&once);
691 ovs_mutex_lock(&key_mutex);
692 if (list_is_empty(&free_keys)) {
693 key = xmalloc(sizeof *key);
694 key->index = n_keys++;
695 if (key->index >= MAX_KEYS) {
699 key = CONTAINER_OF(list_pop_back(&free_keys),
700 struct ovsthread_key, list_node);
702 list_push_back(&inuse_keys, &key->list_node);
703 key->destructor = destructor;
704 ovs_mutex_unlock(&key_mutex);
709 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
712 * This function is similar to xpthread_key_delete(). */
714 ovsthread_key_delete(ovsthread_key_t key)
716 struct ovsthread_key_slots *slots;
718 ovs_mutex_lock(&key_mutex);
720 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
721 list_remove(&key->list_node);
722 list_push_back(&free_keys, &key->list_node);
724 /* Clear this slot in all threads. */
725 LIST_FOR_EACH (slots, list_node, &slots_list) {
726 clear_slot(slots, key->index);
729 ovs_mutex_unlock(&key_mutex);
733 ovsthread_key_lookup__(const struct ovsthread_key *key)
735 struct ovsthread_key_slots *slots;
738 slots = pthread_getspecific(tsd_key);
740 slots = xzalloc(sizeof *slots);
742 ovs_mutex_lock(&key_mutex);
743 pthread_setspecific(tsd_key, slots);
744 list_push_back(&slots_list, &slots->list_node);
745 ovs_mutex_unlock(&key_mutex);
748 p2 = slots->p1[key->index / L2_SIZE];
750 p2 = xzalloc(L2_SIZE * sizeof *p2);
751 slots->p1[key->index / L2_SIZE] = p2;
754 return &p2[key->index % L2_SIZE];
757 /* Sets the value of thread-specific data item 'key', in the current thread, to
760 * This function is similar to pthread_setspecific(). */
762 ovsthread_setspecific(ovsthread_key_t key, const void *value)
764 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
767 /* Returns the value of thread-specific data item 'key' in the current thread.
769 * This function is similar to pthread_getspecific(). */
771 ovsthread_getspecific(ovsthread_key_t key)
773 return *ovsthread_key_lookup__(key);