Home | History | Annotate | Line # | Download | only in libpthread
pthread_mutex.c revision 1.6
      1 /*	$NetBSD: pthread_mutex.c,v 1.6 2003/01/22 13:49:14 scw 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 	/*
    173 	 * Note that if we get the lock, we don't have to deal with any
    174 	 * non-default lock type handling.
    175 	 */
    176 	if (__predict_false(pthread__simple_lock_try(&mutex->ptm_lock) == 0)) {
    177 		error = pthread_mutex_lock_slow(mutex);
    178 		if (error)
    179 			return error;
    180 	}
    181 
    182 	/* We have the lock! */
    183 	mutex->ptm_owner = pthread__self();
    184 
    185 	return 0;
    186 }
    187 
    188 
    189 static int
    190 pthread_mutex_lock_slow(pthread_mutex_t *mutex)
    191 {
    192 	pthread_t self;
    193 
    194 	self = pthread__self();
    195 
    196 	while (/*CONSTCOND*/1) {
    197 		if (pthread__simple_lock_try(&mutex->ptm_lock))
    198 			break; /* got it! */
    199 
    200 		/* Okay, didn't look free. Get the interlock... */
    201 		pthread_spinlock(self, &mutex->ptm_interlock);
    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 		if (mutex->ptm_lock == __SIMPLELOCK_LOCKED) {
    210 			struct mutex_private *mp;
    211 
    212 			GET_MUTEX_PRIVATE(mutex, mp);
    213 
    214 			if (mutex->ptm_owner == self) {
    215 				switch (mp->type) {
    216 				case PTHREAD_MUTEX_ERRORCHECK:
    217 					pthread_spinunlock(self,
    218 					    &mutex->ptm_interlock);
    219 					return EDEADLK;
    220 
    221 				case PTHREAD_MUTEX_RECURSIVE:
    222 					/*
    223 					 * It's safe to do this without
    224 					 * holding the interlock, because
    225 					 * we only modify it if we know we
    226 					 * own the mutex.
    227 					 */
    228 					pthread_spinunlock(self,
    229 					    &mutex->ptm_interlock);
    230 					if (mp->recursecount == INT_MAX)
    231 						return EAGAIN;
    232 					mp->recursecount++;
    233 					return 0;
    234 				}
    235 			}
    236 
    237 			PTQ_INSERT_TAIL(&mutex->ptm_blocked, self, pt_sleep);
    238 			/*
    239 			 * Locking a mutex is not a cancellation
    240 			 * point, so we don't need to do the
    241 			 * test-cancellation dance. We may get woken
    242 			 * up spuriously by pthread_cancel, though,
    243 			 * but it's okay since we're just going to
    244 			 * retry.
    245 			 */
    246 			pthread_spinlock(self, &self->pt_statelock);
    247 			self->pt_state = PT_STATE_BLOCKED_QUEUE;
    248 			self->pt_sleepobj = mutex;
    249 			self->pt_sleepq = &mutex->ptm_blocked;
    250 			self->pt_sleeplock = &mutex->ptm_interlock;
    251 			pthread_spinunlock(self, &self->pt_statelock);
    252 
    253 			pthread__block(self, &mutex->ptm_interlock);
    254 			/* interlock is not held when we return */
    255 		} else {
    256 			pthread_spinunlock(self, &mutex->ptm_interlock);
    257 		}
    258 		/* Go around for another try. */
    259 	}
    260 
    261 	return 0;
    262 }
    263 
    264 
    265 int
    266 pthread_mutex_trylock(pthread_mutex_t *mutex)
    267 {
    268 	pthread_t self = pthread__self();
    269 
    270 #ifdef ERRORCHECK
    271 	if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
    272 		return EINVAL;
    273 #endif
    274 
    275 	if (pthread__simple_lock_try(&mutex->ptm_lock) == 0) {
    276 		struct mutex_private *mp;
    277 
    278 		GET_MUTEX_PRIVATE(mutex, mp);
    279 
    280 		/*
    281 		 * These tests can be performed without holding the
    282 		 * interlock because these fields are only modified
    283 		 * if we know we own the mutex.
    284 		 */
    285 		if (mutex->ptm_owner == self) {
    286 			switch (mp->type) {
    287 			case PTHREAD_MUTEX_ERRORCHECK:
    288 				return EDEADLK;
    289 
    290 			case PTHREAD_MUTEX_RECURSIVE:
    291 				if (mp->recursecount == INT_MAX)
    292 					return EAGAIN;
    293 				mp->recursecount++;
    294 				return 0;
    295 			}
    296 		}
    297 
    298 		return EBUSY;
    299 	}
    300 
    301 	mutex->ptm_owner = self;
    302 
    303 	return 0;
    304 }
    305 
    306 
    307 int
    308 pthread_mutex_unlock(pthread_mutex_t *mutex)
    309 {
    310 	struct mutex_private *mp;
    311 	pthread_t self, blocked;
    312 
    313 	self = pthread__self();
    314 
    315 #ifdef ERRORCHECK
    316 	if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
    317 		return EINVAL;
    318 
    319 	if (mutex->ptm_lock != __SIMPLELOCK_LOCKED)
    320 		return EPERM; /* Not exactly the right error. */
    321 #endif
    322 
    323 	GET_MUTEX_PRIVATE(mutex, mp);
    324 
    325 	/*
    326 	 * These tests can be performed without holding the
    327 	 * interlock because these fields are only modified
    328 	 * if we know we own the mutex.
    329 	 */
    330 	switch (mp->type) {
    331 	case PTHREAD_MUTEX_ERRORCHECK:
    332 		if (mutex->ptm_owner != self)
    333 			return EPERM;
    334 		break;
    335 
    336 	case PTHREAD_MUTEX_RECURSIVE:
    337 		if (mutex->ptm_owner != self)
    338 			return EPERM;
    339 		if (mp->recursecount != 0) {
    340 			mp->recursecount--;
    341 			return 0;
    342 		}
    343 		break;
    344 	}
    345 
    346 	pthread_spinlock(self, &mutex->ptm_interlock);
    347 	blocked = PTQ_FIRST(&mutex->ptm_blocked);
    348 	if (blocked)
    349 		PTQ_REMOVE(&mutex->ptm_blocked, blocked, pt_sleep);
    350 	mutex->ptm_owner = NULL;
    351 	pthread__simple_unlock(&mutex->ptm_lock);
    352 	pthread_spinunlock(self, &mutex->ptm_interlock);
    353 
    354 	/* Give the head of the blocked queue another try. */
    355 	if (blocked)
    356 		pthread__sched(self, blocked);
    357 
    358 	return 0;
    359 }
    360 
    361 int
    362 pthread_mutexattr_init(pthread_mutexattr_t *attr)
    363 {
    364 	struct mutexattr_private *map;
    365 
    366 #ifdef ERRORCHECK
    367 	if (attr == NULL)
    368 		return EINVAL;
    369 #endif
    370 
    371 	map = malloc(sizeof(*map));
    372 	if (map == NULL)
    373 		return ENOMEM;
    374 
    375 	*map = mutexattr_private_default;
    376 
    377 	attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
    378 	attr->ptma_private = map;
    379 
    380 	return 0;
    381 }
    382 
    383 
    384 int
    385 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
    386 {
    387 
    388 #ifdef ERRORCHECK
    389 	if ((attr == NULL) ||
    390 	    (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
    391 		return EINVAL;
    392 #endif
    393 
    394 	attr->ptma_magic = _PT_MUTEXATTR_DEAD;
    395 	if (attr->ptma_private != NULL)
    396 		free(attr->ptma_private);
    397 
    398 	return 0;
    399 }
    400 
    401 
    402 int
    403 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
    404 {
    405 	struct mutexattr_private *map;
    406 
    407 #ifdef ERRORCHECK
    408 	if ((attr == NULL) ||
    409 	    (attr->ptma_magic != _PT_MUTEXATTR_MAGIC) ||
    410 	    (typep == NULL))
    411 		return EINVAL;
    412 #endif
    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 #ifdef ERRORCHECK
    428 	if ((attr == NULL) ||
    429 	    (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
    430 		return EINVAL;
    431 #endif
    432 	map = attr->ptma_private;
    433 
    434 	switch (type) {
    435 	case PTHREAD_MUTEX_NORMAL:
    436 	case PTHREAD_MUTEX_ERRORCHECK:
    437 	case PTHREAD_MUTEX_RECURSIVE:
    438 		map->type = type;
    439 		break;
    440 
    441 	default:
    442 		return EINVAL;
    443 	}
    444 
    445 	return 0;
    446 }
    447 
    448 
    449 int
    450 pthread_once(pthread_once_t *once_control, void (*routine)(void))
    451 {
    452 
    453 	if (once_control->pto_done == 0) {
    454 		pthread_mutex_lock(&once_control->pto_mutex);
    455 		if (once_control->pto_done == 0) {
    456 			routine();
    457 			once_control->pto_done = 1;
    458 		}
    459 		pthread_mutex_unlock(&once_control->pto_mutex);
    460 	}
    461 
    462 	return 0;
    463 }
    464