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