mutex.c 29.6 KB
Newer Older
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright (C) 2005 Philippe Gerum <rpm@xenomai.org>.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include <errno.h>
19
#include <string.h>
20
#include <limits.h>
21
#include <pthread.h>
22
#include <asm/xenomai/syscall.h>
23
#include "current.h"
24
#include "internal.h"
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
25

26
/**
27 28
 * @ingroup cobalt_api
 * @defgroup cobalt_api_mutex Mutual exclusion
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
 *
 * Cobalt/POSIX mutual exclusion services
 *
 * A mutex is a MUTual EXclusion device, and is useful for protecting
 * shared data structures from concurrent modifications, and implementing
 * critical sections and monitors.
 *
 * A mutex has two possible states: unlocked (not owned by any thread), and
 * locked (owned by one thread). A mutex can never be owned by two different
 * threads simultaneously. A thread attempting to lock a mutex that is already
 * locked by another thread is suspended until the owning thread unlocks the
 * mutex first.
 *
 * Before it can be used, a mutex has to be initialized with
 * pthread_mutex_init(). An attribute object, which reference may be passed to
 * this service, allows to select the features of the created mutex, namely its
 * @a type (see pthread_mutexattr_settype()), the priority @a protocol it
 * uses (see pthread_mutexattr_setprotocol()) and whether it may be shared
 * between several processes (see pthread_mutexattr_setpshared()).
 *
 * By default, Cobalt mutexes are of the normal type, use no
 * priority protocol and may not be shared between several processes.
 *
52 53 54 55 56 57
 * Note that pthread_mutex_init() should be used to initialize a mutex, using
 * the static initializer @a PTHREAD_MUTEX_INITIALIZER will delay the
 * initialization to the first method called on the mutex and will
 * most likely introduce switches to secondary mode.
 * The documentation (and specifically api-tags) of the mutex services assumes
 * a mutex was explicitly initialised with pthread_mutex_init().
58 59 60 61
 *
 *@{
 */

62
static pthread_mutexattr_t cobalt_default_mutexattr;
63 64 65
static union cobalt_mutex_union cobalt_autoinit_mutex_union;
static pthread_mutex_t *const cobalt_autoinit_mutex =
	&cobalt_autoinit_mutex_union.native_mutex;
66

67
void cobalt_mutex_init(void)
68
{
69
	struct cobalt_mutex_shadow *_mutex =
70
		&cobalt_autoinit_mutex_union.shadow_mutex;
71 72 73
	pthread_mutexattr_t rt_init_mattr;
	int err __attribute__((unused));

74
	pthread_mutexattr_init(&cobalt_default_mutexattr);
75 76 77

	pthread_mutexattr_init(&rt_init_mattr);
	pthread_mutexattr_setprotocol(&rt_init_mattr, PTHREAD_PRIO_INHERIT);
78
	_mutex->magic = ~COBALT_MUTEX_MAGIC;
79
	err = __COBALT(pthread_mutex_init(cobalt_autoinit_mutex,
80 81 82
						&rt_init_mattr));
	assert(err == 0);
	pthread_mutexattr_destroy(&rt_init_mattr);
83 84
}

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
/**
 * Initialize a mutex.
 *
 * This services initializes the mutex @a mx, using the mutex attributes object
 * @a attr. If @a attr is @a NULL, default attributes are used (see
 * pthread_mutexattr_init()).
 *
 * @param mutex the mutex to be initialized;
 *
 * @param attr the mutex attributes object.
 *
 * @return 0 on success,
 * @return an error number if:
 * - EINVAL, the mutex attributes object @a attr is invalid or uninitialized;
 * - EBUSY, the mutex @a mx was already initialized;
100
 * - ENOMEM, insufficient memory available from the system heap to initialize the
101
 *   mutex, increase CONFIG_XENO_OPT_SYS_HEAPSZ.
102
 * - EAGAIN, insufficient memory available to initialize the
103
 *   mutex, increase CONFIG_XENO_OPT_SHARED_HEAPSZ for a process-shared
104
 *   mutex, or CONFIG_XENO_OPT_PRIVATE_HEAPSZ for a process-private mutex.
105
 * - EAGAIN, no registry slot available, check/raise CONFIG_XENO_OPT_REGISTRY_NRSLOTS.
106 107 108
 * - ENOSYS, @a attr mentions priority protection
 *  (PTHREAD_PRIO_PROTECT), but the C library does not provide
 *  pthread_mutexattr_get/setprioceiling().
109 110 111 112 113
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_init.html">
 * Specification.</a>
 *
114
 * @apitags{thread-unrestricted}
115
 */
