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