a20b2fd934a93907f5e1d90eda22463f989269c9
[sliver-openvswitch.git] / lib / ovs-thread.c
1 /*
2  * Copyright (c) 2013, 2014 Nicira, Inc.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "ovs-thread.h"
19 #include <errno.h>
20 #include <poll.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include "compiler.h"
24 #include "hash.h"
25 #include "poll-loop.h"
26 #include "socket-util.h"
27 #include "util.h"
28
29 #ifdef __CHECKER__
30 /* Omit the definitions in this file because they are somewhat difficult to
31  * write without prompting "sparse" complaints, without ugliness or
32  * cut-and-paste.  Since "sparse" is just a checker, not a compiler, it
33  * doesn't matter that we don't define them. */
34 #else
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(ovs_thread);
38
39 /* If there is a reason that we cannot fork anymore (unless the fork will be
40  * immediately followed by an exec), then this points to a string that
41  * explains why. */
42 static const char *must_not_fork;
43
44 /* True if we created any threads beyond the main initial thread. */
45 static bool multithreaded;
46
47 #define LOCK_FUNCTION(TYPE, FUN) \
48     void \
49     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
50                             const char *where) \
51         OVS_NO_THREAD_SAFETY_ANALYSIS \
52     { \
53         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
54         int error = pthread_##TYPE##_##FUN(&l->lock); \
55         if (OVS_UNLIKELY(error)) { \
56             ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
57         } \
58         l->where = where; \
59     }
60 LOCK_FUNCTION(mutex, lock);
61 LOCK_FUNCTION(rwlock, rdlock);
62 LOCK_FUNCTION(rwlock, wrlock);
63
64 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
65     int \
66     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
67                             const char *where) \
68         OVS_NO_THREAD_SAFETY_ANALYSIS \
69     { \
70         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
71         int error = pthread_##TYPE##_##FUN(&l->lock); \
72         if (OVS_UNLIKELY(error) && error != EBUSY) { \
73             ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
74         } \
75         if (!error) { \
76             l->where = where; \
77         } \
78         return error; \
79     }
80 TRY_LOCK_FUNCTION(mutex, trylock);
81 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
82 TRY_LOCK_FUNCTION(rwlock, trywrlock);
83
84 #define UNLOCK_FUNCTION(TYPE, FUN) \
85     void \
86     ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
87         OVS_NO_THREAD_SAFETY_ANALYSIS \
88     { \
89         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
90         int error; \
91         l->where = NULL; \
92         error = pthread_##TYPE##_##FUN(&l->lock); \
93         if (OVS_UNLIKELY(error)) { \
94             ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
95         } \
96     }
97 UNLOCK_FUNCTION(mutex, unlock);
98 UNLOCK_FUNCTION(mutex, destroy);
99 UNLOCK_FUNCTION(rwlock, unlock);
100 UNLOCK_FUNCTION(rwlock, destroy);
101
102 #define XPTHREAD_FUNC1(FUNCTION, PARAM1)                \
103     void                                                \
104     x##FUNCTION(PARAM1 arg1)                            \
105     {                                                   \
106         int error = FUNCTION(arg1);                     \
107         if (OVS_UNLIKELY(error)) {                      \
108             ovs_abort(error, "%s failed", #FUNCTION);   \
109         }                                               \
110     }
111 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2)        \
112     void                                                \
113     x##FUNCTION(PARAM1 arg1, PARAM2 arg2)               \
114     {                                                   \
115         int error = FUNCTION(arg1, arg2);               \
116         if (OVS_UNLIKELY(error)) {                      \
117             ovs_abort(error, "%s failed", #FUNCTION);   \
118         }                                               \
119     }
120
121 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
122 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
123 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
124 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
125 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
126 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
127
128 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
129 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
130 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
131 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
132
133 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
134
135 typedef void destructor_func(void *);
136 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
137 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
138 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
139
140 static void
141 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
142 {
143     struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
144     pthread_mutexattr_t attr;
145     int error;
146
147     l->where = NULL;
148     xpthread_mutexattr_init(&attr);
149     xpthread_mutexattr_settype(&attr, type);
150     error = pthread_mutex_init(&l->lock, &attr);
151     if (OVS_UNLIKELY(error)) {
152         ovs_abort(error, "pthread_mutex_init failed");
153     }
154     xpthread_mutexattr_destroy(&attr);
155 }
156
157 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
158 void
159 ovs_mutex_init(const struct ovs_mutex *mutex)
160 {
161     ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
162 }
163
164 /* Initializes 'mutex' as a recursive mutex. */
165 void
166 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
167 {
168     ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
169 }
170
171 void
172 ovs_rwlock_init(const struct ovs_rwlock *l_)
173 {
174     struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
175     int error;
176
177     l->where = NULL;
178     error = pthread_rwlock_init(&l->lock, NULL);
179     if (OVS_UNLIKELY(error)) {
180         ovs_abort(error, "pthread_rwlock_init failed");
181     }
182 }
183
184 void
185 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
186 {
187     struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
188     int error = pthread_cond_wait(cond, &mutex->lock);
189     if (OVS_UNLIKELY(error)) {
190         ovs_abort(error, "pthread_cond_wait failed");
191     }
192 }
193 \f
194 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
195
196 struct ovsthread_aux {
197     void *(*start)(void *);
198     void *arg;
199 };
200
201 static void *
202 ovsthread_wrapper(void *aux_)
203 {
204     static atomic_uint next_id = ATOMIC_VAR_INIT(1);
205
206     struct ovsthread_aux *auxp = aux_;
207     struct ovsthread_aux aux;
208     unsigned int id;
209
210     atomic_add(&next_id, 1, &id);
211     *ovsthread_id_get() = id;
212
213     aux = *auxp;
214     free(auxp);
215
216     return aux.start(aux.arg);
217 }
218
219 void
220 xpthread_create(pthread_t *threadp, pthread_attr_t *attr,
221                 void *(*start)(void *), void *arg)
222 {
223     struct ovsthread_aux *aux;
224     pthread_t thread;
225     int error;
226
227     forbid_forking("multiple threads exist");
228     multithreaded = true;
229
230     aux = xmalloc(sizeof *aux);
231     aux->start = start;
232     aux->arg = arg;
233
234     error = pthread_create(threadp ? threadp : &thread, attr,
235                            ovsthread_wrapper, aux);
236     if (error) {
237         ovs_abort(error, "pthread_create failed");
238     }
239 }
240 \f
241 bool
242 ovsthread_once_start__(struct ovsthread_once *once)
243 {
244     ovs_mutex_lock(&once->mutex);
245     if (!ovsthread_once_is_done__(once)) {
246         return false;
247     }
248     ovs_mutex_unlock(&once->mutex);
249     return true;
250 }
251
252 void
253 ovsthread_once_done(struct ovsthread_once *once)
254 {
255     atomic_store(&once->done, true);
256     ovs_mutex_unlock(&once->mutex);
257 }
258 \f
259 /* Asserts that the process has not yet created any threads (beyond the initial
260  * thread).
261  *
262  * ('where' is used in logging.  Commonly one would use
263  * assert_single_threaded() to automatically provide the caller's source file
264  * and line number for 'where'.) */
265 void
266 assert_single_threaded_at(const char *where)
267 {
268     if (multithreaded) {
269         VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
270                    where);
271     }
272 }
273
274 /* Forks the current process (checking that this is allowed).  Aborts with
275  * VLOG_FATAL if fork() returns an error, and otherwise returns the value
276  * returned by fork().
277  *
278  * ('where' is used in logging.  Commonly one would use xfork() to
279  * automatically provide the caller's source file and line number for
280  * 'where'.) */
281 pid_t
282 xfork_at(const char *where)
283 {
284     pid_t pid;
285
286     if (must_not_fork) {
287         VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
288                    where, must_not_fork);
289     }
290
291     pid = fork();
292     if (pid < 0) {
293         VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
294     }
295     return pid;
296 }
297
298 /* Notes that the process must not call fork() from now on, for the specified
299  * 'reason'.  (The process may still fork() if it execs itself immediately
300  * afterward.) */
301 void
302 forbid_forking(const char *reason)
303 {
304     ovs_assert(reason != NULL);
305     must_not_fork = reason;
306 }
307
308 /* Returns true if the process is allowed to fork, false otherwise. */
309 bool
310 may_fork(void)
311 {
312     return !must_not_fork;
313 }
314 \f
315 /* ovsthread_counter.
316  *
317  * We implement the counter as an array of N_COUNTERS individual counters, each
318  * with its own lock.  Each thread uses one of the counters chosen based on a
319  * hash of the thread's ID, the idea being that, statistically, different
320  * threads will tend to use different counters and therefore avoid
321  * interfering with each other.
322  *
323  * Undoubtedly, better implementations are possible. */
324
325 /* Basic counter structure. */
326 struct ovsthread_counter__ {
327     struct ovs_mutex mutex;
328     unsigned long long int value;
329 };
330
331 /* Pad the basic counter structure to 64 bytes to avoid cache line
332  * interference. */
333 struct ovsthread_counter {
334     struct ovsthread_counter__ c;
335     char pad[ROUND_UP(sizeof(struct ovsthread_counter__), 64)
336              - sizeof(struct ovsthread_counter__)];
337 };
338
339 #define N_COUNTERS 16
340
341 struct ovsthread_counter *
342 ovsthread_counter_create(void)
343 {
344     struct ovsthread_counter *c;
345     int i;
346
347     c = xmalloc(N_COUNTERS * sizeof *c);
348     for (i = 0; i < N_COUNTERS; i++) {
349         ovs_mutex_init(&c[i].c.mutex);
350         c[i].c.value = 0;
351     }
352     return c;
353 }
354
355 void
356 ovsthread_counter_destroy(struct ovsthread_counter *c)
357 {
358     if (c) {
359         int i;
360
361         for (i = 0; i < N_COUNTERS; i++) {
362             ovs_mutex_destroy(&c[i].c.mutex);
363         }
364         free(c);
365     }
366 }
367
368 void
369 ovsthread_counter_inc(struct ovsthread_counter *c, unsigned long long int n)
370 {
371     c = &c[hash_int(ovsthread_id_self(), 0) % N_COUNTERS];
372
373     ovs_mutex_lock(&c->c.mutex);
374     c->c.value += n;
375     ovs_mutex_unlock(&c->c.mutex);
376 }
377
378 unsigned long long int
379 ovsthread_counter_read(const struct ovsthread_counter *c)
380 {
381     unsigned long long int sum;
382     int i;
383
384     sum = 0;
385     for (i = 0; i < N_COUNTERS; i++) {
386         ovs_mutex_lock(&c[i].c.mutex);
387         sum += c[i].c.value;
388         ovs_mutex_unlock(&c[i].c.mutex);
389     }
390     return sum;
391 }
392 \f
393 /* Parses /proc/cpuinfo for the total number of physical cores on this system
394  * across all CPU packages, not counting hyper-threads.
395  *
396  * Sets *n_cores to the total number of cores on this system, or 0 if the
397  * number cannot be determined. */
398 static void
399 parse_cpuinfo(long int *n_cores)
400 {
401     static const char file_name[] = "/proc/cpuinfo";
402     char line[128];
403     uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
404     long int cores = 0;
405     FILE *stream;
406
407     stream = fopen(file_name, "r");
408     if (!stream) {
409         VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
410         return;
411     }
412
413     while (fgets(line, sizeof line, stream)) {
414         unsigned int id;
415
416         /* Find the next CPU package. */
417         if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
418             if (id > 63) {
419                 VLOG_WARN("Counted over 64 CPU packages on this system. "
420                           "Parsing %s for core count may be inaccurate.",
421                           file_name);
422                 cores = 0;
423                 break;
424             }
425
426             if (cpu & (1 << id)) {
427                 /* We've already counted this package's cores. */
428                 continue;
429             }
430             cpu |= 1 << id;
431
432             /* Find the number of cores for this package. */
433             while (fgets(line, sizeof line, stream)) {
434                 int count;
435
436                 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
437                     cores += count;
438                     break;
439                 }
440             }
441         }
442     }
443     fclose(stream);
444
445     *n_cores = cores;
446 }
447
448 /* Returns the total number of cores on this system, or 0 if the number cannot
449  * be determined.
450  *
451  * Tries not to count hyper-threads, but may be inaccurate - particularly on
452  * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
453  * formatted different to the layout that parse_cpuinfo() expects. */
454 int
455 count_cpu_cores(void)
456 {
457     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
458     static long int n_cores;
459
460     if (ovsthread_once_start(&once)) {
461         parse_cpuinfo(&n_cores);
462         if (!n_cores) {
463             n_cores = sysconf(_SC_NPROCESSORS_ONLN);
464         }
465         ovsthread_once_done(&once);
466     }
467
468     return n_cores > 0 ? n_cores : 0;
469 }
470 \f
471 /* ovsthread_key. */
472
473 #define L1_SIZE 1024
474 #define L2_SIZE 1024
475 #define MAX_KEYS (L1_SIZE * L2_SIZE)
476
477 /* A piece of thread-specific data. */
478 struct ovsthread_key {
479     struct list list_node;      /* In 'inuse_keys' or 'free_keys'. */
480     void (*destructor)(void *); /* Called at thread exit. */
481
482     /* Indexes into the per-thread array in struct ovsthread_key_slots.
483      * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
484     unsigned int index;
485 };
486
487 /* Per-thread data structure. */
488 struct ovsthread_key_slots {
489     struct list list_node;      /* In 'slots_list'. */
490     void **p1[L1_SIZE];
491 };
492
493 /* Contains "struct ovsthread_key_slots *". */
494 static pthread_key_t tsd_key;
495
496 /* Guards data structures below. */
497 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
498
499 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
500  * yet destroyed.
501  *
502  * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
503  * ready for reuse.  (We keep them around only to be able to easily locate
504  * free indexes.)
505  *
506  * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
507  * from 0 to n_keys - 1, inclusive. */
508 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
509     = LIST_INITIALIZER(&inuse_keys);
510 static struct list free_keys OVS_GUARDED_BY(key_mutex)
511     = LIST_INITIALIZER(&free_keys);
512 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
513
514 /* All existing struct ovsthread_key_slots. */
515 static struct list slots_list OVS_GUARDED_BY(key_mutex)
516     = LIST_INITIALIZER(&slots_list);
517
518 static void *
519 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
520 {
521     void **p2 = slots->p1[index / L2_SIZE];
522     if (p2) {
523         void **valuep = &p2[index % L2_SIZE];
524         void *value = *valuep;
525         *valuep = NULL;
526         return value;
527     } else {
528         return NULL;
529     }
530 }
531
532 static void
533 ovsthread_key_destruct__(void *slots_)
534 {
535     struct ovsthread_key_slots *slots = slots_;
536     struct ovsthread_key *key;
537     unsigned int n;
538     int i;
539
540     ovs_mutex_lock(&key_mutex);
541     list_remove(&slots->list_node);
542     LIST_FOR_EACH (key, list_node, &inuse_keys) {
543         void *value = clear_slot(slots, key->index);
544         if (value && key->destructor) {
545             key->destructor(value);
546         }
547     }
548     n = n_keys;
549     ovs_mutex_unlock(&key_mutex);
550
551     for (i = 0; i < n / L2_SIZE; i++) {
552         free(slots->p1[i]);
553     }
554     free(slots);
555 }
556
557 /* Initializes '*keyp' as a thread-specific data key.  The data items are
558  * initially null in all threads.
559  *
560  * If a thread exits with non-null data, then 'destructor', if nonnull, will be
561  * called passing the final data value as its argument.  'destructor' must not
562  * call any thread-specific data functions in this API.
563  *
564  * This function is similar to xpthread_key_create(). */
565 void
566 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
567 {
568     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
569     struct ovsthread_key *key;
570
571     if (ovsthread_once_start(&once)) {
572         xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
573         ovsthread_once_done(&once);
574     }
575
576     ovs_mutex_lock(&key_mutex);
577     if (list_is_empty(&free_keys)) {
578         key = xmalloc(sizeof *key);
579         key->index = n_keys++;
580         if (key->index >= MAX_KEYS) {
581             abort();
582         }
583     } else {
584         key = CONTAINER_OF(list_pop_back(&free_keys),
585                             struct ovsthread_key, list_node);
586     }
587     list_push_back(&inuse_keys, &key->list_node);
588     key->destructor = destructor;
589     ovs_mutex_unlock(&key_mutex);
590
591     *keyp = key;
592 }
593
594 /* Frees 'key'.  The destructor supplied to ovsthread_key_create(), if any, is
595  * not called.
596  *
597  * This function is similar to xpthread_key_delete(). */
598 void
599 ovsthread_key_delete(ovsthread_key_t key)
600 {
601     struct ovsthread_key_slots *slots;
602
603     ovs_mutex_lock(&key_mutex);
604
605     /* Move 'key' from 'inuse_keys' to 'free_keys'. */
606     list_remove(&key->list_node);
607     list_push_back(&free_keys, &key->list_node);
608
609     /* Clear this slot in all threads. */
610     LIST_FOR_EACH (slots, list_node, &slots_list) {
611         clear_slot(slots, key->index);
612     }
613
614     ovs_mutex_unlock(&key_mutex);
615 }
616
617 static void **
618 ovsthread_key_lookup__(const struct ovsthread_key *key)
619 {
620     struct ovsthread_key_slots *slots;
621     void **p2;
622
623     slots = pthread_getspecific(tsd_key);
624     if (!slots) {
625         slots = xzalloc(sizeof *slots);
626
627         ovs_mutex_lock(&key_mutex);
628         pthread_setspecific(tsd_key, slots);
629         list_push_back(&slots_list, &slots->list_node);
630         ovs_mutex_unlock(&key_mutex);
631     }
632
633     p2 = slots->p1[key->index / L2_SIZE];
634     if (!p2) {
635         p2 = xzalloc(L2_SIZE * sizeof *p2);
636         slots->p1[key->index / L2_SIZE] = p2;
637     }
638
639     return &p2[key->index % L2_SIZE];
640 }
641
642 /* Sets the value of thread-specific data item 'key', in the current thread, to
643  * 'value'.
644  *
645  * This function is similar to pthread_setspecific(). */
646 void
647 ovsthread_setspecific(ovsthread_key_t key, const void *value)
648 {
649     *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
650 }
651
652 /* Returns the value of thread-specific data item 'key' in the current thread.
653  *
654  * This function is similar to pthread_getspecific(). */
655 void *
656 ovsthread_getspecific(ovsthread_key_t key)
657 {
658     return *ovsthread_key_lookup__(key);
659 }
660 #endif