116 117
COBALT_IMPL(int, pthread_mutex_init, (pthread_mutex_t *mutex,
				      const pthread_mutexattr_t *attr))
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
118
{
119
	struct cobalt_mutex_shadow *_mutex =
120
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
121
	struct cobalt_mutex_state *state;
122 123
	struct cobalt_mutexattr kmattr;
	int err, tmp;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
124

125
	if (_mutex->magic == COBALT_MUTEX_MAGIC) {
126
		err = -XENOMAI_SYSCALL1(sc_cobalt_mutex_check_init, _mutex);
127 128 129
		if (err)
			return err;
	}
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	if (attr == NULL)
		attr = &cobalt_default_mutexattr;

	err = pthread_mutexattr_getpshared(attr, &tmp);
	if (err)
		return err;
	kmattr.pshared = tmp;

	err = pthread_mutexattr_gettype(attr, &tmp);
	if (err)
		return err;
	kmattr.type = tmp;

	err = pthread_mutexattr_getprotocol(attr, &tmp);
	if (err)
		return err;
	kmattr.protocol = tmp;

149 150 151 152 153 154 155 156 157 158 159
	if (kmattr.protocol == PTHREAD_PRIO_PROTECT) {
		err = pthread_mutexattr_getprioceiling(attr, &tmp);
		if (err)
			return err;
		if (tmp == 0 ||	/* Could not cope with null minpri. */
		    tmp < __cobalt_std_fifo_minpri ||
		    tmp > __cobalt_std_fifo_maxpri)
			return EINVAL;
		kmattr.ceiling = tmp - 1;
	}

160
	err = -XENOMAI_SYSCALL2(sc_cobalt_mutex_init, _mutex, &kmattr);
161 162
	if (err)
		return err;
163

164 165
	state = mutex_get_state(_mutex);
	cobalt_commit_memory(state);
166

167
	return err;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
168 169
}

170
/**
171
 * Test if a mutex structure contains a valid autoinitializer.
172
 *
173 174
 * @return the mutex type on success,
 * @return -1 if not in supported autoinitializer state
175
 */
176 177
static int __attribute__((cold))
	cobalt_mutex_autoinit_type(const pthread_mutex_t *mutex)
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
178
{
179 180 181 182
	static const pthread_mutex_t mutex_initializers[] = {
#if HAVE_DECL_PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
		PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP,
#endif
183
#if HAVE_DECL_PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
184
		PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
185
#endif
186 187 188
		PTHREAD_MUTEX_INITIALIZER
	};
	static const int mutex_types[] = {
189
#if HAVE_DECL_PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
190
		PTHREAD_MUTEX_ERRORCHECK_NP,
191
#endif
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
#if HAVE_DECL_PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
		PTHREAD_MUTEX_RECURSIVE_NP,
#endif
		PTHREAD_MUTEX_DEFAULT
	};
	int i;

	for (i = sizeof(mutex_types) / sizeof(mutex_types[0]); i > 0; --i) {
		if (memcmp(mutex, &mutex_initializers[i - 1],
				sizeof(mutex_initializers[0])) == 0)
			return mutex_types[i - 1];
	}
	return -1;
}

static int __attribute__((cold))
	cobalt_mutex_doautoinit(union cobalt_mutex_union *umutex)
{
	struct cobalt_mutex_shadow *_mutex = &umutex->shadow_mutex;
211
	int err __attribute__((unused));
212
	pthread_mutexattr_t mattr;
213
	int ret = 0, type;
214

215 216
	type = cobalt_mutex_autoinit_type(&umutex->native_mutex);
	if (type < 0)
217 218 219
		return EINVAL;

	pthread_mutexattr_init(&mattr);
220
	pthread_mutexattr_settype(&mattr, type);
221
	err = __COBALT(pthread_mutex_lock(cobalt_autoinit_mutex));
222 223 224 225
	if (err) {
		ret = err;
		goto out;
	}
226
	if (_mutex->magic != COBALT_MUTEX_MAGIC)
227 228
		ret = __COBALT(pthread_mutex_init(&umutex->native_mutex,
			&mattr));
229
	err = __COBALT(pthread_mutex_unlock(cobalt_autoinit_mutex));
230 231 232 233
	if (err) {
		if (ret == 0)
			ret = err;
	}
234

235
  out:
236 237
	pthread_mutexattr_destroy(&mattr);

238
	return ret;
239 240
}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
static inline int cobalt_mutex_autoinit(union cobalt_mutex_union *umutex)
{
	if (unlikely(umutex->shadow_mutex.magic != COBALT_MUTEX_MAGIC))
		return cobalt_mutex_doautoinit(umutex);
	return 0;
}

