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