pthread_mutex.c revision 1.11 1 /* $NetBSD: pthread_mutex.c,v 1.11 2003/04/16 18:30:43 nathanw Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2003 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 Jason R. Thorpe.
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_mutex.c,v 1.11 2003/04/16 18:30:43 nathanw Exp $");
41
42 #include <errno.h>
43 #include <limits.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "pthread.h"
48 #include "pthread_int.h"
49
50 static int pthread_mutex_lock_slow(pthread_mutex_t *);
51
52 __strong_alias(__libc_mutex_init,pthread_mutex_init)
53 __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
54 __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
55 __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
56 __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
57
58 __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
59 __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
60 __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
61
62 __strong_alias(__libc_thr_once,pthread_once)
63
64 struct mutex_private {
65 int type;
66 int recursecount;
67 };
68
69 static const struct mutex_private mutex_private_default = {
70 PTHREAD_MUTEX_DEFAULT,
71 0,
72 };
73
74 struct mutexattr_private {
75 int type;
76 };
77
78 static const struct mutexattr_private mutexattr_private_default = {
79 PTHREAD_MUTEX_DEFAULT,
80 };
81
82 /*
83 * If the mutex does not already have private data (i.e. was statically
84 * initialized), then give it the default.
85 */
86 #define GET_MUTEX_PRIVATE(mutex, mp) \
87 do { \
88 if (__predict_false((mp = (mutex)->ptm_private) == NULL)) { \
89 /* LINTED cast away const */ \
90 mp = ((mutex)->ptm_private = \
91 (void *)&mutex_private_default); \
92 } \
93 } while (/*CONSTCOND*/0)
94
95 int
96 pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
97 {
98 struct mutexattr_private *map;
99 struct mutex_private *mp;
100
101 #ifdef ERRORCHECK
102 if ((mutex == NULL) ||
103 (attr && (attr->ptma_magic != _PT_MUTEXATTR_MAGIC)))
104 return EINVAL;
105 #endif
106
107 if (attr != NULL && (map = attr->ptma_private) != NULL &&
108 memcmp(map, &mutexattr_private_default, sizeof(*map)) != 0) {
109 mp = malloc(sizeof(*mp));
110 if (mp == NULL)
111 return ENOMEM;
112
113 mp->type = map->type;
114 mp->recursecount = 0;
115 } else {
116 /* LINTED cast away const */
117 mp = (struct mutex_private *) &mutex_private_default;
118 }
119
120 mutex->ptm_magic = _PT_MUTEX_MAGIC;
121 mutex->ptm_owner = NULL;
122 pthread_lockinit(&mutex->ptm_lock);
123 pthread_lockinit(&mutex->ptm_interlock);
124 PTQ_INIT(&mutex->ptm_blocked);
125 mutex->ptm_private = mp;
126
127 return 0;
128 }
129
130
131 int
132 pthread_mutex_destroy(pthread_mutex_t *mutex)
133 {
134
135 #ifdef ERRORCHECK
136 if ((mutex == NULL) ||
137 (mutex->ptm_magic != _PT_MUTEX_MAGIC) ||
138 (mutex->ptm_lock != __SIMPLELOCK_UNLOCKED))
139 return EINVAL;
140 #endif
141
142 mutex->ptm_magic = _PT_MUTEX_DEAD;
143 if (mutex->ptm_private != NULL &&
144 mutex->ptm_private != (const void *)&mutex_private_default)
145 free(mutex->ptm_private);
146
147 return 0;
148 }
149
150
151 /*
152 * Note regarding memory visibility: Pthreads has rules about memory
153 * visibility and mutexes. Very roughly: Memory a thread can see when
154 * it unlocks a mutex can be seen by another thread that locks the
155 * same mutex.
156 *
157 * A memory barrier after a lock and before an unlock will provide
158 * this behavior. This code relies on pthread__simple_lock_try() to issue
159 * a barrier after obtaining a lock, and on pthread__simple_unlock() to
160 * issue a barrier before releasing a lock.
161 */
162
163 int
164 pthread_mutex_lock(pthread_mutex_t *mutex)
165 {
166 int error;
167
168 #ifdef ERRORCHECK
169 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
170 return EINVAL;
171 #endif
172
173 PTHREADD_ADD(PTHREADD_MUTEX_LOCK);
174 /*
175 * Note that if we get the lock, we don't have to deal with any
176 * non-default lock type handling.
177 */
178 if (__predict_false(pthread__simple_lock_try(&mutex->ptm_lock) == 0)) {
179 error = pthread_mutex_lock_slow(mutex);
180 if (error)
181 return error;
182 }
183
184 /* We have the lock! */
185 /*
186 * Identifying ourselves may be slow, and this assignment is
187 * only needed for (a) debugging identity of the owning thread
188 * and (b) handling errorcheck and recursive mutexes. It's
189 * better to just stash our stack pointer here and let those
190 * slow exception cases compute the stack->thread mapping.
191 */
192 mutex->ptm_owner = (pthread_t)pthread__sp();
193
194 return 0;
195 }
196
197
198 static int
199 pthread_mutex_lock_slow(pthread_mutex_t *mutex)
200 {
201 pthread_t self;
202
203 self = pthread__self();
204
205 PTHREADD_ADD(PTHREADD_MUTEX_LOCK_SLOW);
206 while (/*CONSTCOND*/1) {
207 if (pthread__simple_lock_try(&mutex->ptm_lock))
208 break; /* got it! */
209
210 /* Okay, didn't look free. Get the interlock... */
211 pthread_spinlock(self, &mutex->ptm_interlock);
212 /*
213 * The mutex_unlock routine will get the interlock
214 * before looking at the list of sleepers, so if the
215 * lock is held we can safely put ourselves on the
216 * sleep queue. If it's not held, we can try taking it
217 * again.
218 */
219 if (mutex->ptm_lock == __SIMPLELOCK_LOCKED) {
220 struct mutex_private *mp;
221
222 GET_MUTEX_PRIVATE(mutex, mp);
223
224 if (pthread__id(mutex->ptm_owner) == self) {
225 switch (mp->type) {
226 case PTHREAD_MUTEX_ERRORCHECK:
227 pthread_spinunlock(self,
228 &mutex->ptm_interlock);
229 return EDEADLK;
230
231 case PTHREAD_MUTEX_RECURSIVE:
232 /*
233 * It's safe to do this without
234 * holding the interlock, because
235 * we only modify it if we know we
236 * own the mutex.
237 */
238 pthread_spinunlock(self,
239 &mutex->ptm_interlock);
240 if (mp->recursecount == INT_MAX)
241 return EAGAIN;
242 mp->recursecount++;
243 return 0;
244 }
245 }
246
247 PTQ_INSERT_HEAD(&mutex->ptm_blocked, self, pt_sleep);
248 /*
249 * Locking a mutex is not a cancellation
250 * point, so we don't need to do the
251 * test-cancellation dance. We may get woken
252 * up spuriously by pthread_cancel or signals,
253 * but it's okay since we're just going to
254 * retry.
255 */
256 pthread_spinlock(self, &self->pt_statelock);
257 self->pt_state = PT_STATE_BLOCKED_QUEUE;
258 self->pt_sleepobj = mutex;
259 self->pt_sleepq = &mutex->ptm_blocked;
260 self->pt_sleeplock = &mutex->ptm_interlock;
261 pthread_spinunlock(self, &self->pt_statelock);
262
263 pthread__block(self, &mutex->ptm_interlock);
264 /* interlock is not held when we return */
265 } else {
266 pthread_spinunlock(self, &mutex->ptm_interlock);
267 }
268 /* Go around for another try. */
269 }
270
271 return 0;
272 }
273
274
275 int
276 pthread_mutex_trylock(pthread_mutex_t *mutex)
277 {
278
279 #ifdef ERRORCHECK
280 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
281 return EINVAL;
282 #endif
283
284 PTHREADD_ADD(PTHREADD_MUTEX_TRYLOCK);
285 if (pthread__simple_lock_try(&mutex->ptm_lock) == 0) {
286 pthread_t self;
287 struct mutex_private *mp;
288
289 GET_MUTEX_PRIVATE(mutex, mp);
290
291 /*
292 * These tests can be performed without holding the
293 * interlock because these fields are only modified
294 * if we know we own the mutex.
295 */
296 self = pthread__self();
297 if (pthread__id(mutex->ptm_owner) == self) {
298 switch (mp->type) {
299 case PTHREAD_MUTEX_ERRORCHECK:
300 return EDEADLK;
301
302 case PTHREAD_MUTEX_RECURSIVE:
303 if (mp->recursecount == INT_MAX)
304 return EAGAIN;
305 mp->recursecount++;
306 return 0;
307 }
308 }
309
310 return EBUSY;
311 }
312
313 /* see comment at the end of pthread_mutex_lock() */
314 mutex->ptm_owner = (pthread_t)pthread__sp();
315
316 return 0;
317 }
318
319
320 int
321 pthread_mutex_unlock(pthread_mutex_t *mutex)
322 {
323 struct mutex_private *mp;
324 pthread_t self, blocked;
325
326 #ifdef ERRORCHECK
327 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
328 return EINVAL;
329
330 if (mutex->ptm_lock != __SIMPLELOCK_LOCKED)
331 return EPERM; /* Not exactly the right error. */
332 #endif
333 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK);
334
335 GET_MUTEX_PRIVATE(mutex, mp);
336
337 /*
338 * These tests can be performed without holding the
339 * interlock because these fields are only modified
340 * if we know we own the mutex.
341 */
342 switch (mp->type) {
343 case PTHREAD_MUTEX_ERRORCHECK:
344 if (pthread__id(mutex->ptm_owner) != pthread__self())
345 return EPERM;
346 break;
347
348 case PTHREAD_MUTEX_RECURSIVE:
349 if (pthread__id(mutex->ptm_owner) != pthread__self())
350 return EPERM;
351 if (mp->recursecount != 0) {
352 mp->recursecount--;
353 return 0;
354 }
355 break;
356 }
357
358 mutex->ptm_owner = NULL;
359 pthread__simple_unlock(&mutex->ptm_lock);
360 /*
361 * Do a double-checked locking dance to see if there are any
362 * waiters. If we don't see any waiters, we can exit, because
363 * we've already released the lock. If we do see waiters, they
364 * were probably waiting on us... there's a slight chance that
365 * they are waiting on a different thread's ownership of the
366 * lock that happened between the unlock above and this
367 * examination of the queue; if so, no harm is done, as the
368 * waiter will loop and see that the mutex is still locked.
369 */
370 if (!PTQ_EMPTY(&mutex->ptm_blocked)) {
371 self = pthread__self();
372 pthread_spinlock(self, &mutex->ptm_interlock);
373 blocked = PTQ_FIRST(&mutex->ptm_blocked);
374 if (blocked)
375 PTQ_REMOVE(&mutex->ptm_blocked, blocked, pt_sleep);
376 pthread_spinunlock(self, &mutex->ptm_interlock);
377
378 /* Give the head of the blocked queue another try. */
379 if (blocked) {
380 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK_UNBLOCK);
381 pthread__sched(self, blocked);
382 }
383 }
384 return 0;
385 }
386
387 int
388 pthread_mutexattr_init(pthread_mutexattr_t *attr)
389 {
390 struct mutexattr_private *map;
391
392 #ifdef ERRORCHECK
393 if (attr == NULL)
394 return EINVAL;
395 #endif
396
397 map = malloc(sizeof(*map));
398 if (map == NULL)
399 return ENOMEM;
400
401 *map = mutexattr_private_default;
402
403 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
404 attr->ptma_private = map;
405
406 return 0;
407 }
408
409
410 int
411 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
412 {
413
414 #ifdef ERRORCHECK
415 if ((attr == NULL) ||
416 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
417 return EINVAL;
418 #endif
419
420 attr->ptma_magic = _PT_MUTEXATTR_DEAD;
421 if (attr->ptma_private != NULL)
422 free(attr->ptma_private);
423
424 return 0;
425 }
426
427
428 int
429 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
430 {
431 struct mutexattr_private *map;
432
433 #ifdef ERRORCHECK
434 if ((attr == NULL) ||
435 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC) ||
436 (typep == NULL))
437 return EINVAL;
438 #endif
439
440 map = attr->ptma_private;
441
442 *typep = map->type;
443
444 return 0;
445 }
446
447
448 int
449 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
450 {
451 struct mutexattr_private *map;
452
453 #ifdef ERRORCHECK
454 if ((attr == NULL) ||
455 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
456 return EINVAL;
457 #endif
458 map = attr->ptma_private;
459
460 switch (type) {
461 case PTHREAD_MUTEX_NORMAL:
462 case PTHREAD_MUTEX_ERRORCHECK:
463 case PTHREAD_MUTEX_RECURSIVE:
464 map->type = type;
465 break;
466
467 default:
468 return EINVAL;
469 }
470
471 return 0;
472 }
473
474
475 int
476 pthread_once(pthread_once_t *once_control, void (*routine)(void))
477 {
478
479 if (once_control->pto_done == 0) {
480 pthread_mutex_lock(&once_control->pto_mutex);
481 if (once_control->pto_done == 0) {
482 routine();
483 once_control->pto_done = 1;
484 }
485 pthread_mutex_unlock(&once_control->pto_mutex);
486 }
487
488 return 0;
489 }
490