/**
 * Destroy a mutex.
 *
 * This service destroys the mutex @a mx, if it is unlocked and not referenced
 * by any condition variable. The mutex becomes invalid for all mutex services
 * (they all return the EINVAL error) except pthread_mutex_init().
 *
 * @param mutex the mutex to be destroyed.
 *
 * @return 0 on success,
 * @return an error number if:
 * - EINVAL, the mutex @a mx is invalid;
 * - EPERM, the mutex is not process-shared and does not belong to the current
 *   process;
 * - EBUSY, the mutex is locked, or used by a condition variable.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_destroy.html">
 * Specification.</a>
 *
 * @apitags{thread-unrestricted}
 */
COBALT_IMPL(int, pthread_mutex_destroy, (pthread_mutex_t *mutex))
{
	struct cobalt_mutex_shadow *_mutex =
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
	int err;

	if (unlikely(_mutex->magic != COBALT_MUTEX_MAGIC))
		return (cobalt_mutex_autoinit_type(mutex) < 0) ? EINVAL : 0;

	err = XENOMAI_SYSCALL1(sc_cobalt_mutex_destroy, _mutex);

	return -err;
}

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
/**
 * Lock a mutex.
 *
 * This service attempts to lock the mutex @a mx. If the mutex is free, it
 * becomes locked. If it was locked by another thread than the current one, the
 * current thread is suspended until the mutex is unlocked. If it was already
 * locked by the current mutex, the behaviour of this service depends on the
 * mutex type :
 * - for mutexes of the @a PTHREAD_MUTEX_NORMAL type, this service deadlocks;
 * - for mutexes of the @a PTHREAD_MUTEX_ERRORCHECK type, this service returns
 *   the EDEADLK error number;
 * - for mutexes of the @a PTHREAD_MUTEX_RECURSIVE type, this service increments
 *   the lock recursion count and returns 0.
 *
 * @param mutex the mutex to be locked.
 *
 * @return 0 on success
 * @return an error number if:
302
 * - EPERM, the caller is not allowed to perform the operation;
303 304 305 306 307 308 309 310 311 312 313 314
 * - EINVAL, the mutex @a mx is invalid;
 * - EPERM, the mutex is not process-shared and does not belong to the current
 *   process;
 * - EDEADLK, the mutex is of the @a PTHREAD_MUTEX_ERRORCHECK type and was
 *   already locked by the current thread;
 * - EAGAIN, the mutex is of the @a PTHREAD_MUTEX_RECURSIVE type and the maximum
 *   number of recursive locks has been exceeded.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_lock.html">
 * Specification.</a>
 *
315
 * @apitags{xthread-only, switch-primary}
316
 */
317
COBALT_IMPL(int, pthread_mutex_lock, (pthread_mutex_t *mutex))
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
318
{
319
	struct cobalt_mutex_shadow *_mutex =
320
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
321 322
	struct xnthread_user_window *u_window;
	int status, ret, lazy_protect = 0;
323
	xnhandle_t cur;
324

325
	cur = cobalt_get_current();
326
	if (cur == XN_NO_HANDLE)
327 328
		return EPERM;

329 330 331
	ret = cobalt_mutex_autoinit((union cobalt_mutex_union *)mutex);
	if (ret)
		return ret;
332

333
	/*
334 335 336
	 * We track resource ownership for auto-relax of non real-time
	 * shadows and some debug features, so we must always obtain
	 * them via a syscall.
337
	 */
338
	status = cobalt_get_current_mode();
339
	if ((status & (XNRELAX|XNWEAK|XNDEBUG)) == 0) {
340 341 342
		if (_mutex->attr.protocol == PTHREAD_PRIO_PROTECT)
			goto protect;
fast_path:
343 344
		ret = xnsynch_fast_acquire(mutex_get_ownerp(_mutex), cur);
		if (ret == 0) {
345
			_mutex->lockcnt = 1;
346 347
			return 0;
		}
348
	} else {
349
slow_path:
350 351 352
		ret = xnsynch_fast_owner_check(mutex_get_ownerp(_mutex), cur);
		if (ret == 0)
			ret = -EBUSY;
353
	}
354

355 356 357 358
	if (ret == -EBUSY) {
		if (lazy_protect)
			u_window->pp_pending = XN_NO_HANDLE;

359
		switch(_mutex->attr.type) {
360 361 362 363 364 365 366
		case PTHREAD_MUTEX_NORMAL:
			break;

		case PTHREAD_MUTEX_ERRORCHECK:
			return EDEADLK;

		case PTHREAD_MUTEX_RECURSIVE:
367
			if (_mutex->lockcnt == UINT32_MAX)
368
				return EAGAIN;
369
			++_mutex->lockcnt;
370
			return 0;
371
		}
372
	}
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
373

374 375 376
	do
		ret = XENOMAI_SYSCALL1(sc_cobalt_mutex_lock, _mutex);
	while (ret == -EINTR);
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
377

378
	if (ret == 0)
379
		_mutex->lockcnt = 1;
380

381
	return -ret;
382 383 384 385 386 387 388 389 390 391 392
protect:	
	u_window = cobalt_get_current_window();
	/*
	 * Can't nest lazy ceiling requests, have to take the slow
	 * path when this happens.
	 */
	if (u_window->pp_pending != XN_NO_HANDLE)
		goto slow_path;
	u_window->pp_pending = _mutex->handle;
	lazy_protect = 1;
	goto fast_path;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
393 394
}

