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