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"
27 #include "socket-util.h"
31 /* Omit the definitions in this file because they are somewhat difficult to
32 * write without prompting "sparse" complaints, without ugliness or
33 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
34 * doesn't matter that we don't define them. */
38 VLOG_DEFINE_THIS_MODULE(ovs_thread);
40 /* If there is a reason that we cannot fork anymore (unless the fork will be
41 * immediately followed by an exec), then this points to a string that
43 static const char *must_not_fork;
45 /* True if we created any threads beyond the main initial thread. */
46 static bool multithreaded;
48 #define LOCK_FUNCTION(TYPE, FUN) \
50 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
52 OVS_NO_THREAD_SAFETY_ANALYSIS \
54 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
55 int error = pthread_##TYPE##_##FUN(&l->lock); \
56 if (OVS_UNLIKELY(error)) { \
57 ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
61 LOCK_FUNCTION(mutex, lock);
62 LOCK_FUNCTION(rwlock, rdlock);
63 LOCK_FUNCTION(rwlock, wrlock);
65 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
67 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
69 OVS_NO_THREAD_SAFETY_ANALYSIS \
71 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
72 int error = pthread_##TYPE##_##FUN(&l->lock); \
73 if (OVS_UNLIKELY(error) && error != EBUSY) { \
74 ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
81 TRY_LOCK_FUNCTION(mutex, trylock);
82 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
83 TRY_LOCK_FUNCTION(rwlock, trywrlock);
85 #define UNLOCK_FUNCTION(TYPE, FUN) \
87 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
88 OVS_NO_THREAD_SAFETY_ANALYSIS \
90 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
93 error = pthread_##TYPE##_##FUN(&l->lock); \
94 if (OVS_UNLIKELY(error)) { \
95 ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
98 UNLOCK_FUNCTION(mutex, unlock);
99 UNLOCK_FUNCTION(mutex, destroy);
100 UNLOCK_FUNCTION(rwlock, unlock);
101 UNLOCK_FUNCTION(rwlock, destroy);
103 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
105 x##FUNCTION(PARAM1 arg1) \
107 int error = FUNCTION(arg1); \
108 if (OVS_UNLIKELY(error)) { \
109 ovs_abort(error, "%s failed", #FUNCTION); \
112 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
114 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
116 int error = FUNCTION(arg1, arg2); \
117 if (OVS_UNLIKELY(error)) { \
118 ovs_abort(error, "%s failed", #FUNCTION); \
121 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
123 x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3) \
125 int error = FUNCTION(arg1, arg2, arg3); \
126 if (OVS_UNLIKELY(error)) { \
127 ovs_abort(error, "%s failed", #FUNCTION); \
131 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
132 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
133 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
134 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
135 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
136 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
138 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
139 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
140 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
141 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
144 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
145 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
146 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
147 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
149 XPTHREAD_FUNC3(pthread_barrier_init, pthread_barrier_t *,
150 pthread_barrierattr_t *, unsigned int);
151 XPTHREAD_FUNC1(pthread_barrier_destroy, pthread_barrier_t *);
153 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
155 typedef void destructor_func(void *);
156 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
157 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
158 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
161 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
163 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
164 pthread_mutexattr_t attr;
168 xpthread_mutexattr_init(&attr);
169 xpthread_mutexattr_settype(&attr, type);
170 error = pthread_mutex_init(&l->lock, &attr);
171 if (OVS_UNLIKELY(error)) {
172 ovs_abort(error, "pthread_mutex_init failed");
174 xpthread_mutexattr_destroy(&attr);
177 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
179 ovs_mutex_init(const struct ovs_mutex *mutex)
181 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
184 /* Initializes 'mutex' as a recursive mutex. */
186 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
188 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
191 /* Initializes 'mutex' as a recursive mutex. */
193 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
195 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
196 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
198 ovs_mutex_init(mutex);
203 ovs_rwlock_init(const struct ovs_rwlock *l_)
205 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
206 pthread_rwlockattr_t attr;
211 xpthread_rwlockattr_init(&attr);
212 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
213 xpthread_rwlockattr_setkind_np(
214 &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
216 error = pthread_rwlock_init(&l->lock, NULL);
217 if (OVS_UNLIKELY(error)) {
218 ovs_abort(error, "pthread_rwlock_init failed");
220 xpthread_rwlockattr_destroy(&attr);
224 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
226 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
229 ovsrcu_quiesce_start();
230 error = pthread_cond_wait(cond, &mutex->lock);
231 ovsrcu_quiesce_end();
233 if (OVS_UNLIKELY(error)) {
234 ovs_abort(error, "pthread_cond_wait failed");
239 xpthread_barrier_wait(pthread_barrier_t *barrier)
243 ovsrcu_quiesce_start();
244 error = pthread_barrier_wait(barrier);
245 ovsrcu_quiesce_end();
247 if (error && OVS_UNLIKELY(error != PTHREAD_BARRIER_SERIAL_THREAD)) {
248 ovs_abort(error, "pthread_barrier_wait failed");
254 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
256 struct ovsthread_aux {
257 void *(*start)(void *);
263 ovsthread_wrapper(void *aux_)
265 static atomic_uint next_id = ATOMIC_VAR_INIT(1);
267 struct ovsthread_aux *auxp = aux_;
268 struct ovsthread_aux aux;
271 atomic_add(&next_id, 1, &id);
272 *ovsthread_id_get() = id;
277 set_subprogram_name("%s%u", aux.name, id);
279 ovsrcu_quiesce_end();
280 return aux.start(aux.arg);
283 /* Starts a thread that calls 'start(arg)'. Sets the thread's name to 'name'
284 * (suffixed by its ovsthread_id()). Returns the new thread's pthread_t. */
286 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
288 struct ovsthread_aux *aux;
292 forbid_forking("multiple threads exist");
293 multithreaded = true;
294 ovsrcu_quiesce_end();
296 aux = xmalloc(sizeof *aux);
299 ovs_strlcpy(aux->name, name, sizeof aux->name);
301 error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
303 ovs_abort(error, "pthread_create failed");
309 ovsthread_once_start__(struct ovsthread_once *once)
311 ovs_mutex_lock(&once->mutex);
312 if (!ovsthread_once_is_done__(once)) {
315 ovs_mutex_unlock(&once->mutex);
320 ovsthread_once_done(struct ovsthread_once *once)
322 atomic_store(&once->done, true);
323 ovs_mutex_unlock(&once->mutex);
327 single_threaded(void)
329 return !multithreaded;
332 /* Asserts that the process has not yet created any threads (beyond the initial
335 * ('where' is used in logging. Commonly one would use
336 * assert_single_threaded() to automatically provide the caller's source file
337 * and line number for 'where'.) */
339 assert_single_threaded_at(const char *where)
342 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
348 /* Forks the current process (checking that this is allowed). Aborts with
349 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
350 * returned by fork().
352 * ('where' is used in logging. Commonly one would use xfork() to
353 * automatically provide the caller's source file and line number for
356 xfork_at(const char *where)
361 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
362 where, must_not_fork);
367 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
373 /* Notes that the process must not call fork() from now on, for the specified
374 * 'reason'. (The process may still fork() if it execs itself immediately
377 forbid_forking(const char *reason)
379 ovs_assert(reason != NULL);
380 must_not_fork = reason;
383 /* Returns true if the process is allowed to fork, false otherwise. */
387 return !must_not_fork;
390 /* ovsthread_stats. */
393 ovsthread_stats_init(struct ovsthread_stats *stats)
397 ovs_mutex_init(&stats->mutex);
398 for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
399 stats->buckets[i] = NULL;
404 ovsthread_stats_destroy(struct ovsthread_stats *stats)
406 ovs_mutex_destroy(&stats->mutex);
410 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
411 void *(*new_bucket)(void))
413 unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
414 void *bucket = stats->buckets[idx];
416 ovs_mutex_lock(&stats->mutex);
417 bucket = stats->buckets[idx];
419 bucket = stats->buckets[idx] = new_bucket();
421 ovs_mutex_unlock(&stats->mutex);
427 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
429 for (; i < ARRAY_SIZE(stats->buckets); i++) {
430 if (stats->buckets[i]) {
438 /* Parses /proc/cpuinfo for the total number of physical cores on this system
439 * across all CPU packages, not counting hyper-threads.
441 * Sets *n_cores to the total number of cores on this system, or 0 if the
442 * number cannot be determined. */
444 parse_cpuinfo(long int *n_cores)
446 static const char file_name[] = "/proc/cpuinfo";
448 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
452 stream = fopen(file_name, "r");
454 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
458 while (fgets(line, sizeof line, stream)) {
461 /* Find the next CPU package. */
462 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
464 VLOG_WARN("Counted over 64 CPU packages on this system. "
465 "Parsing %s for core count may be inaccurate.",
471 if (cpu & (1 << id)) {
472 /* We've already counted this package's cores. */
477 /* Find the number of cores for this package. */
478 while (fgets(line, sizeof line, stream)) {
481 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
493 /* Returns the total number of cores on this system, or 0 if the number cannot
496 * Tries not to count hyper-threads, but may be inaccurate - particularly on
497 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
498 * formatted different to the layout that parse_cpuinfo() expects. */
500 count_cpu_cores(void)
502 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
503 static long int n_cores;
505 if (ovsthread_once_start(&once)) {
507 parse_cpuinfo(&n_cores);
509 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
513 GetSystemInfo(&sysinfo);
514 n_cores = sysinfo.dwNumberOfProcessors;
516 ovsthread_once_done(&once);
519 return n_cores > 0 ? n_cores : 0;
526 #define MAX_KEYS (L1_SIZE * L2_SIZE)
528 /* A piece of thread-specific data. */
529 struct ovsthread_key {
530 struct list list_node; /* In 'inuse_keys' or 'free_keys'. */
531 void (*destructor)(void *); /* Called at thread exit. */
533 /* Indexes into the per-thread array in struct ovsthread_key_slots.
534 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
538 /* Per-thread data structure. */
539 struct ovsthread_key_slots {
540 struct list list_node; /* In 'slots_list'. */
544 /* Contains "struct ovsthread_key_slots *". */
545 static pthread_key_t tsd_key;
547 /* Guards data structures below. */
548 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
550 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
553 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
554 * ready for reuse. (We keep them around only to be able to easily locate
557 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
558 * from 0 to n_keys - 1, inclusive. */
559 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
560 = LIST_INITIALIZER(&inuse_keys);
561 static struct list free_keys OVS_GUARDED_BY(key_mutex)
562 = LIST_INITIALIZER(&free_keys);
563 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
565 /* All existing struct ovsthread_key_slots. */
566 static struct list slots_list OVS_GUARDED_BY(key_mutex)
567 = LIST_INITIALIZER(&slots_list);
570 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
572 void **p2 = slots->p1[index / L2_SIZE];
574 void **valuep = &p2[index % L2_SIZE];
575 void *value = *valuep;
584 ovsthread_key_destruct__(void *slots_)
586 struct ovsthread_key_slots *slots = slots_;
587 struct ovsthread_key *key;
591 ovs_mutex_lock(&key_mutex);
592 list_remove(&slots->list_node);
593 LIST_FOR_EACH (key, list_node, &inuse_keys) {
594 void *value = clear_slot(slots, key->index);
595 if (value && key->destructor) {
596 key->destructor(value);
600 ovs_mutex_unlock(&key_mutex);
602 for (i = 0; i < n / L2_SIZE; i++) {
608 /* Initializes '*keyp' as a thread-specific data key. The data items are
609 * initially null in all threads.
611 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
612 * called passing the final data value as its argument. 'destructor' must not
613 * call any thread-specific data functions in this API.
615 * This function is similar to xpthread_key_create(). */
617 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
619 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
620 struct ovsthread_key *key;
622 if (ovsthread_once_start(&once)) {
623 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
624 ovsthread_once_done(&once);
627 ovs_mutex_lock(&key_mutex);
628 if (list_is_empty(&free_keys)) {
629 key = xmalloc(sizeof *key);
630 key->index = n_keys++;
631 if (key->index >= MAX_KEYS) {
635 key = CONTAINER_OF(list_pop_back(&free_keys),
636 struct ovsthread_key, list_node);
638 list_push_back(&inuse_keys, &key->list_node);
639 key->destructor = destructor;
640 ovs_mutex_unlock(&key_mutex);
645 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
648 * This function is similar to xpthread_key_delete(). */
650 ovsthread_key_delete(ovsthread_key_t key)
652 struct ovsthread_key_slots *slots;
654 ovs_mutex_lock(&key_mutex);
656 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
657 list_remove(&key->list_node);
658 list_push_back(&free_keys, &key->list_node);
660 /* Clear this slot in all threads. */
661 LIST_FOR_EACH (slots, list_node, &slots_list) {
662 clear_slot(slots, key->index);
665 ovs_mutex_unlock(&key_mutex);
669 ovsthread_key_lookup__(const struct ovsthread_key *key)
671 struct ovsthread_key_slots *slots;
674 slots = pthread_getspecific(tsd_key);
676 slots = xzalloc(sizeof *slots);
678 ovs_mutex_lock(&key_mutex);
679 pthread_setspecific(tsd_key, slots);
680 list_push_back(&slots_list, &slots->list_node);
681 ovs_mutex_unlock(&key_mutex);
684 p2 = slots->p1[key->index / L2_SIZE];
686 p2 = xzalloc(L2_SIZE * sizeof *p2);
687 slots->p1[key->index / L2_SIZE] = p2;
690 return &p2[key->index % L2_SIZE];
693 /* Sets the value of thread-specific data item 'key', in the current thread, to
696 * This function is similar to pthread_setspecific(). */
698 ovsthread_setspecific(ovsthread_key_t key, const void *value)
700 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
703 /* Returns the value of thread-specific data item 'key' in the current thread.
705 * This function is similar to pthread_getspecific(). */
707 ovsthread_getspecific(ovsthread_key_t key)
709 return *ovsthread_key_lookup__(key);