7d38c8001b9f3ae66ac0b29a5f7696405757ed1f
[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     thread_set_nonpmd();
338
339     return aux.start(aux.arg);
340 }
341
342 /* Starts a thread that calls 'start(arg)'.  Sets the thread's name to 'name'
343  * (suffixed by its ovsthread_id()).  Returns the new thread's pthread_t. */
344 pthread_t
345 ovs_thread_create(const char *name, void *(*start)(void *), void *arg)
346 {
347     struct ovsthread_aux *aux;
348     pthread_t thread;
349     int error;
350
351     forbid_forking("multiple threads exist");
352     multithreaded = true;
353     ovsrcu_quiesce_end();
354
355     aux = xmalloc(sizeof *aux);
356     aux->start = start;
357     aux->arg = arg;
358     ovs_strlcpy(aux->name, name, sizeof aux->name);
359
360     error = pthread_create(&thread, NULL, ovsthread_wrapper, aux);
361     if (error) {
362         ovs_abort(error, "pthread_create failed");
363     }
364     return thread;
365 }
366 \f
367 bool
368 ovsthread_once_start__(struct ovsthread_once *once)
369 {
370     ovs_mutex_lock(&once->mutex);
371     /* Mutex synchronizes memory, so we get the current value of 'done'. */
372     if (!once->done) {
373         return true;
374     }
375     ovs_mutex_unlock(&once->mutex);
376     return false;
377 }
378
379 void
380 ovsthread_once_done(struct ovsthread_once *once)
381 {
382     /* We need release semantics here, so that the following store may not
383      * be moved ahead of any of the preceding initialization operations.
384      * A release atomic_thread_fence provides that prior memory accesses
385      * will not be reordered to take place after the following store. */
386     atomic_thread_fence(memory_order_release);
387     once->done = true;
388     ovs_mutex_unlock(&once->mutex);
389 }
390 \f
391 bool
392 single_threaded(void)
393 {
394     return !multithreaded;
395 }
396
397 /* Asserts that the process has not yet created any threads (beyond the initial
398  * thread).
399  *
400  * ('where' is used in logging.  Commonly one would use
401  * assert_single_threaded() to automatically provide the caller's source file
402  * and line number for 'where'.) */
403 void
404 assert_single_threaded_at(const char *where)
405 {
406     if (multithreaded) {
407         VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
408                    where);
409     }
410 }
411
412 #ifndef _WIN32
413 /* Forks the current process (checking that this is allowed).  Aborts with
414  * VLOG_FATAL if fork() returns an error, and otherwise returns the value
415  * returned by fork().
416  *
417  * ('where' is used in logging.  Commonly one would use xfork() to
418  * automatically provide the caller's source file and line number for
419  * 'where'.) */
420 pid_t
421 xfork_at(const char *where)
422 {
423     pid_t pid;
424
425     if (must_not_fork) {
426         VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
427                    where, must_not_fork);
428     }
429
430     pid = fork();
431     if (pid < 0) {
432         VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
433     }
434     return pid;
435 }
436 #endif
437
438 /* Notes that the process must not call fork() from now on, for the specified
439  * 'reason'.  (The process may still fork() if it execs itself immediately
440  * afterward.) */
441 void
442 forbid_forking(const char *reason)
443 {
444     ovs_assert(reason != NULL);
445     must_not_fork = reason;
446 }
447
448 /* Returns true if the process is allowed to fork, false otherwise. */
449 bool
450 may_fork(void)
451 {
452     return !must_not_fork;
453 }
454 \f
455 /* ovsthread_stats. */
456
457 void
458 ovsthread_stats_init(struct ovsthread_stats *stats)
459 {
460     int i;
461
462     ovs_mutex_init(&stats->mutex);
463     for (i = 0; i < ARRAY_SIZE(stats->buckets); i++) {
464         stats->buckets[i] = NULL;
465     }
466 }
467
468 void
469 ovsthread_stats_destroy(struct ovsthread_stats *stats)
470 {
471     ovs_mutex_destroy(&stats->mutex);
472 }
473
474 void *
475 ovsthread_stats_bucket_get(struct ovsthread_stats *stats,
476                            void *(*new_bucket)(void))
477 {
478     unsigned int idx = ovsthread_id_self() & (ARRAY_SIZE(stats->buckets) - 1);
479     void *bucket = stats->buckets[idx];
480     if (!bucket) {
481         ovs_mutex_lock(&stats->mutex);
482         bucket = stats->buckets[idx];
483         if (!bucket) {
484             bucket = stats->buckets[idx] = new_bucket();
485         }
486         ovs_mutex_unlock(&stats->mutex);
487     }
488     return bucket;
489 }
490
491 size_t
492 ovs_thread_stats_next_bucket(const struct ovsthread_stats *stats, size_t i)
493 {
494     for (; i < ARRAY_SIZE(stats->buckets); i++) {
495         if (stats->buckets[i]) {
496             break;
497         }
498     }
499     return i;
500 }
501
502 \f
503 /* Parses /proc/cpuinfo for the total number of physical cores on this system
504  * across all CPU packages, not counting hyper-threads.
505  *
506  * Sets *n_cores to the total number of cores on this system, or 0 if the
507  * number cannot be determined. */
508 static void
509 parse_cpuinfo(long int *n_cores)
510 {
511     static const char file_name[] = "/proc/cpuinfo";
512     char line[128];
513     uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
514     long int cores = 0;
515     FILE *stream;
516
517     stream = fopen(file_name, "r");
518     if (!stream) {
519         VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
520         return;
521     }
522
523     while (fgets(line, sizeof line, stream)) {
524         unsigned int id;
525
526         /* Find the next CPU package. */
527         if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
528             if (id > 63) {
529                 VLOG_WARN("Counted over 64 CPU packages on this system. "
530                           "Parsing %s for core count may be inaccurate.",
531                           file_name);
532                 cores = 0;
533                 break;
534             }
535
536             if (cpu & (1ULL << id)) {
537                 /* We've already counted this package's cores. */
538                 continue;
539             }
540             cpu |= 1ULL << id;
541
542             /* Find the number of cores for this package. */
543             while (fgets(line, sizeof line, stream)) {
544                 int count;
545
546                 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
547                     cores += count;
548                     break;
549                 }
550             }
551         }
552     }
553     fclose(stream);
554
555     *n_cores = cores;
556 }
557
558 /* Returns the total number of cores on this system, or 0 if the number cannot
559  * be determined.
560  *
561  * Tries not to count hyper-threads, but may be inaccurate - particularly on
562  * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
563  * formatted different to the layout that parse_cpuinfo() expects. */
564 int
565 count_cpu_cores(void)
566 {
567     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
568     static long int n_cores;
569
570     if (ovsthread_once_start(&once)) {
571 #ifndef _WIN32
572         parse_cpuinfo(&n_cores);
573         if (!n_cores) {
574             n_cores = sysconf(_SC_NPROCESSORS_ONLN);
575         }
576 #else
577         SYSTEM_INFO sysinfo;
578         GetSystemInfo(&sysinfo);
579         n_cores = sysinfo.dwNumberOfProcessors;
580 #endif
581         ovsthread_once_done(&once);
582     }
583
584     return n_cores > 0 ? n_cores : 0;
585 }
586 \f
587 /* ovsthread_key. */
588
589 #define L1_SIZE 1024
590 #define L2_SIZE 1024
591 #define MAX_KEYS (L1_SIZE * L2_SIZE)
592
593 /* A piece of thread-specific data. */
594 struct ovsthread_key {
595     struct ovs_list list_node;  /* In 'inuse_keys' or 'free_keys'. */
596     void (*destructor)(void *); /* Called at thread exit. */
597
598     /* Indexes into the per-thread array in struct ovsthread_key_slots.
599      * This key's data is stored in p1[index / L2_SIZE][index % L2_SIZE]. */
600     unsigned int index;
601 };
602
603 /* Per-thread data structure. */
604 struct ovsthread_key_slots {
605     struct ovs_list list_node;  /* In 'slots_list'. */
606     void **p1[L1_SIZE];
607 };
608
609 /* Contains "struct ovsthread_key_slots *". */
610 static pthread_key_t tsd_key;
611
612 /* Guards data structures below. */
613 static struct ovs_mutex key_mutex = OVS_MUTEX_INITIALIZER;
614
615 /* 'inuse_keys' holds "struct ovsthread_key"s that have been created and not
616  * yet destroyed.
617  *
618  * 'free_keys' holds "struct ovsthread_key"s that have been deleted and are
619  * ready for reuse.  (We keep them around only to be able to easily locate
620  * free indexes.)
621  *
622  * Together, 'inuse_keys' and 'free_keys' hold an ovsthread_key for every index
623  * from 0 to n_keys - 1, inclusive. */
624 static struct ovs_list inuse_keys OVS_GUARDED_BY(key_mutex)
625     = OVS_LIST_INITIALIZER(&inuse_keys);
626 static struct ovs_list free_keys OVS_GUARDED_BY(key_mutex)
627     = OVS_LIST_INITIALIZER(&free_keys);
628 static unsigned int n_keys OVS_GUARDED_BY(key_mutex);
629
630 /* All existing struct ovsthread_key_slots. */
631 static struct ovs_list slots_list OVS_GUARDED_BY(key_mutex)
632     = OVS_LIST_INITIALIZER(&slots_list);
633
634 static void *
635 clear_slot(struct ovsthread_key_slots *slots, unsigned int index)
636 {
637     void **p2 = slots->p1[index / L2_SIZE];
638     if (p2) {
639         void **valuep = &p2[index % L2_SIZE];
640         void *value = *valuep;
641         *valuep = NULL;
642         return value;
643     } else {
644         return NULL;
645     }
646 }
647
648 static void
649 ovsthread_key_destruct__(void *slots_)
650 {
651     struct ovsthread_key_slots *slots = slots_;
652     struct ovsthread_key *key;
653     unsigned int n;
654     int i;
655
656     ovs_mutex_lock(&key_mutex);
657     list_remove(&slots->list_node);
658     LIST_FOR_EACH (key, list_node, &inuse_keys) {
659         void *value = clear_slot(slots, key->index);
660         if (value && key->destructor) {
661             key->destructor(value);
662         }
663     }
664     n = n_keys;
665     ovs_mutex_unlock(&key_mutex);
666
667     for (i = 0; i < n / L2_SIZE; i++) {
668         free(slots->p1[i]);
669     }
670     free(slots);
671 }
672
673 /* Initializes '*keyp' as a thread-specific data key.  The data items are
674  * initially null in all threads.
675  *
676  * If a thread exits with non-null data, then 'destructor', if nonnull, will be
677  * called passing the final data value as its argument.  'destructor' must not
678  * call any thread-specific data functions in this API.
679  *
680  * This function is similar to xpthread_key_create(). */
681 void
682 ovsthread_key_create(ovsthread_key_t *keyp, void (*destructor)(void *))
683 {
684     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
685     struct ovsthread_key *key;
686
687     if (ovsthread_once_start(&once)) {
688         xpthread_key_create(&tsd_key, ovsthread_key_destruct__);
689         ovsthread_once_done(&once);
690     }
691
692     ovs_mutex_lock(&key_mutex);
693     if (list_is_empty(&free_keys)) {
694         key = xmalloc(sizeof *key);
695         key->index = n_keys++;
696         if (key->index >= MAX_KEYS) {
697             abort();
698         }
699     } else {
700         key = CONTAINER_OF(list_pop_back(&free_keys),
701                             struct ovsthread_key, list_node);
702     }
703     list_push_back(&inuse_keys, &key->list_node);
704     key->destructor = destructor;
705     ovs_mutex_unlock(&key_mutex);
706
707     *keyp = key;
708 }
709
710 /* Frees 'key'.  The destructor supplied to ovsthread_key_create(), if any, is
711  * not called.
712  *
713  * This function is similar to xpthread_key_delete(). */
714 void
715 ovsthread_key_delete(ovsthread_key_t key)
716 {
717     struct ovsthread_key_slots *slots;
718
719     ovs_mutex_lock(&key_mutex);
720
721     /* Move 'key' from 'inuse_keys' to 'free_keys'. */
722     list_remove(&key->list_node);
723     list_push_back(&free_keys, &key->list_node);
724
725     /* Clear this slot in all threads. */
726     LIST_FOR_EACH (slots, list_node, &slots_list) {
727         clear_slot(slots, key->index);
728     }
729
730     ovs_mutex_unlock(&key_mutex);
731 }
732
733 static void **
734 ovsthread_key_lookup__(const struct ovsthread_key *key)
735 {
736     struct ovsthread_key_slots *slots;
737     void **p2;
738
739     slots = pthread_getspecific(tsd_key);
740     if (!slots) {
741         slots = xzalloc(sizeof *slots);
742
743         ovs_mutex_lock(&key_mutex);
744         pthread_setspecific(tsd_key, slots);
745         list_push_back(&slots_list, &slots->list_node);
746         ovs_mutex_unlock(&key_mutex);
747     }
748
749     p2 = slots->p1[key->index / L2_SIZE];
750     if (!p2) {
751         p2 = xzalloc(L2_SIZE * sizeof *p2);
752         slots->p1[key->index / L2_SIZE] = p2;
753     }
754
755     return &p2[key->index % L2_SIZE];
756 }
757
758 /* Sets the value of thread-specific data item 'key', in the current thread, to
759  * 'value'.
760  *
761  * This function is similar to pthread_setspecific(). */
762 void
763 ovsthread_setspecific(ovsthread_key_t key, const void *value)
764 {
765     *ovsthread_key_lookup__(key) = CONST_CAST(void *, value);
766 }
767
768 /* Returns the value of thread-specific data item 'key' in the current thread.
769  *
770  * This function is similar to pthread_getspecific(). */
771 void *
772 ovsthread_getspecific(ovsthread_key_t key)
773 {
774     return *ovsthread_key_lookup__(key);
775 }
776 #endif