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