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