1 /* $NetBSD: pthread_tsd.c,v 1.10 2012/11/22 08:32:36 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, 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.10 2012/11/22 08:32:36 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@news.cpqcorp.net> 163 * Date: Thu, 21 Feb 2002 09:06:17 -0500 164 * http://groups.google.com/groups?\ 165 * hl=en&selm=u97d8.29%24fL6.200%40news.cpqcorp.net 166 * 167 * Given: 168 * 169 * 1: Applications are not required to clear keys in all 170 * threads before calling pthread_key_delete(). 171 * 2: Clearing pointers without running destructors is a 172 * memory leak. 173 * 3: The pthread_key_delete() function is expressly forbidden 174 * to run any destructors. 175 * 176 * Option 1: Make this function effectively a no-op and 177 * prohibit key reuse. This is a possible resource-exhaustion 178 * problem given that we have a static storage area for keys, 179 * but having a non-static storage area would make 180 * pthread_setspecific() expensive (might need to realloc the 181 * TSD array). 182 * 183 * Option 2: Ignore the specified behavior of 184 * pthread_key_create() and leave the old values. If an 185 * application deletes a key that still has non-NULL values in 186 * some threads... it's probably a memory leak and hence 187 * incorrect anyway, and we're within our rights to let the 188 * application lose. However, it's possible (if unlikely) that 189 * the application is storing pointers to non-heap data, or 190 * non-pointers that have been wedged into a void pointer, so 191 * we can't entirely write off such applications as incorrect. 192 * This could also lead to running (new) destructors on old 193 * data that was never supposed to be associated with that 194 * destructor. 195 * 196 * Option 3: Follow the specified behavior of 197 * pthread_key_create(). Either pthread_key_create() or 198 * pthread_key_delete() would then have to clear the values in 199 * every thread's slot for that key. In order to guarantee the 200 * visibility of the NULL value in other threads, there would 201 * have to be synchronization operations in both the clearer 202 * and pthread_getspecific(). Putting synchronization in 203 * pthread_getspecific() is a big performance lose. But in 204 * reality, only (buggy) reuse of an old key would require 205 * this synchronization; for a new key, there has to be a 206 * memory-visibility propagating event between the call to 207 * pthread_key_create() and pthread_getspecific() with that 208 * key, so setting the entries to NULL without synchronization 209 * will work, subject to problem (2) above. However, it's kind 210 * of slow. 211 * 212 * Note that the argument in option 3 only applies because we 213 * keep TSD in ordinary memory which follows the pthreads 214 * visibility rules. The visibility rules are not required by 215 * the standard to apply to TSD, so the argument doesn't 216 * apply in general, just to this implementation. 217 */ 218 219 /* 220 * We do option 3; we find the list of all pt_specific structures 221 * threaded on the key we are deleting, unthread them, and set the 222 * pointer to NULL. Finally we unthread the entry, freeing it for 223 * further use. 224 * 225 * We don't call the destructor here, it is the responsibility 226 * of the application to cleanup the storage: 227 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/\ 228 * pthread_key_delete.html 229 */ 230 struct pt_specific *pt; 231 232 pthread__assert(key >= 0 && key < PTHREAD_KEYS_MAX); 233 234 pthread_mutex_lock(&tsd_mutex); 235 236 pthread__assert(pthread__tsd_destructors[key] != NULL); 237 238 while ((pt = PTQ_FIRST(&pthread__tsd_list[key])) != NULL) { 239 PTQ_REMOVE(&pthread__tsd_list[key], pt, pts_next); 240 pt->pts_value = NULL; 241 pt->pts_next.ptqe_prev = NULL; 242 } 243 244 pthread__tsd_destructors[key] = NULL; 245 pthread_mutex_unlock(&tsd_mutex); 246 247 return 0; 248 } 249 250 /* Perform thread-exit-time destruction of thread-specific data. */ 251 void 252 pthread__destroy_tsd(pthread_t self) 253 { 254 int i, done, iterations; 255 void *val; 256 void (*destructor)(void *); 257 258 if (!self->pt_havespecific) 259 return; 260 pthread_mutex_unlock(&self->pt_lock); 261 262 /* Butenhof, section 5.4.2 (page 167): 263 * 264 * ``Also, Pthreads sets the thread-specific data value for a 265 * key to NULL before calling that key's destructor (passing 266 * the previous value of the key) when a thread terminates [*]. 267 * ... 268 * [*] That is, unfortunately, not what the standard 269 * says. This is one of the problems with formal standards - 270 * they say what they say, not what they were intended to 271 * say. Somehow, an error crept in, and the sentence 272 * specifying that "the implementation clears the 273 * thread-specific data value before calling the destructor" 274 * was deleted. Nobody noticed, and the standard was approved 275 * with the error. So the standard says (by omission) that if 276 * you want to write a portable application using 277 * thread-specific data, that will not hang on thread 278 * termination, you must call pthread_setspecific within your 279 * destructor function to change the value to NULL. This would 280 * be silly, and any serious implementation of Pthreads will 281 * violate the standard in this respect. Of course, the 282 * standard will be fixed, probably by the 1003.1n amendment 283 * (assorted corrections to 1003.1c-1995), but that will take 284 * a while.'' 285 */ 286 287 iterations = 4; /* We're not required to try very hard */ 288 do { 289 done = 1; 290 for (i = 0; i < PTHREAD_KEYS_MAX; i++) { 291 struct pt_specific *pt = &self->pt_specific[i]; 292 if (pt->pts_next.ptqe_prev == NULL) 293 continue; 294 pthread_mutex_lock(&tsd_mutex); 295 296 if (pt->pts_next.ptqe_prev != NULL) { 297 PTQ_REMOVE(&pthread__tsd_list[i], pt, pts_next); 298 val = pt->pts_value; 299 pt->pts_value = NULL; 300 pt->pts_next.ptqe_prev = NULL; 301 destructor = pthread__tsd_destructors[i]; 302 } else 303 destructor = NULL; 304 305 pthread_mutex_unlock(&tsd_mutex); 306 if (destructor != NULL) { 307 done = 0; 308 (*destructor)(val); 309 } 310 } 311 } while (!done && iterations--); 312 313 self->pt_havespecific = 0; 314 pthread_mutex_lock(&self->pt_lock); 315 } 316