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