Home | History | Annotate | Line # | Download | only in libpthread
pthread_tsd.c revision 1.9
      1 /*	$NetBSD: pthread_tsd.c,v 1.9 2012/11/21 19:19:24 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.9 2012/11/21 19:19:24 christos 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 
     41 
     42 static pthread_mutex_t tsd_mutex = PTHREAD_MUTEX_INITIALIZER;
     43 static int nextkey;
     44 
     45 PTQ_HEAD(pthread__tsd_list, pt_specific)
     46     pthread__tsd_list[PTHREAD_KEYS_MAX];
     47 void (*pthread__tsd_destructors[PTHREAD_KEYS_MAX])(void *);
     48 
     49 __strong_alias(__libc_thr_keycreate,pthread_key_create)
     50 __strong_alias(__libc_thr_keydelete,pthread_key_delete)
     51 
     52 static void
     53 /*ARGSUSED*/
     54 null_destructor(void *p)
     55 {
     56 }
     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 available slot:
     67 	 * The condition for an available slot is one with the destructor
     68 	 * not being NULL. If the desired destructor is NULL we set it to
     69 	 * our own internal destructor to satisfy the non NULL condition.
     70 	 */
     71 	/* 1. Search from "nextkey" to the end of the list. */
     72 	for (i = nextkey; i < PTHREAD_KEYS_MAX; i++)
     73 		if (pthread__tsd_destructors[i] == NULL)
     74 			break;
     75 
     76 	if (i == PTHREAD_KEYS_MAX) {
     77 		/* 2. If that didn't work, search from the start
     78 		 *    of the list back to "nextkey".
     79 		 */
     80 		for (i = 0; i < nextkey; i++)
     81 			if (pthread__tsd_destructors[i] == NULL)
     82 				break;
     83 
     84 		if (i == nextkey) {
     85 			/* If we didn't find one here, there isn't one
     86 			 * to be found.
     87 			 */
     88 			pthread_mutex_unlock(&tsd_mutex);
     89 			return EAGAIN;
     90 		}
     91 	}
     92 
     93 	/* Got one. */
     94 	pthread__assert(PTQ_EMPTY(&pthread__tsd_list[i]));
     95 	pthread__tsd_destructors[i] = destructor ? destructor : null_destructor;
     96 
     97 	nextkey = (i + 1) % PTHREAD_KEYS_MAX;
     98 	pthread_mutex_unlock(&tsd_mutex);
     99 	*key = i;
    100 
    101 	return 0;
    102 }
    103 
    104 /*
    105  * Each thread holds an array of PTHREAD_KEYS_MAX pt_specific list
    106  * elements. When an element is used it is inserted into the appropriate
    107  * key bucket of pthread__tsd_list. This means that ptqe_prev == NULL,
    108  * means that the element is not threaded, ptqe_prev != NULL it is
    109  * already part of the list. When we set to a NULL value we delete from the
    110  * list if it was in the list, and when we set to non-NULL value, we insert
    111  * in the list if it was not already there.
    112  *
    113  * We keep this global array of lists of threads that have called
    114  * pthread_set_specific with non-null values, for each key so that
    115  * we don't have to check all threads for non-NULL values in
    116  * pthread_key_destroy
    117  *
    118  * We could keep an accounting of the number of specific used
    119  * entries per thread, so that we can update pt_havespecific when we delete
    120  * the last one, but we don't bother for now
    121  */
    122 int
    123 pthread__add_specific(pthread_t self, pthread_key_t key, const void *value)
    124 {
    125 	struct pt_specific *pt;
    126 
    127 	pthread__assert(key >= 0 && key < PTHREAD_KEYS_MAX);
    128 
    129 	pthread_mutex_lock(&tsd_mutex);
    130 	pthread__assert(pthread__tsd_destructors[key] != NULL);
    131 	pt = &self->pt_specific[key];
    132 	self->pt_havespecific = 1;
    133 	if (value) {
    134 		if (pt->pts_next.ptqe_prev == NULL)
    135 			PTQ_INSERT_HEAD(&pthread__tsd_list[key], pt, pts_next);
    136 	} else {
    137 		if (pt->pts_next.ptqe_prev != NULL) {
    138 			PTQ_REMOVE(&pthread__tsd_list[key], pt, pts_next);
    139 			pt->pts_next.ptqe_prev = NULL;
    140 		}
    141 	}
    142 	pt->pts_value = __UNCONST(value);
    143 	pthread_mutex_unlock(&tsd_mutex);
    144 
    145 	return 0;
    146 }
    147 
    148 int
    149 pthread_key_delete(pthread_key_t key)
    150 {
    151 
    152 	/*
    153 	 * This is tricky.  The standard says of pthread_key_create()
    154 	 * that new keys have the value NULL associated with them in
    155 	 * all threads.  According to people who were present at the
    156 	 * standardization meeting, that requirement was written
    157 	 * before pthread_key_delete() was introduced, and not
    158 	 * reconsidered when it was.
    159 	 *
    160 	 * See David Butenhof's article in comp.programming.threads:
    161 	 * Subject: Re: TSD key reusing issue
    162 	 * Message-ID: <u97d8.29$fL6.200 (at) news.cpqcorp.net>
    163 	 * Date: Thu, 21 Feb 2002 09:06:17 -0500
    164 	 * http://groups.google.com/groups?hl=en&selm=u97d8.29%24fL6.200%40news.cpqcorp.net
    165 	 *
    166 	 * Given:
    167 	 *
    168 	 * 1: Applications are not required to clear keys in all
    169 	 *    threads before calling pthread_key_delete().
    170 	 * 2: Clearing pointers without running destructors is a
    171 	 *    memory leak.
    172 	 * 3: The pthread_key_delete() function is expressly forbidden
    173 	 *    to run any destructors.
    174 	 *
    175 	 * Option 1: Make this function effectively a no-op and
    176 	 * prohibit key reuse. This is a possible resource-exhaustion
    177 	 * problem given that we have a static storage area for keys,
    178 	 * but having a non-static storage area would make
    179 	 * pthread_setspecific() expensive (might need to realloc the
    180 	 * TSD array).
    181 	 *
    182 	 * Option 2: Ignore the specified behavior of
    183 	 * pthread_key_create() and leave the old values. If an
    184 	 * application deletes a key that still has non-NULL values in
    185 	 * some threads... it's probably a memory leak and hence
    186 	 * incorrect anyway, and we're within our rights to let the
    187 	 * application lose. However, it's possible (if unlikely) that
    188 	 * the application is storing pointers to non-heap data, or
    189 	 * non-pointers that have been wedged into a void pointer, so
    190 	 * we can't entirely write off such applications as incorrect.
    191 	 * This could also lead to running (new) destructors on old
    192 	 * data that was never supposed to be associated with that
    193 	 * destructor.
    194 	 *
    195 	 * Option 3: Follow the specified behavior of
    196 	 * pthread_key_create().  Either pthread_key_create() or
    197 	 * pthread_key_delete() would then have to clear the values in
    198 	 * every thread's slot for that key. In order to guarantee the
    199 	 * visibility of the NULL value in other threads, there would
    200 	 * have to be synchronization operations in both the clearer
    201 	 * and pthread_getspecific().  Putting synchronization in
    202 	 * pthread_getspecific() is a big performance lose.  But in
    203 	 * reality, only (buggy) reuse of an old key would require
    204 	 * this synchronization; for a new key, there has to be a
    205 	 * memory-visibility propagating event between the call to
    206 	 * pthread_key_create() and pthread_getspecific() with that
    207 	 * key, so setting the entries to NULL without synchronization
    208 	 * will work, subject to problem (2) above. However, it's kind
    209 	 * of slow.
    210 	 *
    211 	 * Note that the argument in option 3 only applies because we
    212 	 * keep TSD in ordinary memory which follows the pthreads
    213 	 * visibility rules. The visibility rules are not required by
    214 	 * the standard to apply to TSD, so the argument doesn't
    215 	 * apply in general, just to this implementation.
    216 	 */
    217 
    218 	/*
    219 	 * We do option 3; we find the list of all pt_specific structures
    220 	 * threaded on the key we are deleting, unthread them, set the
    221 	 * pointer to NULL, and call the destructor on a saved pointer.
    222 	 * Finally we unthread the entry, freeing it from further use.
    223 	 */
    224 	struct pt_specific *pt;
    225 	void (*destructor)(void *);
    226 
    227 	pthread__assert(key >= 0 && key < PTHREAD_KEYS_MAX);
    228 
    229 	pthread_mutex_lock(&tsd_mutex);
    230 
    231 	pthread__assert(pthread__tsd_destructors[key] != NULL);
    232 
    233 	destructor = pthread__tsd_destructors[key];
    234 	if (destructor == null_destructor)
    235 		destructor = NULL;
    236 
    237 	while ((pt = PTQ_FIRST(&pthread__tsd_list[key])) != NULL) {
    238 		void *v;
    239 		PTQ_REMOVE(&pthread__tsd_list[key], pt, pts_next);
    240 		v = pt->pts_value;
    241 		pt->pts_value = NULL;
    242 		pt->pts_next.ptqe_prev = NULL;
    243 		if (destructor && v) {
    244 			pthread_mutex_unlock(&tsd_mutex);
    245 			(*destructor)(v);
    246 			pthread_mutex_lock(&tsd_mutex);
    247 		}
    248 	}
    249 
    250 	pthread__tsd_destructors[key] = NULL;
    251 	pthread_mutex_unlock(&tsd_mutex);
    252 
    253 	return 0;
    254 }
    255 
    256 /* Perform thread-exit-time destruction of thread-specific data. */
    257 void
    258 pthread__destroy_tsd(pthread_t self)
    259 {
    260 	int i, done, iterations;
    261 	void *val;
    262 	void (*destructor)(void *);
    263 
    264 	if (!self->pt_havespecific)
    265 		return;
    266 	pthread_mutex_unlock(&self->pt_lock);
    267 
    268 	/* Butenhof, section 5.4.2 (page 167):
    269 	 *
    270 	 * ``Also, Pthreads sets the thread-specific data value for a
    271 	 * key to NULL before calling that key's destructor (passing
    272 	 * the previous value of the key) when a thread terminates [*].
    273 	 * ...
    274 	 * [*] That is, unfortunately, not what the standard
    275 	 * says. This is one of the problems with formal standards -
    276 	 * they say what they say, not what they were intended to
    277 	 * say. Somehow, an error crept in, and the sentence
    278 	 * specifying that "the implementation clears the
    279 	 * thread-specific data value before calling the destructor"
    280 	 * was deleted. Nobody noticed, and the standard was approved
    281 	 * with the error. So the standard says (by omission) that if
    282 	 * you want to write a portable application using
    283 	 * thread-specific data, that will not hang on thread
    284 	 * termination, you must call pthread_setspecific within your
    285 	 * destructor function to change the value to NULL. This would
    286 	 * be silly, and any serious implementation of Pthreads will
    287 	 * violate the standard in this respect. Of course, the
    288 	 * standard will be fixed, probably by the 1003.1n amendment
    289 	 * (assorted corrections to 1003.1c-1995), but that will take
    290 	 * a while.''
    291 	 */
    292 
    293 	iterations = 4; /* We're not required to try very hard */
    294 	do {
    295 		done = 1;
    296 		for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
    297 			struct pt_specific *pt = &self->pt_specific[i];
    298 			if (pt->pts_next.ptqe_prev == NULL)
    299 				continue;
    300 			pthread_mutex_lock(&tsd_mutex);
    301 
    302 			if (pt->pts_next.ptqe_prev != NULL)  {
    303 				PTQ_REMOVE(&pthread__tsd_list[i], pt, pts_next);
    304 				val = pt->pts_value;
    305 				pt->pts_value = NULL;
    306 				pt->pts_next.ptqe_prev = NULL;
    307 				destructor = pthread__tsd_destructors[i];
    308 			} else
    309 				destructor = NULL;
    310 
    311 			pthread_mutex_unlock(&tsd_mutex);
    312 			if (destructor != NULL) {
    313 				done = 0;
    314 				(*destructor)(val);
    315 			}
    316 		}
    317 	} while (!done && iterations--);
    318 
    319 	self->pt_havespecific = 0;
    320 	pthread_mutex_lock(&self->pt_lock);
    321 }
    322