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