ovs-thread: Add new support for thread-specific data.
[cascardo/ovs.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 "poll-loop.h"
25 #include "socket-util.h"
26 #include "util.h"
27
28 #ifdef __CHECKER__
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. */
33 #else
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(ovs_thread);
37
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
40  * explains why. */
41 static const char *must_not_fork;
42
43 /* True if we created any threads beyond the main initial thread. */
44 static bool multithreaded;
45
46 #define LOCK_FUNCTION(TYPE, FUN) \
47     void \
48     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
49                             const char *where) \
50         OVS_NO_THREAD_SAFETY_ANALYSIS \
51     { \
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); \
56         } \
57         l->where = where; \
58     }
59 LOCK_FUNCTION(mutex, lock);
60 LOCK_FUNCTION(rwlock, rdlock);
61 LOCK_FUNCTION(rwlock, wrlock);
62
63 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
64     int \
65     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
66                             const char *where) \
67         OVS_NO_THREAD_SAFETY_ANALYSIS \
68     { \
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); \
73         } \
74         if (!error) { \
75             l->where = where; \
76         } \
77         return error; \
78     }
79 TRY_LOCK_FUNCTION(mutex, trylock);
80 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
81 TRY_LOCK_FUNCTION(rwlock, trywrlock);
82
83 #define UNLOCK_FUNCTION(TYPE, FUN) \
84     void \
85     ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
86         OVS_NO_THREAD_SAFETY_ANALYSIS \
87     { \
88         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
89         int error; \
90         l->where = NULL; \
91         error = pthread_##TYPE##_##FUN(&l->lock); \
92         if (OVS_UNLIKELY(error)) { \
93             ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
94         } \
95     }
96 UNLOCK_FUNCTION(mutex, unlock);
97 UNLOCK_FUNCTION(mutex, destroy);
98 UNLOCK_FUNCTION(rwlock, unlock);
99 UNLOCK_FUNCTION(rwlock, destroy);
100
101 #define XPTHREAD_FUNC1(FUNCTION, PARAM1)                \
102     void                                                \
103     x##FUNCTION(PARAM1 arg1)                            \
104     {                                                   \
105         int error = FUNCTION(arg1);                     \
106         if (OVS_UNLIKELY(error)) {                      \
107             ovs_abort(error, "%s failed", #FUNCTION);   \
108         }                                               \
109     }
110 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2)        \
111     void                                                \
112     x##FUNCTION(PARAM1 arg1, PARAM2 arg2)               \
113     {                                                   \
114         int error = FUNCTION(arg1, arg2);               \
115         if (OVS_UNLIKELY(error)) {                      \
116             ovs_abort(error, "%s failed", #FUNCTION);   \
117         }                                               \
118     }
119
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 *);
126
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 *);
131
132 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
133
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 *);
138
139 static void
140 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
141 {
142     struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
143     pthread_mutexattr_t attr;
144     int error;
145
146     l->where = NULL;
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");
152     }
153     xpthread_mutexattr_destroy(&attr);
154 }
155
156 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
157 void
158 ovs_mutex_init(const struct ovs_mutex *mutex)
159 {
160     ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
161 }
162
163 /* Initializes 'mutex' as a recursive mutex. */
164 void
165 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
166 {
167     ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
168 }
169
170 void
171 ovs_rwlock_init(const struct ovs_rwlock *l_)
172 {
173     struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
174     int error;
175
176     l->where = NULL;
177     error = pthread_rwlock_init(&l->lock, NULL);
178     if (OVS_UNLIKELY(error)) {
179         ovs_abort(error, "pthread_rwlock_init failed");
180     }
181 }
182
183 void
184 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
185 {
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");
190     }
191 }
192 \f
193 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
194
195 struct ovsthread_aux {
196     void *(*start)(void *);
197     void *arg;
198 };
199
200 static void *
201 ovsthread_wrapper(void *aux_)
202 {
203     static atomic_uint next_id = ATOMIC_VAR_INIT(1);
204
205     struct ovsthread_aux *auxp = aux_;
206     struct ovsthread_aux aux;
207     unsigned int id;
208
209     atomic_add(&next_id, 1, &id);
210     *ovsthread_id_get() = id;
211
212     aux = *auxp;
213     free(auxp);
214
215     return aux.start(aux.arg);
216 }
217
218 void
219 xpthread_create(pthread_t *threadp, pthread_attr_t *attr,
220                 void *(*start)(void *), void *arg)
221 {
222     struct ovsthread_aux *aux;
223     pthread_t thread;
224     int error;
225
226     forbid_forking("multiple threads exist");
227     multithreaded = true;
228
229     aux = xmalloc(sizeof *aux);
230     aux->start = start;
231     aux->arg = arg;
232
233     error = pthread_create(threadp ? threadp : &thread, attr,
234                            ovsthread_wrapper, aux);
235     if (error) {
236         ovs_abort(error, "pthread_create failed");
237     }
238 }
239 \f
240 bool
241 ovsthread_once_start__(struct ovsthread_once *once)
242 {
243     ovs_mutex_lock(&once->mutex);
244     if (!ovsthread_once_is_done__(once)) {
245         return false;
246     }
247     ovs_mutex_unlock(&once->mutex);
248     return true;
249 }
250
251 void
252 ovsthread_once_done(struct ovsthread_once *once)
253 {
254     atomic_store(&once->done, true);
255     ovs_mutex_unlock(&once->mutex);
256 }
257 \f
258 /* Asserts that the process has not yet created any threads (beyond the initial
259  * thread).
260  *
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'.) */
264 void
265 assert_single_threaded_at(const char *where)
266 {
267     if (multithreaded) {
268         VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
269                    where);
270     }
271 }
272
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().
276  *
277  * ('where' is used in logging.  Commonly one would use xfork() to
278  * automatically provide the caller's source file and line number for
279  * 'where'.) */
280 pid_t
281 xfork_at(const char *where)
282 {
283     pid_t pid;
284
285     if (must_not_fork) {
286         VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
287                    where, must_not_fork);
288     }
289
290     pid = fork();
291     if (pid < 0) {
292         VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
293     }
294     return pid;
295 }
296
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
299  * afterward.) */
300 void
301 forbid_forking(const char *reason)
302 {
303     ovs_assert(reason != NULL);
304     must_not_fork = reason;
305 }
306
307 /* Returns true if the process is allowed to fork, false otherwise. */
308 bool
309 may_fork(void)
310 {
311     return !must_not_fork;
312 }
313 \f
314 /* Parses /proc/cpuinfo for the total number of physical cores on this system
315  * across all CPU packages, not counting hyper-threads.
316  *
317  * Sets *n_cores to the total number of cores on this system, or 0 if the
318  * number cannot be determined. */
319 static void
320 parse_cpuinfo(long int *n_cores)
321 {
322     static const char file_name[] = "/proc/cpuinfo";
323     char line[128];
324     uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
325     long int cores = 0;
326     FILE *stream;
327
328     stream = fopen(file_name, "r");
329     if (!stream) {
330         VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
331         return;
332     }
333
334     while (fgets(line, sizeof line, stream)) {
335         unsigned int id;
336
337         /* Find the next CPU package. */
338         if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
339             if (id > 63) {
340                 VLOG_WARN("Counted over 64 CPU packages on this system. "
341                           "Parsing %s for core count may be inaccurate.",
342                           file_name);
343                 cores = 0;
344                 break;
345             }
346
347             if (cpu & (1 << id)) {
348                 /* We've already counted this package's cores. */
349                 continue;
350             }
351             cpu |= 1 << id;
352
353             /* Find the number of cores for this package. */
354             while (fgets(line, sizeof line, stream)) {
355                 int count;
356
357                 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
358                     cores += count;
359                     break;
360                 }
361             }
362         }
363     }
364     fclose(stream);
365
366     *n_cores = cores;
367 }
368
369 /* Returns the total number of cores on this system, or 0 if the number cannot
370  * be determined.
371  *
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. */
375 int
376 count_cpu_cores(void)
377 {
378     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
379     static long int n_cores;
380
381     if (ovsthread_once_start(&once)) {
382         parse_cpuinfo(&n_cores);
383         if (!n_cores) {
384             n_cores = sysconf(_SC_NPROCESSORS_ONLN);
385         }
386         ovsthread_once_done(&once);
387     }
388
389     return n_cores > 0 ? n_cores : 0;
390 }
391 \f
392 /* ovsthread_key. */
393
394 #define L1_SIZE 1024
395 #define L2_SIZE 1024
396 #define MAX_KEYS (L1_SIZE * L2_SIZE)
397
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. */
402
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]. */
405     unsigned int index;
406 };
407
408 /* Per-thread data structure. */
409 struct ovsthread_key_slots {
410     struct list list_node;      /* In 'slots_list'. */
411     void **p1[L1_SIZE];
412 };
413
414 /* Contains "struct ovsthread_key_slots *". */
415 static pthread_key_t tsd_key;
416
417 /* Guards data structures below. */
418 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
419
420 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
421  * yet destroyed.
422  *
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
425  * free indexes.)
426  *
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);
434
435 /* All existing struct ovsthread_key_slots. */
436 static struct list slots_list OVS_GUARDED_BY(key_mutex)
437     = LIST_INITIALIZER(&slots_list);
438
439 static void *
440 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
441 {
442     void **p2 = slots->p1[index / L2_SIZE];
443     if (p2) {
444         void **valuep = &p2[index % L2_SIZE];
445         void *value = *valuep;
446         *valuep = NULL;
447         return value;
448     } else {
449         return NULL;
450     }
451 }
452
453 static void
454 ovsthread_key_destruct__(void *slots_)
455 {
456     struct ovsthread_key_slots *slots = slots_;
457     struct ovsthread_key *key;
458     unsigned int n;
459     int i;
460
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);
467         }
468     }
469     n = n_keys;
470     ovs_mutex_unlock(&key_mutex);
471
472     for (i = 0; i < n / L2_SIZE; i++) {
473         free(slots->p1[i]);
474     }
475     free(slots);
476 }
477
478 /* Initializes '*keyp' as a thread-specific data key.  The data items are
479  * initially null in all threads.
480  *
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.
484  *
485  * This function is similar to xpthread_key_create(). */
486 void
487 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
488 {
489     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
490     struct ovsthread_key *key;
491
492     if (ovsthread_once_start(&once)) {
493         xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
494         ovsthread_once_done(&once);
495     }
496
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) {
502             abort();
503         }
504     } else {
505         key = CONTAINER_OF(list_pop_back(&free_keys),
506                             struct ovsthread_key, list_node);
507     }
508     list_push_back(&inuse_keys, &key->list_node);
509     key->destructor = destructor;
510     ovs_mutex_unlock(&key_mutex);
511
512     *keyp = key;
513 }
514
515 /* Frees 'key'.  The destructor supplied to ovsthread_key_create(), if any, is
516  * not called.
517  *
518  * This function is similar to xpthread_key_delete(). */
519 void
520 ovsthread_key_delete(ovsthread_key_t key)
521 {
522     struct ovsthread_key_slots *slots;
523
524     ovs_mutex_lock(&key_mutex);
525
526     /* Move 'key' from 'inuse_keys' to 'free_keys'. */
527     list_remove(&key->list_node);
528     list_push_back(&free_keys, &key->list_node);
529
530     /* Clear this slot in all threads. */
531     LIST_FOR_EACH (slots, list_node, &slots_list) {
532         clear_slot(slots, key->index);
533     }
534
535     ovs_mutex_unlock(&key_mutex);
536 }
537
538 static void **
539 ovsthread_key_lookup__(const struct ovsthread_key *key)
540 {
541     struct ovsthread_key_slots *slots;
542     void **p2;
543
544     slots = pthread_getspecific(tsd_key);
545     if (!slots) {
546         slots = xzalloc(sizeof *slots);
547
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);
552     }
553
554     p2 = slots->p1[key->index / L2_SIZE];
555     if (!p2) {
556         p2 = xzalloc(L2_SIZE * sizeof *p2);
557         slots->p1[key->index / L2_SIZE] = p2;
558     }
559
560     return &p2[key->index % L2_SIZE];
561 }
562
563 /* Sets the value of thread-specific data item 'key', in the current thread, to
564  * 'value'.
565  *
566  * This function is similar to pthread_setspecific(). */
567 void
568 ovsthread_setspecific(ovsthread_key_t key, const void *value)
569 {
570     *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
571 }
572
573 /* Returns the value of thread-specific data item 'key' in the current thread.
574  *
575  * This function is similar to pthread_getspecific(). */
576 void *
577 ovsthread_getspecific(ovsthread_key_t key)
578 {
579     return *ovsthread_key_lookup__(key);
580 }
581 #endif