395 396 397 398 399 400 401 402 403 404 405 406 407 408
/**
 * Attempt, during a bounded time, to lock a mutex.
 *
 * This service is equivalent to pthread_mutex_lock(), except that if the mutex
 * @a mx is locked by another thread than the current one, this service only
 * suspends the current thread until the timeout specified by @a to expires.
 *
 * @param mutex the mutex to be locked;
 *
 * @param to the timeout, expressed as an absolute value of the CLOCK_REALTIME
 * clock.
 *
 * @return 0 on success;
 * @return an error number if:
409
 * - EPERM, the caller is not allowed to perform the operation;
410 411 412 413 414 415 416 417 418 419 420 421 422 423
 * - EINVAL, the mutex @a mx is invalid;
 * - EPERM, the mutex is not process-shared and does not belong to the current
 *   process;
 * - ETIMEDOUT, the mutex could not be locked and the specified timeout
 *   expired;
 * - EDEADLK, the mutex is of the @a PTHREAD_MUTEX_ERRORCHECK type and the mutex
 *   was already locked by the current thread;
 * - EAGAIN, the mutex is of the @a PTHREAD_MUTEX_RECURSIVE type and the maximum
 *   number of recursive locks has been exceeded.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_timedlock.html">
 * Specification.</a>
 *
424
 * @apitags{xthread-only, switch-primary}
425
 */
426 427
COBALT_IMPL(int, pthread_mutex_timedlock, (pthread_mutex_t *mutex,
					   const struct timespec *to))
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
428
{
429
	struct cobalt_mutex_shadow *_mutex =
430
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
431 432
	struct xnthread_user_window *u_window;
	int status, ret, lazy_protect = 0;
433
	xnhandle_t cur;
434

435
	cur = cobalt_get_current();
436
	if (cur == XN_NO_HANDLE)
437 438
		return EPERM;

439 440 441
	ret = cobalt_mutex_autoinit((union cobalt_mutex_union *)mutex);
	if (ret)
		return ret;
442

443
	/* See __cobalt_pthread_mutex_lock() */
444
	status = cobalt_get_current_mode();
445
	if ((status & (XNRELAX|XNWEAK|XNDEBUG)) == 0) {
446 447 448
		if (_mutex->attr.protocol == PTHREAD_PRIO_PROTECT)
			goto protect;
fast_path:
449 450
		ret = xnsynch_fast_acquire(mutex_get_ownerp(_mutex), cur);
		if (ret == 0) {
451
			_mutex->lockcnt = 1;
452 453
			return 0;
		}
454
	} else {
455
slow_path:
456 457 458
		ret = xnsynch_fast_owner_check(mutex_get_ownerp(_mutex), cur);
		if (ret == 0)
			ret = -EBUSY;
459
	}
460

461 462 463 464
	if (ret == -EBUSY) {
		if (lazy_protect)
			u_window->pp_pending = XN_NO_HANDLE;
			
465
		switch(_mutex->attr.type) {
466 467
		case PTHREAD_MUTEX_NORMAL:
			break;
468

469 470
		case PTHREAD_MUTEX_ERRORCHECK:
			return EDEADLK;
471

472
		case PTHREAD_MUTEX_RECURSIVE:
473
			if (_mutex->lockcnt == UINT32_MAX)
474
				return EAGAIN;
475

476
			++_mutex->lockcnt;
477 478
			return 0;
		}
479
	}
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
480

481
	do {
482 483
		ret = XENOMAI_SYSCALL2(sc_cobalt_mutex_timedlock, _mutex, to);
	} while (ret == -EINTR);
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
484

485
	if (ret == 0)
486
		_mutex->lockcnt = 1;
487
	return -ret;
488 489 490 491 492 493 494 495 496 497 498
protect:	
	u_window = cobalt_get_current_window();
	/*
	 * Can't nest lazy ceiling requests, have to take the slow
	 * path when this happens.
	 */
	if (u_window->pp_pending != XN_NO_HANDLE)
		goto slow_path;
	u_window->pp_pending = _mutex->handle;
	lazy_protect = 1;
	goto fast_path;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
499 500
}

