xref: /netbsd-src/lib/libpthread/pthread_specific.c (revision 453f6b99a313f2f372963fe81f55bf6f811e3f55)
1 /*	$NetBSD: pthread_specific.c,v 1.4 2003/01/21 23:29:22 nathanw Exp $	*/
2 
3 /*-
4  * Copyright (c) 2001 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.
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /* Functions and structures dealing with thread-specific data */
40 #include <assert.h>
41 #include <errno.h>
42 #include <sys/cdefs.h>
43 
44 #include "pthread.h"
45 #include "pthread_int.h"
46 
47 static pthread_mutex_t tsd_mutex = PTHREAD_MUTEX_INITIALIZER;
48 static int nextkey;
49 int pthread__tsd_alloc[PTHREAD_KEYS_MAX];
50 void (*pthread__tsd_destructors[PTHREAD_KEYS_MAX])(void *);
51 
52 __strong_alias(__libc_thr_keycreate,pthread_key_create)
53 __strong_alias(__libc_thr_setspecific,pthread_setspecific)
54 __strong_alias(__libc_thr_getspecific,pthread_getspecific)
55 __strong_alias(__libc_thr_keydelete,pthread_key_delete)
56 
57 int
58 pthread_key_create(pthread_key_t *key, void (*destructor)(void *))
59 {
60 	int i;
61 
62 	/* Get a lock on the allocation list */
63 	pthread_mutex_lock(&tsd_mutex);
64 
65 	/* Find an avaliable slot */
66 	/* 1. Search from "nextkey" to the end of the list. */
67 	for (i = nextkey; i < PTHREAD_KEYS_MAX; i++)
68 		if (pthread__tsd_alloc[i] == 0)
69 			break;
70 
71 	if (i == PTHREAD_KEYS_MAX) {
72 		/* 2. If that didn't work, search from the start
73 		 *    of the list back to "nextkey".
74 		 */
75 		for (i = 0; i < nextkey; i++)
76 			if (pthread__tsd_alloc[i] == 0)
77 				break;
78 
79 		if (i == nextkey) {
80 			/* If we didn't find one here, there isn't one
81 			 * to be found.
82 			 */
83 			pthread_mutex_unlock(&tsd_mutex);
84 			return EAGAIN;
85 		}
86 	}
87 
88 	/* Got one. */
89 	pthread__tsd_alloc[i] = 1;
90 	nextkey = (i + 1) % PTHREAD_KEYS_MAX;
91 	pthread__tsd_destructors[i] = destructor;
92 	pthread_mutex_unlock(&tsd_mutex);
93 	*key = i;
94 
95 	return 0;
96 }
97 
98 int
99 pthread_key_delete(pthread_key_t key)
100 {
101 
102 	/*
103 	 * This is tricky.  The standard says of pthread_key_create()
104 	 * that new keys have the value NULL associated with them in
105 	 * all threads.  According to people who were present at the
106 	 * standardization meeting, that requirement was written
107 	 * before pthread_key_delete() was introduced, and not
108 	 * reconsidered when it was.
109 	 *
110 	 * See David Butenhof's article in comp.programming.threads:
111 	 * Subject: Re: TSD key reusing issue
112 	 * Message-ID: <u97d8.29$fL6.200@news.cpqcorp.net>
113 	 * Date: Thu, 21 Feb 2002 09:06:17 -0500
114 	 * http://groups.google.com/groups?hl=en&selm=u97d8.29%24fL6.200%40news.cpqcorp.net
115 	 *
116 	 * Given:
117 	 *
118 	 * 1: Applications are not required to clear keys in all
119 	 *    threads before calling pthread_key_delete().
120 	 * 2: Clearing pointers without running destructors is a
121 	 *    memory leak.
122 	 * 3: The pthread_key_delete() function is expressly forbidden
123 	 *    to run any destructors.
124 	 *
125 	 * Option 1: Make this function effectively a no-op and
126 	 * prohibit key reuse. This is a possible resource-exhaustion
127 	 * problem given that we have a static storage area for keys,
128 	 * but having a non-static storage area would make
129 	 * pthread_setspecific() expensive (might need to realloc the
130 	 * TSD array).
131 	 *
132 	 * Option 2: Ignore the specified behavior of
133 	 * pthread_key_create() and leave the old values. If an
134 	 * application deletes a key that still has non-NULL values in
135 	 * some threads... it's probably a memory leak and hence
136 	 * incorrect anyway, and we're within our rights to let the
137 	 * application lose. However, it's possible (if unlikely) that
138 	 * the application is storing pointers to non-heap data, or
139 	 * non-pointers that have been wedged into a void pointer, so
140 	 * we can't entirely write off such applications as incorrect.
141 	 * This could also lead to running (new) destructors on old
142 	 * data that was never supposed to be associated with that
143 	 * destructor.
144 	 *
145 	 * Option 3: Follow the specified behavior of
146 	 * pthread_key_create().  Either pthread_key_create() or
147 	 * pthread_key_delete() would then have to clear the values in
148 	 * every thread's slot for that key. In order to guarantee the
149 	 * visibility of the NULL value in other threads, there would
150 	 * have to be synchronization operations in both the clearer
151 	 * and pthread_getspecific().  Putting synchronization in
152 	 * pthread_getspecific() is a big performance lose.  But in
153 	 * reality, only (buggy) reuse of an old key would require
154 	 * this synchronization; for a new key, there has to be a
155 	 * memory-visibility propagating event between the call to
156 	 * pthread_key_create() and pthread_getspecific() with that
157 	 * key, so setting the entries to NULL without synchronization
158 	 * will work, subject to problem (2) above. However, it's kind
159 	 * of slow.
160 	 *
161 	 * Note that the argument in option 3 only applies because we
162 	 * keep TSD in ordinary memory which follows the pthreads
163 	 * visibility rules. The visibility rules are not required by
164 	 * the standard to apply to TSD, so this arguemnt doesn't
165 	 * apply in general, just to this implementation.
166 	 */
167 
168 	/* For the momemt, we're going with option 1. */
169 	pthread_mutex_lock(&tsd_mutex);
170 	pthread__tsd_destructors[key] = NULL;
171 	pthread_mutex_unlock(&tsd_mutex);
172 
173 	return 0;
174 }
175 
176 int
177 pthread_setspecific(pthread_key_t key, const void *value)
178 {
179 	pthread_t self;
180 
181 	if (pthread__tsd_alloc[key] == 0)
182 		return EINVAL;
183 
184 	self = pthread__self();
185 	/*
186 	 * We can't win here on constness. Having been given a
187 	 * "const void *", we can only assign it to other const void *,
188 	 * and return it from functions that are const void *, without
189 	 * generating a warning.
190 	 */
191 	/*LINTED const cast*/
192 	self->pt_specific[key] = (void *) value;
193 
194 	return 0;
195 }
196 
197 void*
198 pthread_getspecific(pthread_key_t key)
199 {
200 	pthread_t self;
201 
202 	if (pthread__tsd_alloc[key] == 0)
203 		return NULL;
204 
205 	self = pthread__self();
206 	return (self->pt_specific[key]);
207 }
208 
209 /* Perform thread-exit-time destruction of thread-specific data. */
210 void
211 pthread__destroy_tsd(pthread_t self)
212 {
213 	int i, done, iterations;
214 	void *val;
215 	void (*destructor)(void *);
216 
217 	/* Butenhof, section 5.4.2 (page 167):
218 	 *
219 	 * ``Also, Pthreads sets the thread-specific data value for a
220 	 * key to NULL before calling that key's destructor (passing
221 	 * the previous value of the key) when a thread terminates [*].
222 	 * ...
223 	 * [*] That is, unfortunately, not what the standard
224 	 * says. This is one of the problems with formal standards -
225 	 * they say what they say, not what they were intended to
226 	 * say. Somehow, an error crept in, and the sentence
227 	 * specifying that "the implementation clears the
228 	 * thread-specific data value before calling the destructor"
229 	 * was deleted. Nobody noticed, and the standard was approved
230 	 * with the error. So the standard says (by omission) that if
231 	 * you want to write a portable application using
232 	 * thread-specific data, that will not hang on thread
233 	 * termination, you must call pthread_setspecific within your
234 	 * destructor function to change the value to NULL. This would
235 	 * be silly, and any serious implementation of Pthreads will
236 	 * violate the standard in this respect. Of course, the
237 	 * standard will be fixed, probably by the 1003.1n amendment
238 	 * (assorted corrections to 1003.1c-1995), but that will take
239 	 * a while.''
240 	 */
241 
242 	iterations = PTHREAD_DESTRUCTOR_ITERATIONS;
243 	do {
244 		done = 1;
245 		for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
246 			if (self->pt_specific[i] != NULL) {
247 				pthread_mutex_lock(&tsd_mutex);
248 				destructor = pthread__tsd_destructors[i];
249 				pthread_mutex_unlock(&tsd_mutex);
250 			    if (destructor != NULL) {
251 				    done = 0;
252 				    val = self->pt_specific[i];
253 				    self->pt_specific[i] = NULL; /* see above */
254 				    (*destructor)(val);
255 			    }
256 			}
257 		}
258 	} while (!done && iterations--);
259 }
260