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