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"
24 #include "poll-loop.h"
25 #include "socket-util.h"
29 /* Omit the definitions in this file because they are somewhat difficult to
30 * write without prompting "sparse" complaints, without ugliness or
31 * cut-and-paste. Since "sparse" is just a checker, not a compiler, it
32 * doesn't matter that we don't define them. */
36 VLOG_DEFINE_THIS_MODULE(ovs_thread);
38 /* If there is a reason that we cannot fork anymore (unless the fork will be
39 * immediately followed by an exec), then this points to a string that
41 static const char *must_not_fork;
43 /* True if we created any threads beyond the main initial thread. */
44 static bool multithreaded;
46 #define LOCK_FUNCTION(TYPE, FUN) \
48 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
50 OVS_NO_THREAD_SAFETY_ANALYSIS \
52 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
53 int error = pthread_##TYPE##_##FUN(&l->lock); \
54 if (OVS_UNLIKELY(error)) { \
55 ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
59 LOCK_FUNCTION(mutex, lock);
60 LOCK_FUNCTION(rwlock, rdlock);
61 LOCK_FUNCTION(rwlock, wrlock);
63 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
65 ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
67 OVS_NO_THREAD_SAFETY_ANALYSIS \
69 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
70 int error = pthread_##TYPE##_##FUN(&l->lock); \
71 if (OVS_UNLIKELY(error) && error != EBUSY) { \
72 ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
79 TRY_LOCK_FUNCTION(mutex, trylock);
80 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
81 TRY_LOCK_FUNCTION(rwlock, trywrlock);
83 #define UNLOCK_FUNCTION(TYPE, FUN) \
85 ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
86 OVS_NO_THREAD_SAFETY_ANALYSIS \
88 struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
91 error = pthread_##TYPE##_##FUN(&l->lock); \
92 if (OVS_UNLIKELY(error)) { \
93 ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
96 UNLOCK_FUNCTION(mutex, unlock);
97 UNLOCK_FUNCTION(mutex, destroy);
98 UNLOCK_FUNCTION(rwlock, unlock);
99 UNLOCK_FUNCTION(rwlock, destroy);
101 #define XPTHREAD_FUNC1(FUNCTION, PARAM1) \
103 x##FUNCTION(PARAM1 arg1) \
105 int error = FUNCTION(arg1); \
106 if (OVS_UNLIKELY(error)) { \
107 ovs_abort(error, "%s failed", #FUNCTION); \
110 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2) \
112 x##FUNCTION(PARAM1 arg1, PARAM2 arg2) \
114 int error = FUNCTION(arg1, arg2); \
115 if (OVS_UNLIKELY(error)) { \
116 ovs_abort(error, "%s failed", #FUNCTION); \
120 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
121 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
122 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
123 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
124 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
125 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
127 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
128 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
129 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
130 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
132 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
134 typedef void destructor_func(void *);
135 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
136 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
137 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
140 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
142 struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
143 pthread_mutexattr_t attr;
147 xpthread_mutexattr_init(&attr);
148 xpthread_mutexattr_settype(&attr, type);
149 error = pthread_mutex_init(&l->lock, &attr);
150 if (OVS_UNLIKELY(error)) {
151 ovs_abort(error, "pthread_mutex_init failed");
153 xpthread_mutexattr_destroy(&attr);
156 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
158 ovs_mutex_init(const struct ovs_mutex *mutex)
160 ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
163 /* Initializes 'mutex' as a recursive mutex. */
165 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
167 ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
171 ovs_rwlock_init(const struct ovs_rwlock *l_)
173 struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
177 error = pthread_rwlock_init(&l->lock, NULL);
178 if (OVS_UNLIKELY(error)) {
179 ovs_abort(error, "pthread_rwlock_init failed");
184 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
186 struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
187 int error = pthread_cond_wait(cond, &mutex->lock);
188 if (OVS_UNLIKELY(error)) {
189 ovs_abort(error, "pthread_cond_wait failed");
193 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
195 struct ovsthread_aux {
196 void *(*start)(void *);
201 ovsthread_wrapper(void *aux_)
203 static atomic_uint next_id = ATOMIC_VAR_INIT(1);
205 struct ovsthread_aux *auxp = aux_;
206 struct ovsthread_aux aux;
209 atomic_add(&next_id, 1, &id);
210 *ovsthread_id_get() = id;
215 return aux.start(aux.arg);
219 xpthread_create(pthread_t *threadp, pthread_attr_t *attr,
220 void *(*start)(void *), void *arg)
222 struct ovsthread_aux *aux;
226 forbid_forking("multiple threads exist");
227 multithreaded = true;
229 aux = xmalloc(sizeof *aux);
233 error = pthread_create(threadp ? threadp : &thread, attr,
234 ovsthread_wrapper, aux);
236 ovs_abort(error, "pthread_create failed");
241 ovsthread_once_start__(struct ovsthread_once *once)
243 ovs_mutex_lock(&once->mutex);
244 if (!ovsthread_once_is_done__(once)) {
247 ovs_mutex_unlock(&once->mutex);
252 ovsthread_once_done(struct ovsthread_once *once)
254 atomic_store(&once->done, true);
255 ovs_mutex_unlock(&once->mutex);
258 /* Asserts that the process has not yet created any threads (beyond the initial
261 * ('where' is used in logging. Commonly one would use
262 * assert_single_threaded() to automatically provide the caller's source file
263 * and line number for 'where'.) */
265 assert_single_threaded_at(const char *where)
268 VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
273 /* Forks the current process (checking that this is allowed). Aborts with
274 * VLOG_FATAL if fork() returns an error, and otherwise returns the value
275 * returned by fork().
277 * ('where' is used in logging. Commonly one would use xfork() to
278 * automatically provide the caller's source file and line number for
281 xfork_at(const char *where)
286 VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
287 where, must_not_fork);
292 VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
297 /* Notes that the process must not call fork() from now on, for the specified
298 * 'reason'. (The process may still fork() if it execs itself immediately
301 forbid_forking(const char *reason)
303 ovs_assert(reason != NULL);
304 must_not_fork = reason;
307 /* Returns true if the process is allowed to fork, false otherwise. */
311 return !must_not_fork;
314 /* Parses /proc/cpuinfo for the total number of physical cores on this system
315 * across all CPU packages, not counting hyper-threads.
317 * Sets *n_cores to the total number of cores on this system, or 0 if the
318 * number cannot be determined. */
320 parse_cpuinfo(long int *n_cores)
322 static const char file_name[] = "/proc/cpuinfo";
324 uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
328 stream = fopen(file_name, "r");
330 VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
334 while (fgets(line, sizeof line, stream)) {
337 /* Find the next CPU package. */
338 if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
340 VLOG_WARN("Counted over 64 CPU packages on this system. "
341 "Parsing %s for core count may be inaccurate.",
347 if (cpu & (1 << id)) {
348 /* We've already counted this package's cores. */
353 /* Find the number of cores for this package. */
354 while (fgets(line, sizeof line, stream)) {
357 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
369 /* Returns the total number of cores on this system, or 0 if the number cannot
372 * Tries not to count hyper-threads, but may be inaccurate - particularly on
373 * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
374 * formatted different to the layout that parse_cpuinfo() expects. */
376 count_cpu_cores(void)
378 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
379 static long int n_cores;
381 if (ovsthread_once_start(&once)) {
382 parse_cpuinfo(&n_cores);
384 n_cores = sysconf(_SC_NPROCESSORS_ONLN);
386 ovsthread_once_done(&once);
389 return n_cores > 0 ? n_cores : 0;
396 #define MAX_KEYS (L1_SIZE * L2_SIZE)
398 /* A piece of thread-specific data. */
399 struct ovsthread_key {
400 struct list list_node; /* In 'inuse_keys' or 'free_keys'. */
401 void (*destructor)(void *); /* Called at thread exit. */
403 /* Indexes into the per-thread array in struct ovsthread_key_slots.
404 * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
408 /* Per-thread data structure. */
409 struct ovsthread_key_slots {
410 struct list list_node; /* In 'slots_list'. */
414 /* Contains "struct ovsthread_key_slots *". */
415 static pthread_key_t tsd_key;
417 /* Guards data structures below. */
418 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
420 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
423 * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
424 * ready for reuse. (We keep them around only to be able to easily locate
427 * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
428 * from 0 to n_keys - 1, inclusive. */
429 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
430 = LIST_INITIALIZER(&inuse_keys);
431 static struct list free_keys OVS_GUARDED_BY(key_mutex)
432 = LIST_INITIALIZER(&free_keys);
433 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
435 /* All existing struct ovsthread_key_slots. */
436 static struct list slots_list OVS_GUARDED_BY(key_mutex)
437 = LIST_INITIALIZER(&slots_list);
440 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
442 void **p2 = slots->p1[index / L2_SIZE];
444 void **valuep = &p2[index % L2_SIZE];
445 void *value = *valuep;
454 ovsthread_key_destruct__(void *slots_)
456 struct ovsthread_key_slots *slots = slots_;
457 struct ovsthread_key *key;
461 ovs_mutex_lock(&key_mutex);
462 list_remove(&slots->list_node);
463 LIST_FOR_EACH (key, list_node, &inuse_keys) {
464 void *value = clear_slot(slots, key->index);
465 if (value && key->destructor) {
466 key->destructor(value);
470 ovs_mutex_unlock(&key_mutex);
472 for (i = 0; i < n / L2_SIZE; i++) {
478 /* Initializes '*keyp' as a thread-specific data key. The data items are
479 * initially null in all threads.
481 * If a thread exits with non-null data, then 'destructor', if nonnull, will be
482 * called passing the final data value as its argument. 'destructor' must not
483 * call any thread-specific data functions in this API.
485 * This function is similar to xpthread_key_create(). */
487 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
489 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
490 struct ovsthread_key *key;
492 if (ovsthread_once_start(&once)) {
493 xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
494 ovsthread_once_done(&once);
497 ovs_mutex_lock(&key_mutex);
498 if (list_is_empty(&free_keys)) {
499 key = xmalloc(sizeof *key);
500 key->index = n_keys++;
501 if (key->index >= MAX_KEYS) {
505 key = CONTAINER_OF(list_pop_back(&free_keys),
506 struct ovsthread_key, list_node);
508 list_push_back(&inuse_keys, &key->list_node);
509 key->destructor = destructor;
510 ovs_mutex_unlock(&key_mutex);
515 /* Frees 'key'. The destructor supplied to ovsthread_key_create(), if any, is
518 * This function is similar to xpthread_key_delete(). */
520 ovsthread_key_delete(ovsthread_key_t key)
522 struct ovsthread_key_slots *slots;
524 ovs_mutex_lock(&key_mutex);
526 /* Move 'key' from 'inuse_keys' to 'free_keys'. */
527 list_remove(&key->list_node);
528 list_push_back(&free_keys, &key->list_node);
530 /* Clear this slot in all threads. */
531 LIST_FOR_EACH (slots, list_node, &slots_list) {
532 clear_slot(slots, key->index);
535 ovs_mutex_unlock(&key_mutex);
539 ovsthread_key_lookup__(const struct ovsthread_key *key)
541 struct ovsthread_key_slots *slots;
544 slots = pthread_getspecific(tsd_key);
546 slots = xzalloc(sizeof *slots);
548 ovs_mutex_lock(&key_mutex);
549 pthread_setspecific(tsd_key, slots);
550 list_push_back(&slots_list, &slots->list_node);
551 ovs_mutex_unlock(&key_mutex);
554 p2 = slots->p1[key->index / L2_SIZE];
556 p2 = xzalloc(L2_SIZE * sizeof *p2);
557 slots->p1[key->index / L2_SIZE] = p2;
560 return &p2[key->index % L2_SIZE];
563 /* Sets the value of thread-specific data item 'key', in the current thread, to
566 * This function is similar to pthread_setspecific(). */
568 ovsthread_setspecific(ovsthread_key_t key, const void *value)
570 *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
573 /* Returns the value of thread-specific data item 'key' in the current thread.
575 * This function is similar to pthread_getspecific(). */
577 ovsthread_getspecific(ovsthread_key_t key)
579 return *ovsthread_key_lookup__(key);