76cbbd325504dfb2dffa6eaa27081dab6a82a1a9
[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 #define XPTHREAD_FUNC3(FUNCTION, PARAM1, PARAM2, PARAM3)\
121     void                                                \
122     x##FUNCTION(PARAM1 arg1, PARAM2 arg2, PARAM3 arg3)  \
123     {                                                   \
124         int error = FUNCTION(arg1, arg2, arg3);         \
125         if (OVS_UNLIKELY(error)) {                      \
126             ovs_abort(error, "%s failed", #FUNCTION);   \
127         }                                               \
128     }
129
130 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
131 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
132 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
133 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
134 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
135 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
136
137 XPTHREAD_FUNC1(pthread_rwlockattr_init, pthread_rwlockattr_t *);
138 XPTHREAD_FUNC1(pthread_rwlockattr_destroy, pthread_rwlockattr_t *);
139 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
140 XPTHREAD_FUNC2(pthread_rwlockattr_setkind_np, pthread_rwlockattr_t *, int);
141 #endif
142
143 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
144 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
145 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
146 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
147
148 XPTHREAD_FUNC3(pthread_barrier_init, pthread_barrier_t *,
149                pthread_barrierattr_t *, unsigned int);
150 XPTHREAD_FUNC1(pthread_barrier_destroy, pthread_barrier_t *);
151
152 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
153
154 typedef void destructor_func(void *);
155 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
156 XPTHREAD_FUNC1(pthread_key_delete, pthread_key_t);
157 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
158
159 static void
160 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
161 {
162     struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
163     pthread_mutexattr_t attr;
164     int error;
165
166     l->where = NULL;
167     xpthread_mutexattr_init(&attr);
168     xpthread_mutexattr_settype(&attr, type);
169     error = pthread_mutex_init(&l->lock, &attr);
170     if (OVS_UNLIKELY(error)) {
171         ovs_abort(error, "pthread_mutex_init failed");
172     }
173     xpthread_mutexattr_destroy(&attr);
174 }
175
176 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
177 void
178 ovs_mutex_init(const struct ovs_mutex *mutex)
179 {
180     ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
181 }
182
183 /* Initializes 'mutex' as a recursive mutex. */
184 void
185 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
186 {
187     ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
188 }
189
190 /* Initializes 'mutex' as a recursive mutex. */
191 void
192 ovs_mutex_init_adaptive(const struct ovs_mutex *mutex)
193 {
194 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
195     ovs_mutex_init__(mutex, PTHREAD_MUTEX_ADAPTIVE_NP);
196 #else
197     ovs_mutex_init(mutex);
198 #endif
199 }
200
201 void
202 ovs_rwlock_init(const struct ovs_rwlock *l_)
203 {
204     struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
205     pthread_rwlockattr_t attr;
206     int error;
207
208     l->where = NULL;
209
210     xpthread_rwlockattr_init(&attr);
211 #ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
212     xpthread_rwlockattr_setkind_np(
213         &attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
214 #endif
215     error = pthread_rwlock_init(&l->lock, NULL);
216     if (OVS_UNLIKELY(error)) {
217         ovs_abort(error, "pthread_rwlock_init failed");
218     }
219     xpthread_rwlockattr_destroy(&attr);
220 }
221
222 void
223 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
224 {
225     struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
226     int error = pthread_cond_wait(cond, &mutex->lock);
227     if (OVS_UNLIKELY(error)) {
228         ovs_abort(error, "pthread_cond_wait failed");
229     }
230 }
231
232 int
233 xpthread_barrier_wait(pthread_barrier_t *barrier)
234 {
235     int error;
236
237     error = pthread_barrier_wait(barrier);
238     if (error && OVS_UNLIKELY(error != PTHREAD_BARRIER_SERIAL_THREAD)) {
239         ovs_abort(error, "pthread_barrier_wait failed");
240     }
241
242     return error;
243 }
244 \f
245 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
246
247 struct ovsthread_aux {
248     void *(*start)(void *);
249     void *arg;
250 };
251
252 static void *
253 ovsthread_wrapper(void *aux_)
254 {
255     static atomic_uint next_id = ATOMIC_VAR_INIT(1);
256
257     struct ovsthread_aux *auxp = aux_;
258     struct ovsthread_aux aux;
259     unsigned int id;
260
261     atomic_add(&next_id, 1, &id);
262     *ovsthread_id_get() = id;
263
264     aux = *auxp;
265     free(auxp);
266
267     return aux.start(aux.arg);
268 }
269
270 void
271 xpthread_create(pthread_t *threadp, pthread_attr_t *attr,
272                 void *(*start)(void *), void *arg)
273 {
274     struct ovsthread_aux *aux;
275     pthread_t thread;
276     int error;
277
278     forbid_forking("multiple threads exist");
279     multithreaded = true;
280
281     aux = xmalloc(sizeof *aux);
282     aux->start = start;
283     aux->arg = arg;
284
285     error = pthread_create(threadp ? threadp : &thread, attr,
286                            ovsthread_wrapper, aux);
287     if (error) {
288         ovs_abort(error, "pthread_create failed");
289     }
290 }
291 \f
292 bool
293 ovsthread_once_start__(struct ovsthread_once *once)
294 {
295     ovs_mutex_lock(&once->mutex);
296     if (!ovsthread_once_is_done__(once)) {
297         return false;
298     }
299     ovs_mutex_unlock(&once->mutex);
300     return true;
301 }
302
303 void
304 ovsthread_once_done(struct ovsthread_once *once)
305 {
306     atomic_store(&once->done, true);
307     ovs_mutex_unlock(&once->mutex);
308 }
309 \f
310 /* Asserts that the process has not yet created any threads (beyond the initial
311  * thread).
312  *
313  * ('where' is used in logging.  Commonly one would use
314  * assert_single_threaded() to automatically provide the caller's source file
315  * and line number for 'where'.) */
316 void
317 assert_single_threaded_at(const char *where)
318 {
319     if (multithreaded) {
320         VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
321                    where);
322     }
323 }
324
325 #ifndef _WIN32
326 /* Forks the current process (checking that this is allowed).  Aborts with
327  * VLOG_FATAL if fork() returns an error, and otherwise returns the value
328  * returned by fork().
329  *
330  * ('where' is used in logging.  Commonly one would use xfork() to
331  * automatically provide the caller's source file and line number for
332  * 'where'.) */
333 pid_t
334 xfork_at(const char *where)
335 {
336     pid_t pid;
337
338     if (must_not_fork) {
339         VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
340                    where, must_not_fork);
341     }
342
343     pid = fork();
344     if (pid < 0) {
345         VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
346     }
347     return pid;
348 }
349 #endif
350
351 /* Notes that the process must not call fork() from now on, for the specified
352  * 'reason'.  (The process may still fork() if it execs itself immediately
353  * afterward.) */
354 void
355 forbid_forking(const char *reason)
356 {
357     ovs_assert(reason != NULL);
358     must_not_fork = reason;
359 }
360
361 /* Returns true if the process is allowed to fork, false otherwise. */
362 bool
363 may_fork(void)
364 {
365     return !must_not_fork;
366 }
367 \f
368 /* ovsthread_counter.
369  *
370  * We implement the counter as an array of N_COUNTERS individual counters, each
371  * with its own lock.  Each thread uses one of the counters chosen based on a
372  * hash of the thread's ID, the idea being that, statistically, different
373  * threads will tend to use different counters and therefore avoid
374  * interfering with each other.
375  *
376  * Undoubtedly, better implementations are possible. */
377
378 /* Basic counter structure. */
379 struct ovsthread_counter__ {
380     struct ovs_mutex mutex;
381     unsigned long long int value;
382 };
383
384 /* Pad the basic counter structure to 64 bytes to avoid cache line
385  * interference. */
386 struct ovsthread_counter {
387     struct ovsthread_counter__ c;
388     char pad[ROUND_UP(sizeof(struct ovsthread_counter__), 64)
389              - sizeof(struct ovsthread_counter__)];
390 };
391
392 #define N_COUNTERS 16
393
394 struct ovsthread_counter *
395 ovsthread_counter_create(void)
396 {
397     struct ovsthread_counter *c;
398     int i;
399
400     c = xmalloc(N_COUNTERS * sizeof *c);
401     for (i = 0; i < N_COUNTERS; i++) {
402         ovs_mutex_init(&c[i].c.mutex);
403         c[i].c.value = 0;
404     }
405     return c;
406 }
407
408 void
409 ovsthread_counter_destroy(struct ovsthread_counter *c)
410 {
411     if (c) {
412         int i;
413
414         for (i = 0; i < N_COUNTERS; i++) {
415             ovs_mutex_destroy(&c[i].c.mutex);
416         }
417         free(c);
418     }
419 }
420
421 void
422 ovsthread_counter_inc(struct ovsthread_counter *c, unsigned long long int n)
423 {
424     c = &c[hash_int(ovsthread_id_self(), 0) % N_COUNTERS];
425
426     ovs_mutex_lock(&c->c.mutex);
427     c->c.value += n;
428     ovs_mutex_unlock(&c->c.mutex);
429 }
430
431 unsigned long long int
432 ovsthread_counter_read(const struct ovsthread_counter *c)
433 {
434     unsigned long long int sum;
435     int i;
436
437     sum = 0;
438     for (i = 0; i < N_COUNTERS; i++) {
439         ovs_mutex_lock(&c[i].c.mutex);
440         sum += c[i].c.value;
441         ovs_mutex_unlock(&c[i].c.mutex);
442     }
443     return sum;
444 }
445 \f
446 /* Parses /proc/cpuinfo for the total number of physical cores on this system
447  * across all CPU packages, not counting hyper-threads.
448  *
449  * Sets *n_cores to the total number of cores on this system, or 0 if the
450  * number cannot be determined. */
451 static void
452 parse_cpuinfo(long int *n_cores)
453 {
454     static const char file_name[] = "/proc/cpuinfo";
455     char line[128];
456     uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
457     long int cores = 0;
458     FILE *stream;
459
460     stream = fopen(file_name, "r");
461     if (!stream) {
462         VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
463         return;
464     }
465
466     while (fgets(line, sizeof line, stream)) {
467         unsigned int id;
468
469         /* Find the next CPU package. */
470         if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
471             if (id > 63) {
472                 VLOG_WARN("Counted over 64 CPU packages on this system. "
473                           "Parsing %s for core count may be inaccurate.",
474                           file_name);
475                 cores = 0;
476                 break;
477             }
478
479             if (cpu & (1 << id)) {
480                 /* We've already counted this package's cores. */
481                 continue;
482             }
483             cpu |= 1 << id;
484
485             /* Find the number of cores for this package. */
486             while (fgets(line, sizeof line, stream)) {
487                 int count;
488
489                 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
490                     cores += count;
491                     break;
492                 }
493             }
494         }
495     }
496     fclose(stream);
497
498     *n_cores = cores;
499 }
500
501 /* Returns the total number of cores on this system, or 0 if the number cannot
502  * be determined.
503  *
504  * Tries not to count hyper-threads, but may be inaccurate - particularly on
505  * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
506  * formatted different to the layout that parse_cpuinfo() expects. */
507 int
508 count_cpu_cores(void)
509 {
510     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
511     static long int n_cores;
512
513     if (ovsthread_once_start(&once)) {
514 #ifndef _WIN32
515         parse_cpuinfo(&n_cores);
516         if (!n_cores) {
517             n_cores = sysconf(_SC_NPROCESSORS_ONLN);
518         }
519 #else
520         SYSTEM_INFO sysinfo;
521         GetSystemInfo(&sysinfo);
522         n_cores = sysinfo.dwNumberOfProcessors;
523 #endif
524         ovsthread_once_done(&once);
525     }
526
527     return n_cores > 0 ? n_cores : 0;
528 }
529 \f
530 /* ovsthread_key. */
531
532 #define L1_SIZE 1024
533 #define L2_SIZE 1024
534 #define MAX_KEYS (L1_SIZE * L2_SIZE)
535
536 /* A piece of thread-specific data. */
537 struct ovsthread_key {
538     struct list list_node;      /* In 'inuse_keys' or 'free_keys'. */
539     void (*destructor)(void *); /* Called at thread exit. */
540
541     /* Indexes into the per-thread array in struct ovsthread_key_slots.
542      * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
543     unsigned int index;
544 };
545
546 /* Per-thread data structure. */
547 struct ovsthread_key_slots {
548     struct list list_node;      /* In 'slots_list'. */
549     void **p1[L1_SIZE];
550 };
551
552 /* Contains "struct ovsthread_key_slots *". */
553 static pthread_key_t tsd_key;
554
555 /* Guards data structures below. */
556 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
557
558 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
559  * yet destroyed.
560  *
561  * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
562  * ready for reuse.  (We keep them around only to be able to easily locate
563  * free indexes.)
564  *
565  * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
566  * from 0 to n_keys - 1, inclusive. */
567 static struct list inuse_keys OVS_GUARDED_BY(key_mutex)
568     = LIST_INITIALIZER(&inuse_keys);
569 static struct list free_keys OVS_GUARDED_BY(key_mutex)
570     = LIST_INITIALIZER(&free_keys);
571 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
572
573 /* All existing struct ovsthread_key_slots. */
574 static struct list slots_list OVS_GUARDED_BY(key_mutex)
575     = LIST_INITIALIZER(&slots_list);
576
577 static void *
578 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
579 {
580     void **p2 = slots->p1[index / L2_SIZE];
581     if (p2) {
582         void **valuep = &p2[index % L2_SIZE];
583         void *value = *valuep;
584         *valuep = NULL;
585         return value;
586     } else {
587         return NULL;
588     }
589 }
590
591 static void
592 ovsthread_key_destruct__(void *slots_)
593 {
594     struct ovsthread_key_slots *slots = slots_;
595     struct ovsthread_key *key;
596     unsigned int n;
597     int i;
598
599     ovs_mutex_lock(&key_mutex);
600     list_remove(&slots->list_node);
601     LIST_FOR_EACH (key, list_node, &inuse_keys) {
602         void *value = clear_slot(slots, key->index);
603         if (value && key->destructor) {
604             key->destructor(value);
605         }
606     }
607     n = n_keys;
608     ovs_mutex_unlock(&key_mutex);
609
610     for (i = 0; i < n / L2_SIZE; i++) {
611         free(slots->p1[i]);
612     }
613     free(slots);
614 }
615
616 /* Initializes '*keyp' as a thread-specific data key.  The data items are
617  * initially null in all threads.
618  *
619  * If a thread exits with non-null data, then 'destructor', if nonnull, will be
620  * called passing the final data value as its argument.  'destructor' must not
621  * call any thread-specific data functions in this API.
622  *
623  * This function is similar to xpthread_key_create(). */
624 void
625 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
626 {
627     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
628     struct ovsthread_key *key;
629
630     if (ovsthread_once_start(&once)) {
631         xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
632         ovsthread_once_done(&once);
633     }
634
635     ovs_mutex_lock(&key_mutex);
636     if (list_is_empty(&free_keys)) {
637         key = xmalloc(sizeof *key);
638         key->index = n_keys++;
639         if (key->index >= MAX_KEYS) {
640             abort();
641         }
642     } else {
643         key = CONTAINER_OF(list_pop_back(&free_keys),
644                             struct ovsthread_key, list_node);
645     }
646     list_push_back(&inuse_keys, &key->list_node);
647     key->destructor = destructor;
648     ovs_mutex_unlock(&key_mutex);
649
650     *keyp = key;
651 }
652
653 /* Frees 'key'.  The destructor supplied to ovsthread_key_create(), if any, is
654  * not called.
655  *
656  * This function is similar to xpthread_key_delete(). */
657 void
658 ovsthread_key_delete(ovsthread_key_t key)
659 {
660     struct ovsthread_key_slots *slots;
661
662     ovs_mutex_lock(&key_mutex);
663
664     /* Move 'key' from 'inuse_keys' to 'free_keys'. */
665     list_remove(&key->list_node);
666     list_push_back(&free_keys, &key->list_node);
667
668     /* Clear this slot in all threads. */
669     LIST_FOR_EACH (slots, list_node, &slots_list) {
670         clear_slot(slots, key->index);
671     }
672
673     ovs_mutex_unlock(&key_mutex);
674 }
675
676 static void **
677 ovsthread_key_lookup__(const struct ovsthread_key *key)
678 {
679     struct ovsthread_key_slots *slots;
680     void **p2;
681
682     slots = pthread_getspecific(tsd_key);
683     if (!slots) {
684         slots = xzalloc(sizeof *slots);
685
686         ovs_mutex_lock(&key_mutex);
687         pthread_setspecific(tsd_key, slots);
688         list_push_back(&slots_list, &slots->list_node);
689         ovs_mutex_unlock(&key_mutex);
690     }
691
692     p2 = slots->p1[key->index / L2_SIZE];
693     if (!p2) {
694         p2 = xzalloc(L2_SIZE * sizeof *p2);
695         slots->p1[key->index / L2_SIZE] = p2;
696     }
697
698     return &p2[key->index % L2_SIZE];
699 }
700
701 /* Sets the value of thread-specific data item 'key', in the current thread, to
702  * 'value'.
703  *
704  * This function is similar to pthread_setspecific(). */
705 void
706 ovsthread_setspecific(ovsthread_key_t key, const void *value)
707 {
708     *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
709 }
710
711 /* Returns the value of thread-specific data item 'key' in the current thread.
712  *
713  * This function is similar to pthread_getspecific(). */
714 void *
715 ovsthread_getspecific(ovsthread_key_t key)
716 {
717     return *ovsthread_key_lookup__(key);
718 }
719 #endif