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