501 502 503 504 505 506 507 508 509 510 511
/**
 * Attempt to lock a mutex.
 *
 * This service is equivalent to pthread_mutex_lock(), except that if the mutex
 * @a mx is locked by another thread than the current one, this service returns
 * immediately.
 *
 * @param mutex the mutex to be locked.
 *
 * @return 0 on success;
 * @return an error number if:
512
 * - EPERM, the caller is not allowed to perform the operation;
513 514 515 516 517 518 519 520 521 522 523
 * - EINVAL, the mutex is invalid;
 * - EPERM, the mutex is not process-shared and does not belong to the current
 *   process;
 * - EBUSY, the mutex was locked by another thread than the current one;
 * - EAGAIN, the mutex is recursive, and the maximum number of recursive locks
 *   has been exceeded.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_trylock.html">
 * Specification.</a>
 *
524
 * @apitags{xthread-only, switch-primary}
525
 */
526
COBALT_IMPL(int, pthread_mutex_trylock, (pthread_mutex_t *mutex))
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
527
{
528
	struct cobalt_mutex_shadow *_mutex =
529
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
530 531
	struct xnthread_user_window *u_window;
	int status, ret, lazy_protect = 0;
532
	xnhandle_t cur;
533

534
	cur = cobalt_get_current();
535
	if (cur == XN_NO_HANDLE)
536 537
		return EPERM;

538 539 540 541
	ret = cobalt_mutex_autoinit((union cobalt_mutex_union *)mutex);
	if (ret)
		return ret;

542
	status = cobalt_get_current_mode();
543
	if ((status & (XNRELAX|XNWEAK|XNDEBUG)) == 0) {
544 545 546 547 548
		if (_mutex->attr.protocol == PTHREAD_PRIO_PROTECT)
			goto protect;
fast_path:
		ret = xnsynch_fast_acquire(mutex_get_ownerp(_mutex), cur);
		if (ret == 0) {
549
			_mutex->lockcnt = 1;
550 551 552
			return 0;
		}
	} else {
553 554
slow_path:
		ret = xnsynch_fast_owner_check(mutex_get_ownerp(_mutex), cur);
555 556
		if (ret == 0)
			ret = -EBUSY;
557
	}
558

559 560 561 562
	if (ret == -EBUSY) {
		if (lazy_protect)
			u_window->pp_pending = XN_NO_HANDLE;

563 564 565
		if (_mutex->attr.type == PTHREAD_MUTEX_RECURSIVE) {
			if (_mutex->lockcnt == UINT32_MAX)
				return EAGAIN;
566

567 568 569
			++_mutex->lockcnt;
			return 0;
		}
570

571
		return EBUSY;
572 573
	}

574
	do {
575 576
		ret = XENOMAI_SYSCALL1(sc_cobalt_mutex_trylock, _mutex);
	} while (ret == -EINTR);
577

578
	if (ret == 0)
579
		_mutex->lockcnt = 1;
580

581
	return -ret;
582 583

protect:
584 585 586 587 588 589 590 591 592 593
	u_window = cobalt_get_current_window();
	/*
	 * Can't nest lazy ceiling requests, have to take the slow
	 * path when this happens.
	 */
	if (u_window->pp_pending != XN_NO_HANDLE)
		goto slow_path;
	u_window->pp_pending = _mutex->handle;
	lazy_protect = 1;
	goto fast_path;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
594 595
}

