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"
29 #include "poll-loop.h"
31 #include "socket-util.h"
35 /* Omit the definitions in this file because they are somewhat difficult to
36 * write without prompting "sparse" complaints, without ugliness or
37 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
38 * doesn't matter that we don't define them. */
42 VLOG_DEFINE_THIS_MODULE(ovs_thread);
44 /* If there is a reason that we cannot fork anymore (unless the fork will be
45 * immediately followed by an exec), then this points to a string that
47 static const char *must_not_fork;
49 /* True if we created any threads beyond the main initial thread. */
50 static bool multithreaded;
52 #define LOCK_FUNCTION(TYPE, FUN) \
54 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
56 OVS_NO_THREAD_SAFETY_ANALYSIS \
58 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
61 /* Verify that 'l' was initialized. */ \
62 if (OVS_UNLIKELY(!l->where)) { \
63 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
67 error = pthread_##TYPE##_##FUN(&l->lock); \
68 if (OVS_UNLIKELY(error)) { \
69 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
73 LOCK_FUNCTION(mutex, lock);
74 LOCK_FUNCTION(rwlock, rdlock);
75 LOCK_FUNCTION(rwlock, wrlock);
77 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
79 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
81 OVS_NO_THREAD_SAFETY_ANALYSIS \
83 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
86 /* Verify that 'l' was initialized. */ \
87 if (OVS_UNLIKELY(!l->where)) { \
88 ovs_abort(0, "%s: %s() passed uninitialized ovs_"#TYPE, \
92 error = pthread_##TYPE##_##FUN(&l->lock); \
93 if (OVS_UNLIKELY(error) && error != EBUSY) { \
94 ovs_abort(error, "%s: pthread_%s_%s failed", where, #TYPE, #FUN); \
101 TRY_LOCK_FUNCTION(mutex, trylock);
102 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
103 TRY_LOCK_FUNCTION(rwlock, trywrlock);
105 #define UNLOCK_FUNCTION(TYPE, FUN, WHERE) \
107 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
108 OVS_NO_THREAD_SAFETY_ANALYSIS \
110 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
113 /* Verify that 'l' was initialized. */ \
114 ovs_assert(l->where); \
117 error = pthread_##TYPE##_##FUN(&l->lock); \
118 if (OVS_UNLIKELY(error)) { \
119 ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
122 UNLOCK_FUNCTION(mutex, unlock, "<unlocked>");
123 UNLOCK_FUNCTION(mutex, destroy, NULL);
124 UNLOCK_FUNCTION(rwlock, unlock, "<unlocked>");
125 UNLOCK_FUNCTION(rwlock, destroy, NULL);
127 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
129 x##FUNCTION(PARAM1 arg1) \
131 int error = FUNCTION(arg1); \
132 if (OVS_UNLIKELY(error)) { \
133 ovs_abort(error, "%s failed", #FUNCTION); \
136 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
138 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
140 int error = FUNCTION(arg1, arg2); \
141 if (OVS_UNLIKELY(error)) { \
142 ovs_abort(error, "%s failed", #FUNCTION); \
145 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
147 x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3) \
149 int error = FUNCTION(arg1, arg2, arg3); \
150 if (OVS_UNLIKELY(error)) { \
151 ovs_abort(error, "%s failed", #FUNCTION); \
155 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
156 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
157 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
158 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
159 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
160 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
162 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
163 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
164 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
165 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
168 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
169 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
170 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
171 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
173 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
175 typedef void destructor_func(void *);
176 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
177 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
178 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
181 XPTHREAD_FUNC3(pthread_sigmask, int, const sigset_t *, sigset_t *);
185 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
187 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
188 pthread_mutexattr_t attr;
191 l->where = "<unlocked>";
192 xpthread_mutexattr_init(&attr);
193 xpthread_mutexattr_settype(&attr, type);
194 error = pthread_mutex_init(&l->lock, &attr);
195 if (OVS_UNLIKELY(error)) {
196 ovs_abort(error, "pthread_mutex_init failed");
198 xpthread_mutexattr_destroy(&attr);
201 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
203 ovs_mutex_init(const struct ovs_mutex *mutex)
205 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
208 /* Initializes 'mutex' as a recursive mutex. */
210 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
212 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
215 /* Initializes 'mutex' as a recursive mutex. */
217 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
219 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
220 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
222 ovs_mutex_init(mutex);
227 ovs_rwlock_init(const struct ovs_rwlock *l_)
229 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
230 pthread_rwlockattr_t attr;
233 l->where = "<unlocked>";
235 xpthread_rwlockattr_init(&attr);
236 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
237 xpthread_rwlockattr_setkind_np(
238 &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
240 error = pthread_rwlock_init(&l->lock, NULL);
241 if (OVS_UNLIKELY(error)) {
242 ovs_abort(error, "pthread_rwlock_init failed");
244 xpthread_rwlockattr_destroy(&attr);
248 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
250 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
253 ovsrcu_quiesce_start();
254 error = pthread_cond_wait(cond, &mutex->lock);
255 ovsrcu_quiesce_end();
257 if (OVS_UNLIKELY(error)) {
258 ovs_abort(error, "pthread_cond_wait failed");
262 /* Initializes the 'barrier'. 'size' is the number of threads
263 * expected to hit the barrier. */
265 ovs_barrier_init(struct ovs_barrier *barrier, uint32_t size)
267 barrier->size = size;
268 atomic_init(&barrier->count, 0);
269 barrier->seq = seq_create();
272 /* Destroys the 'barrier'. */
274 ovs_barrier_destroy(struct ovs_barrier *barrier)
276 seq_destroy(barrier->seq);
279 /* Makes the calling thread block on the 'barrier' until all
280 * 'barrier->size' threads hit the barrier. */
282 ovs_barrier_block(struct ovs_barrier *barrier)
284 uint64_t seq = seq_read(barrier->seq);
287 atomic_add(&barrier->count, 1, &orig);
288 if (orig + 1 == barrier->size) {
289 atomic_store(&barrier->count, 0);
290 seq_change(barrier->seq);
293 /* To prevent thread from waking up by other event,
294 * keeps waiting for the change of 'barrier->seq'. */
295 while (seq == seq_read(barrier->seq)) {
296 seq_wait(barrier->seq, seq);
301 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
303 struct ovsthread_aux {
304 void *(*start)(void *);
310 ovsthread_wrapper(void *aux_)
312 static atomic_uint next_id = ATOMIC_VAR_INIT(1);
314 struct ovsthread_aux *auxp = aux_;
315 struct ovsthread_aux aux;
318 atomic_add(&next_id, 1, &id);
319 *ovsthread_id_get() = id;
324 /* The order of the following calls is important, because
325 * ovsrcu_quiesce_end() saves a copy of the thread name. */
326 set_subprogram_name("%s%u", aux.name, id);
327 ovsrcu_quiesce_end();
329 return aux.start(aux.arg);
332 /* Starts a thread that calls 'start(arg)'. Sets the thread's name to 'name'
333 * (suffixed by its ovsthread_id()). Returns the new thread's pthread_t. */
335 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
337 struct ovsthread_aux *aux;
341 forbid_forking("multiple threads exist");
342 multithreaded = true;
343 ovsrcu_quiesce_end();
345 aux = xmalloc(sizeof *aux);
348 ovs_strlcpy(aux->name, name, sizeof aux->name);
350 error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
352 ovs_abort(error, "pthread_create failed");
358 ovsthread_once_start__(struct ovsthread_once *once)
360 ovs_mutex_lock(&once->mutex);
361 if (!ovsthread_once_is_done__(once)) {
364 ovs_mutex_unlock(&once->mutex);
369 ovsthread_once_done(struct ovsthread_once *once)
371 atomic_store(&once->done, true);
372 ovs_mutex_unlock(&once->mutex);
376 single_threaded(void)
378 return !multithreaded;
381 /* Asserts that the process has not yet created any threads (beyond the initial
384 * ('where' is used in logging. Commonly one would use
385 * assert_single_threaded() to automatically provide the caller's source file
386 * and line number for 'where'.) */
388 assert_single_threaded_at(const char *where)
391 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
397 /* Forks the current process (checking that this is allowed). Aborts with
398 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
399 * returned by fork().
401 * ('where' is used in logging. Commonly one would use xfork() to
402 * automatically provide the caller's source file and line number for
405 xfork_at(const char *where)
410 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
411 where, must_not_fork);
416 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
422 /* Notes that the process must not call fork() from now on, for the specified
423 * 'reason'. (The process may still fork() if it execs itself immediately
426 forbid_forking(const char *reason)
428 ovs_assert(reason != NULL);
429 must_not_fork = reason;
432 /* Returns true if the process is allowed to fork, false otherwise. */
436 return !must_not_fork;
439 /* ovsthread_stats. */
442 ovsthread_stats_init(struct ovsthread_stats *stats)
446 ovs_mutex_init(&stats->mutex);
447 for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
448 stats->buckets[i] = NULL;
453 ovsthread_stats_destroy(struct ovsthread_stats *stats)
455 ovs_mutex_destroy(&stats->mutex);
459 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
460 void *(*new_bucket)(void))
462 unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
463 void *bucket = stats->buckets[idx];
465 ovs_mutex_lock(&stats->mutex);
466 bucket = stats->buckets[idx];
468 bucket = stats->buckets[idx] = new_bucket();
470 ovs_mutex_unlock(&stats->mutex);
476 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
478 for (; i < ARRAY_SIZE(stats->buckets); i++) {
479 if (stats->buckets[i]) {
487 /* Parses /proc/cpuinfo for the total number of physical cores on this system
488 * across all CPU packages, not counting hyper-threads.
490 * Sets *n_cores to the total number of cores on this system, or 0 if the
491 * number cannot be determined. */
493 parse_cpuinfo(long int *n_cores)
495 static const char file_name[] = "/proc/cpuinfo";
497 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
501 stream = fopen(file_name, "r");
503 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
507 while (fgets(line, sizeof line, stream)) {
510 /* Find the next CPU package. */
511 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
513 VLOG_WARN("Counted over 64 CPU packages on this system. "
514 "Parsing %s for core count may be inaccurate.",
520 if (cpu & (1 << id)) {
521 /* We've already counted this package's cores. */
526 /* Find the number of cores for this package. */
527 while (fgets(line, sizeof line, stream)) {
530 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
542 /* Returns the total number of cores on this system, or 0 if the number cannot
545 * Tries not to count hyper-threads, but may be inaccurate - particularly on
546 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
547 * formatted different to the layout that parse_cpuinfo() expects. */
549 count_cpu_cores(void)
551 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
552 static long int n_cores;
554 if (ovsthread_once_start(&once)) {
556 parse_cpuinfo(&n_cores);
558 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
562 GetSystemInfo(&sysinfo);
563 n_cores = sysinfo.dwNumberOfProcessors;
565 ovsthread_once_done(&once);
568 return n_cores > 0 ? n_cores : 0;
575 #define MAX_KEYS (L1_SIZE * L2_SIZE)
577 /* A piece of thread-specific data. */
578 struct ovsthread_key {
579 struct list list_node; /* In 'inuse_keys' or 'free_keys'. */
580 void (*destructor)(void *); /* Called at thread exit. */
582 /* Indexes into the per-thread array in struct ovsthread_key_slots.
583 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
587 /* Per-thread data structure. */
588 struct ovsthread_key_slots {
589 struct list list_node; /* In 'slots_list'. */
593 /* Contains "struct ovsthread_key_slots *". */
594 static pthread_key_t tsd_key;
596 /* Guards data structures below. */
597 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
599 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
602 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
603 * ready for reuse. (We keep them around only to be able to easily locate
606 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
607 * from 0 to n_keys - 1, inclusive. */
608 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
609 = LIST_INITIALIZER(&inuse_keys);
610 static struct list free_keys OVS_GUARDED_BY(key_mutex)
611 = LIST_INITIALIZER(&free_keys);
612 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
614 /* All existing struct ovsthread_key_slots. */
615 static struct list slots_list OVS_GUARDED_BY(key_mutex)
616 = LIST_INITIALIZER(&slots_list);
619 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
621 void **p2 = slots->p1[index / L2_SIZE];
623 void **valuep = &p2[index % L2_SIZE];
624 void *value = *valuep;
633 ovsthread_key_destruct__(void *slots_)
635 struct ovsthread_key_slots *slots = slots_;
636 struct ovsthread_key *key;
640 ovs_mutex_lock(&key_mutex);
641 list_remove(&slots->list_node);
642 LIST_FOR_EACH (key, list_node, &inuse_keys) {
643 void *value = clear_slot(slots, key->index);
644 if (value && key->destructor) {
645 key->destructor(value);
649 ovs_mutex_unlock(&key_mutex);
651 for (i = 0; i < n / L2_SIZE; i++) {
657 /* Initializes '*keyp' as a thread-specific data key. The data items are
658 * initially null in all threads.
660 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
661 * called passing the final data value as its argument. 'destructor' must not
662 * call any thread-specific data functions in this API.
664 * This function is similar to xpthread_key_create(). */
666 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
668 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
669 struct ovsthread_key *key;
671 if (ovsthread_once_start(&once)) {
672 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
673 ovsthread_once_done(&once);
676 ovs_mutex_lock(&key_mutex);
677 if (list_is_empty(&free_keys)) {
678 key = xmalloc(sizeof *key);
679 key->index = n_keys++;
680 if (key->index >= MAX_KEYS) {
684 key = CONTAINER_OF(list_pop_back(&free_keys),
685 struct ovsthread_key, list_node);
687 list_push_back(&inuse_keys, &key->list_node);
688 key->destructor = destructor;
689 ovs_mutex_unlock(&key_mutex);
694 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
697 * This function is similar to xpthread_key_delete(). */
699 ovsthread_key_delete(ovsthread_key_t key)
701 struct ovsthread_key_slots *slots;
703 ovs_mutex_lock(&key_mutex);
705 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
706 list_remove(&key->list_node);
707 list_push_back(&free_keys, &key->list_node);
709 /* Clear this slot in all threads. */
710 LIST_FOR_EACH (slots, list_node, &slots_list) {
711 clear_slot(slots, key->index);
714 ovs_mutex_unlock(&key_mutex);
718 ovsthread_key_lookup__(const struct ovsthread_key *key)
720 struct ovsthread_key_slots *slots;
723 slots = pthread_getspecific(tsd_key);
725 slots = xzalloc(sizeof *slots);
727 ovs_mutex_lock(&key_mutex);
728 pthread_setspecific(tsd_key, slots);
729 list_push_back(&slots_list, &slots->list_node);
730 ovs_mutex_unlock(&key_mutex);
733 p2 = slots->p1[key->index / L2_SIZE];
735 p2 = xzalloc(L2_SIZE * sizeof *p2);
736 slots->p1[key->index / L2_SIZE] = p2;
739 return &p2[key->index % L2_SIZE];
742 /* Sets the value of thread-specific data item 'key', in the current thread, to
745 * This function is similar to pthread_setspecific(). */
747 ovsthread_setspecific(ovsthread_key_t key, const void *value)
749 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
752 /* Returns the value of thread-specific data item 'key' in the current thread.
754 * This function is similar to pthread_getspecific(). */
756 ovsthread_getspecific(ovsthread_key_t key)
758 return *ovsthread_key_lookup__(key);