pthread_mutex.c revision 1.12 1 /* $NetBSD: pthread_mutex.c,v 1.12 2003/04/16 18:59:12 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.12 2003/04/16 18:59:12 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_RECURSIVE:
300 if (mp->recursecount == INT_MAX)
301 return EAGAIN;
302 mp->recursecount++;
303 return 0;
304 }
305 }
306
307 return EBUSY;
308 }
309
310 /* see comment at the end of pthread_mutex_lock() */
311 mutex->ptm_owner = (pthread_t)pthread__sp();
312
313 return 0;
314 }
315
316
317 int
318 pthread_mutex_unlock(pthread_mutex_t *mutex)
319 {
320 struct mutex_private *mp;
321 pthread_t self, blocked;
322
323 #ifdef ERRORCHECK
324 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
325 return EINVAL;
326
327 if (mutex->ptm_lock != __SIMPLELOCK_LOCKED)
328 return EPERM; /* Not exactly the right error. */
329 #endif
330 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK);
331
332 GET_MUTEX_PRIVATE(mutex, mp);
333
334 /*
335 * These tests can be performed without holding the
336 * interlock because these fields are only modified
337 * if we know we own the mutex.
338 */
339 switch (mp->type) {
340 case PTHREAD_MUTEX_ERRORCHECK:
341 if (pthread__id(mutex->ptm_owner) != pthread__self())
342 return EPERM;
343 break;
344
345 case PTHREAD_MUTEX_RECURSIVE:
346 if (pthread__id(mutex->ptm_owner) != pthread__self())
347 return EPERM;
348 if (mp->recursecount != 0) {
349 mp->recursecount--;
350 return 0;
351 }
352 break;
353 }
354
355 mutex->ptm_owner = NULL;
356 pthread__simple_unlock(&mutex->ptm_lock);
357 /*
358 * Do a double-checked locking dance to see if there are any
359 * waiters. If we don't see any waiters, we can exit, because
360 * we've already released the lock. If we do see waiters, they
361 * were probably waiting on us... there's a slight chance that
362 * they are waiting on a different thread's ownership of the
363 * lock that happened between the unlock above and this
364 * examination of the queue; if so, no harm is done, as the
365 * waiter will loop and see that the mutex is still locked.
366 */
367 if (!PTQ_EMPTY(&mutex->ptm_blocked)) {
368 self = pthread__self();
369 pthread_spinlock(self, &mutex->ptm_interlock);
370 blocked = PTQ_FIRST(&mutex->ptm_blocked);
371 if (blocked)
372 PTQ_REMOVE(&mutex->ptm_blocked, blocked, pt_sleep);
373 pthread_spinunlock(self, &mutex->ptm_interlock);
374
375 /* Give the head of the blocked queue another try. */
376 if (blocked) {
377 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK_UNBLOCK);
378 pthread__sched(self, blocked);
379 }
380 }
381 return 0;
382 }
383
384 int
385 pthread_mutexattr_init(pthread_mutexattr_t *attr)
386 {
387 struct mutexattr_private *map;
388
389 #ifdef ERRORCHECK
390 if (attr == NULL)
391 return EINVAL;
392 #endif
393
394 map = malloc(sizeof(*map));
395 if (map == NULL)
396 return ENOMEM;
397
398 *map = mutexattr_private_default;
399
400 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
401 attr->ptma_private = map;
402
403 return 0;
404 }
405
406
407 int
408 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
409 {
410
411 #ifdef ERRORCHECK
412 if ((attr == NULL) ||
413 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
414 return EINVAL;
415 #endif
416
417 attr->ptma_magic = _PT_MUTEXATTR_DEAD;
418 if (attr->ptma_private != NULL)
419 free(attr->ptma_private);
420
421 return 0;
422 }
423
424
425 int
426 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
427 {
428 struct mutexattr_private *map;
429
430 #ifdef ERRORCHECK
431 if ((attr == NULL) ||
432 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC) ||
433 (typep == NULL))
434 return EINVAL;
435 #endif
436
437 map = attr->ptma_private;
438
439 *typep = map->type;
440
441 return 0;
442 }
443
444
445 int
446 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
447 {
448 struct mutexattr_private *map;
449
450 #ifdef ERRORCHECK
451 if ((attr == NULL) ||
452 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
453 return EINVAL;
454 #endif
455 map = attr->ptma_private;
456
457 switch (type) {
458 case PTHREAD_MUTEX_NORMAL:
459 case PTHREAD_MUTEX_ERRORCHECK:
460 case PTHREAD_MUTEX_RECURSIVE:
461 map->type = type;
462 break;
463
464 default:
465 return EINVAL;
466 }
467
468 return 0;
469 }
470
471
472 int
473 pthread_once(pthread_once_t *once_control, void (*routine)(void))
474 {
475
476 if (once_control->pto_done == 0) {
477 pthread_mutex_lock(&once_control->pto_mutex);
478 if (once_control->pto_done == 0) {
479 routine();
480 once_control->pto_done = 1;
481 }
482 pthread_mutex_unlock(&once_control->pto_mutex);
483 }
484
485 return 0;
486 }
487