596 597 598
/**
 * Unlock a mutex.
 *
599 600 601 602
 * This service unlocks the @a mutex. If @a mutex is of the @a
 * PTHREAD_MUTEX_RECURSIVE and the locking recursion count is greater
 * than one, the lock recursion count is decremented and the mutex
 * remains locked.
603 604 605 606 607 608 609 610 611
 *
 * Attempting to unlock a mutex which is not locked or which is locked by
 * another thread than the current one yields the EPERM error, whatever the
 * mutex @a type attribute.
 *
 * @param mutex the mutex to be released.
 *
 * @return 0 on success;
 * @return an error number if:
612 613
 * - EPERM, the caller is not allowed to perform the operation;
 * - EINVAL, the mutex @a mutex is invalid;
614 615 616 617 618 619
 * - EPERM, the mutex was not locked by the current thread.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_unlock.html">
 * Specification.</a>
 *
620
 * @apitags{xthread-only, switch-primary}
621
 */
622
COBALT_IMPL(int, pthread_mutex_unlock, (pthread_mutex_t *mutex))
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
623
{
624
	struct cobalt_mutex_shadow *_mutex =
625
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
626
	struct xnthread_user_window *u_window;
627 628
	struct cobalt_mutex_state *state;
	xnhandle_t cur;
629
	int err;
630

631 632 633 634
	err = cobalt_mutex_autoinit((union cobalt_mutex_union *)mutex);
	if (err)
		return err;

635
	cur = cobalt_get_current();
636 637
	if (cur == XN_NO_HANDLE)
		return EPERM;
638

639 640
	state = mutex_get_state(_mutex);
	if (xnsynch_fast_owner_check(&state->owner, cur) != 0)
641
		return EPERM;
642

643 644
	if (_mutex->lockcnt > 1) {
		--_mutex->lockcnt;
645
		return 0;
646 647
	}

648
	if ((state->flags & COBALT_MUTEX_COND_SIGNAL))
649 650
		goto do_syscall;

651
	if (cobalt_get_current_mode() & (XNWEAK|XNDEBUG))
652 653
		goto do_syscall;

654 655 656
	if (xnsynch_fast_release(&state->owner, cur)) {
		if (_mutex->attr.protocol == PTHREAD_PRIO_PROTECT)
			goto unprotect;
657
		return 0;
658
	}
659
do_syscall:
660
	do {
661
		err = XENOMAI_SYSCALL1(sc_cobalt_mutex_unlock, _mutex);
662
	} while (err == -EINTR);
663 664

	return -err;
665

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
unprotect:
	u_window = cobalt_get_current_window();
	u_window->pp_pending = XN_NO_HANDLE;

	return 0;
}

/**
 * Set a mutex's priority ceiling.
 *
 * This routine acquires the specified mutex, then changes the
 * associated priority ceiling value and releases it.  @a prioceiling
 * must be between the values returned by sched_get_priority_min() and
 * sched_get_priority_max(), inclusive.
 *
 * The Cobalt implementation applies the priority ceiling protocol
 * using the previous ceiling value during this operation. The new
 * priority ceiling will apply next time the @a mutex transitions from
 * the unlocked to locked state.
 *
 * @param mutex the target mutex.
 *
 * @param prioceiling the new ceiling value.
 *
 * @param old_ceiling on success and if this parameter is non-NULL,
 * the previous ceiling value is copied to this address.
 *
 * @return 0 on success;
 * @return an error number if:
 * - EPERM, the caller is not allowed to perform the operation;
 * - EINVAL, @a mutex is invalid;
 * - EINVAL, @a mutex is not of type PTHREAD_PRIO_PROTECT;
 * - EINVAL, @a prioceiling is out of range;
 *
 * @see
 * <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_setprioceiling.html">
 * Specification.</a>
 *
 * @apitags{xthread-only, switch-primary}
 *
 * @note If the calling thread's priority is higher than the mutex's
 * new priority ceiling, the operation will nevertheless succeed; the
 * Cobalt core never decreases the effective priority of a thread
 * which locks a priority-protected mutex.
 */
COBALT_IMPL(int, pthread_mutex_setprioceiling,
	    (pthread_mutex_t *__restrict mutex,
	     int prioceiling, int *__restrict old_ceiling))
{
	struct cobalt_mutex_shadow *_mutex =
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
	struct cobalt_mutex_state *state;
	int ret;

	if (_mutex->magic != COBALT_MUTEX_MAGIC ||
	    _mutex->attr.protocol != PTHREAD_PRIO_PROTECT)
		return EINVAL;
	
	if (prioceiling < __cobalt_std_fifo_minpri ||
	    prioceiling > __cobalt_std_fifo_maxpri)
		return EINVAL;

	ret = __COBALT(pthread_mutex_lock(mutex));
	if (ret)
		return ret;

	state = mutex_get_state(_mutex);
	if (old_ceiling)
		*old_ceiling = state->ceiling;

	state->ceiling = prioceiling;

	return __COBALT(pthread_mutex_unlock(mutex));
}

