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