pthread_tsd.c revision 1.7.4.3 1 /* $NetBSD: pthread_tsd.c,v 1.7.4.3 2014/05/22 11:36:59 yamt Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Nathan J. Williams, by Andrew Doran, and by Christos Zoulas.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 __RCSID("$NetBSD: pthread_tsd.c,v 1.7.4.3 2014/05/22 11:36:59 yamt Exp $");
34
35 /* Functions and structures dealing with thread-specific data */
36 #include <errno.h>
37
38 #include "pthread.h"
39 #include "pthread_int.h"
40 #include "reentrant.h"
41
42
43 static pthread_mutex_t tsd_mutex = PTHREAD_MUTEX_INITIALIZER;
44 static int nextkey;
45
46 PTQ_HEAD(pthread__tsd_list, pt_specific)
47 pthread__tsd_list[PTHREAD_KEYS_MAX];
48 void (*pthread__tsd_destructors[PTHREAD_KEYS_MAX])(void *);
49
50 __strong_alias(__libc_thr_keycreate,pthread_key_create)
51 __strong_alias(__libc_thr_keydelete,pthread_key_delete)
52
53 static void
54 /*ARGSUSED*/
55 null_destructor(void *p)
56 {
57 }
58
59 #include <err.h>
60 #include <stdlib.h>
61 int
62 pthread_key_create(pthread_key_t *key, void (*destructor)(void *))
63 {
64 int i;
65
66 if (__predict_false(__uselibcstub))
67 return __libc_thr_keycreate_stub(key, destructor);
68
69 /* Get a lock on the allocation list */
70 pthread_mutex_lock(&tsd_mutex);
71
72 /* Find an available slot:
73 * The condition for an available slot is one with the destructor
74 * not being NULL. If the desired destructor is NULL we set it to
75 * our own internal destructor to satisfy the non NULL condition.
76 */
77 /* 1. Search from "nextkey" to the end of the list. */
78 for (i = nextkey; i < PTHREAD_KEYS_MAX; i++)
79 if (pthread__tsd_destructors[i] == NULL)
80 break;
81
82 if (i == PTHREAD_KEYS_MAX) {
83 /* 2. If that didn't work, search from the start
84 * of the list back to "nextkey".
85 */
86 for (i = 0; i < nextkey; i++)
87 if (pthread__tsd_destructors[i] == NULL)
88 break;
89
90 if (i == nextkey) {
91 /* If we didn't find one here, there isn't one
92 * to be found.
93 */
94 pthread_mutex_unlock(&tsd_mutex);
95 return EAGAIN;
96 }
97 }
98
99 /* Got one. */
100 pthread__assert(PTQ_EMPTY(&pthread__tsd_list[i]));
101 pthread__tsd_destructors[i] = destructor ? destructor : null_destructor;
102
103 nextkey = (i + 1) % PTHREAD_KEYS_MAX;
104 pthread_mutex_unlock(&tsd_mutex);
105 *key = i;
106
107 return 0;
108 }
109
110 /*
111 * Each thread holds an array of PTHREAD_KEYS_MAX pt_specific list
112 * elements. When an element is used it is inserted into the appropriate
113 * key bucket of pthread__tsd_list. This means that ptqe_prev == NULL,
114 * means that the element is not threaded, ptqe_prev != NULL it is
115 * already part of the list. When we set to a NULL value we delete from the
116 * list if it was in the list, and when we set to non-NULL value, we insert
117 * in the list if it was not already there.
118 *
119 * We keep this global array of lists of threads that have called
120 * pthread_set_specific with non-null values, for each key so that
121 * we don't have to check all threads for non-NULL values in
122 * pthread_key_destroy
123 *
124 * We could keep an accounting of the number of specific used
125 * entries per thread, so that we can update pt_havespecific when we delete
126 * the last one, but we don't bother for now
127 */
128 int
129 pthread__add_specific(pthread_t self, pthread_key_t key, const void *value)
130 {
131 struct pt_specific *pt;
132
133 pthread__assert(key >= 0 && key < PTHREAD_KEYS_MAX);
134
135 pthread_mutex_lock(&tsd_mutex);
136 pthread__assert(pthread__tsd_destructors[key] != NULL);
137 pt = &self->pt_specific[key];
138 self->pt_havespecific = 1;
139 if (value) {
140 if (pt->pts_next.ptqe_prev == NULL)
141 PTQ_INSERT_HEAD(&pthread__tsd_list[key], pt, pts_next);
142 } else {
143 if (pt->pts_next.ptqe_prev != NULL) {
144 PTQ_REMOVE(&pthread__tsd_list[key], pt, pts_next);
145 pt->pts_next.ptqe_prev = NULL;
146 }
147 }
148 pt->pts_value = __UNCONST(value);
149 pthread_mutex_unlock(&tsd_mutex);
150
151 return 0;
152 }
153
154 int
155 pthread_key_delete(pthread_key_t key)
156 {
157 /*
158 * This is tricky. The standard says of pthread_key_create()
159 * that new keys have the value NULL associated with them in
160 * all threads. According to people who were present at the
161 * standardization meeting, that requirement was written
162 * before pthread_key_delete() was introduced, and not
163 * reconsidered when it was.
164 *
165 * See David Butenhof's article in comp.programming.threads:
166 * Subject: Re: TSD key reusing issue
167 * Message-ID: <u97d8.29$fL6.200 (at) news.cpqcorp.net>
168 * Date: Thu, 21 Feb 2002 09:06:17 -0500
169 * http://groups.google.com/groups?\
170 * hl=en&selm=u97d8.29%24fL6.200%40news.cpqcorp.net
171 *
172 * Given:
173 *
174 * 1: Applications are not required to clear keys in all
175 * threads before calling pthread_key_delete().
176 * 2: Clearing pointers without running destructors is a
177 * memory leak.
178 * 3: The pthread_key_delete() function is expressly forbidden
179 * to run any destructors.
180 *
181 * Option 1: Make this function effectively a no-op and
182 * prohibit key reuse. This is a possible resource-exhaustion
183 * problem given that we have a static storage area for keys,
184 * but having a non-static storage area would make
185 * pthread_setspecific() expensive (might need to realloc the
186 * TSD array).
187 *
188 * Option 2: Ignore the specified behavior of
189 * pthread_key_create() and leave the old values. If an
190 * application deletes a key that still has non-NULL values in
191 * some threads... it's probably a memory leak and hence
192 * incorrect anyway, and we're within our rights to let the
193 * application lose. However, it's possible (if unlikely) that
194 * the application is storing pointers to non-heap data, or
195 * non-pointers that have been wedged into a void pointer, so
196 * we can't entirely write off such applications as incorrect.
197 * This could also lead to running (new) destructors on old
198 * data that was never supposed to be associated with that
199 * destructor.
200 *
201 * Option 3: Follow the specified behavior of
202 * pthread_key_create(). Either pthread_key_create() or
203 * pthread_key_delete() would then have to clear the values in
204 * every thread's slot for that key. In order to guarantee the
205 * visibility of the NULL value in other threads, there would
206 * have to be synchronization operations in both the clearer
207 * and pthread_getspecific(). Putting synchronization in
208 * pthread_getspecific() is a big performance lose. But in
209 * reality, only (buggy) reuse of an old key would require
210 * this synchronization; for a new key, there has to be a
211 * memory-visibility propagating event between the call to
212 * pthread_key_create() and pthread_getspecific() with that
213 * key, so setting the entries to NULL without synchronization
214 * will work, subject to problem (2) above. However, it's kind
215 * of slow.
216 *
217 * Note that the argument in option 3 only applies because we
218 * keep TSD in ordinary memory which follows the pthreads
219 * visibility rules. The visibility rules are not required by
220 * the standard to apply to TSD, so the argument doesn't
221 * apply in general, just to this implementation.
222 */
223
224 /*
225 * We do option 3; we find the list of all pt_specific structures
226 * threaded on the key we are deleting, unthread them, and set the
227 * pointer to NULL. Finally we unthread the entry, freeing it for
228 * further use.
229 *
230 * We don't call the destructor here, it is the responsibility
231 * of the application to cleanup the storage:
232 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/\
233 * pthread_key_delete.html
234 */
235 struct pt_specific *pt;
236
237 if (__predict_false(__uselibcstub))
238 return __libc_thr_keydelete_stub(key);
239
240 pthread__assert(key >= 0 && key < PTHREAD_KEYS_MAX);
241
242 pthread_mutex_lock(&tsd_mutex);
243
244 pthread__assert(pthread__tsd_destructors[key] != NULL);
245
246 while ((pt = PTQ_FIRST(&pthread__tsd_list[key])) != NULL) {
247 PTQ_REMOVE(&pthread__tsd_list[key], pt, pts_next);
248 pt->pts_value = NULL;
249 pt->pts_next.ptqe_prev = NULL;
250 }
251
252 pthread__tsd_destructors[key] = NULL;
253 pthread_mutex_unlock(&tsd_mutex);
254
255 return 0;
256 }
257
258 /* Perform thread-exit-time destruction of thread-specific data. */
259 void
260 pthread__destroy_tsd(pthread_t self)
261 {
262 int i, done, iterations;
263 void *val;
264 void (*destructor)(void *);
265
266 if (!self->pt_havespecific)
267 return;
268 pthread_mutex_unlock(&self->pt_lock);
269
270 /* Butenhof, section 5.4.2 (page 167):
271 *
272 * ``Also, Pthreads sets the thread-specific data value for a
273 * key to NULL before calling that key's destructor (passing
274 * the previous value of the key) when a thread terminates [*].
275 * ...
276 * [*] That is, unfortunately, not what the standard
277 * says. This is one of the problems with formal standards -
278 * they say what they say, not what they were intended to
279 * say. Somehow, an error crept in, and the sentence
280 * specifying that "the implementation clears the
281 * thread-specific data value before calling the destructor"
282 * was deleted. Nobody noticed, and the standard was approved
283 * with the error. So the standard says (by omission) that if
284 * you want to write a portable application using
285 * thread-specific data, that will not hang on thread
286 * termination, you must call pthread_setspecific within your
287 * destructor function to change the value to NULL. This would
288 * be silly, and any serious implementation of Pthreads will
289 * violate the standard in this respect. Of course, the
290 * standard will be fixed, probably by the 1003.1n amendment
291 * (assorted corrections to 1003.1c-1995), but that will take
292 * a while.''
293 */
294
295 iterations = 4; /* We're not required to try very hard */
296 do {
297 done = 1;
298 for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
299 struct pt_specific *pt = &self->pt_specific[i];
300 if (pt->pts_next.ptqe_prev == NULL)
301 continue;
302 pthread_mutex_lock(&tsd_mutex);
303
304 if (pt->pts_next.ptqe_prev != NULL) {
305 PTQ_REMOVE(&pthread__tsd_list[i], pt, pts_next);
306 val = pt->pts_value;
307 pt->pts_value = NULL;
308 pt->pts_next.ptqe_prev = NULL;
309 destructor = pthread__tsd_destructors[i];
310 } else
311 destructor = NULL;
312
313 pthread_mutex_unlock(&tsd_mutex);
314 if (destructor != NULL) {
315 done = 0;
316 (*destructor)(val);
317 }
318 }
319 } while (!done && iterations--);
320
321 self->pt_havespecific = 0;
322 pthread_mutex_lock(&self->pt_lock);
323 }
324