/**
 * Get a mutex's priority ceiling.
 *
 * This routine retrieves the priority ceiling value of the specified
 * mutex.
 *
 * @param mutex the target mutex.
 *
 * @param prioceiling on success, the current ceiling value is copied
 * to this address.
 *
 * @return 0 on success;
 * @return an error number if:
 * - EINVAL, @a mutex is invalid;
 * - EINVAL, @a mutex is not of type PTHREAD_PRIO_PROTECT;
 *
 * @see
 * <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_getprioceiling.html">
 * Specification.</a>
 *
 * @apitags{thread-unrestricted}
 */
COBALT_IMPL(int, pthread_mutex_getprioceiling,
	    (pthread_mutex_t *__restrict mutex, int *__restrict prioceiling))
{
	struct cobalt_mutex_shadow *_mutex =
		&((union cobalt_mutex_union *)mutex)->shadow_mutex;
	struct cobalt_mutex_state *state;

	if (_mutex->magic != COBALT_MUTEX_MAGIC ||
	    _mutex->attr.protocol != PTHREAD_PRIO_PROTECT)
		return EINVAL;
	
	state = mutex_get_state(_mutex);
	*prioceiling = state->ceiling;

	return 0;
Gilles Chanteperdrix's avatar
Gilles Chanteperdrix committed
778
}
779

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
/**
 * Initialize a mutex attributes object.
 *
 * This services initializes the mutex attributes object @a attr with default
 * values for all attributes. Default value are :
 * - for the @a type attribute, @a PTHREAD_MUTEX_NORMAL;
 * - for the @a protocol attribute, @a PTHREAD_PRIO_NONE;
 * - for the @a pshared attribute, @a PTHREAD_PROCESS_PRIVATE.
 *
 * If this service is called specifying a mutex attributes object that was
 * already initialized, the attributes object is reinitialized.
 *
 * @param attr the mutex attributes object to be initialized.
 *
 * @return 0 on success;
 * @return an error number if:
 * - ENOMEM, the mutex attributes object pointer @a attr is @a NULL.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_init.html">
 * Specification.</a>
 *
802
 * @apitags{thread-unrestricted}
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
 */
int pthread_mutexattr_init(pthread_mutexattr_t * attr);

/**
 * Destroy a mutex attributes object.
 *
 * This service destroys the mutex attributes object @a attr. The object becomes
 * invalid for all mutex services (they all return EINVAL) except
 * pthread_mutexattr_init().
 *
 * @param attr the initialized mutex attributes object to be destroyed.
 *
 * @return 0 on success;
 * @return an error number if:
 * - EINVAL, the mutex attributes object @a attr is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_destroy.html">
 * Specification.</a>
 *
823
 * @apitags{thread-unrestricted}
824 825 826 827 828 829 830 831 832
 */
int pthread_mutexattr_destroy(pthread_mutexattr_t * attr);

/**
 * Get the mutex type attribute from a mutex attributes object.
 *
 * This service stores, at the address @a type, the value of the @a type
 * attribute in the mutex attributes object @a attr.
 *
833 834 835
 * See pthread_mutex_lock() and pthread_mutex_unlock() for a
 * description of the values of the @a type attribute and their effect
 * on a mutex.
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
 *
 * @param attr an initialized mutex attributes object,
 *
 * @param type address where the @a type attribute value will be stored on
 * success.
 *
 * @return 0 on sucess,
 * @return an error number if:
 * - EINVAL, the @a type address is invalid;
 * - EINVAL, the mutex attributes object @a attr is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_gettype.html">
 * Specification.</a>
 *
851
 * @apitags{thread-unrestricted}
852 853 854 855 856 857 858 859 860
 */
int pthread_mutexattr_gettype(const pthread_mutexattr_t * attr, int *type);

/**
 * Set the mutex type attribute of a mutex attributes object.
 *
 * This service set the @a type attribute of the mutex attributes object
 * @a attr.
 *
861 862 863
 * See pthread_mutex_lock() and pthread_mutex_unlock() for a
 * description of the values of the @a type attribute and their effect
 * on a mutex.
864 865
 *
 * The @a PTHREAD_MUTEX_DEFAULT default @a type is the same as @a
866 867
 * PTHREAD_MUTEX_NORMAL. Note that using a recursive Cobalt mutex with
 * a Cobalt condition variable is safe (see pthread_cond_wait()
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
 * documentation).
 *
 * @param attr an initialized mutex attributes object,
 *
 * @param type value of the @a type attribute.
 *
 * @return 0 on success,
 * @return an error number if:
 * - EINVAL, the mutex attributes object @a attr is invalid;
 * - EINVAL, the value of @a type is invalid for the @a type attribute.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_settype.html">
 * Specification.</a>
 *
883
 * @apitags{thread-unrestricted}
884 885 886 887 888 889 890 891 892
 */
int pthread_mutexattr_settype(pthread_mutexattr_t * attr, int type);

/**
 * Get the protocol attribute from a mutex attributes object.
 *
 * This service stores, at the address @a proto, the value of the @a protocol
 * attribute in the mutex attributes object @a attr.
 *
893 894 895
 * The @a protcol attribute may be one of @a PTHREAD_PRIO_NONE, @a
 * PTHREAD_PRIO_INHERIT or @a PTHREAD_PRIO_PROTECT. See
 * pthread_mutexattr_setprotocol() for the meaning of these constants.
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
 *
 * @param attr an initialized mutex attributes object;
 *
 * @param proto address where the value of the @a protocol attribute will be
 * stored on success.
 *
 * @return 0 on success,
 * @return an error number if:
 * - EINVAL, the @a proto address is invalid;
 * - EINVAL, the mutex attributes object @a attr is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_getprotocol.html">
 * Specification.</a>
 *
911
 * @apitags{thread-unrestricted}
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
 */
int pthread_mutexattr_getprotocol(const pthread_mutexattr_t * attr, int *proto);

/**
 * Set the protocol attribute of a mutex attributes object.
 *
 * This service set the @a type attribute of the mutex attributes object
 * @a attr.
 *
 * @param attr an initialized mutex attributes object,
 *
 * @param proto value of the @a protocol attribute, may be one of:
 * - PTHREAD_PRIO_NONE, meaning that a mutex created with the attributes object
 *   @a attr will not follow any priority protocol;
 * - PTHREAD_PRIO_INHERIT, meaning that a mutex created with the attributes
 *   object @a attr, will follow the priority inheritance protocol.
928 929
 * - PTHREAD_PRIO_PROTECT, meaning that a mutex created with the attributes
 *   object @a attr, will follow the priority protect protocol.
930 931 932 933 934 935 936 937 938 939 940
 *
 * @return 0 on success,
 * @return an error number if:
 * - EINVAL, the mutex attributes object @a attr is invalid;
 * - ENOTSUP, the value of @a proto is unsupported;
 * - EINVAL, the value of @a proto is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_setprotocol.html">
 * Specification.</a>
 *
941
 * @apitags{thread-unrestricted}
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
 */
int pthread_mutexattr_setprotocol(pthread_mutexattr_t * attr, int proto);

/**
 * Get the process-shared attribute of a mutex attributes object.
 *
 * This service stores, at the address @a pshared, the value of the @a pshared
 * attribute in the mutex attributes object @a attr.
 *
 * The @a pashared attribute may only be one of @a PTHREAD_PROCESS_PRIVATE or
 * @a PTHREAD_PROCESS_SHARED. See pthread_mutexattr_setpshared() for the meaning
 * of these two constants.
 *
 * @param attr an initialized mutex attributes object;
 *
 * @param pshared address where the value of the @a pshared attribute will be
 * stored on success.
 *
 * @return 0 on success;
 * @return an error number if:
 * - EINVAL, the @a pshared address is invalid;
 * - EINVAL, the mutex attributes object @a attr is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_getpshared.html">
 * Specification.</a>
 *
969
 * @apitags{thread-unrestricted}
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
 */
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, int *pshared);

/**
 * Set the process-shared attribute of a mutex attributes object.
 *
 * This service set the @a pshared attribute of the mutex attributes object @a
 * attr.
 *
 * @param attr an initialized mutex attributes object.
 *
 * @param pshared value of the @a pshared attribute, may be one of:
 * - PTHREAD_PROCESS_PRIVATE, meaning that a mutex created with the attributes
 *   object @a attr will only be accessible by threads within the same process
 *   as the thread that initialized the mutex;
 * - PTHREAD_PROCESS_SHARED, meaning that a mutex created with the attributes
 *   object @a attr will be accessible by any thread that has access to the
 *   memory where the mutex is allocated.
 *
 * @return 0 on success,
 * @return an error status if:
 * - EINVAL, the mutex attributes object @a attr is invalid;
 * - EINVAL, the value of @a pshared is invalid.
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutexattr_setpshared.html">
 * Specification.</a>
 *
998
 * @apitags{thread-unrestricted}
999 1000 1001
 */
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);

1002
/** @} */