xref: /onnv-gate/usr/src/lib/libc/port/threads/synch.c (revision 7907:ca1310195b6f)
10Sstevel@tonic-gate /*
20Sstevel@tonic-gate  * CDDL HEADER START
30Sstevel@tonic-gate  *
40Sstevel@tonic-gate  * The contents of this file are subject to the terms of the
51893Sraf  * Common Development and Distribution License (the "License").
61893Sraf  * You may not use this file except in compliance with the License.
70Sstevel@tonic-gate  *
80Sstevel@tonic-gate  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
90Sstevel@tonic-gate  * or http://www.opensolaris.org/os/licensing.
100Sstevel@tonic-gate  * See the License for the specific language governing permissions
110Sstevel@tonic-gate  * and limitations under the License.
120Sstevel@tonic-gate  *
130Sstevel@tonic-gate  * When distributing Covered Code, include this CDDL HEADER in each
140Sstevel@tonic-gate  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
150Sstevel@tonic-gate  * If applicable, add the following below this CDDL HEADER, with the
160Sstevel@tonic-gate  * fields enclosed by brackets "[]" replaced with your own identifying
170Sstevel@tonic-gate  * information: Portions Copyright [yyyy] [name of copyright owner]
180Sstevel@tonic-gate  *
190Sstevel@tonic-gate  * CDDL HEADER END
200Sstevel@tonic-gate  */
211219Sraf 
220Sstevel@tonic-gate /*
235891Sraf  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
240Sstevel@tonic-gate  * Use is subject to license terms.
250Sstevel@tonic-gate  */
260Sstevel@tonic-gate 
270Sstevel@tonic-gate #include "lint.h"
280Sstevel@tonic-gate #include "thr_uberdata.h"
296247Sraf #include <sys/rtpriocntl.h>
306057Sraf #include <sys/sdt.h>
316057Sraf #include <atomic.h>
320Sstevel@tonic-gate 
336247Sraf #if defined(THREAD_DEBUG)
346247Sraf #define	INCR32(x)	(((x) != UINT32_MAX)? (x)++ : 0)
356247Sraf #define	INCR(x)		((x)++)
366247Sraf #define	DECR(x)		((x)--)
376247Sraf #define	MAXINCR(m, x)	((m < ++x)? (m = x) : 0)
386247Sraf #else
396247Sraf #define	INCR32(x)
406247Sraf #define	INCR(x)
416247Sraf #define	DECR(x)
426247Sraf #define	MAXINCR(m, x)
436247Sraf #endif
446247Sraf 
450Sstevel@tonic-gate /*
460Sstevel@tonic-gate  * This mutex is initialized to be held by lwp#1.
470Sstevel@tonic-gate  * It is used to block a thread that has returned from a mutex_lock()
484574Sraf  * of a LOCK_PRIO_INHERIT mutex with an unrecoverable error.
490Sstevel@tonic-gate  */
500Sstevel@tonic-gate mutex_t	stall_mutex = DEFAULTMUTEX;
510Sstevel@tonic-gate 
520Sstevel@tonic-gate static int shared_mutex_held(mutex_t *);
534574Sraf static int mutex_queuelock_adaptive(mutex_t *);
544574Sraf static void mutex_wakeup_all(mutex_t *);
550Sstevel@tonic-gate 
560Sstevel@tonic-gate /*
570Sstevel@tonic-gate  * Lock statistics support functions.
580Sstevel@tonic-gate  */
590Sstevel@tonic-gate void
600Sstevel@tonic-gate record_begin_hold(tdb_mutex_stats_t *msp)
610Sstevel@tonic-gate {
620Sstevel@tonic-gate 	tdb_incr(msp->mutex_lock);
630Sstevel@tonic-gate 	msp->mutex_begin_hold = gethrtime();
640Sstevel@tonic-gate }
650Sstevel@tonic-gate 
660Sstevel@tonic-gate hrtime_t
670Sstevel@tonic-gate record_hold_time(tdb_mutex_stats_t *msp)
680Sstevel@tonic-gate {
690Sstevel@tonic-gate 	hrtime_t now = gethrtime();
700Sstevel@tonic-gate 
710Sstevel@tonic-gate 	if (msp->mutex_begin_hold)
720Sstevel@tonic-gate 		msp->mutex_hold_time += now - msp->mutex_begin_hold;
730Sstevel@tonic-gate 	msp->mutex_begin_hold = 0;
740Sstevel@tonic-gate 	return (now);
750Sstevel@tonic-gate }
760Sstevel@tonic-gate 
770Sstevel@tonic-gate /*
780Sstevel@tonic-gate  * Called once at library initialization.
790Sstevel@tonic-gate  */
800Sstevel@tonic-gate void
810Sstevel@tonic-gate mutex_setup(void)
820Sstevel@tonic-gate {
830Sstevel@tonic-gate 	if (set_lock_byte(&stall_mutex.mutex_lockw))
840Sstevel@tonic-gate 		thr_panic("mutex_setup() cannot acquire stall_mutex");
850Sstevel@tonic-gate 	stall_mutex.mutex_owner = (uintptr_t)curthread;
860Sstevel@tonic-gate }
870Sstevel@tonic-gate 
880Sstevel@tonic-gate /*
895629Sraf  * The default spin count of 1000 is experimentally determined.
905629Sraf  * On sun4u machines with any number of processors it could be raised
910Sstevel@tonic-gate  * to 10,000 but that (experimentally) makes almost no difference.
925629Sraf  * The environment variable:
930Sstevel@tonic-gate  *	_THREAD_ADAPTIVE_SPIN=count
945629Sraf  * can be used to override and set the count in the range [0 .. 1,000,000].
950Sstevel@tonic-gate  */
960Sstevel@tonic-gate int	thread_adaptive_spin = 1000;
970Sstevel@tonic-gate uint_t	thread_max_spinners = 100;
980Sstevel@tonic-gate int	thread_queue_verify = 0;
990Sstevel@tonic-gate static	int	ncpus;
1000Sstevel@tonic-gate 
1010Sstevel@tonic-gate /*
1020Sstevel@tonic-gate  * Distinguish spinning for queue locks from spinning for regular locks.
1035629Sraf  * We try harder to acquire queue locks by spinning.
1040Sstevel@tonic-gate  * The environment variable:
1050Sstevel@tonic-gate  *	_THREAD_QUEUE_SPIN=count
1060Sstevel@tonic-gate  * can be used to override and set the count in the range [0 .. 1,000,000].
1070Sstevel@tonic-gate  */
1085629Sraf int	thread_queue_spin = 10000;
1090Sstevel@tonic-gate 
1104574Sraf #define	ALL_ATTRIBUTES				\
1114574Sraf 	(LOCK_RECURSIVE | LOCK_ERRORCHECK |	\
1124574Sraf 	LOCK_PRIO_INHERIT | LOCK_PRIO_PROTECT |	\
1134574Sraf 	LOCK_ROBUST)
1140Sstevel@tonic-gate 
1150Sstevel@tonic-gate /*
1164574Sraf  * 'type' can be one of USYNC_THREAD, USYNC_PROCESS, or USYNC_PROCESS_ROBUST,
1174574Sraf  * augmented by zero or more the flags:
1184574Sraf  *	LOCK_RECURSIVE
1194574Sraf  *	LOCK_ERRORCHECK
1204574Sraf  *	LOCK_PRIO_INHERIT
1214574Sraf  *	LOCK_PRIO_PROTECT
1224574Sraf  *	LOCK_ROBUST
1230Sstevel@tonic-gate  */
1246812Sraf #pragma weak _mutex_init = mutex_init
1250Sstevel@tonic-gate /* ARGSUSED2 */
1260Sstevel@tonic-gate int
1276812Sraf mutex_init(mutex_t *mp, int type, void *arg)
1280Sstevel@tonic-gate {
1294574Sraf 	int basetype = (type & ~ALL_ATTRIBUTES);
1306247Sraf 	const pcclass_t *pccp;
1314574Sraf 	int error = 0;
1326247Sraf 	int ceil;
1334574Sraf 
1344574Sraf 	if (basetype == USYNC_PROCESS_ROBUST) {
1354574Sraf 		/*
1364574Sraf 		 * USYNC_PROCESS_ROBUST is a deprecated historical type.
1374574Sraf 		 * We change it into (USYNC_PROCESS | LOCK_ROBUST) but
1384574Sraf 		 * retain the USYNC_PROCESS_ROBUST flag so we can return
1394574Sraf 		 * ELOCKUNMAPPED when necessary (only USYNC_PROCESS_ROBUST
1404574Sraf 		 * mutexes will ever draw ELOCKUNMAPPED).
1414574Sraf 		 */
1424574Sraf 		type |= (USYNC_PROCESS | LOCK_ROBUST);
1434574Sraf 		basetype = USYNC_PROCESS;
1444574Sraf 	}
1454574Sraf 
1466247Sraf 	if (type & LOCK_PRIO_PROTECT)
1476247Sraf 		pccp = get_info_by_policy(SCHED_FIFO);
1486247Sraf 	if ((basetype != USYNC_THREAD && basetype != USYNC_PROCESS) ||
1494574Sraf 	    (type & (LOCK_PRIO_INHERIT | LOCK_PRIO_PROTECT))
1506247Sraf 	    == (LOCK_PRIO_INHERIT | LOCK_PRIO_PROTECT) ||
1516247Sraf 	    ((type & LOCK_PRIO_PROTECT) &&
1526247Sraf 	    ((ceil = *(int *)arg) < pccp->pcc_primin ||
1536247Sraf 	    ceil > pccp->pcc_primax))) {
1544574Sraf 		error = EINVAL;
1554574Sraf 	} else if (type & LOCK_ROBUST) {
1564574Sraf 		/*
1574574Sraf 		 * Callers of mutex_init() with the LOCK_ROBUST attribute
1584574Sraf 		 * are required to pass an initially all-zero mutex.
1594574Sraf 		 * Multiple calls to mutex_init() are allowed; all but
1604574Sraf 		 * the first return EBUSY.  A call to mutex_init() is
1614574Sraf 		 * allowed to make an inconsistent robust lock consistent
1624574Sraf 		 * (for historical usage, even though the proper interface
1634574Sraf 		 * for this is mutex_consistent()).  Note that we use
1644574Sraf 		 * atomic_or_16() to set the LOCK_INITED flag so as
1654574Sraf 		 * not to disturb surrounding bits (LOCK_OWNERDEAD, etc).
1664574Sraf 		 */
1674574Sraf 		if (!(mp->mutex_flag & LOCK_INITED)) {
1684574Sraf 			mp->mutex_type = (uint8_t)type;
1696812Sraf 			atomic_or_16(&mp->mutex_flag, LOCK_INITED);
1704574Sraf 			mp->mutex_magic = MUTEX_MAGIC;
1714574Sraf 		} else if (type != mp->mutex_type ||
1726247Sraf 		    ((type & LOCK_PRIO_PROTECT) && mp->mutex_ceiling != ceil)) {
1734574Sraf 			error = EINVAL;
1746812Sraf 		} else if (mutex_consistent(mp) != 0) {
1754574Sraf 			error = EBUSY;
1764574Sraf 		}
1774574Sraf 		/* register a process robust mutex with the kernel */
1784574Sraf 		if (basetype == USYNC_PROCESS)
1794574Sraf 			register_lock(mp);
1804574Sraf 	} else {
1816515Sraf 		(void) memset(mp, 0, sizeof (*mp));
1820Sstevel@tonic-gate 		mp->mutex_type = (uint8_t)type;
1830Sstevel@tonic-gate 		mp->mutex_flag = LOCK_INITED;
1844574Sraf 		mp->mutex_magic = MUTEX_MAGIC;
1850Sstevel@tonic-gate 	}
1864574Sraf 
1876247Sraf 	if (error == 0 && (type & LOCK_PRIO_PROTECT)) {
1886247Sraf 		mp->mutex_ceiling = ceil;
1896247Sraf 	}
1904574Sraf 
1917255Sraf 	/*
1927255Sraf 	 * This should be at the beginning of the function,
1937255Sraf 	 * but for the sake of old broken applications that
1947255Sraf 	 * do not have proper alignment for their mutexes
1957255Sraf 	 * (and don't check the return code from mutex_init),
1967255Sraf 	 * we put it here, after initializing the mutex regardless.
1977255Sraf 	 */
1987255Sraf 	if (error == 0 &&
1997255Sraf 	    ((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
2007255Sraf 	    curthread->ul_misaligned == 0)
2017255Sraf 		error = EINVAL;
2027255Sraf 
2030Sstevel@tonic-gate 	return (error);
2040Sstevel@tonic-gate }
2050Sstevel@tonic-gate 
2060Sstevel@tonic-gate /*
2076247Sraf  * Delete mp from list of ceiling mutexes owned by curthread.
2080Sstevel@tonic-gate  * Return 1 if the head of the chain was updated.
2090Sstevel@tonic-gate  */
2100Sstevel@tonic-gate int
2110Sstevel@tonic-gate _ceil_mylist_del(mutex_t *mp)
2120Sstevel@tonic-gate {
2130Sstevel@tonic-gate 	ulwp_t *self = curthread;
2140Sstevel@tonic-gate 	mxchain_t **mcpp;
2150Sstevel@tonic-gate 	mxchain_t *mcp;
2160Sstevel@tonic-gate 
2176247Sraf 	for (mcpp = &self->ul_mxchain;
2186247Sraf 	    (mcp = *mcpp) != NULL;
2196247Sraf 	    mcpp = &mcp->mxchain_next) {
2206247Sraf 		if (mcp->mxchain_mx == mp) {
2216247Sraf 			*mcpp = mcp->mxchain_next;
2226247Sraf 			lfree(mcp, sizeof (*mcp));
2236247Sraf 			return (mcpp == &self->ul_mxchain);
2246247Sraf 		}
2256247Sraf 	}
2266247Sraf 	return (0);
2270Sstevel@tonic-gate }
2280Sstevel@tonic-gate 
2290Sstevel@tonic-gate /*
2306247Sraf  * Add mp to the list of ceiling mutexes owned by curthread.
2310Sstevel@tonic-gate  * Return ENOMEM if no memory could be allocated.
2320Sstevel@tonic-gate  */
2330Sstevel@tonic-gate int
2340Sstevel@tonic-gate _ceil_mylist_add(mutex_t *mp)
2350Sstevel@tonic-gate {
2360Sstevel@tonic-gate 	ulwp_t *self = curthread;
2370Sstevel@tonic-gate 	mxchain_t *mcp;
2380Sstevel@tonic-gate 
2390Sstevel@tonic-gate 	if ((mcp = lmalloc(sizeof (*mcp))) == NULL)
2400Sstevel@tonic-gate 		return (ENOMEM);
2410Sstevel@tonic-gate 	mcp->mxchain_mx = mp;
2420Sstevel@tonic-gate 	mcp->mxchain_next = self->ul_mxchain;
2430Sstevel@tonic-gate 	self->ul_mxchain = mcp;
2440Sstevel@tonic-gate 	return (0);
2450Sstevel@tonic-gate }
2460Sstevel@tonic-gate 
2470Sstevel@tonic-gate /*
2486247Sraf  * Helper function for _ceil_prio_inherit() and _ceil_prio_waive(), below.
2496247Sraf  */
2506247Sraf static void
2516247Sraf set_rt_priority(ulwp_t *self, int prio)
2526247Sraf {
2536247Sraf 	pcparms_t pcparm;
2546247Sraf 
2556247Sraf 	pcparm.pc_cid = self->ul_rtclassid;
2566247Sraf 	((rtparms_t *)pcparm.pc_clparms)->rt_tqnsecs = RT_NOCHANGE;
2576247Sraf 	((rtparms_t *)pcparm.pc_clparms)->rt_pri = prio;
2586515Sraf 	(void) priocntl(P_LWPID, self->ul_lwpid, PC_SETPARMS, &pcparm);
2596247Sraf }
2606247Sraf 
2616247Sraf /*
2626247Sraf  * Inherit priority from ceiling.
2636247Sraf  * This changes the effective priority, not the assigned priority.
2640Sstevel@tonic-gate  */
2650Sstevel@tonic-gate void
2666247Sraf _ceil_prio_inherit(int prio)
2670Sstevel@tonic-gate {
2680Sstevel@tonic-gate 	ulwp_t *self = curthread;
2696247Sraf 
2706247Sraf 	self->ul_epri = prio;
2716247Sraf 	set_rt_priority(self, prio);
2720Sstevel@tonic-gate }
2730Sstevel@tonic-gate 
2740Sstevel@tonic-gate /*
2750Sstevel@tonic-gate  * Waive inherited ceiling priority.  Inherit from head of owned ceiling locks
2760Sstevel@tonic-gate  * if holding at least one ceiling lock.  If no ceiling locks are held at this
2770Sstevel@tonic-gate  * point, disinherit completely, reverting back to assigned priority.
2780Sstevel@tonic-gate  */
2790Sstevel@tonic-gate void
2800Sstevel@tonic-gate _ceil_prio_waive(void)
2810Sstevel@tonic-gate {
2820Sstevel@tonic-gate 	ulwp_t *self = curthread;
2836247Sraf 	mxchain_t *mcp = self->ul_mxchain;
2846247Sraf 	int prio;
2856247Sraf 
2866247Sraf 	if (mcp == NULL) {
2876247Sraf 		prio = self->ul_pri;
2886247Sraf 		self->ul_epri = 0;
2890Sstevel@tonic-gate 	} else {
2906247Sraf 		prio = mcp->mxchain_mx->mutex_ceiling;
2916247Sraf 		self->ul_epri = prio;
2920Sstevel@tonic-gate 	}
2936247Sraf 	set_rt_priority(self, prio);
2940Sstevel@tonic-gate }
2950Sstevel@tonic-gate 
2960Sstevel@tonic-gate /*
2975629Sraf  * Clear the lock byte.  Retain the waiters byte and the spinners byte.
2985629Sraf  * Return the old value of the lock word.
2995629Sraf  */
3005629Sraf static uint32_t
3015629Sraf clear_lockbyte(volatile uint32_t *lockword)
3025629Sraf {
3035629Sraf 	uint32_t old;
3045629Sraf 	uint32_t new;
3055629Sraf 
3065629Sraf 	do {
3075629Sraf 		old = *lockword;
3085629Sraf 		new = old & ~LOCKMASK;
3095629Sraf 	} while (atomic_cas_32(lockword, old, new) != old);
3105629Sraf 
3115629Sraf 	return (old);
3125629Sraf }
3135629Sraf 
3145629Sraf /*
3156057Sraf  * Same as clear_lockbyte(), but operates on mutex_lockword64.
3166057Sraf  * The mutex_ownerpid field is cleared along with the lock byte.
3176057Sraf  */
3186057Sraf static uint64_t
3196057Sraf clear_lockbyte64(volatile uint64_t *lockword64)
3206057Sraf {
3216057Sraf 	uint64_t old;
3226057Sraf 	uint64_t new;
3236057Sraf 
3246057Sraf 	do {
3256057Sraf 		old = *lockword64;
3266057Sraf 		new = old & ~LOCKMASK64;
3276057Sraf 	} while (atomic_cas_64(lockword64, old, new) != old);
3286057Sraf 
3296057Sraf 	return (old);
3306057Sraf }
3316057Sraf 
3326057Sraf /*
3336057Sraf  * Similar to set_lock_byte(), which only tries to set the lock byte.
3347255Sraf  * Here, we attempt to set the lock byte AND the mutex_ownerpid, keeping
3357255Sraf  * the remaining bytes constant.  This atomic operation is required for the
3367255Sraf  * correctness of process-shared robust locks, otherwise there would be
3377255Sraf  * a window or vulnerability in which the lock byte had been set but the
3387255Sraf  * mutex_ownerpid had not yet been set.  If the process were to die in
3397255Sraf  * this window of vulnerability (due to some other thread calling exit()
3407255Sraf  * or the process receiving a fatal signal), the mutex would be left locked
3417255Sraf  * but without a process-ID to determine which process was holding the lock.
3427255Sraf  * The kernel would then be unable to mark the robust mutex as LOCK_OWNERDEAD
3437255Sraf  * when the process died.  For all other cases of process-shared locks, this
3447255Sraf  * operation is just a convenience, for the sake of common code.
3457255Sraf  *
3467255Sraf  * This operation requires process-shared robust locks to be properly
3477255Sraf  * aligned on an 8-byte boundary, at least on sparc machines, lest the
3487255Sraf  * operation incur an alignment fault.  This is automatic when locks
3497255Sraf  * are declared properly using the mutex_t or pthread_mutex_t data types
3507255Sraf  * and the application does not allocate dynamic memory on less than an
3517255Sraf  * 8-byte boundary.  See the 'horrible hack' comments below for cases
3527255Sraf  * dealing with such broken applications.
3536057Sraf  */
3546057Sraf static int
3556057Sraf set_lock_byte64(volatile uint64_t *lockword64, pid_t ownerpid)
3566057Sraf {
3576057Sraf 	uint64_t old;
3586057Sraf 	uint64_t new;
3596057Sraf 
3606057Sraf 	old = *lockword64 & ~LOCKMASK64;
3616057Sraf 	new = old | ((uint64_t)(uint_t)ownerpid << PIDSHIFT) | LOCKBYTE64;
3626057Sraf 	if (atomic_cas_64(lockword64, old, new) == old)
3636057Sraf 		return (LOCKCLEAR);
3646057Sraf 
3656057Sraf 	return (LOCKSET);
3666057Sraf }
3676057Sraf 
3686057Sraf /*
3695629Sraf  * Increment the spinners count in the mutex lock word.
3705629Sraf  * Return 0 on success.  Return -1 if the count would overflow.
3715629Sraf  */
3725629Sraf static int
3735629Sraf spinners_incr(volatile uint32_t *lockword, uint8_t max_spinners)
3745629Sraf {
3755629Sraf 	uint32_t old;
3765629Sraf 	uint32_t new;
3775629Sraf 
3785629Sraf 	do {
3795629Sraf 		old = *lockword;
3805629Sraf 		if (((old & SPINNERMASK) >> SPINNERSHIFT) >= max_spinners)
3815629Sraf 			return (-1);
3825629Sraf 		new = old + (1 << SPINNERSHIFT);
3835629Sraf 	} while (atomic_cas_32(lockword, old, new) != old);
3845629Sraf 
3855629Sraf 	return (0);
3865629Sraf }
3875629Sraf 
3885629Sraf /*
3895629Sraf  * Decrement the spinners count in the mutex lock word.
3905629Sraf  * Return the new value of the lock word.
3915629Sraf  */
3925629Sraf static uint32_t
3935629Sraf spinners_decr(volatile uint32_t *lockword)
3945629Sraf {
3955629Sraf 	uint32_t old;
3965629Sraf 	uint32_t new;
3975629Sraf 
3985629Sraf 	do {
3995629Sraf 		new = old = *lockword;
4005629Sraf 		if (new & SPINNERMASK)
4015629Sraf 			new -= (1 << SPINNERSHIFT);
4025629Sraf 	} while (atomic_cas_32(lockword, old, new) != old);
4035629Sraf 
4045629Sraf 	return (new);
4055629Sraf }
4065629Sraf 
4075629Sraf /*
4080Sstevel@tonic-gate  * Non-preemptive spin locks.  Used by queue_lock().
4090Sstevel@tonic-gate  * No lock statistics are gathered for these locks.
4105629Sraf  * No DTrace probes are provided for these locks.
4110Sstevel@tonic-gate  */
4120Sstevel@tonic-gate void
4130Sstevel@tonic-gate spin_lock_set(mutex_t *mp)
4140Sstevel@tonic-gate {
4150Sstevel@tonic-gate 	ulwp_t *self = curthread;
4160Sstevel@tonic-gate 
4170Sstevel@tonic-gate 	no_preempt(self);
4180Sstevel@tonic-gate 	if (set_lock_byte(&mp->mutex_lockw) == 0) {
4190Sstevel@tonic-gate 		mp->mutex_owner = (uintptr_t)self;
4200Sstevel@tonic-gate 		return;
4210Sstevel@tonic-gate 	}
4220Sstevel@tonic-gate 	/*
4230Sstevel@tonic-gate 	 * Spin for a while, attempting to acquire the lock.
4240Sstevel@tonic-gate 	 */
4256247Sraf 	INCR32(self->ul_spin_lock_spin);
4260Sstevel@tonic-gate 	if (mutex_queuelock_adaptive(mp) == 0 ||
4270Sstevel@tonic-gate 	    set_lock_byte(&mp->mutex_lockw) == 0) {
4280Sstevel@tonic-gate 		mp->mutex_owner = (uintptr_t)self;
4290Sstevel@tonic-gate 		return;
4300Sstevel@tonic-gate 	}
4310Sstevel@tonic-gate 	/*
4320Sstevel@tonic-gate 	 * Try harder if we were previously at a no premption level.
4330Sstevel@tonic-gate 	 */
4340Sstevel@tonic-gate 	if (self->ul_preempt > 1) {
4356247Sraf 		INCR32(self->ul_spin_lock_spin2);
4360Sstevel@tonic-gate 		if (mutex_queuelock_adaptive(mp) == 0 ||
4370Sstevel@tonic-gate 		    set_lock_byte(&mp->mutex_lockw) == 0) {
4380Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
4390Sstevel@tonic-gate 			return;
4400Sstevel@tonic-gate 		}
4410Sstevel@tonic-gate 	}
4420Sstevel@tonic-gate 	/*
4430Sstevel@tonic-gate 	 * Give up and block in the kernel for the mutex.
4440Sstevel@tonic-gate 	 */
4456247Sraf 	INCR32(self->ul_spin_lock_sleep);
4460Sstevel@tonic-gate 	(void) ___lwp_mutex_timedlock(mp, NULL);
4470Sstevel@tonic-gate 	mp->mutex_owner = (uintptr_t)self;
4480Sstevel@tonic-gate }
4490Sstevel@tonic-gate 
4500Sstevel@tonic-gate void
4510Sstevel@tonic-gate spin_lock_clear(mutex_t *mp)
4520Sstevel@tonic-gate {
4530Sstevel@tonic-gate 	ulwp_t *self = curthread;
4540Sstevel@tonic-gate 
4550Sstevel@tonic-gate 	mp->mutex_owner = 0;
4564570Sraf 	if (atomic_swap_32(&mp->mutex_lockword, 0) & WAITERMASK) {
4574574Sraf 		(void) ___lwp_mutex_wakeup(mp, 0);
4586247Sraf 		INCR32(self->ul_spin_lock_wakeup);
4590Sstevel@tonic-gate 	}
4600Sstevel@tonic-gate 	preempt(self);
4610Sstevel@tonic-gate }
4620Sstevel@tonic-gate 
4630Sstevel@tonic-gate /*
4640Sstevel@tonic-gate  * Allocate the sleep queue hash table.
4650Sstevel@tonic-gate  */
4660Sstevel@tonic-gate void
4670Sstevel@tonic-gate queue_alloc(void)
4680Sstevel@tonic-gate {
4690Sstevel@tonic-gate 	ulwp_t *self = curthread;
4700Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
4716247Sraf 	queue_head_t *qp;
4720Sstevel@tonic-gate 	void *data;
4730Sstevel@tonic-gate 	int i;
4740Sstevel@tonic-gate 
4750Sstevel@tonic-gate 	/*
4760Sstevel@tonic-gate 	 * No locks are needed; we call here only when single-threaded.
4770Sstevel@tonic-gate 	 */
4780Sstevel@tonic-gate 	ASSERT(self == udp->ulwp_one);
4790Sstevel@tonic-gate 	ASSERT(!udp->uberflags.uf_mt);
4806515Sraf 	if ((data = mmap(NULL, 2 * QHASHSIZE * sizeof (queue_head_t),
4810Sstevel@tonic-gate 	    PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, (off_t)0))
4820Sstevel@tonic-gate 	    == MAP_FAILED)
4830Sstevel@tonic-gate 		thr_panic("cannot allocate thread queue_head table");
4846247Sraf 	udp->queue_head = qp = (queue_head_t *)data;
4856247Sraf 	for (i = 0; i < 2 * QHASHSIZE; qp++, i++) {
4866247Sraf 		qp->qh_type = (i < QHASHSIZE)? MX : CV;
4876247Sraf 		qp->qh_lock.mutex_flag = LOCK_INITED;
4886247Sraf 		qp->qh_lock.mutex_magic = MUTEX_MAGIC;
4896247Sraf 		qp->qh_hlist = &qp->qh_def_root;
4906247Sraf #if defined(THREAD_DEBUG)
4916247Sraf 		qp->qh_hlen = 1;
4926247Sraf 		qp->qh_hmax = 1;
4936247Sraf #endif
4944574Sraf 	}
4950Sstevel@tonic-gate }
4960Sstevel@tonic-gate 
4970Sstevel@tonic-gate #if defined(THREAD_DEBUG)
4980Sstevel@tonic-gate 
4990Sstevel@tonic-gate /*
5000Sstevel@tonic-gate  * Debugging: verify correctness of a sleep queue.
5010Sstevel@tonic-gate  */
5020Sstevel@tonic-gate void
5030Sstevel@tonic-gate QVERIFY(queue_head_t *qp)
5040Sstevel@tonic-gate {
5050Sstevel@tonic-gate 	ulwp_t *self = curthread;
5060Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
5076247Sraf 	queue_root_t *qrp;
5080Sstevel@tonic-gate 	ulwp_t *ulwp;
5090Sstevel@tonic-gate 	ulwp_t *prev;
5100Sstevel@tonic-gate 	uint_t index;
5116247Sraf 	uint32_t cnt;
5120Sstevel@tonic-gate 	char qtype;
5130Sstevel@tonic-gate 	void *wchan;
5140Sstevel@tonic-gate 
5150Sstevel@tonic-gate 	ASSERT(qp >= udp->queue_head && (qp - udp->queue_head) < 2 * QHASHSIZE);
5160Sstevel@tonic-gate 	ASSERT(MUTEX_OWNED(&qp->qh_lock, self));
5176247Sraf 	for (cnt = 0, qrp = qp->qh_hlist; qrp != NULL; qrp = qrp->qr_next) {
5186247Sraf 		cnt++;
5196247Sraf 		ASSERT((qrp->qr_head != NULL && qrp->qr_tail != NULL) ||
5206247Sraf 		    (qrp->qr_head == NULL && qrp->qr_tail == NULL));
5216247Sraf 	}
5226247Sraf 	ASSERT(qp->qh_hlen == cnt && qp->qh_hmax >= cnt);
5236247Sraf 	qtype = ((qp - udp->queue_head) < QHASHSIZE)? MX : CV;
5246247Sraf 	ASSERT(qp->qh_type == qtype);
5250Sstevel@tonic-gate 	if (!thread_queue_verify)
5260Sstevel@tonic-gate 		return;
5270Sstevel@tonic-gate 	/* real expensive stuff, only for _THREAD_QUEUE_VERIFY */
5286247Sraf 	for (cnt = 0, qrp = qp->qh_hlist; qrp != NULL; qrp = qrp->qr_next) {
5296247Sraf 		for (prev = NULL, ulwp = qrp->qr_head; ulwp != NULL;
5306247Sraf 		    prev = ulwp, ulwp = ulwp->ul_link) {
5316247Sraf 			cnt++;
5326247Sraf 			if (ulwp->ul_writer)
5336247Sraf 				ASSERT(prev == NULL || prev->ul_writer);
5346247Sraf 			ASSERT(ulwp->ul_qtype == qtype);
5356247Sraf 			ASSERT(ulwp->ul_wchan != NULL);
5366247Sraf 			ASSERT(ulwp->ul_sleepq == qp);
5376247Sraf 			wchan = ulwp->ul_wchan;
5386247Sraf 			ASSERT(qrp->qr_wchan == wchan);
5396247Sraf 			index = QUEUE_HASH(wchan, qtype);
5406247Sraf 			ASSERT(&udp->queue_head[index] == qp);
5416247Sraf 		}
5426247Sraf 		ASSERT(qrp->qr_tail == prev);
5430Sstevel@tonic-gate 	}
5440Sstevel@tonic-gate 	ASSERT(qp->qh_qlen == cnt);
5450Sstevel@tonic-gate }
5460Sstevel@tonic-gate 
5470Sstevel@tonic-gate #else	/* THREAD_DEBUG */
5480Sstevel@tonic-gate 
5490Sstevel@tonic-gate #define	QVERIFY(qp)
5500Sstevel@tonic-gate 
5510Sstevel@tonic-gate #endif	/* THREAD_DEBUG */
5520Sstevel@tonic-gate 
5530Sstevel@tonic-gate /*
5540Sstevel@tonic-gate  * Acquire a queue head.
5550Sstevel@tonic-gate  */
5560Sstevel@tonic-gate queue_head_t *
5570Sstevel@tonic-gate queue_lock(void *wchan, int qtype)
5580Sstevel@tonic-gate {
5590Sstevel@tonic-gate 	uberdata_t *udp = curthread->ul_uberdata;
5600Sstevel@tonic-gate 	queue_head_t *qp;
5616247Sraf 	queue_root_t *qrp;
5620Sstevel@tonic-gate 
5630Sstevel@tonic-gate 	ASSERT(qtype == MX || qtype == CV);
5640Sstevel@tonic-gate 
5650Sstevel@tonic-gate 	/*
5660Sstevel@tonic-gate 	 * It is possible that we could be called while still single-threaded.
5670Sstevel@tonic-gate 	 * If so, we call queue_alloc() to allocate the queue_head[] array.
5680Sstevel@tonic-gate 	 */
5690Sstevel@tonic-gate 	if ((qp = udp->queue_head) == NULL) {
5700Sstevel@tonic-gate 		queue_alloc();
5710Sstevel@tonic-gate 		qp = udp->queue_head;
5720Sstevel@tonic-gate 	}
5730Sstevel@tonic-gate 	qp += QUEUE_HASH(wchan, qtype);
5740Sstevel@tonic-gate 	spin_lock_set(&qp->qh_lock);
5756247Sraf 	for (qrp = qp->qh_hlist; qrp != NULL; qrp = qrp->qr_next)
5766247Sraf 		if (qrp->qr_wchan == wchan)
5776247Sraf 			break;
5786247Sraf 	if (qrp == NULL && qp->qh_def_root.qr_head == NULL) {
5796247Sraf 		/* the default queue root is available; use it */
5806247Sraf 		qrp = &qp->qh_def_root;
5816247Sraf 		qrp->qr_wchan = wchan;
5826247Sraf 		ASSERT(qrp->qr_next == NULL);
5836247Sraf 		ASSERT(qrp->qr_tail == NULL &&
5846247Sraf 		    qrp->qr_rtcount == 0 && qrp->qr_qlen == 0);
5856247Sraf 	}
5866247Sraf 	qp->qh_wchan = wchan;	/* valid until queue_unlock() is called */
5876247Sraf 	qp->qh_root = qrp;	/* valid until queue_unlock() is called */
5886247Sraf 	INCR32(qp->qh_lockcount);
5890Sstevel@tonic-gate 	QVERIFY(qp);
5900Sstevel@tonic-gate 	return (qp);
5910Sstevel@tonic-gate }
5920Sstevel@tonic-gate 
5930Sstevel@tonic-gate /*
5940Sstevel@tonic-gate  * Release a queue head.
5950Sstevel@tonic-gate  */
5960Sstevel@tonic-gate void
5970Sstevel@tonic-gate queue_unlock(queue_head_t *qp)
5980Sstevel@tonic-gate {
5990Sstevel@tonic-gate 	QVERIFY(qp);
6000Sstevel@tonic-gate 	spin_lock_clear(&qp->qh_lock);
6010Sstevel@tonic-gate }
6020Sstevel@tonic-gate 
6030Sstevel@tonic-gate /*
6040Sstevel@tonic-gate  * For rwlock queueing, we must queue writers ahead of readers of the
6050Sstevel@tonic-gate  * same priority.  We do this by making writers appear to have a half
6060Sstevel@tonic-gate  * point higher priority for purposes of priority comparisons below.
6070Sstevel@tonic-gate  */
6080Sstevel@tonic-gate #define	CMP_PRIO(ulwp)	((real_priority(ulwp) << 1) + (ulwp)->ul_writer)
6090Sstevel@tonic-gate 
6100Sstevel@tonic-gate void
6116247Sraf enqueue(queue_head_t *qp, ulwp_t *ulwp, int force_fifo)
6120Sstevel@tonic-gate {
6136247Sraf 	queue_root_t *qrp;
6140Sstevel@tonic-gate 	ulwp_t **ulwpp;
6150Sstevel@tonic-gate 	ulwp_t *next;
6160Sstevel@tonic-gate 	int pri = CMP_PRIO(ulwp);
6176247Sraf 
6180Sstevel@tonic-gate 	ASSERT(MUTEX_OWNED(&qp->qh_lock, curthread));
6190Sstevel@tonic-gate 	ASSERT(ulwp->ul_sleepq != qp);
6200Sstevel@tonic-gate 
6216247Sraf 	if ((qrp = qp->qh_root) == NULL) {
6226247Sraf 		/* use the thread's queue root for the linkage */
6236247Sraf 		qrp = &ulwp->ul_queue_root;
6246247Sraf 		qrp->qr_next = qp->qh_hlist;
6256247Sraf 		qrp->qr_prev = NULL;
6266247Sraf 		qrp->qr_head = NULL;
6276247Sraf 		qrp->qr_tail = NULL;
6286247Sraf 		qrp->qr_wchan = qp->qh_wchan;
6296247Sraf 		qrp->qr_rtcount = 0;
6306247Sraf 		qrp->qr_qlen = 0;
6316247Sraf 		qrp->qr_qmax = 0;
6326247Sraf 		qp->qh_hlist->qr_prev = qrp;
6336247Sraf 		qp->qh_hlist = qrp;
6346247Sraf 		qp->qh_root = qrp;
6356247Sraf 		MAXINCR(qp->qh_hmax, qp->qh_hlen);
6366247Sraf 	}
6376247Sraf 
6380Sstevel@tonic-gate 	/*
6390Sstevel@tonic-gate 	 * LIFO queue ordering is unfair and can lead to starvation,
6400Sstevel@tonic-gate 	 * but it gives better performance for heavily contended locks.
6410Sstevel@tonic-gate 	 * We use thread_queue_fifo (range is 0..8) to determine
6420Sstevel@tonic-gate 	 * the frequency of FIFO vs LIFO queuing:
6430Sstevel@tonic-gate 	 *	0 : every 256th time	(almost always LIFO)
6440Sstevel@tonic-gate 	 *	1 : every 128th time
6450Sstevel@tonic-gate 	 *	2 : every 64th  time
6460Sstevel@tonic-gate 	 *	3 : every 32nd  time
6470Sstevel@tonic-gate 	 *	4 : every 16th  time	(the default value, mostly LIFO)
6480Sstevel@tonic-gate 	 *	5 : every 8th   time
6490Sstevel@tonic-gate 	 *	6 : every 4th   time
6500Sstevel@tonic-gate 	 *	7 : every 2nd   time
6510Sstevel@tonic-gate 	 *	8 : every time		(never LIFO, always FIFO)
6520Sstevel@tonic-gate 	 * Note that there is always some degree of FIFO ordering.
6530Sstevel@tonic-gate 	 * This breaks live lock conditions that occur in applications
6540Sstevel@tonic-gate 	 * that are written assuming (incorrectly) that threads acquire
6550Sstevel@tonic-gate 	 * locks fairly, that is, in roughly round-robin order.
6566247Sraf 	 * In any event, the queue is maintained in kernel priority order.
6570Sstevel@tonic-gate 	 *
6586247Sraf 	 * If force_fifo is non-zero, fifo queueing is forced.
6590Sstevel@tonic-gate 	 * SUSV3 requires this for semaphores.
6600Sstevel@tonic-gate 	 */
6616247Sraf 	if (qrp->qr_head == NULL) {
6620Sstevel@tonic-gate 		/*
6630Sstevel@tonic-gate 		 * The queue is empty.  LIFO/FIFO doesn't matter.
6640Sstevel@tonic-gate 		 */
6656247Sraf 		ASSERT(qrp->qr_tail == NULL);
6666247Sraf 		ulwpp = &qrp->qr_head;
6676247Sraf 	} else if (force_fifo |
6686247Sraf 	    (((++qp->qh_qcnt << curthread->ul_queue_fifo) & 0xff) == 0)) {
6690Sstevel@tonic-gate 		/*
6700Sstevel@tonic-gate 		 * Enqueue after the last thread whose priority is greater
6710Sstevel@tonic-gate 		 * than or equal to the priority of the thread being queued.
6720Sstevel@tonic-gate 		 * Attempt first to go directly onto the tail of the queue.
6730Sstevel@tonic-gate 		 */
6746247Sraf 		if (pri <= CMP_PRIO(qrp->qr_tail))
6756247Sraf 			ulwpp = &qrp->qr_tail->ul_link;
6760Sstevel@tonic-gate 		else {
6776247Sraf 			for (ulwpp = &qrp->qr_head; (next = *ulwpp) != NULL;
6780Sstevel@tonic-gate 			    ulwpp = &next->ul_link)
6790Sstevel@tonic-gate 				if (pri > CMP_PRIO(next))
6800Sstevel@tonic-gate 					break;
6810Sstevel@tonic-gate 		}
6820Sstevel@tonic-gate 	} else {
6830Sstevel@tonic-gate 		/*
6840Sstevel@tonic-gate 		 * Enqueue before the first thread whose priority is less
6850Sstevel@tonic-gate 		 * than or equal to the priority of the thread being queued.
6860Sstevel@tonic-gate 		 * Hopefully we can go directly onto the head of the queue.
6870Sstevel@tonic-gate 		 */
6886247Sraf 		for (ulwpp = &qrp->qr_head; (next = *ulwpp) != NULL;
6890Sstevel@tonic-gate 		    ulwpp = &next->ul_link)
6900Sstevel@tonic-gate 			if (pri >= CMP_PRIO(next))
6910Sstevel@tonic-gate 				break;
6920Sstevel@tonic-gate 	}
6930Sstevel@tonic-gate 	if ((ulwp->ul_link = *ulwpp) == NULL)
6946247Sraf 		qrp->qr_tail = ulwp;
6950Sstevel@tonic-gate 	*ulwpp = ulwp;
6960Sstevel@tonic-gate 
6970Sstevel@tonic-gate 	ulwp->ul_sleepq = qp;
6986247Sraf 	ulwp->ul_wchan = qp->qh_wchan;
6996247Sraf 	ulwp->ul_qtype = qp->qh_type;
7006247Sraf 	if ((ulwp->ul_schedctl != NULL &&
7016247Sraf 	    ulwp->ul_schedctl->sc_cid == ulwp->ul_rtclassid) |
7026247Sraf 	    ulwp->ul_pilocks) {
7036247Sraf 		ulwp->ul_rtqueued = 1;
7046247Sraf 		qrp->qr_rtcount++;
7056247Sraf 	}
7066247Sraf 	MAXINCR(qrp->qr_qmax, qrp->qr_qlen);
7076247Sraf 	MAXINCR(qp->qh_qmax, qp->qh_qlen);
7086247Sraf }
7096247Sraf 
7106247Sraf /*
7116247Sraf  * Helper function for queue_slot() and queue_slot_rt().
7126247Sraf  * Try to find a non-suspended thread on the queue.
7136247Sraf  */
7146247Sraf static ulwp_t **
7156247Sraf queue_slot_runnable(ulwp_t **ulwpp, ulwp_t **prevp, int rt)
7166247Sraf {
7176247Sraf 	ulwp_t *ulwp;
7186247Sraf 	ulwp_t **foundpp = NULL;
7196247Sraf 	int priority = -1;
7206247Sraf 	ulwp_t *prev;
7216247Sraf 	int tpri;
7226247Sraf 
7236247Sraf 	for (prev = NULL;
7246247Sraf 	    (ulwp = *ulwpp) != NULL;
7256247Sraf 	    prev = ulwp, ulwpp = &ulwp->ul_link) {
7266247Sraf 		if (ulwp->ul_stop)	/* skip suspended threads */
7276247Sraf 			continue;
7286247Sraf 		tpri = rt? CMP_PRIO(ulwp) : 0;
7296247Sraf 		if (tpri > priority) {
7306247Sraf 			foundpp = ulwpp;
7316247Sraf 			*prevp = prev;
7326247Sraf 			priority = tpri;
7336247Sraf 			if (!rt)
7346247Sraf 				break;
7356247Sraf 		}
7366247Sraf 	}
7376247Sraf 	return (foundpp);
7380Sstevel@tonic-gate }
7390Sstevel@tonic-gate 
7400Sstevel@tonic-gate /*
7416247Sraf  * For real-time, we search the entire queue because the dispatch
7426247Sraf  * (kernel) priorities may have changed since enqueueing.
7430Sstevel@tonic-gate  */
7440Sstevel@tonic-gate static ulwp_t **
7456247Sraf queue_slot_rt(ulwp_t **ulwpp_org, ulwp_t **prevp)
7466247Sraf {
7476247Sraf 	ulwp_t **ulwpp = ulwpp_org;
7486247Sraf 	ulwp_t *ulwp = *ulwpp;
7496247Sraf 	ulwp_t **foundpp = ulwpp;
7506247Sraf 	int priority = CMP_PRIO(ulwp);
7516247Sraf 	ulwp_t *prev;
7526247Sraf 	int tpri;
7536247Sraf 
7546247Sraf 	for (prev = ulwp, ulwpp = &ulwp->ul_link;
7556247Sraf 	    (ulwp = *ulwpp) != NULL;
7566247Sraf 	    prev = ulwp, ulwpp = &ulwp->ul_link) {
7576247Sraf 		tpri = CMP_PRIO(ulwp);
7586247Sraf 		if (tpri > priority) {
7596247Sraf 			foundpp = ulwpp;
7606247Sraf 			*prevp = prev;
7616247Sraf 			priority = tpri;
7626247Sraf 		}
7636247Sraf 	}
7646247Sraf 	ulwp = *foundpp;
7656247Sraf 
7666247Sraf 	/*
7676247Sraf 	 * Try not to return a suspended thread.
7686247Sraf 	 * This mimics the old libthread's behavior.
7696247Sraf 	 */
7706247Sraf 	if (ulwp->ul_stop &&
7716247Sraf 	    (ulwpp = queue_slot_runnable(ulwpp_org, prevp, 1)) != NULL) {
7726247Sraf 		foundpp = ulwpp;
7736247Sraf 		ulwp = *foundpp;
7746247Sraf 	}
7756247Sraf 	ulwp->ul_rt = 1;
7766247Sraf 	return (foundpp);
7776247Sraf }
7786247Sraf 
7796247Sraf ulwp_t **
7806247Sraf queue_slot(queue_head_t *qp, ulwp_t **prevp, int *more)
7816247Sraf {
7826247Sraf 	queue_root_t *qrp;
7836247Sraf 	ulwp_t **ulwpp;
7846247Sraf 	ulwp_t *ulwp;
7856247Sraf 	int rt;
7866247Sraf 
7876247Sraf 	ASSERT(MUTEX_OWNED(&qp->qh_lock, curthread));
7886247Sraf 
7896247Sraf 	if ((qrp = qp->qh_root) == NULL || (ulwp = qrp->qr_head) == NULL) {
7906247Sraf 		*more = 0;
7916247Sraf 		return (NULL);		/* no lwps on the queue */
7926247Sraf 	}
7936247Sraf 	rt = (qrp->qr_rtcount != 0);
7946247Sraf 	*prevp = NULL;
7956247Sraf 	if (ulwp->ul_link == NULL) {	/* only one lwp on the queue */
7966247Sraf 		*more = 0;
7976247Sraf 		ulwp->ul_rt = rt;
7986247Sraf 		return (&qrp->qr_head);
7996247Sraf 	}
8006247Sraf 	*more = 1;
8016247Sraf 
8026247Sraf 	if (rt)		/* real-time queue */
8036247Sraf 		return (queue_slot_rt(&qrp->qr_head, prevp));
8046247Sraf 	/*
8056247Sraf 	 * Try not to return a suspended thread.
8066247Sraf 	 * This mimics the old libthread's behavior.
8076247Sraf 	 */
8086247Sraf 	if (ulwp->ul_stop &&
8096247Sraf 	    (ulwpp = queue_slot_runnable(&qrp->qr_head, prevp, 0)) != NULL) {
8106247Sraf 		ulwp = *ulwpp;
8116247Sraf 		ulwp->ul_rt = 0;
8126247Sraf 		return (ulwpp);
8136247Sraf 	}
8146247Sraf 	/*
8156247Sraf 	 * The common case; just pick the first thread on the queue.
8166247Sraf 	 */
8176247Sraf 	ulwp->ul_rt = 0;
8186247Sraf 	return (&qrp->qr_head);
8196247Sraf }
8206247Sraf 
8216247Sraf /*
8226247Sraf  * Common code for unlinking an lwp from a user-level sleep queue.
8236247Sraf  */
8246247Sraf void
8256247Sraf queue_unlink(queue_head_t *qp, ulwp_t **ulwpp, ulwp_t *prev)
8266247Sraf {
8276247Sraf 	queue_root_t *qrp = qp->qh_root;
8286247Sraf 	queue_root_t *nqrp;
8296247Sraf 	ulwp_t *ulwp = *ulwpp;
8306247Sraf 	ulwp_t *next;
8316247Sraf 
8326247Sraf 	ASSERT(MUTEX_OWNED(&qp->qh_lock, curthread));
8336247Sraf 	ASSERT(qp->qh_wchan != NULL && ulwp->ul_wchan == qp->qh_wchan);
8346247Sraf 
8356247Sraf 	DECR(qp->qh_qlen);
8366247Sraf 	DECR(qrp->qr_qlen);
8376247Sraf 	if (ulwp->ul_rtqueued) {
8386247Sraf 		ulwp->ul_rtqueued = 0;
8396247Sraf 		qrp->qr_rtcount--;
8406247Sraf 	}
8416247Sraf 	next = ulwp->ul_link;
8426247Sraf 	*ulwpp = next;
8436247Sraf 	ulwp->ul_link = NULL;
8446247Sraf 	if (qrp->qr_tail == ulwp)
8456247Sraf 		qrp->qr_tail = prev;
8466247Sraf 	if (qrp == &ulwp->ul_queue_root) {
8476247Sraf 		/*
8486247Sraf 		 * We can't continue to use the unlinked thread's
8496247Sraf 		 * queue root for the linkage.
8506247Sraf 		 */
8516247Sraf 		queue_root_t *qr_next = qrp->qr_next;
8526247Sraf 		queue_root_t *qr_prev = qrp->qr_prev;
8536247Sraf 
8546247Sraf 		if (qrp->qr_tail) {
8556247Sraf 			/* switch to using the last thread's queue root */
8566247Sraf 			ASSERT(qrp->qr_qlen != 0);
8576247Sraf 			nqrp = &qrp->qr_tail->ul_queue_root;
8586247Sraf 			*nqrp = *qrp;
8596247Sraf 			if (qr_next)
8606247Sraf 				qr_next->qr_prev = nqrp;
8616247Sraf 			if (qr_prev)
8626247Sraf 				qr_prev->qr_next = nqrp;
8636247Sraf 			else
8646247Sraf 				qp->qh_hlist = nqrp;
8656247Sraf 			qp->qh_root = nqrp;
8666247Sraf 		} else {
8676247Sraf 			/* empty queue root; just delete from the hash list */
8686247Sraf 			ASSERT(qrp->qr_qlen == 0);
8696247Sraf 			if (qr_next)
8706247Sraf 				qr_next->qr_prev = qr_prev;
8716247Sraf 			if (qr_prev)
8726247Sraf 				qr_prev->qr_next = qr_next;
8736247Sraf 			else
8746247Sraf 				qp->qh_hlist = qr_next;
8756247Sraf 			qp->qh_root = NULL;
8766247Sraf 			DECR(qp->qh_hlen);
8776247Sraf 		}
8786247Sraf 	}
8796247Sraf }
8806247Sraf 
8816247Sraf ulwp_t *
8826247Sraf dequeue(queue_head_t *qp, int *more)
8830Sstevel@tonic-gate {
8840Sstevel@tonic-gate 	ulwp_t **ulwpp;
8850Sstevel@tonic-gate 	ulwp_t *ulwp;
8866247Sraf 	ulwp_t *prev;
8876247Sraf 
8886247Sraf 	if ((ulwpp = queue_slot(qp, &prev, more)) == NULL)
8890Sstevel@tonic-gate 		return (NULL);
8900Sstevel@tonic-gate 	ulwp = *ulwpp;
8916247Sraf 	queue_unlink(qp, ulwpp, prev);
8920Sstevel@tonic-gate 	ulwp->ul_sleepq = NULL;
8930Sstevel@tonic-gate 	ulwp->ul_wchan = NULL;
8940Sstevel@tonic-gate 	return (ulwp);
8950Sstevel@tonic-gate }
8960Sstevel@tonic-gate 
8970Sstevel@tonic-gate /*
8980Sstevel@tonic-gate  * Return a pointer to the highest priority thread sleeping on wchan.
8990Sstevel@tonic-gate  */
9000Sstevel@tonic-gate ulwp_t *
9016247Sraf queue_waiter(queue_head_t *qp)
9020Sstevel@tonic-gate {
9030Sstevel@tonic-gate 	ulwp_t **ulwpp;
9046247Sraf 	ulwp_t *prev;
9056247Sraf 	int more;
9066247Sraf 
9076247Sraf 	if ((ulwpp = queue_slot(qp, &prev, &more)) == NULL)
9080Sstevel@tonic-gate 		return (NULL);
9090Sstevel@tonic-gate 	return (*ulwpp);
9100Sstevel@tonic-gate }
9110Sstevel@tonic-gate 
9126247Sraf int
9136247Sraf dequeue_self(queue_head_t *qp)
9140Sstevel@tonic-gate {
9150Sstevel@tonic-gate 	ulwp_t *self = curthread;
9166247Sraf 	queue_root_t *qrp;
9170Sstevel@tonic-gate 	ulwp_t **ulwpp;
9180Sstevel@tonic-gate 	ulwp_t *ulwp;
9196247Sraf 	ulwp_t *prev;
9200Sstevel@tonic-gate 	int found = 0;
9210Sstevel@tonic-gate 
9220Sstevel@tonic-gate 	ASSERT(MUTEX_OWNED(&qp->qh_lock, self));
9230Sstevel@tonic-gate 
9240Sstevel@tonic-gate 	/* find self on the sleep queue */
9256247Sraf 	if ((qrp = qp->qh_root) != NULL) {
9266247Sraf 		for (prev = NULL, ulwpp = &qrp->qr_head;
9276247Sraf 		    (ulwp = *ulwpp) != NULL;
9286247Sraf 		    prev = ulwp, ulwpp = &ulwp->ul_link) {
9296247Sraf 			if (ulwp == self) {
9306247Sraf 				queue_unlink(qp, ulwpp, prev);
9316247Sraf 				self->ul_cvmutex = NULL;
9326247Sraf 				self->ul_sleepq = NULL;
9336247Sraf 				self->ul_wchan = NULL;
9346247Sraf 				found = 1;
9356247Sraf 				break;
9366247Sraf 			}
9370Sstevel@tonic-gate 		}
9380Sstevel@tonic-gate 	}
9390Sstevel@tonic-gate 
9400Sstevel@tonic-gate 	if (!found)
9410Sstevel@tonic-gate 		thr_panic("dequeue_self(): curthread not found on queue");
9420Sstevel@tonic-gate 
9436247Sraf 	return ((qrp = qp->qh_root) != NULL && qrp->qr_head != NULL);
9440Sstevel@tonic-gate }
9450Sstevel@tonic-gate 
9460Sstevel@tonic-gate /*
9470Sstevel@tonic-gate  * Called from call_user_handler() and _thrp_suspend() to take
9480Sstevel@tonic-gate  * ourself off of our sleep queue so we can grab locks.
9490Sstevel@tonic-gate  */
9500Sstevel@tonic-gate void
9510Sstevel@tonic-gate unsleep_self(void)
9520Sstevel@tonic-gate {
9530Sstevel@tonic-gate 	ulwp_t *self = curthread;
9540Sstevel@tonic-gate 	queue_head_t *qp;
9550Sstevel@tonic-gate 
9560Sstevel@tonic-gate 	/*
9570Sstevel@tonic-gate 	 * Calling enter_critical()/exit_critical() here would lead
9580Sstevel@tonic-gate 	 * to recursion.  Just manipulate self->ul_critical directly.
9590Sstevel@tonic-gate 	 */
9600Sstevel@tonic-gate 	self->ul_critical++;
9610Sstevel@tonic-gate 	while (self->ul_sleepq != NULL) {
9620Sstevel@tonic-gate 		qp = queue_lock(self->ul_wchan, self->ul_qtype);
9630Sstevel@tonic-gate 		/*
9640Sstevel@tonic-gate 		 * We may have been moved from a CV queue to a
9650Sstevel@tonic-gate 		 * mutex queue while we were attempting queue_lock().
9660Sstevel@tonic-gate 		 * If so, just loop around and try again.
9670Sstevel@tonic-gate 		 * dequeue_self() clears self->ul_sleepq.
9680Sstevel@tonic-gate 		 */
9696247Sraf 		if (qp == self->ul_sleepq)
9706247Sraf 			(void) dequeue_self(qp);
9710Sstevel@tonic-gate 		queue_unlock(qp);
9720Sstevel@tonic-gate 	}
9736247Sraf 	self->ul_writer = 0;
9740Sstevel@tonic-gate 	self->ul_critical--;
9750Sstevel@tonic-gate }
9760Sstevel@tonic-gate 
9770Sstevel@tonic-gate /*
9780Sstevel@tonic-gate  * Common code for calling the the ___lwp_mutex_timedlock() system call.
9790Sstevel@tonic-gate  * Returns with mutex_owner and mutex_ownerpid set correctly.
9800Sstevel@tonic-gate  */
9814574Sraf static int
9820Sstevel@tonic-gate mutex_lock_kernel(mutex_t *mp, timespec_t *tsp, tdb_mutex_stats_t *msp)
9830Sstevel@tonic-gate {
9840Sstevel@tonic-gate 	ulwp_t *self = curthread;
9850Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
9864574Sraf 	int mtype = mp->mutex_type;
9870Sstevel@tonic-gate 	hrtime_t begin_sleep;
9884574Sraf 	int acquired;
9890Sstevel@tonic-gate 	int error;
9900Sstevel@tonic-gate 
9910Sstevel@tonic-gate 	self->ul_sp = stkptr();
9920Sstevel@tonic-gate 	self->ul_wchan = mp;
9930Sstevel@tonic-gate 	if (__td_event_report(self, TD_SLEEP, udp)) {
9940Sstevel@tonic-gate 		self->ul_td_evbuf.eventnum = TD_SLEEP;
9950Sstevel@tonic-gate 		self->ul_td_evbuf.eventdata = mp;
9960Sstevel@tonic-gate 		tdb_event(TD_SLEEP, udp);
9970Sstevel@tonic-gate 	}
9980Sstevel@tonic-gate 	if (msp) {
9990Sstevel@tonic-gate 		tdb_incr(msp->mutex_sleep);
10000Sstevel@tonic-gate 		begin_sleep = gethrtime();
10010Sstevel@tonic-gate 	}
10020Sstevel@tonic-gate 
10030Sstevel@tonic-gate 	DTRACE_PROBE1(plockstat, mutex__block, mp);
10040Sstevel@tonic-gate 
1005*7907SRoger.Faulkner@Sun.COM 	/* defer signals until the assignment of mp->mutex_owner */
1006*7907SRoger.Faulkner@Sun.COM 	sigoff(self);
10070Sstevel@tonic-gate 	for (;;) {
10084574Sraf 		/*
10094574Sraf 		 * A return value of EOWNERDEAD or ELOCKUNMAPPED
10104574Sraf 		 * means we successfully acquired the lock.
10114574Sraf 		 */
10124574Sraf 		if ((error = ___lwp_mutex_timedlock(mp, tsp)) != 0 &&
10134574Sraf 		    error != EOWNERDEAD && error != ELOCKUNMAPPED) {
10144574Sraf 			acquired = 0;
10150Sstevel@tonic-gate 			break;
10160Sstevel@tonic-gate 		}
10170Sstevel@tonic-gate 
10184574Sraf 		if (mtype & USYNC_PROCESS) {
10190Sstevel@tonic-gate 			/*
10200Sstevel@tonic-gate 			 * Defend against forkall().  We may be the child,
10210Sstevel@tonic-gate 			 * in which case we don't actually own the mutex.
10220Sstevel@tonic-gate 			 */
10230Sstevel@tonic-gate 			enter_critical(self);
10240Sstevel@tonic-gate 			if (mp->mutex_ownerpid == udp->pid) {
10250Sstevel@tonic-gate 				mp->mutex_owner = (uintptr_t)self;
10260Sstevel@tonic-gate 				exit_critical(self);
10274574Sraf 				acquired = 1;
10280Sstevel@tonic-gate 				break;
10290Sstevel@tonic-gate 			}
10300Sstevel@tonic-gate 			exit_critical(self);
10310Sstevel@tonic-gate 		} else {
10320Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
10334574Sraf 			acquired = 1;
10340Sstevel@tonic-gate 			break;
10350Sstevel@tonic-gate 		}
10360Sstevel@tonic-gate 	}
1037*7907SRoger.Faulkner@Sun.COM 	sigon(self);
1038*7907SRoger.Faulkner@Sun.COM 
10390Sstevel@tonic-gate 	if (msp)
10400Sstevel@tonic-gate 		msp->mutex_sleep_time += gethrtime() - begin_sleep;
10410Sstevel@tonic-gate 	self->ul_wchan = NULL;
10420Sstevel@tonic-gate 	self->ul_sp = 0;
10430Sstevel@tonic-gate 
10444574Sraf 	if (acquired) {
10454574Sraf 		DTRACE_PROBE2(plockstat, mutex__blocked, mp, 1);
10464574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
10474574Sraf 	} else {
10484574Sraf 		DTRACE_PROBE2(plockstat, mutex__blocked, mp, 0);
10494574Sraf 		DTRACE_PROBE2(plockstat, mutex__error, mp, error);
10504574Sraf 	}
10514574Sraf 
10520Sstevel@tonic-gate 	return (error);
10530Sstevel@tonic-gate }
10540Sstevel@tonic-gate 
10550Sstevel@tonic-gate /*
10560Sstevel@tonic-gate  * Common code for calling the ___lwp_mutex_trylock() system call.
10570Sstevel@tonic-gate  * Returns with mutex_owner and mutex_ownerpid set correctly.
10580Sstevel@tonic-gate  */
10590Sstevel@tonic-gate int
10600Sstevel@tonic-gate mutex_trylock_kernel(mutex_t *mp)
10610Sstevel@tonic-gate {
10620Sstevel@tonic-gate 	ulwp_t *self = curthread;
10630Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
10644574Sraf 	int mtype = mp->mutex_type;
10650Sstevel@tonic-gate 	int error;
10664574Sraf 	int acquired;
10670Sstevel@tonic-gate 
1068*7907SRoger.Faulkner@Sun.COM 	sigoff(self);
10690Sstevel@tonic-gate 	for (;;) {
10704574Sraf 		/*
10714574Sraf 		 * A return value of EOWNERDEAD or ELOCKUNMAPPED
10724574Sraf 		 * means we successfully acquired the lock.
10734574Sraf 		 */
10744574Sraf 		if ((error = ___lwp_mutex_trylock(mp)) != 0 &&
10754574Sraf 		    error != EOWNERDEAD && error != ELOCKUNMAPPED) {
10764574Sraf 			acquired = 0;
10770Sstevel@tonic-gate 			break;
10780Sstevel@tonic-gate 		}
10790Sstevel@tonic-gate 
10804574Sraf 		if (mtype & USYNC_PROCESS) {
10810Sstevel@tonic-gate 			/*
10820Sstevel@tonic-gate 			 * Defend against forkall().  We may be the child,
10830Sstevel@tonic-gate 			 * in which case we don't actually own the mutex.
10840Sstevel@tonic-gate 			 */
10850Sstevel@tonic-gate 			enter_critical(self);
10860Sstevel@tonic-gate 			if (mp->mutex_ownerpid == udp->pid) {
10870Sstevel@tonic-gate 				mp->mutex_owner = (uintptr_t)self;
10880Sstevel@tonic-gate 				exit_critical(self);
10894574Sraf 				acquired = 1;
10900Sstevel@tonic-gate 				break;
10910Sstevel@tonic-gate 			}
10920Sstevel@tonic-gate 			exit_critical(self);
10930Sstevel@tonic-gate 		} else {
10940Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
10954574Sraf 			acquired = 1;
10960Sstevel@tonic-gate 			break;
10970Sstevel@tonic-gate 		}
10980Sstevel@tonic-gate 	}
1099*7907SRoger.Faulkner@Sun.COM 	sigon(self);
11000Sstevel@tonic-gate 
11014574Sraf 	if (acquired) {
11024574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
11034574Sraf 	} else if (error != EBUSY) {
11044574Sraf 		DTRACE_PROBE2(plockstat, mutex__error, mp, error);
11054574Sraf 	}
11064574Sraf 
11070Sstevel@tonic-gate 	return (error);
11080Sstevel@tonic-gate }
11090Sstevel@tonic-gate 
11100Sstevel@tonic-gate volatile sc_shared_t *
11110Sstevel@tonic-gate setup_schedctl(void)
11120Sstevel@tonic-gate {
11130Sstevel@tonic-gate 	ulwp_t *self = curthread;
11140Sstevel@tonic-gate 	volatile sc_shared_t *scp;
11150Sstevel@tonic-gate 	sc_shared_t *tmp;
11160Sstevel@tonic-gate 
11170Sstevel@tonic-gate 	if ((scp = self->ul_schedctl) == NULL && /* no shared state yet */
11180Sstevel@tonic-gate 	    !self->ul_vfork &&			/* not a child of vfork() */
11190Sstevel@tonic-gate 	    !self->ul_schedctl_called) {	/* haven't been called before */
11200Sstevel@tonic-gate 		enter_critical(self);
11210Sstevel@tonic-gate 		self->ul_schedctl_called = &self->ul_uberdata->uberflags;
11220Sstevel@tonic-gate 		if ((tmp = __schedctl()) != (sc_shared_t *)(-1))
11230Sstevel@tonic-gate 			self->ul_schedctl = scp = tmp;
11240Sstevel@tonic-gate 		exit_critical(self);
11250Sstevel@tonic-gate 	}
11260Sstevel@tonic-gate 	/*
11270Sstevel@tonic-gate 	 * Unless the call to setup_schedctl() is surrounded
11280Sstevel@tonic-gate 	 * by enter_critical()/exit_critical(), the address
11290Sstevel@tonic-gate 	 * we are returning could be invalid due to a forkall()
11300Sstevel@tonic-gate 	 * having occurred in another thread.
11310Sstevel@tonic-gate 	 */
11320Sstevel@tonic-gate 	return (scp);
11330Sstevel@tonic-gate }
11340Sstevel@tonic-gate 
11350Sstevel@tonic-gate /*
11360Sstevel@tonic-gate  * Interfaces from libsched, incorporated into libc.
11370Sstevel@tonic-gate  * libsched.so.1 is now a filter library onto libc.
11380Sstevel@tonic-gate  */
11396812Sraf #pragma weak schedctl_lookup = schedctl_init
11400Sstevel@tonic-gate schedctl_t *
11416812Sraf schedctl_init(void)
11420Sstevel@tonic-gate {
11430Sstevel@tonic-gate 	volatile sc_shared_t *scp = setup_schedctl();
11440Sstevel@tonic-gate 	return ((scp == NULL)? NULL : (schedctl_t *)&scp->sc_preemptctl);
11450Sstevel@tonic-gate }
11460Sstevel@tonic-gate 
11470Sstevel@tonic-gate void
11486812Sraf schedctl_exit(void)
11490Sstevel@tonic-gate {
11500Sstevel@tonic-gate }
11510Sstevel@tonic-gate 
11520Sstevel@tonic-gate /*
11530Sstevel@tonic-gate  * Contract private interface for java.
11540Sstevel@tonic-gate  * Set up the schedctl data if it doesn't exist yet.
11550Sstevel@tonic-gate  * Return a pointer to the pointer to the schedctl data.
11560Sstevel@tonic-gate  */
11570Sstevel@tonic-gate volatile sc_shared_t *volatile *
11580Sstevel@tonic-gate _thr_schedctl(void)
11590Sstevel@tonic-gate {
11600Sstevel@tonic-gate 	ulwp_t *self = curthread;
11610Sstevel@tonic-gate 	volatile sc_shared_t *volatile *ptr;
11620Sstevel@tonic-gate 
11630Sstevel@tonic-gate 	if (self->ul_vfork)
11640Sstevel@tonic-gate 		return (NULL);
11650Sstevel@tonic-gate 	if (*(ptr = &self->ul_schedctl) == NULL)
11660Sstevel@tonic-gate 		(void) setup_schedctl();
11670Sstevel@tonic-gate 	return (ptr);
11680Sstevel@tonic-gate }
11690Sstevel@tonic-gate 
11700Sstevel@tonic-gate /*
11710Sstevel@tonic-gate  * Block signals and attempt to block preemption.
11720Sstevel@tonic-gate  * no_preempt()/preempt() must be used in pairs but can be nested.
11730Sstevel@tonic-gate  */
11740Sstevel@tonic-gate void
11750Sstevel@tonic-gate no_preempt(ulwp_t *self)
11760Sstevel@tonic-gate {
11770Sstevel@tonic-gate 	volatile sc_shared_t *scp;
11780Sstevel@tonic-gate 
11790Sstevel@tonic-gate 	if (self->ul_preempt++ == 0) {
11800Sstevel@tonic-gate 		enter_critical(self);
11810Sstevel@tonic-gate 		if ((scp = self->ul_schedctl) != NULL ||
11820Sstevel@tonic-gate 		    (scp = setup_schedctl()) != NULL) {
11830Sstevel@tonic-gate 			/*
11840Sstevel@tonic-gate 			 * Save the pre-existing preempt value.
11850Sstevel@tonic-gate 			 */
11860Sstevel@tonic-gate 			self->ul_savpreempt = scp->sc_preemptctl.sc_nopreempt;
11870Sstevel@tonic-gate 			scp->sc_preemptctl.sc_nopreempt = 1;
11880Sstevel@tonic-gate 		}
11890Sstevel@tonic-gate 	}
11900Sstevel@tonic-gate }
11910Sstevel@tonic-gate 
11920Sstevel@tonic-gate /*
11930Sstevel@tonic-gate  * Undo the effects of no_preempt().
11940Sstevel@tonic-gate  */
11950Sstevel@tonic-gate void
11960Sstevel@tonic-gate preempt(ulwp_t *self)
11970Sstevel@tonic-gate {
11980Sstevel@tonic-gate 	volatile sc_shared_t *scp;
11990Sstevel@tonic-gate 
12000Sstevel@tonic-gate 	ASSERT(self->ul_preempt > 0);
12010Sstevel@tonic-gate 	if (--self->ul_preempt == 0) {
12020Sstevel@tonic-gate 		if ((scp = self->ul_schedctl) != NULL) {
12030Sstevel@tonic-gate 			/*
12040Sstevel@tonic-gate 			 * Restore the pre-existing preempt value.
12050Sstevel@tonic-gate 			 */
12060Sstevel@tonic-gate 			scp->sc_preemptctl.sc_nopreempt = self->ul_savpreempt;
12070Sstevel@tonic-gate 			if (scp->sc_preemptctl.sc_yield &&
12080Sstevel@tonic-gate 			    scp->sc_preemptctl.sc_nopreempt == 0) {
12096515Sraf 				yield();
12100Sstevel@tonic-gate 				if (scp->sc_preemptctl.sc_yield) {
12110Sstevel@tonic-gate 					/*
12120Sstevel@tonic-gate 					 * Shouldn't happen.  This is either
12130Sstevel@tonic-gate 					 * a race condition or the thread
12140Sstevel@tonic-gate 					 * just entered the real-time class.
12150Sstevel@tonic-gate 					 */
12166515Sraf 					yield();
12170Sstevel@tonic-gate 					scp->sc_preemptctl.sc_yield = 0;
12180Sstevel@tonic-gate 				}
12190Sstevel@tonic-gate 			}
12200Sstevel@tonic-gate 		}
12210Sstevel@tonic-gate 		exit_critical(self);
12220Sstevel@tonic-gate 	}
12230Sstevel@tonic-gate }
12240Sstevel@tonic-gate 
12250Sstevel@tonic-gate /*
12260Sstevel@tonic-gate  * If a call to preempt() would cause the current thread to yield or to
12270Sstevel@tonic-gate  * take deferred actions in exit_critical(), then unpark the specified
12280Sstevel@tonic-gate  * lwp so it can run while we delay.  Return the original lwpid if the
12290Sstevel@tonic-gate  * unpark was not performed, else return zero.  The tests are a repeat
12300Sstevel@tonic-gate  * of some of the tests in preempt(), above.  This is a statistical
12310Sstevel@tonic-gate  * optimization solely for cond_sleep_queue(), below.
12320Sstevel@tonic-gate  */
12330Sstevel@tonic-gate static lwpid_t
12340Sstevel@tonic-gate preempt_unpark(ulwp_t *self, lwpid_t lwpid)
12350Sstevel@tonic-gate {
12360Sstevel@tonic-gate 	volatile sc_shared_t *scp = self->ul_schedctl;
12370Sstevel@tonic-gate 
12380Sstevel@tonic-gate 	ASSERT(self->ul_preempt == 1 && self->ul_critical > 0);
12390Sstevel@tonic-gate 	if ((scp != NULL && scp->sc_preemptctl.sc_yield) ||
12400Sstevel@tonic-gate 	    (self->ul_curplease && self->ul_critical == 1)) {
12410Sstevel@tonic-gate 		(void) __lwp_unpark(lwpid);
12420Sstevel@tonic-gate 		lwpid = 0;
12430Sstevel@tonic-gate 	}
12440Sstevel@tonic-gate 	return (lwpid);
12450Sstevel@tonic-gate }
12460Sstevel@tonic-gate 
12470Sstevel@tonic-gate /*
12484613Sraf  * Spin for a while (if 'tryhard' is true), trying to grab the lock.
12490Sstevel@tonic-gate  * If this fails, return EBUSY and let the caller deal with it.
12500Sstevel@tonic-gate  * If this succeeds, return 0 with mutex_owner set to curthread.
12510Sstevel@tonic-gate  */
12524574Sraf static int
12534613Sraf mutex_trylock_adaptive(mutex_t *mp, int tryhard)
12540Sstevel@tonic-gate {
12550Sstevel@tonic-gate 	ulwp_t *self = curthread;
12564574Sraf 	int error = EBUSY;
12570Sstevel@tonic-gate 	ulwp_t *ulwp;
12580Sstevel@tonic-gate 	volatile sc_shared_t *scp;
12595629Sraf 	volatile uint8_t *lockp = (volatile uint8_t *)&mp->mutex_lockw;
12605629Sraf 	volatile uint64_t *ownerp = (volatile uint64_t *)&mp->mutex_owner;
12615629Sraf 	uint32_t new_lockword;
12625629Sraf 	int count = 0;
12635629Sraf 	int max_count;
12645629Sraf 	uint8_t max_spinners;
12654574Sraf 
12664574Sraf 	ASSERT(!(mp->mutex_type & USYNC_PROCESS));
12674574Sraf 
1268*7907SRoger.Faulkner@Sun.COM 	if (MUTEX_OWNED(mp, self))
12690Sstevel@tonic-gate 		return (EBUSY);
12700Sstevel@tonic-gate 
1271*7907SRoger.Faulkner@Sun.COM 	enter_critical(self);
1272*7907SRoger.Faulkner@Sun.COM 
12734574Sraf 	/* short-cut, not definitive (see below) */
12744574Sraf 	if (mp->mutex_flag & LOCK_NOTRECOVERABLE) {
12754574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
12765629Sraf 		error = ENOTRECOVERABLE;
12775629Sraf 		goto done;
12784574Sraf 	}
12794574Sraf 
12805629Sraf 	/*
12815629Sraf 	 * Make one attempt to acquire the lock before
12825629Sraf 	 * incurring the overhead of the spin loop.
12835629Sraf 	 */
12845629Sraf 	if (set_lock_byte(lockp) == 0) {
12855629Sraf 		*ownerp = (uintptr_t)self;
12865629Sraf 		error = 0;
12875629Sraf 		goto done;
12885629Sraf 	}
12895629Sraf 	if (!tryhard)
12905629Sraf 		goto done;
12915629Sraf 	if (ncpus == 0)
12925629Sraf 		ncpus = (int)_sysconf(_SC_NPROCESSORS_ONLN);
12935629Sraf 	if ((max_spinners = self->ul_max_spinners) >= ncpus)
12945629Sraf 		max_spinners = ncpus - 1;
12955629Sraf 	max_count = (max_spinners != 0)? self->ul_adaptive_spin : 0;
12965629Sraf 	if (max_count == 0)
12975629Sraf 		goto done;
12985629Sraf 
12990Sstevel@tonic-gate 	/*
13000Sstevel@tonic-gate 	 * This spin loop is unfair to lwps that have already dropped into
13010Sstevel@tonic-gate 	 * the kernel to sleep.  They will starve on a highly-contended mutex.
13020Sstevel@tonic-gate 	 * This is just too bad.  The adaptive spin algorithm is intended
13030Sstevel@tonic-gate 	 * to allow programs with highly-contended locks (that is, broken
13040Sstevel@tonic-gate 	 * programs) to execute with reasonable speed despite their contention.
13050Sstevel@tonic-gate 	 * Being fair would reduce the speed of such programs and well-written
13060Sstevel@tonic-gate 	 * programs will not suffer in any case.
13070Sstevel@tonic-gate 	 */
1308*7907SRoger.Faulkner@Sun.COM 	if (spinners_incr(&mp->mutex_lockword, max_spinners) == -1)
13095629Sraf 		goto done;
13105629Sraf 	DTRACE_PROBE1(plockstat, mutex__spin, mp);
13115629Sraf 	for (count = 1; ; count++) {
13120Sstevel@tonic-gate 		if (*lockp == 0 && set_lock_byte(lockp) == 0) {
13130Sstevel@tonic-gate 			*ownerp = (uintptr_t)self;
13144574Sraf 			error = 0;
13154574Sraf 			break;
13160Sstevel@tonic-gate 		}
13175629Sraf 		if (count == max_count)
13185629Sraf 			break;
13190Sstevel@tonic-gate 		SMT_PAUSE();
13200Sstevel@tonic-gate 		/*
13210Sstevel@tonic-gate 		 * Stop spinning if the mutex owner is not running on
13220Sstevel@tonic-gate 		 * a processor; it will not drop the lock any time soon
13230Sstevel@tonic-gate 		 * and we would just be wasting time to keep spinning.
13240Sstevel@tonic-gate 		 *
13250Sstevel@tonic-gate 		 * Note that we are looking at another thread (ulwp_t)
13260Sstevel@tonic-gate 		 * without ensuring that the other thread does not exit.
13270Sstevel@tonic-gate 		 * The scheme relies on ulwp_t structures never being
13280Sstevel@tonic-gate 		 * deallocated by the library (the library employs a free
13290Sstevel@tonic-gate 		 * list of ulwp_t structs that are reused when new threads
13300Sstevel@tonic-gate 		 * are created) and on schedctl shared memory never being
13310Sstevel@tonic-gate 		 * deallocated once created via __schedctl().
13320Sstevel@tonic-gate 		 *
13330Sstevel@tonic-gate 		 * Thus, the worst that can happen when the spinning thread
13340Sstevel@tonic-gate 		 * looks at the owner's schedctl data is that it is looking
13350Sstevel@tonic-gate 		 * at some other thread's schedctl data.  This almost never
13360Sstevel@tonic-gate 		 * happens and is benign when it does.
13370Sstevel@tonic-gate 		 */
13380Sstevel@tonic-gate 		if ((ulwp = (ulwp_t *)(uintptr_t)*ownerp) != NULL &&
13390Sstevel@tonic-gate 		    ((scp = ulwp->ul_schedctl) == NULL ||
13400Sstevel@tonic-gate 		    scp->sc_state != SC_ONPROC))
13410Sstevel@tonic-gate 			break;
13420Sstevel@tonic-gate 	}
13435629Sraf 	new_lockword = spinners_decr(&mp->mutex_lockword);
13445629Sraf 	if (error && (new_lockword & (LOCKMASK | SPINNERMASK)) == 0) {
13455629Sraf 		/*
13465629Sraf 		 * We haven't yet acquired the lock, the lock
13475629Sraf 		 * is free, and there are no other spinners.
13485629Sraf 		 * Make one final attempt to acquire the lock.
13495629Sraf 		 *
13505629Sraf 		 * This isn't strictly necessary since mutex_lock_queue()
13515629Sraf 		 * (the next action this thread will take if it doesn't
13525629Sraf 		 * acquire the lock here) makes one attempt to acquire
13535629Sraf 		 * the lock before putting the thread to sleep.
13545629Sraf 		 *
13555629Sraf 		 * If the next action for this thread (on failure here)
13565629Sraf 		 * were not to call mutex_lock_queue(), this would be
13575629Sraf 		 * necessary for correctness, to avoid ending up with an
13585629Sraf 		 * unheld mutex with waiters but no one to wake them up.
13595629Sraf 		 */
13605629Sraf 		if (set_lock_byte(lockp) == 0) {
13615629Sraf 			*ownerp = (uintptr_t)self;
13625629Sraf 			error = 0;
13635629Sraf 		}
13645629Sraf 		count++;
13655629Sraf 	}
13660Sstevel@tonic-gate 
13675629Sraf done:
13684574Sraf 	if (error == 0 && (mp->mutex_flag & LOCK_NOTRECOVERABLE)) {
13694574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
13704574Sraf 		/*
13716057Sraf 		 * We shouldn't own the mutex.
13726057Sraf 		 * Just clear the lock; everyone has already been waked up.
13734574Sraf 		 */
1374*7907SRoger.Faulkner@Sun.COM 		*ownerp = 0;
13756057Sraf 		(void) clear_lockbyte(&mp->mutex_lockword);
13764574Sraf 		error = ENOTRECOVERABLE;
13774574Sraf 	}
13784574Sraf 
1379*7907SRoger.Faulkner@Sun.COM 	exit_critical(self);
1380*7907SRoger.Faulkner@Sun.COM 
13814574Sraf 	if (error) {
13825629Sraf 		if (count) {
13835629Sraf 			DTRACE_PROBE2(plockstat, mutex__spun, 0, count);
13845629Sraf 		}
13854574Sraf 		if (error != EBUSY) {
13864574Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, error);
13874574Sraf 		}
13884574Sraf 	} else {
13895629Sraf 		if (count) {
13905629Sraf 			DTRACE_PROBE2(plockstat, mutex__spun, 1, count);
13915629Sraf 		}
13924574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, count);
13934574Sraf 		if (mp->mutex_flag & LOCK_OWNERDEAD) {
13944574Sraf 			ASSERT(mp->mutex_type & LOCK_ROBUST);
13954574Sraf 			error = EOWNERDEAD;
13964574Sraf 		}
13974574Sraf 	}
13984574Sraf 
13994574Sraf 	return (error);
14000Sstevel@tonic-gate }
14010Sstevel@tonic-gate 
14020Sstevel@tonic-gate /*
14030Sstevel@tonic-gate  * Same as mutex_trylock_adaptive(), except specifically for queue locks.
14040Sstevel@tonic-gate  * The owner field is not set here; the caller (spin_lock_set()) sets it.
14050Sstevel@tonic-gate  */
14064574Sraf static int
14070Sstevel@tonic-gate mutex_queuelock_adaptive(mutex_t *mp)
14080Sstevel@tonic-gate {
14090Sstevel@tonic-gate 	ulwp_t *ulwp;
14100Sstevel@tonic-gate 	volatile sc_shared_t *scp;
14110Sstevel@tonic-gate 	volatile uint8_t *lockp;
14120Sstevel@tonic-gate 	volatile uint64_t *ownerp;
14130Sstevel@tonic-gate 	int count = curthread->ul_queue_spin;
14140Sstevel@tonic-gate 
14150Sstevel@tonic-gate 	ASSERT(mp->mutex_type == USYNC_THREAD);
14160Sstevel@tonic-gate 
14170Sstevel@tonic-gate 	if (count == 0)
14180Sstevel@tonic-gate 		return (EBUSY);
14190Sstevel@tonic-gate 
14200Sstevel@tonic-gate 	lockp = (volatile uint8_t *)&mp->mutex_lockw;
14210Sstevel@tonic-gate 	ownerp = (volatile uint64_t *)&mp->mutex_owner;
14220Sstevel@tonic-gate 	while (--count >= 0) {
14230Sstevel@tonic-gate 		if (*lockp == 0 && set_lock_byte(lockp) == 0)
14240Sstevel@tonic-gate 			return (0);
14250Sstevel@tonic-gate 		SMT_PAUSE();
14260Sstevel@tonic-gate 		if ((ulwp = (ulwp_t *)(uintptr_t)*ownerp) != NULL &&
14270Sstevel@tonic-gate 		    ((scp = ulwp->ul_schedctl) == NULL ||
14280Sstevel@tonic-gate 		    scp->sc_state != SC_ONPROC))
14290Sstevel@tonic-gate 			break;
14300Sstevel@tonic-gate 	}
14310Sstevel@tonic-gate 
14320Sstevel@tonic-gate 	return (EBUSY);
14330Sstevel@tonic-gate }
14340Sstevel@tonic-gate 
14350Sstevel@tonic-gate /*
14360Sstevel@tonic-gate  * Like mutex_trylock_adaptive(), but for process-shared mutexes.
14374613Sraf  * Spin for a while (if 'tryhard' is true), trying to grab the lock.
14380Sstevel@tonic-gate  * If this fails, return EBUSY and let the caller deal with it.
14390Sstevel@tonic-gate  * If this succeeds, return 0 with mutex_owner set to curthread
14400Sstevel@tonic-gate  * and mutex_ownerpid set to the current pid.
14410Sstevel@tonic-gate  */
14424574Sraf static int
14434613Sraf mutex_trylock_process(mutex_t *mp, int tryhard)
14440Sstevel@tonic-gate {
14450Sstevel@tonic-gate 	ulwp_t *self = curthread;
14465629Sraf 	uberdata_t *udp = self->ul_uberdata;
14474574Sraf 	int error = EBUSY;
14486057Sraf 	volatile uint64_t *lockp = (volatile uint64_t *)&mp->mutex_lockword64;
14495629Sraf 	uint32_t new_lockword;
14505629Sraf 	int count = 0;
14515629Sraf 	int max_count;
14525629Sraf 	uint8_t max_spinners;
14534574Sraf 
14547255Sraf #if defined(__sparc) && !defined(_LP64)
14557255Sraf 	/* horrible hack, necessary only on 32-bit sparc */
14567255Sraf 	int fix_alignment_problem =
14577255Sraf 	    (((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
14587255Sraf 	    self->ul_misaligned && !(mp->mutex_type & LOCK_ROBUST));
14597255Sraf #endif
14607255Sraf 
14614574Sraf 	ASSERT(mp->mutex_type & USYNC_PROCESS);
14624574Sraf 
14634574Sraf 	if (shared_mutex_held(mp))
14640Sstevel@tonic-gate 		return (EBUSY);
14650Sstevel@tonic-gate 
1466*7907SRoger.Faulkner@Sun.COM 	enter_critical(self);
1467*7907SRoger.Faulkner@Sun.COM 
14684574Sraf 	/* short-cut, not definitive (see below) */
14694574Sraf 	if (mp->mutex_flag & LOCK_NOTRECOVERABLE) {
14704574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
14715629Sraf 		error = ENOTRECOVERABLE;
14725629Sraf 		goto done;
14734574Sraf 	}
14744574Sraf 
14755629Sraf 	/*
14765629Sraf 	 * Make one attempt to acquire the lock before
14775629Sraf 	 * incurring the overhead of the spin loop.
14785629Sraf 	 */
14797255Sraf #if defined(__sparc) && !defined(_LP64)
14807255Sraf 	/* horrible hack, necessary only on 32-bit sparc */
14817255Sraf 	if (fix_alignment_problem) {
14827255Sraf 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
14837255Sraf 			mp->mutex_ownerpid = udp->pid;
14847255Sraf 			mp->mutex_owner = (uintptr_t)self;
14857255Sraf 			error = 0;
14867255Sraf 			goto done;
14877255Sraf 		}
14887255Sraf 	} else
14897255Sraf #endif
14906057Sraf 	if (set_lock_byte64(lockp, udp->pid) == 0) {
14915629Sraf 		mp->mutex_owner = (uintptr_t)self;
14926057Sraf 		/* mp->mutex_ownerpid was set by set_lock_byte64() */
14935629Sraf 		error = 0;
14945629Sraf 		goto done;
14955629Sraf 	}
14965629Sraf 	if (!tryhard)
14975629Sraf 		goto done;
14984574Sraf 	if (ncpus == 0)
14994574Sraf 		ncpus = (int)_sysconf(_SC_NPROCESSORS_ONLN);
15005629Sraf 	if ((max_spinners = self->ul_max_spinners) >= ncpus)
15015629Sraf 		max_spinners = ncpus - 1;
15025629Sraf 	max_count = (max_spinners != 0)? self->ul_adaptive_spin : 0;
15035629Sraf 	if (max_count == 0)
15045629Sraf 		goto done;
15055629Sraf 
15060Sstevel@tonic-gate 	/*
15070Sstevel@tonic-gate 	 * This is a process-shared mutex.
15080Sstevel@tonic-gate 	 * We cannot know if the owner is running on a processor.
15090Sstevel@tonic-gate 	 * We just spin and hope that it is on a processor.
15100Sstevel@tonic-gate 	 */
1511*7907SRoger.Faulkner@Sun.COM 	if (spinners_incr(&mp->mutex_lockword, max_spinners) == -1)
15125629Sraf 		goto done;
15135629Sraf 	DTRACE_PROBE1(plockstat, mutex__spin, mp);
15145629Sraf 	for (count = 1; ; count++) {
15157255Sraf #if defined(__sparc) && !defined(_LP64)
15167255Sraf 		/* horrible hack, necessary only on 32-bit sparc */
15177255Sraf 		if (fix_alignment_problem) {
15187255Sraf 			if ((*lockp & LOCKMASK64) == 0 &&
15197255Sraf 			    set_lock_byte(&mp->mutex_lockw) == 0) {
15207255Sraf 				mp->mutex_ownerpid = udp->pid;
15217255Sraf 				mp->mutex_owner = (uintptr_t)self;
15227255Sraf 				error = 0;
15237255Sraf 				break;
15247255Sraf 			}
15257255Sraf 		} else
15267255Sraf #endif
15276057Sraf 		if ((*lockp & LOCKMASK64) == 0 &&
15286057Sraf 		    set_lock_byte64(lockp, udp->pid) == 0) {
15294574Sraf 			mp->mutex_owner = (uintptr_t)self;
15306057Sraf 			/* mp->mutex_ownerpid was set by set_lock_byte64() */
15314574Sraf 			error = 0;
15324574Sraf 			break;
15334574Sraf 		}
15345629Sraf 		if (count == max_count)
15355629Sraf 			break;
15364574Sraf 		SMT_PAUSE();
15374574Sraf 	}
15385629Sraf 	new_lockword = spinners_decr(&mp->mutex_lockword);
15395629Sraf 	if (error && (new_lockword & (LOCKMASK | SPINNERMASK)) == 0) {
15405629Sraf 		/*
15415629Sraf 		 * We haven't yet acquired the lock, the lock
15425629Sraf 		 * is free, and there are no other spinners.
15435629Sraf 		 * Make one final attempt to acquire the lock.
15445629Sraf 		 *
15455629Sraf 		 * This isn't strictly necessary since mutex_lock_kernel()
15465629Sraf 		 * (the next action this thread will take if it doesn't
15475629Sraf 		 * acquire the lock here) makes one attempt to acquire
15485629Sraf 		 * the lock before putting the thread to sleep.
15495629Sraf 		 *
15505629Sraf 		 * If the next action for this thread (on failure here)
15515629Sraf 		 * were not to call mutex_lock_kernel(), this would be
15525629Sraf 		 * necessary for correctness, to avoid ending up with an
15535629Sraf 		 * unheld mutex with waiters but no one to wake them up.
15545629Sraf 		 */
15557255Sraf #if defined(__sparc) && !defined(_LP64)
15567255Sraf 		/* horrible hack, necessary only on 32-bit sparc */
15577255Sraf 		if (fix_alignment_problem) {
15587255Sraf 			if (set_lock_byte(&mp->mutex_lockw) == 0) {
15597255Sraf 				mp->mutex_ownerpid = udp->pid;
15607255Sraf 				mp->mutex_owner = (uintptr_t)self;
15617255Sraf 				error = 0;
15627255Sraf 			}
15637255Sraf 		} else
15647255Sraf #endif
15656057Sraf 		if (set_lock_byte64(lockp, udp->pid) == 0) {
15665629Sraf 			mp->mutex_owner = (uintptr_t)self;
15676057Sraf 			/* mp->mutex_ownerpid was set by set_lock_byte64() */
15685629Sraf 			error = 0;
15695629Sraf 		}
15705629Sraf 		count++;
15715629Sraf 	}
15724574Sraf 
15735629Sraf done:
15744574Sraf 	if (error == 0 && (mp->mutex_flag & LOCK_NOTRECOVERABLE)) {
15754574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
15764574Sraf 		/*
15776057Sraf 		 * We shouldn't own the mutex.
15786057Sraf 		 * Just clear the lock; everyone has already been waked up.
15794574Sraf 		 */
15804574Sraf 		mp->mutex_owner = 0;
15816057Sraf 		/* mp->mutex_ownerpid is cleared by clear_lockbyte64() */
15826057Sraf 		(void) clear_lockbyte64(&mp->mutex_lockword64);
15834574Sraf 		error = ENOTRECOVERABLE;
15840Sstevel@tonic-gate 	}
15850Sstevel@tonic-gate 
1586*7907SRoger.Faulkner@Sun.COM 	exit_critical(self);
1587*7907SRoger.Faulkner@Sun.COM 
15884574Sraf 	if (error) {
15895629Sraf 		if (count) {
15905629Sraf 			DTRACE_PROBE2(plockstat, mutex__spun, 0, count);
15915629Sraf 		}
15924574Sraf 		if (error != EBUSY) {
15934574Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, error);
15944574Sraf 		}
15954574Sraf 	} else {
15965629Sraf 		if (count) {
15975629Sraf 			DTRACE_PROBE2(plockstat, mutex__spun, 1, count);
15985629Sraf 		}
15994574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, count);
16004574Sraf 		if (mp->mutex_flag & (LOCK_OWNERDEAD | LOCK_UNMAPPED)) {
16014574Sraf 			ASSERT(mp->mutex_type & LOCK_ROBUST);
16024574Sraf 			if (mp->mutex_flag & LOCK_OWNERDEAD)
16034574Sraf 				error = EOWNERDEAD;
16044574Sraf 			else if (mp->mutex_type & USYNC_PROCESS_ROBUST)
16054574Sraf 				error = ELOCKUNMAPPED;
16064574Sraf 			else
16074574Sraf 				error = EOWNERDEAD;
16084574Sraf 		}
16094574Sraf 	}
16104574Sraf 
16114574Sraf 	return (error);
16120Sstevel@tonic-gate }
16130Sstevel@tonic-gate 
16140Sstevel@tonic-gate /*
16150Sstevel@tonic-gate  * Mutex wakeup code for releasing a USYNC_THREAD mutex.
16160Sstevel@tonic-gate  * Returns the lwpid of the thread that was dequeued, if any.
16170Sstevel@tonic-gate  * The caller of mutex_wakeup() must call __lwp_unpark(lwpid)
16180Sstevel@tonic-gate  * to wake up the specified lwp.
16190Sstevel@tonic-gate  */
16204574Sraf static lwpid_t
16210Sstevel@tonic-gate mutex_wakeup(mutex_t *mp)
16220Sstevel@tonic-gate {
16230Sstevel@tonic-gate 	lwpid_t lwpid = 0;
16246247Sraf 	int more;
16250Sstevel@tonic-gate 	queue_head_t *qp;
16260Sstevel@tonic-gate 	ulwp_t *ulwp;
16270Sstevel@tonic-gate 
16280Sstevel@tonic-gate 	/*
16290Sstevel@tonic-gate 	 * Dequeue a waiter from the sleep queue.  Don't touch the mutex
16300Sstevel@tonic-gate 	 * waiters bit if no one was found on the queue because the mutex
16310Sstevel@tonic-gate 	 * might have been deallocated or reallocated for another purpose.
16320Sstevel@tonic-gate 	 */
16330Sstevel@tonic-gate 	qp = queue_lock(mp, MX);
16346247Sraf 	if ((ulwp = dequeue(qp, &more)) != NULL) {
16350Sstevel@tonic-gate 		lwpid = ulwp->ul_lwpid;
16366247Sraf 		mp->mutex_waiters = more;
16370Sstevel@tonic-gate 	}
16380Sstevel@tonic-gate 	queue_unlock(qp);
16390Sstevel@tonic-gate 	return (lwpid);
16400Sstevel@tonic-gate }
16410Sstevel@tonic-gate 
16420Sstevel@tonic-gate /*
16434574Sraf  * Mutex wakeup code for releasing all waiters on a USYNC_THREAD mutex.
16444574Sraf  */
16454574Sraf static void
16464574Sraf mutex_wakeup_all(mutex_t *mp)
16474574Sraf {
16484574Sraf 	queue_head_t *qp;
16496247Sraf 	queue_root_t *qrp;
16504574Sraf 	int nlwpid = 0;
16514574Sraf 	int maxlwps = MAXLWPS;
16524574Sraf 	ulwp_t *ulwp;
16534574Sraf 	lwpid_t buffer[MAXLWPS];
16544574Sraf 	lwpid_t *lwpid = buffer;
16554574Sraf 
16564574Sraf 	/*
16574574Sraf 	 * Walk the list of waiters and prepare to wake up all of them.
16584574Sraf 	 * The waiters flag has already been cleared from the mutex.
16594574Sraf 	 *
16604574Sraf 	 * We keep track of lwpids that are to be unparked in lwpid[].
16614574Sraf 	 * __lwp_unpark_all() is called to unpark all of them after
16624574Sraf 	 * they have been removed from the sleep queue and the sleep
16634574Sraf 	 * queue lock has been dropped.  If we run out of space in our
16644574Sraf 	 * on-stack buffer, we need to allocate more but we can't call
16654574Sraf 	 * lmalloc() because we are holding a queue lock when the overflow
16664574Sraf 	 * occurs and lmalloc() acquires a lock.  We can't use alloca()
16674574Sraf 	 * either because the application may have allocated a small
16684574Sraf 	 * stack and we don't want to overrun the stack.  So we call
16694574Sraf 	 * alloc_lwpids() to allocate a bigger buffer using the mmap()
16704574Sraf 	 * system call directly since that path acquires no locks.
16714574Sraf 	 */
16724574Sraf 	qp = queue_lock(mp, MX);
16736247Sraf 	for (;;) {
16746247Sraf 		if ((qrp = qp->qh_root) == NULL ||
16756247Sraf 		    (ulwp = qrp->qr_head) == NULL)
16766247Sraf 			break;
16776247Sraf 		ASSERT(ulwp->ul_wchan == mp);
16786247Sraf 		queue_unlink(qp, &qrp->qr_head, NULL);
16796247Sraf 		ulwp->ul_sleepq = NULL;
16806247Sraf 		ulwp->ul_wchan = NULL;
16816247Sraf 		if (nlwpid == maxlwps)
16826247Sraf 			lwpid = alloc_lwpids(lwpid, &nlwpid, &maxlwps);
16836247Sraf 		lwpid[nlwpid++] = ulwp->ul_lwpid;
16844574Sraf 	}
16854574Sraf 
16864574Sraf 	if (nlwpid == 0) {
16874574Sraf 		queue_unlock(qp);
16884574Sraf 	} else {
16895629Sraf 		mp->mutex_waiters = 0;
16904574Sraf 		no_preempt(curthread);
16914574Sraf 		queue_unlock(qp);
16924574Sraf 		if (nlwpid == 1)
16934574Sraf 			(void) __lwp_unpark(lwpid[0]);
16944574Sraf 		else
16954574Sraf 			(void) __lwp_unpark_all(lwpid, nlwpid);
16964574Sraf 		preempt(curthread);
16974574Sraf 	}
16984574Sraf 
16994574Sraf 	if (lwpid != buffer)
17006515Sraf 		(void) munmap((caddr_t)lwpid, maxlwps * sizeof (lwpid_t));
17014574Sraf }
17024574Sraf 
17034574Sraf /*
17045629Sraf  * Release a process-private mutex.
17055629Sraf  * As an optimization, if there are waiters but there are also spinners
17065629Sraf  * attempting to acquire the mutex, then don't bother waking up a waiter;
17075629Sraf  * one of the spinners will acquire the mutex soon and it would be a waste
17085629Sraf  * of resources to wake up some thread just to have it spin for a while
17095629Sraf  * and then possibly go back to sleep.  See mutex_trylock_adaptive().
17100Sstevel@tonic-gate  */
17114574Sraf static lwpid_t
17124574Sraf mutex_unlock_queue(mutex_t *mp, int release_all)
17130Sstevel@tonic-gate {
1714*7907SRoger.Faulkner@Sun.COM 	ulwp_t *self = curthread;
17155629Sraf 	lwpid_t lwpid = 0;
17165629Sraf 	uint32_t old_lockword;
17175629Sraf 
17186057Sraf 	DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
1719*7907SRoger.Faulkner@Sun.COM 	sigoff(self);
17205629Sraf 	mp->mutex_owner = 0;
17215629Sraf 	old_lockword = clear_lockbyte(&mp->mutex_lockword);
17225629Sraf 	if ((old_lockword & WAITERMASK) &&
17235629Sraf 	    (release_all || (old_lockword & SPINNERMASK) == 0)) {
17240Sstevel@tonic-gate 		no_preempt(self);	/* ensure a prompt wakeup */
17255629Sraf 		if (release_all)
17265629Sraf 			mutex_wakeup_all(mp);
17275629Sraf 		else
17285629Sraf 			lwpid = mutex_wakeup(mp);
17295629Sraf 		if (lwpid == 0)
17305629Sraf 			preempt(self);
17314574Sraf 	}
1732*7907SRoger.Faulkner@Sun.COM 	sigon(self);
17330Sstevel@tonic-gate 	return (lwpid);
17340Sstevel@tonic-gate }
17350Sstevel@tonic-gate 
17360Sstevel@tonic-gate /*
17370Sstevel@tonic-gate  * Like mutex_unlock_queue(), but for process-shared mutexes.
17380Sstevel@tonic-gate  */
17394574Sraf static void
17404574Sraf mutex_unlock_process(mutex_t *mp, int release_all)
17410Sstevel@tonic-gate {
17427255Sraf 	ulwp_t *self = curthread;
17436057Sraf 	uint64_t old_lockword64;
17446057Sraf 
17456057Sraf 	DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
1746*7907SRoger.Faulkner@Sun.COM 	sigoff(self);
17470Sstevel@tonic-gate 	mp->mutex_owner = 0;
17487255Sraf #if defined(__sparc) && !defined(_LP64)
17497255Sraf 	/* horrible hack, necessary only on 32-bit sparc */
17507255Sraf 	if (((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
17517255Sraf 	    self->ul_misaligned && !(mp->mutex_type & LOCK_ROBUST)) {
17527255Sraf 		uint32_t old_lockword;
17537255Sraf 		mp->mutex_ownerpid = 0;
17547255Sraf 		old_lockword = clear_lockbyte(&mp->mutex_lockword);
17557255Sraf 		if ((old_lockword & WAITERMASK) &&
17567255Sraf 		    (release_all || (old_lockword & SPINNERMASK) == 0)) {
17577255Sraf 			no_preempt(self);	/* ensure a prompt wakeup */
17587255Sraf 			(void) ___lwp_mutex_wakeup(mp, release_all);
17597255Sraf 			preempt(self);
17607255Sraf 		}
1761*7907SRoger.Faulkner@Sun.COM 		sigon(self);
17627255Sraf 		return;
17637255Sraf 	}
17647255Sraf #endif
17656057Sraf 	/* mp->mutex_ownerpid is cleared by clear_lockbyte64() */
17666057Sraf 	old_lockword64 = clear_lockbyte64(&mp->mutex_lockword64);
17676057Sraf 	if ((old_lockword64 & WAITERMASK64) &&
17686057Sraf 	    (release_all || (old_lockword64 & SPINNERMASK64) == 0)) {
17695629Sraf 		no_preempt(self);	/* ensure a prompt wakeup */
17705629Sraf 		(void) ___lwp_mutex_wakeup(mp, release_all);
17715629Sraf 		preempt(self);
17720Sstevel@tonic-gate 	}
1773*7907SRoger.Faulkner@Sun.COM 	sigon(self);
17740Sstevel@tonic-gate }
17750Sstevel@tonic-gate 
17760Sstevel@tonic-gate void
17770Sstevel@tonic-gate stall(void)
17780Sstevel@tonic-gate {
17790Sstevel@tonic-gate 	for (;;)
17800Sstevel@tonic-gate 		(void) mutex_lock_kernel(&stall_mutex, NULL, NULL);
17810Sstevel@tonic-gate }
17820Sstevel@tonic-gate 
17830Sstevel@tonic-gate /*
17840Sstevel@tonic-gate  * Acquire a USYNC_THREAD mutex via user-level sleep queues.
17850Sstevel@tonic-gate  * We failed set_lock_byte(&mp->mutex_lockw) before coming here.
17864574Sraf  * If successful, returns with mutex_owner set correctly.
17870Sstevel@tonic-gate  */
17880Sstevel@tonic-gate int
17890Sstevel@tonic-gate mutex_lock_queue(ulwp_t *self, tdb_mutex_stats_t *msp, mutex_t *mp,
17900Sstevel@tonic-gate 	timespec_t *tsp)
17910Sstevel@tonic-gate {
17920Sstevel@tonic-gate 	uberdata_t *udp = curthread->ul_uberdata;
17930Sstevel@tonic-gate 	queue_head_t *qp;
17940Sstevel@tonic-gate 	hrtime_t begin_sleep;
17950Sstevel@tonic-gate 	int error = 0;
17960Sstevel@tonic-gate 
17970Sstevel@tonic-gate 	self->ul_sp = stkptr();
17980Sstevel@tonic-gate 	if (__td_event_report(self, TD_SLEEP, udp)) {
17990Sstevel@tonic-gate 		self->ul_wchan = mp;
18000Sstevel@tonic-gate 		self->ul_td_evbuf.eventnum = TD_SLEEP;
18010Sstevel@tonic-gate 		self->ul_td_evbuf.eventdata = mp;
18020Sstevel@tonic-gate 		tdb_event(TD_SLEEP, udp);
18030Sstevel@tonic-gate 	}
18040Sstevel@tonic-gate 	if (msp) {
18050Sstevel@tonic-gate 		tdb_incr(msp->mutex_sleep);
18060Sstevel@tonic-gate 		begin_sleep = gethrtime();
18070Sstevel@tonic-gate 	}
18080Sstevel@tonic-gate 
18090Sstevel@tonic-gate 	DTRACE_PROBE1(plockstat, mutex__block, mp);
18100Sstevel@tonic-gate 
18110Sstevel@tonic-gate 	/*
18120Sstevel@tonic-gate 	 * Put ourself on the sleep queue, and while we are
18130Sstevel@tonic-gate 	 * unable to grab the lock, go park in the kernel.
18140Sstevel@tonic-gate 	 * Take ourself off the sleep queue after we acquire the lock.
18150Sstevel@tonic-gate 	 * The waiter bit can be set/cleared only while holding the queue lock.
18160Sstevel@tonic-gate 	 */
18170Sstevel@tonic-gate 	qp = queue_lock(mp, MX);
18186247Sraf 	enqueue(qp, self, 0);
18190Sstevel@tonic-gate 	mp->mutex_waiters = 1;
18200Sstevel@tonic-gate 	for (;;) {
18210Sstevel@tonic-gate 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
18220Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
18236247Sraf 			mp->mutex_waiters = dequeue_self(qp);
18240Sstevel@tonic-gate 			break;
18250Sstevel@tonic-gate 		}
18260Sstevel@tonic-gate 		set_parking_flag(self, 1);
18270Sstevel@tonic-gate 		queue_unlock(qp);
18280Sstevel@tonic-gate 		/*
18290Sstevel@tonic-gate 		 * __lwp_park() will return the residual time in tsp
18300Sstevel@tonic-gate 		 * if we are unparked before the timeout expires.
18310Sstevel@tonic-gate 		 */
18325629Sraf 		error = __lwp_park(tsp, 0);
18330Sstevel@tonic-gate 		set_parking_flag(self, 0);
18340Sstevel@tonic-gate 		/*
18350Sstevel@tonic-gate 		 * We could have taken a signal or suspended ourself.
18360Sstevel@tonic-gate 		 * If we did, then we removed ourself from the queue.
18370Sstevel@tonic-gate 		 * Someone else may have removed us from the queue
18380Sstevel@tonic-gate 		 * as a consequence of mutex_unlock().  We may have
18390Sstevel@tonic-gate 		 * gotten a timeout from __lwp_park().  Or we may still
18400Sstevel@tonic-gate 		 * be on the queue and this is just a spurious wakeup.
18410Sstevel@tonic-gate 		 */
18420Sstevel@tonic-gate 		qp = queue_lock(mp, MX);
18430Sstevel@tonic-gate 		if (self->ul_sleepq == NULL) {
18445629Sraf 			if (error) {
18456247Sraf 				mp->mutex_waiters = queue_waiter(qp)? 1 : 0;
18465629Sraf 				if (error != EINTR)
18475629Sraf 					break;
18485629Sraf 				error = 0;
18495629Sraf 			}
18500Sstevel@tonic-gate 			if (set_lock_byte(&mp->mutex_lockw) == 0) {
18510Sstevel@tonic-gate 				mp->mutex_owner = (uintptr_t)self;
18520Sstevel@tonic-gate 				break;
18530Sstevel@tonic-gate 			}
18546247Sraf 			enqueue(qp, self, 0);
18550Sstevel@tonic-gate 			mp->mutex_waiters = 1;
18560Sstevel@tonic-gate 		}
18570Sstevel@tonic-gate 		ASSERT(self->ul_sleepq == qp &&
18580Sstevel@tonic-gate 		    self->ul_qtype == MX &&
18590Sstevel@tonic-gate 		    self->ul_wchan == mp);
18600Sstevel@tonic-gate 		if (error) {
18615629Sraf 			if (error != EINTR) {
18626247Sraf 				mp->mutex_waiters = dequeue_self(qp);
18635629Sraf 				break;
18645629Sraf 			}
18655629Sraf 			error = 0;
18660Sstevel@tonic-gate 		}
18670Sstevel@tonic-gate 	}
18680Sstevel@tonic-gate 	ASSERT(self->ul_sleepq == NULL && self->ul_link == NULL &&
18690Sstevel@tonic-gate 	    self->ul_wchan == NULL);
18700Sstevel@tonic-gate 	self->ul_sp = 0;
18710Sstevel@tonic-gate 
18720Sstevel@tonic-gate 	ASSERT(error == 0 || error == EINVAL || error == ETIME);
18734574Sraf 
18744574Sraf 	if (error == 0 && (mp->mutex_flag & LOCK_NOTRECOVERABLE)) {
18754574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
18764574Sraf 		/*
18776057Sraf 		 * We shouldn't own the mutex.
18786057Sraf 		 * Just clear the lock; everyone has already been waked up.
18794574Sraf 		 */
18804574Sraf 		mp->mutex_owner = 0;
18816057Sraf 		(void) clear_lockbyte(&mp->mutex_lockword);
18824574Sraf 		error = ENOTRECOVERABLE;
18834574Sraf 	}
18844574Sraf 
1885*7907SRoger.Faulkner@Sun.COM 	queue_unlock(qp);
1886*7907SRoger.Faulkner@Sun.COM 
1887*7907SRoger.Faulkner@Sun.COM 	if (msp)
1888*7907SRoger.Faulkner@Sun.COM 		msp->mutex_sleep_time += gethrtime() - begin_sleep;
1889*7907SRoger.Faulkner@Sun.COM 
18904574Sraf 	if (error) {
18914574Sraf 		DTRACE_PROBE2(plockstat, mutex__blocked, mp, 0);
18924574Sraf 		DTRACE_PROBE2(plockstat, mutex__error, mp, error);
18934574Sraf 	} else {
18944574Sraf 		DTRACE_PROBE2(plockstat, mutex__blocked, mp, 1);
18954574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
18964574Sraf 		if (mp->mutex_flag & LOCK_OWNERDEAD) {
18974574Sraf 			ASSERT(mp->mutex_type & LOCK_ROBUST);
18984574Sraf 			error = EOWNERDEAD;
18994574Sraf 		}
19004574Sraf 	}
19014574Sraf 
19020Sstevel@tonic-gate 	return (error);
19030Sstevel@tonic-gate }
19040Sstevel@tonic-gate 
19054574Sraf static int
19064574Sraf mutex_recursion(mutex_t *mp, int mtype, int try)
19074574Sraf {
19086812Sraf 	ASSERT(mutex_held(mp));
19094574Sraf 	ASSERT(mtype & (LOCK_RECURSIVE|LOCK_ERRORCHECK));
19104574Sraf 	ASSERT(try == MUTEX_TRY || try == MUTEX_LOCK);
19114574Sraf 
19124574Sraf 	if (mtype & LOCK_RECURSIVE) {
19134574Sraf 		if (mp->mutex_rcount == RECURSION_MAX) {
19144574Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, EAGAIN);
19154574Sraf 			return (EAGAIN);
19164574Sraf 		}
19174574Sraf 		mp->mutex_rcount++;
19184574Sraf 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 1, 0);
19194574Sraf 		return (0);
19204574Sraf 	}
19214574Sraf 	if (try == MUTEX_LOCK) {
19224574Sraf 		DTRACE_PROBE2(plockstat, mutex__error, mp, EDEADLK);
19234574Sraf 		return (EDEADLK);
19244574Sraf 	}
19254574Sraf 	return (EBUSY);
19264574Sraf }
19274574Sraf 
19284574Sraf /*
19294574Sraf  * Register this USYNC_PROCESS|LOCK_ROBUST mutex with the kernel so
19304574Sraf  * it can apply LOCK_OWNERDEAD|LOCK_UNMAPPED if it becomes necessary.
19314574Sraf  * We use tdb_hash_lock here and in the synch object tracking code in
19324574Sraf  * the tdb_agent.c file.  There is no conflict between these two usages.
19334574Sraf  */
19344574Sraf void
19354574Sraf register_lock(mutex_t *mp)
19364574Sraf {
19374574Sraf 	uberdata_t *udp = curthread->ul_uberdata;
19384574Sraf 	uint_t hash = LOCK_HASH(mp);
19394574Sraf 	robust_t *rlp;
19404574Sraf 	robust_t **rlpp;
19414574Sraf 	robust_t **table;
19424574Sraf 
19434574Sraf 	if ((table = udp->robustlocks) == NULL) {
19444574Sraf 		lmutex_lock(&udp->tdb_hash_lock);
19454574Sraf 		if ((table = udp->robustlocks) == NULL) {
19464574Sraf 			table = lmalloc(LOCKHASHSZ * sizeof (robust_t *));
19476812Sraf 			membar_producer();
19484574Sraf 			udp->robustlocks = table;
19494574Sraf 		}
19504574Sraf 		lmutex_unlock(&udp->tdb_hash_lock);
19514574Sraf 	}
19526812Sraf 	membar_consumer();
19534574Sraf 
19544574Sraf 	/*
19554574Sraf 	 * First search the registered table with no locks held.
19564574Sraf 	 * This is safe because the table never shrinks
19574574Sraf 	 * and we can only get a false negative.
19584574Sraf 	 */
19594574Sraf 	for (rlp = table[hash]; rlp != NULL; rlp = rlp->robust_next) {
19604574Sraf 		if (rlp->robust_lock == mp)	/* already registered */
19614574Sraf 			return;
19624574Sraf 	}
19634574Sraf 
19644574Sraf 	/*
19654574Sraf 	 * The lock was not found.
19664574Sraf 	 * Repeat the operation with tdb_hash_lock held.
19674574Sraf 	 */
19684574Sraf 	lmutex_lock(&udp->tdb_hash_lock);
19694574Sraf 
19704574Sraf 	for (rlpp = &table[hash];
19714574Sraf 	    (rlp = *rlpp) != NULL;
19724574Sraf 	    rlpp = &rlp->robust_next) {
19734574Sraf 		if (rlp->robust_lock == mp) {	/* already registered */
19744574Sraf 			lmutex_unlock(&udp->tdb_hash_lock);
19754574Sraf 			return;
19764574Sraf 		}
19774574Sraf 	}
19784574Sraf 
19794574Sraf 	/*
19804574Sraf 	 * The lock has never been registered.
19814574Sraf 	 * Register it now and add it to the table.
19824574Sraf 	 */
19834574Sraf 	(void) ___lwp_mutex_register(mp);
19844574Sraf 	rlp = lmalloc(sizeof (*rlp));
19854574Sraf 	rlp->robust_lock = mp;
19866812Sraf 	membar_producer();
19874574Sraf 	*rlpp = rlp;
19884574Sraf 
19894574Sraf 	lmutex_unlock(&udp->tdb_hash_lock);
19904574Sraf }
19914574Sraf 
19924574Sraf /*
19934574Sraf  * This is called in the child of fork()/forkall() to start over
19944574Sraf  * with a clean slate.  (Each process must register its own locks.)
19954574Sraf  * No locks are needed because all other threads are suspended or gone.
19964574Sraf  */
19974574Sraf void
19984574Sraf unregister_locks(void)
19994574Sraf {
20004574Sraf 	uberdata_t *udp = curthread->ul_uberdata;
20014574Sraf 	uint_t hash;
20024574Sraf 	robust_t **table;
20034574Sraf 	robust_t *rlp;
20044574Sraf 	robust_t *next;
20054574Sraf 
20064574Sraf 	if ((table = udp->robustlocks) != NULL) {
20074574Sraf 		for (hash = 0; hash < LOCKHASHSZ; hash++) {
20084574Sraf 			rlp = table[hash];
20094574Sraf 			while (rlp != NULL) {
20104574Sraf 				next = rlp->robust_next;
20114574Sraf 				lfree(rlp, sizeof (*rlp));
20124574Sraf 				rlp = next;
20134574Sraf 			}
20144574Sraf 		}
20154574Sraf 		lfree(table, LOCKHASHSZ * sizeof (robust_t *));
20164574Sraf 		udp->robustlocks = NULL;
20174574Sraf 	}
20184574Sraf }
20194574Sraf 
20200Sstevel@tonic-gate /*
20210Sstevel@tonic-gate  * Returns with mutex_owner set correctly.
20220Sstevel@tonic-gate  */
20236247Sraf int
20240Sstevel@tonic-gate mutex_lock_internal(mutex_t *mp, timespec_t *tsp, int try)
20250Sstevel@tonic-gate {
20260Sstevel@tonic-gate 	ulwp_t *self = curthread;
20270Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
20280Sstevel@tonic-gate 	int mtype = mp->mutex_type;
20290Sstevel@tonic-gate 	tdb_mutex_stats_t *msp = MUTEX_STATS(mp, udp);
20300Sstevel@tonic-gate 	int error = 0;
20316247Sraf 	int noceil = try & MUTEX_NOCEIL;
20324574Sraf 	uint8_t ceil;
20334574Sraf 	int myprio;
20340Sstevel@tonic-gate 
20356247Sraf 	try &= ~MUTEX_NOCEIL;
20360Sstevel@tonic-gate 	ASSERT(try == MUTEX_TRY || try == MUTEX_LOCK);
20370Sstevel@tonic-gate 
20380Sstevel@tonic-gate 	if (!self->ul_schedctl_called)
20390Sstevel@tonic-gate 		(void) setup_schedctl();
20400Sstevel@tonic-gate 
20410Sstevel@tonic-gate 	if (msp && try == MUTEX_TRY)
20420Sstevel@tonic-gate 		tdb_incr(msp->mutex_try);
20430Sstevel@tonic-gate 
20446812Sraf 	if ((mtype & (LOCK_RECURSIVE|LOCK_ERRORCHECK)) && mutex_held(mp))
20454574Sraf 		return (mutex_recursion(mp, mtype, try));
20460Sstevel@tonic-gate 
20470Sstevel@tonic-gate 	if (self->ul_error_detection && try == MUTEX_LOCK &&
20486812Sraf 	    tsp == NULL && mutex_held(mp))
20490Sstevel@tonic-gate 		lock_error(mp, "mutex_lock", NULL, NULL);
20500Sstevel@tonic-gate 
20516247Sraf 	if ((mtype & LOCK_PRIO_PROTECT) && noceil == 0) {
20526247Sraf 		update_sched(self);
20536247Sraf 		if (self->ul_cid != self->ul_rtclassid) {
20546247Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, EPERM);
20556247Sraf 			return (EPERM);
20566247Sraf 		}
20574574Sraf 		ceil = mp->mutex_ceiling;
20586247Sraf 		myprio = self->ul_epri? self->ul_epri : self->ul_pri;
20594574Sraf 		if (myprio > ceil) {
20604574Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, EINVAL);
20614574Sraf 			return (EINVAL);
20624574Sraf 		}
20634574Sraf 		if ((error = _ceil_mylist_add(mp)) != 0) {
20644574Sraf 			DTRACE_PROBE2(plockstat, mutex__error, mp, error);
20654574Sraf 			return (error);
20660Sstevel@tonic-gate 		}
20674574Sraf 		if (myprio < ceil)
20684574Sraf 			_ceil_prio_inherit(ceil);
20694574Sraf 	}
20704574Sraf 
20714574Sraf 	if ((mtype & (USYNC_PROCESS | LOCK_ROBUST))
20724574Sraf 	    == (USYNC_PROCESS | LOCK_ROBUST))
20734574Sraf 		register_lock(mp);
20744574Sraf 
20754574Sraf 	if (mtype & LOCK_PRIO_INHERIT) {
20764574Sraf 		/* go straight to the kernel */
20774574Sraf 		if (try == MUTEX_TRY)
20784574Sraf 			error = mutex_trylock_kernel(mp);
20794574Sraf 		else	/* MUTEX_LOCK */
20804574Sraf 			error = mutex_lock_kernel(mp, tsp, msp);
20814574Sraf 		/*
20824574Sraf 		 * The kernel never sets or clears the lock byte
20834574Sraf 		 * for LOCK_PRIO_INHERIT mutexes.
20844574Sraf 		 * Set it here for consistency.
20854574Sraf 		 */
20864574Sraf 		switch (error) {
20874574Sraf 		case 0:
20886247Sraf 			self->ul_pilocks++;
20894574Sraf 			mp->mutex_lockw = LOCKSET;
20904574Sraf 			break;
20914574Sraf 		case EOWNERDEAD:
20924574Sraf 		case ELOCKUNMAPPED:
20936247Sraf 			self->ul_pilocks++;
20944574Sraf 			mp->mutex_lockw = LOCKSET;
20954574Sraf 			/* FALLTHROUGH */
20964574Sraf 		case ENOTRECOVERABLE:
20974574Sraf 			ASSERT(mtype & LOCK_ROBUST);
20984574Sraf 			break;
20994574Sraf 		case EDEADLK:
21007376SRoger.Faulkner@Sun.COM 			if (try == MUTEX_TRY) {
21017376SRoger.Faulkner@Sun.COM 				error = EBUSY;
21027376SRoger.Faulkner@Sun.COM 			} else if (tsp != NULL) {	/* simulate a timeout */
21037376SRoger.Faulkner@Sun.COM 				/*
21047376SRoger.Faulkner@Sun.COM 				 * Note: mutex_timedlock() never returns EINTR.
21057376SRoger.Faulkner@Sun.COM 				 */
21067376SRoger.Faulkner@Sun.COM 				timespec_t ts = *tsp;
21077376SRoger.Faulkner@Sun.COM 				timespec_t rts;
21087376SRoger.Faulkner@Sun.COM 
21097376SRoger.Faulkner@Sun.COM 				while (__nanosleep(&ts, &rts) == EINTR)
21107376SRoger.Faulkner@Sun.COM 					ts = rts;
21117376SRoger.Faulkner@Sun.COM 				error = ETIME;
21127376SRoger.Faulkner@Sun.COM 			} else {		/* simulate a deadlock */
21134574Sraf 				stall();
21147376SRoger.Faulkner@Sun.COM 			}
21154574Sraf 			break;
21160Sstevel@tonic-gate 		}
21170Sstevel@tonic-gate 	} else if (mtype & USYNC_PROCESS) {
21184613Sraf 		error = mutex_trylock_process(mp, try == MUTEX_LOCK);
21194574Sraf 		if (error == EBUSY && try == MUTEX_LOCK)
21200Sstevel@tonic-gate 			error = mutex_lock_kernel(mp, tsp, msp);
21215629Sraf 	} else {	/* USYNC_THREAD */
21224613Sraf 		error = mutex_trylock_adaptive(mp, try == MUTEX_LOCK);
21234574Sraf 		if (error == EBUSY && try == MUTEX_LOCK)
21244574Sraf 			error = mutex_lock_queue(self, msp, mp, tsp);
21250Sstevel@tonic-gate 	}
21260Sstevel@tonic-gate 
21270Sstevel@tonic-gate 	switch (error) {
21284574Sraf 	case 0:
21290Sstevel@tonic-gate 	case EOWNERDEAD:
21300Sstevel@tonic-gate 	case ELOCKUNMAPPED:
21314574Sraf 		if (mtype & LOCK_ROBUST)
21324574Sraf 			remember_lock(mp);
21330Sstevel@tonic-gate 		if (msp)
21340Sstevel@tonic-gate 			record_begin_hold(msp);
21350Sstevel@tonic-gate 		break;
21360Sstevel@tonic-gate 	default:
21376247Sraf 		if ((mtype & LOCK_PRIO_PROTECT) && noceil == 0) {
21384574Sraf 			(void) _ceil_mylist_del(mp);
21394574Sraf 			if (myprio < ceil)
21404574Sraf 				_ceil_prio_waive();
21414574Sraf 		}
21420Sstevel@tonic-gate 		if (try == MUTEX_TRY) {
21430Sstevel@tonic-gate 			if (msp)
21440Sstevel@tonic-gate 				tdb_incr(msp->mutex_try_fail);
21450Sstevel@tonic-gate 			if (__td_event_report(self, TD_LOCK_TRY, udp)) {
21460Sstevel@tonic-gate 				self->ul_td_evbuf.eventnum = TD_LOCK_TRY;
21470Sstevel@tonic-gate 				tdb_event(TD_LOCK_TRY, udp);
21480Sstevel@tonic-gate 			}
21490Sstevel@tonic-gate 		}
21500Sstevel@tonic-gate 		break;
21510Sstevel@tonic-gate 	}
21520Sstevel@tonic-gate 
21530Sstevel@tonic-gate 	return (error);
21540Sstevel@tonic-gate }
21550Sstevel@tonic-gate 
21560Sstevel@tonic-gate int
21570Sstevel@tonic-gate fast_process_lock(mutex_t *mp, timespec_t *tsp, int mtype, int try)
21580Sstevel@tonic-gate {
21590Sstevel@tonic-gate 	ulwp_t *self = curthread;
21600Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
21610Sstevel@tonic-gate 
21620Sstevel@tonic-gate 	/*
21630Sstevel@tonic-gate 	 * We know that USYNC_PROCESS is set in mtype and that
21640Sstevel@tonic-gate 	 * zero, one, or both of the flags LOCK_RECURSIVE and
21650Sstevel@tonic-gate 	 * LOCK_ERRORCHECK are set, and that no other flags are set.
21660Sstevel@tonic-gate 	 */
21674574Sraf 	ASSERT((mtype & ~(USYNC_PROCESS|LOCK_RECURSIVE|LOCK_ERRORCHECK)) == 0);
21680Sstevel@tonic-gate 	enter_critical(self);
21697255Sraf #if defined(__sparc) && !defined(_LP64)
21707255Sraf 	/* horrible hack, necessary only on 32-bit sparc */
21717255Sraf 	if (((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
21727255Sraf 	    self->ul_misaligned) {
21737255Sraf 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
21747255Sraf 			mp->mutex_ownerpid = udp->pid;
21757255Sraf 			mp->mutex_owner = (uintptr_t)self;
21767255Sraf 			exit_critical(self);
21777255Sraf 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
21787255Sraf 			return (0);
21797255Sraf 		}
21807255Sraf 	} else
21817255Sraf #endif
21826057Sraf 	if (set_lock_byte64(&mp->mutex_lockword64, udp->pid) == 0) {
21830Sstevel@tonic-gate 		mp->mutex_owner = (uintptr_t)self;
21846057Sraf 		/* mp->mutex_ownerpid was set by set_lock_byte64() */
21850Sstevel@tonic-gate 		exit_critical(self);
21860Sstevel@tonic-gate 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
21870Sstevel@tonic-gate 		return (0);
21880Sstevel@tonic-gate 	}
21890Sstevel@tonic-gate 	exit_critical(self);
21900Sstevel@tonic-gate 
21914574Sraf 	if ((mtype & (LOCK_RECURSIVE|LOCK_ERRORCHECK)) && shared_mutex_held(mp))
21924574Sraf 		return (mutex_recursion(mp, mtype, try));
21934574Sraf 
21944613Sraf 	if (try == MUTEX_LOCK) {
21954613Sraf 		if (mutex_trylock_process(mp, 1) == 0)
21964613Sraf 			return (0);
21970Sstevel@tonic-gate 		return (mutex_lock_kernel(mp, tsp, NULL));
21984613Sraf 	}
21990Sstevel@tonic-gate 
22000Sstevel@tonic-gate 	if (__td_event_report(self, TD_LOCK_TRY, udp)) {
22010Sstevel@tonic-gate 		self->ul_td_evbuf.eventnum = TD_LOCK_TRY;
22020Sstevel@tonic-gate 		tdb_event(TD_LOCK_TRY, udp);
22030Sstevel@tonic-gate 	}
22040Sstevel@tonic-gate 	return (EBUSY);
22050Sstevel@tonic-gate }
22060Sstevel@tonic-gate 
22070Sstevel@tonic-gate static int
22080Sstevel@tonic-gate mutex_lock_impl(mutex_t *mp, timespec_t *tsp)
22090Sstevel@tonic-gate {
22100Sstevel@tonic-gate 	ulwp_t *self = curthread;
22116247Sraf 	int mtype = mp->mutex_type;
22120Sstevel@tonic-gate 	uberflags_t *gflags;
22130Sstevel@tonic-gate 
22147255Sraf 	if (((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
22157255Sraf 	    self->ul_error_detection && self->ul_misaligned == 0)
22167255Sraf 		lock_error(mp, "mutex_lock", NULL, "mutex is misaligned");
22177255Sraf 
22180Sstevel@tonic-gate 	/*
22190Sstevel@tonic-gate 	 * Optimize the case of USYNC_THREAD, including
22200Sstevel@tonic-gate 	 * the LOCK_RECURSIVE and LOCK_ERRORCHECK cases,
22210Sstevel@tonic-gate 	 * no error detection, no lock statistics,
22220Sstevel@tonic-gate 	 * and the process has only a single thread.
22230Sstevel@tonic-gate 	 * (Most likely a traditional single-threaded application.)
22240Sstevel@tonic-gate 	 */
22256247Sraf 	if (((mtype & ~(LOCK_RECURSIVE|LOCK_ERRORCHECK)) |
22266247Sraf 	    self->ul_uberdata->uberflags.uf_all) == 0) {
22270Sstevel@tonic-gate 		/*
22280Sstevel@tonic-gate 		 * Only one thread exists so we don't need an atomic operation.
2229*7907SRoger.Faulkner@Sun.COM 		 * We do, however, need to protect against signals.
22300Sstevel@tonic-gate 		 */
22310Sstevel@tonic-gate 		if (mp->mutex_lockw == 0) {
2232*7907SRoger.Faulkner@Sun.COM 			sigoff(self);
22330Sstevel@tonic-gate 			mp->mutex_lockw = LOCKSET;
22340Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
2235*7907SRoger.Faulkner@Sun.COM 			sigon(self);
22360Sstevel@tonic-gate 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
22370Sstevel@tonic-gate 			return (0);
22380Sstevel@tonic-gate 		}
22394574Sraf 		if (mtype && MUTEX_OWNER(mp) == self)
22404574Sraf 			return (mutex_recursion(mp, mtype, MUTEX_LOCK));
22410Sstevel@tonic-gate 		/*
22420Sstevel@tonic-gate 		 * We have reached a deadlock, probably because the
22430Sstevel@tonic-gate 		 * process is executing non-async-signal-safe code in
22440Sstevel@tonic-gate 		 * a signal handler and is attempting to acquire a lock
22450Sstevel@tonic-gate 		 * that it already owns.  This is not surprising, given
22460Sstevel@tonic-gate 		 * bad programming practices over the years that has
22470Sstevel@tonic-gate 		 * resulted in applications calling printf() and such
22480Sstevel@tonic-gate 		 * in their signal handlers.  Unless the user has told
22490Sstevel@tonic-gate 		 * us that the signal handlers are safe by setting:
22500Sstevel@tonic-gate 		 *	export _THREAD_ASYNC_SAFE=1
22510Sstevel@tonic-gate 		 * we return EDEADLK rather than actually deadlocking.
22520Sstevel@tonic-gate 		 */
22530Sstevel@tonic-gate 		if (tsp == NULL &&
22540Sstevel@tonic-gate 		    MUTEX_OWNER(mp) == self && !self->ul_async_safe) {
22550Sstevel@tonic-gate 			DTRACE_PROBE2(plockstat, mutex__error, mp, EDEADLK);
22560Sstevel@tonic-gate 			return (EDEADLK);
22570Sstevel@tonic-gate 		}
22580Sstevel@tonic-gate 	}
22590Sstevel@tonic-gate 
22600Sstevel@tonic-gate 	/*
22610Sstevel@tonic-gate 	 * Optimize the common cases of USYNC_THREAD or USYNC_PROCESS,
22620Sstevel@tonic-gate 	 * no error detection, and no lock statistics.
22630Sstevel@tonic-gate 	 * Include LOCK_RECURSIVE and LOCK_ERRORCHECK cases.
22640Sstevel@tonic-gate 	 */
22650Sstevel@tonic-gate 	if ((gflags = self->ul_schedctl_called) != NULL &&
22660Sstevel@tonic-gate 	    (gflags->uf_trs_ted |
22670Sstevel@tonic-gate 	    (mtype & ~(USYNC_PROCESS|LOCK_RECURSIVE|LOCK_ERRORCHECK))) == 0) {
22680Sstevel@tonic-gate 		if (mtype & USYNC_PROCESS)
22690Sstevel@tonic-gate 			return (fast_process_lock(mp, tsp, mtype, MUTEX_LOCK));
2270*7907SRoger.Faulkner@Sun.COM 		sigoff(self);
22710Sstevel@tonic-gate 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
22720Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
2273*7907SRoger.Faulkner@Sun.COM 			sigon(self);
22740Sstevel@tonic-gate 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
22750Sstevel@tonic-gate 			return (0);
22760Sstevel@tonic-gate 		}
2277*7907SRoger.Faulkner@Sun.COM 		sigon(self);
22784574Sraf 		if (mtype && MUTEX_OWNER(mp) == self)
22794574Sraf 			return (mutex_recursion(mp, mtype, MUTEX_LOCK));
22804613Sraf 		if (mutex_trylock_adaptive(mp, 1) != 0)
22814574Sraf 			return (mutex_lock_queue(self, NULL, mp, tsp));
22824574Sraf 		return (0);
22830Sstevel@tonic-gate 	}
22840Sstevel@tonic-gate 
22850Sstevel@tonic-gate 	/* else do it the long way */
22860Sstevel@tonic-gate 	return (mutex_lock_internal(mp, tsp, MUTEX_LOCK));
22870Sstevel@tonic-gate }
22880Sstevel@tonic-gate 
22896812Sraf #pragma weak pthread_mutex_lock = mutex_lock
22906812Sraf #pragma weak _mutex_lock = mutex_lock
22910Sstevel@tonic-gate int
22926812Sraf mutex_lock(mutex_t *mp)
22930Sstevel@tonic-gate {
22940Sstevel@tonic-gate 	ASSERT(!curthread->ul_critical || curthread->ul_bindflags);
22950Sstevel@tonic-gate 	return (mutex_lock_impl(mp, NULL));
22960Sstevel@tonic-gate }
22970Sstevel@tonic-gate 
22980Sstevel@tonic-gate int
22996812Sraf pthread_mutex_timedlock(pthread_mutex_t *_RESTRICT_KYWD mp,
23006812Sraf 	const struct timespec *_RESTRICT_KYWD abstime)
23010Sstevel@tonic-gate {
23020Sstevel@tonic-gate 	timespec_t tslocal;
23030Sstevel@tonic-gate 	int error;
23040Sstevel@tonic-gate 
23050Sstevel@tonic-gate 	ASSERT(!curthread->ul_critical || curthread->ul_bindflags);
23060Sstevel@tonic-gate 	abstime_to_reltime(CLOCK_REALTIME, abstime, &tslocal);
23076812Sraf 	error = mutex_lock_impl((mutex_t *)mp, &tslocal);
23080Sstevel@tonic-gate 	if (error == ETIME)
23090Sstevel@tonic-gate 		error = ETIMEDOUT;
23100Sstevel@tonic-gate 	return (error);
23110Sstevel@tonic-gate }
23120Sstevel@tonic-gate 
23130Sstevel@tonic-gate int
23146812Sraf pthread_mutex_reltimedlock_np(pthread_mutex_t *_RESTRICT_KYWD mp,
23156812Sraf 	const struct timespec *_RESTRICT_KYWD reltime)
23160Sstevel@tonic-gate {
23170Sstevel@tonic-gate 	timespec_t tslocal;
23180Sstevel@tonic-gate 	int error;
23190Sstevel@tonic-gate 
23200Sstevel@tonic-gate 	ASSERT(!curthread->ul_critical || curthread->ul_bindflags);
23210Sstevel@tonic-gate 	tslocal = *reltime;
23226812Sraf 	error = mutex_lock_impl((mutex_t *)mp, &tslocal);
23230Sstevel@tonic-gate 	if (error == ETIME)
23240Sstevel@tonic-gate 		error = ETIMEDOUT;
23250Sstevel@tonic-gate 	return (error);
23260Sstevel@tonic-gate }
23270Sstevel@tonic-gate 
23286812Sraf #pragma weak pthread_mutex_trylock = mutex_trylock
23290Sstevel@tonic-gate int
23306812Sraf mutex_trylock(mutex_t *mp)
23310Sstevel@tonic-gate {
23320Sstevel@tonic-gate 	ulwp_t *self = curthread;
23330Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
23346247Sraf 	int mtype = mp->mutex_type;
23350Sstevel@tonic-gate 	uberflags_t *gflags;
23360Sstevel@tonic-gate 
23370Sstevel@tonic-gate 	ASSERT(!curthread->ul_critical || curthread->ul_bindflags);
23386247Sraf 
23390Sstevel@tonic-gate 	/*
23400Sstevel@tonic-gate 	 * Optimize the case of USYNC_THREAD, including
23410Sstevel@tonic-gate 	 * the LOCK_RECURSIVE and LOCK_ERRORCHECK cases,
23420Sstevel@tonic-gate 	 * no error detection, no lock statistics,
23430Sstevel@tonic-gate 	 * and the process has only a single thread.
23440Sstevel@tonic-gate 	 * (Most likely a traditional single-threaded application.)
23450Sstevel@tonic-gate 	 */
23466247Sraf 	if (((mtype & ~(LOCK_RECURSIVE|LOCK_ERRORCHECK)) |
23470Sstevel@tonic-gate 	    udp->uberflags.uf_all) == 0) {
23480Sstevel@tonic-gate 		/*
23490Sstevel@tonic-gate 		 * Only one thread exists so we don't need an atomic operation.
2350*7907SRoger.Faulkner@Sun.COM 		 * We do, however, need to protect against signals.
23510Sstevel@tonic-gate 		 */
23520Sstevel@tonic-gate 		if (mp->mutex_lockw == 0) {
2353*7907SRoger.Faulkner@Sun.COM 			sigoff(self);
23540Sstevel@tonic-gate 			mp->mutex_lockw = LOCKSET;
23550Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
2356*7907SRoger.Faulkner@Sun.COM 			sigon(self);
23570Sstevel@tonic-gate 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
23580Sstevel@tonic-gate 			return (0);
23590Sstevel@tonic-gate 		}
23604574Sraf 		if (mtype && MUTEX_OWNER(mp) == self)
23614574Sraf 			return (mutex_recursion(mp, mtype, MUTEX_TRY));
23620Sstevel@tonic-gate 		return (EBUSY);
23630Sstevel@tonic-gate 	}
23640Sstevel@tonic-gate 
23650Sstevel@tonic-gate 	/*
23660Sstevel@tonic-gate 	 * Optimize the common cases of USYNC_THREAD or USYNC_PROCESS,
23670Sstevel@tonic-gate 	 * no error detection, and no lock statistics.
23680Sstevel@tonic-gate 	 * Include LOCK_RECURSIVE and LOCK_ERRORCHECK cases.
23690Sstevel@tonic-gate 	 */
23700Sstevel@tonic-gate 	if ((gflags = self->ul_schedctl_called) != NULL &&
23710Sstevel@tonic-gate 	    (gflags->uf_trs_ted |
23720Sstevel@tonic-gate 	    (mtype & ~(USYNC_PROCESS|LOCK_RECURSIVE|LOCK_ERRORCHECK))) == 0) {
23730Sstevel@tonic-gate 		if (mtype & USYNC_PROCESS)
23740Sstevel@tonic-gate 			return (fast_process_lock(mp, NULL, mtype, MUTEX_TRY));
2375*7907SRoger.Faulkner@Sun.COM 		sigoff(self);
23760Sstevel@tonic-gate 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
23770Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
2378*7907SRoger.Faulkner@Sun.COM 			sigon(self);
23790Sstevel@tonic-gate 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
23800Sstevel@tonic-gate 			return (0);
23810Sstevel@tonic-gate 		}
2382*7907SRoger.Faulkner@Sun.COM 		sigon(self);
23834574Sraf 		if (mtype && MUTEX_OWNER(mp) == self)
23844574Sraf 			return (mutex_recursion(mp, mtype, MUTEX_TRY));
23854613Sraf 		if (__td_event_report(self, TD_LOCK_TRY, udp)) {
23864613Sraf 			self->ul_td_evbuf.eventnum = TD_LOCK_TRY;
23874613Sraf 			tdb_event(TD_LOCK_TRY, udp);
23880Sstevel@tonic-gate 		}
23894613Sraf 		return (EBUSY);
23900Sstevel@tonic-gate 	}
23910Sstevel@tonic-gate 
23920Sstevel@tonic-gate 	/* else do it the long way */
23930Sstevel@tonic-gate 	return (mutex_lock_internal(mp, NULL, MUTEX_TRY));
23940Sstevel@tonic-gate }
23950Sstevel@tonic-gate 
23960Sstevel@tonic-gate int
23974574Sraf mutex_unlock_internal(mutex_t *mp, int retain_robust_flags)
23980Sstevel@tonic-gate {
23990Sstevel@tonic-gate 	ulwp_t *self = curthread;
24000Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
24010Sstevel@tonic-gate 	int mtype = mp->mutex_type;
24020Sstevel@tonic-gate 	tdb_mutex_stats_t *msp;
24034574Sraf 	int error = 0;
24044574Sraf 	int release_all;
24050Sstevel@tonic-gate 	lwpid_t lwpid;
24060Sstevel@tonic-gate 
24076812Sraf 	if ((mtype & LOCK_ERRORCHECK) && !mutex_held(mp))
24080Sstevel@tonic-gate 		return (EPERM);
24090Sstevel@tonic-gate 
24106812Sraf 	if (self->ul_error_detection && !mutex_held(mp))
24110Sstevel@tonic-gate 		lock_error(mp, "mutex_unlock", NULL, NULL);
24120Sstevel@tonic-gate 
24130Sstevel@tonic-gate 	if ((mtype & LOCK_RECURSIVE) && mp->mutex_rcount != 0) {
24140Sstevel@tonic-gate 		mp->mutex_rcount--;
24150Sstevel@tonic-gate 		DTRACE_PROBE2(plockstat, mutex__release, mp, 1);
24160Sstevel@tonic-gate 		return (0);
24170Sstevel@tonic-gate 	}
24180Sstevel@tonic-gate 
24190Sstevel@tonic-gate 	if ((msp = MUTEX_STATS(mp, udp)) != NULL)
24200Sstevel@tonic-gate 		(void) record_hold_time(msp);
24210Sstevel@tonic-gate 
24224574Sraf 	if (!retain_robust_flags && !(mtype & LOCK_PRIO_INHERIT) &&
24234574Sraf 	    (mp->mutex_flag & (LOCK_OWNERDEAD | LOCK_UNMAPPED))) {
24244574Sraf 		ASSERT(mp->mutex_type & LOCK_ROBUST);
24254574Sraf 		mp->mutex_flag &= ~(LOCK_OWNERDEAD | LOCK_UNMAPPED);
24264574Sraf 		mp->mutex_flag |= LOCK_NOTRECOVERABLE;
24274574Sraf 	}
24284574Sraf 	release_all = ((mp->mutex_flag & LOCK_NOTRECOVERABLE) != 0);
24294574Sraf 
24304574Sraf 	if (mtype & LOCK_PRIO_INHERIT) {
24310Sstevel@tonic-gate 		no_preempt(self);
24320Sstevel@tonic-gate 		mp->mutex_owner = 0;
24336057Sraf 		/* mp->mutex_ownerpid is cleared by ___lwp_mutex_unlock() */
24340Sstevel@tonic-gate 		DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
24354574Sraf 		mp->mutex_lockw = LOCKCLEAR;
24366247Sraf 		self->ul_pilocks--;
24374574Sraf 		error = ___lwp_mutex_unlock(mp);
24380Sstevel@tonic-gate 		preempt(self);
24390Sstevel@tonic-gate 	} else if (mtype & USYNC_PROCESS) {
24405629Sraf 		mutex_unlock_process(mp, release_all);
24410Sstevel@tonic-gate 	} else {	/* USYNC_THREAD */
24424574Sraf 		if ((lwpid = mutex_unlock_queue(mp, release_all)) != 0) {
24430Sstevel@tonic-gate 			(void) __lwp_unpark(lwpid);
24440Sstevel@tonic-gate 			preempt(self);
24450Sstevel@tonic-gate 		}
24460Sstevel@tonic-gate 	}
24470Sstevel@tonic-gate 
24484574Sraf 	if (mtype & LOCK_ROBUST)
24494574Sraf 		forget_lock(mp);
24504574Sraf 
24514574Sraf 	if ((mtype & LOCK_PRIO_PROTECT) && _ceil_mylist_del(mp))
24524574Sraf 		_ceil_prio_waive();
24534574Sraf 
24540Sstevel@tonic-gate 	return (error);
24550Sstevel@tonic-gate }
24560Sstevel@tonic-gate 
24576812Sraf #pragma weak pthread_mutex_unlock = mutex_unlock
24586812Sraf #pragma weak _mutex_unlock = mutex_unlock
24590Sstevel@tonic-gate int
24606812Sraf mutex_unlock(mutex_t *mp)
24610Sstevel@tonic-gate {
24620Sstevel@tonic-gate 	ulwp_t *self = curthread;
24636247Sraf 	int mtype = mp->mutex_type;
24640Sstevel@tonic-gate 	uberflags_t *gflags;
24650Sstevel@tonic-gate 	lwpid_t lwpid;
24660Sstevel@tonic-gate 	short el;
24670Sstevel@tonic-gate 
24680Sstevel@tonic-gate 	/*
24690Sstevel@tonic-gate 	 * Optimize the case of USYNC_THREAD, including
24700Sstevel@tonic-gate 	 * the LOCK_RECURSIVE and LOCK_ERRORCHECK cases,
24710Sstevel@tonic-gate 	 * no error detection, no lock statistics,
24720Sstevel@tonic-gate 	 * and the process has only a single thread.
24730Sstevel@tonic-gate 	 * (Most likely a traditional single-threaded application.)
24740Sstevel@tonic-gate 	 */
24756247Sraf 	if (((mtype & ~(LOCK_RECURSIVE|LOCK_ERRORCHECK)) |
24766247Sraf 	    self->ul_uberdata->uberflags.uf_all) == 0) {
24770Sstevel@tonic-gate 		if (mtype) {
24780Sstevel@tonic-gate 			/*
24790Sstevel@tonic-gate 			 * At this point we know that one or both of the
24800Sstevel@tonic-gate 			 * flags LOCK_RECURSIVE or LOCK_ERRORCHECK is set.
24810Sstevel@tonic-gate 			 */
24820Sstevel@tonic-gate 			if ((mtype & LOCK_ERRORCHECK) && !MUTEX_OWNED(mp, self))
24830Sstevel@tonic-gate 				return (EPERM);
24840Sstevel@tonic-gate 			if ((mtype & LOCK_RECURSIVE) && mp->mutex_rcount != 0) {
24850Sstevel@tonic-gate 				mp->mutex_rcount--;
24860Sstevel@tonic-gate 				DTRACE_PROBE2(plockstat, mutex__release, mp, 1);
24870Sstevel@tonic-gate 				return (0);
24880Sstevel@tonic-gate 			}
24890Sstevel@tonic-gate 		}
24900Sstevel@tonic-gate 		/*
24910Sstevel@tonic-gate 		 * Only one thread exists so we don't need an atomic operation.
24920Sstevel@tonic-gate 		 * Also, there can be no waiters.
24930Sstevel@tonic-gate 		 */
2494*7907SRoger.Faulkner@Sun.COM 		sigoff(self);
24950Sstevel@tonic-gate 		mp->mutex_owner = 0;
24960Sstevel@tonic-gate 		mp->mutex_lockword = 0;
2497*7907SRoger.Faulkner@Sun.COM 		sigon(self);
24980Sstevel@tonic-gate 		DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
24990Sstevel@tonic-gate 		return (0);
25000Sstevel@tonic-gate 	}
25010Sstevel@tonic-gate 
25020Sstevel@tonic-gate 	/*
25030Sstevel@tonic-gate 	 * Optimize the common cases of USYNC_THREAD or USYNC_PROCESS,
25040Sstevel@tonic-gate 	 * no error detection, and no lock statistics.
25050Sstevel@tonic-gate 	 * Include LOCK_RECURSIVE and LOCK_ERRORCHECK cases.
25060Sstevel@tonic-gate 	 */
25070Sstevel@tonic-gate 	if ((gflags = self->ul_schedctl_called) != NULL) {
25080Sstevel@tonic-gate 		if (((el = gflags->uf_trs_ted) | mtype) == 0) {
25090Sstevel@tonic-gate fast_unlock:
25105629Sraf 			if ((lwpid = mutex_unlock_queue(mp, 0)) != 0) {
25110Sstevel@tonic-gate 				(void) __lwp_unpark(lwpid);
25120Sstevel@tonic-gate 				preempt(self);
25130Sstevel@tonic-gate 			}
25140Sstevel@tonic-gate 			return (0);
25150Sstevel@tonic-gate 		}
25160Sstevel@tonic-gate 		if (el)		/* error detection or lock statistics */
25170Sstevel@tonic-gate 			goto slow_unlock;
25180Sstevel@tonic-gate 		if ((mtype & ~(LOCK_RECURSIVE|LOCK_ERRORCHECK)) == 0) {
25190Sstevel@tonic-gate 			/*
25200Sstevel@tonic-gate 			 * At this point we know that one or both of the
25210Sstevel@tonic-gate 			 * flags LOCK_RECURSIVE or LOCK_ERRORCHECK is set.
25220Sstevel@tonic-gate 			 */
25230Sstevel@tonic-gate 			if ((mtype & LOCK_ERRORCHECK) && !MUTEX_OWNED(mp, self))
25240Sstevel@tonic-gate 				return (EPERM);
25250Sstevel@tonic-gate 			if ((mtype & LOCK_RECURSIVE) && mp->mutex_rcount != 0) {
25260Sstevel@tonic-gate 				mp->mutex_rcount--;
25270Sstevel@tonic-gate 				DTRACE_PROBE2(plockstat, mutex__release, mp, 1);
25280Sstevel@tonic-gate 				return (0);
25290Sstevel@tonic-gate 			}
25300Sstevel@tonic-gate 			goto fast_unlock;
25310Sstevel@tonic-gate 		}
25320Sstevel@tonic-gate 		if ((mtype &
25330Sstevel@tonic-gate 		    ~(USYNC_PROCESS|LOCK_RECURSIVE|LOCK_ERRORCHECK)) == 0) {
25340Sstevel@tonic-gate 			/*
25350Sstevel@tonic-gate 			 * At this point we know that zero, one, or both of the
25360Sstevel@tonic-gate 			 * flags LOCK_RECURSIVE or LOCK_ERRORCHECK is set and
25370Sstevel@tonic-gate 			 * that the USYNC_PROCESS flag is set.
25380Sstevel@tonic-gate 			 */
25390Sstevel@tonic-gate 			if ((mtype & LOCK_ERRORCHECK) && !shared_mutex_held(mp))
25400Sstevel@tonic-gate 				return (EPERM);
25410Sstevel@tonic-gate 			if ((mtype & LOCK_RECURSIVE) && mp->mutex_rcount != 0) {
25420Sstevel@tonic-gate 				mp->mutex_rcount--;
25430Sstevel@tonic-gate 				DTRACE_PROBE2(plockstat, mutex__release, mp, 1);
25440Sstevel@tonic-gate 				return (0);
25450Sstevel@tonic-gate 			}
25465629Sraf 			mutex_unlock_process(mp, 0);
25470Sstevel@tonic-gate 			return (0);
25480Sstevel@tonic-gate 		}
25490Sstevel@tonic-gate 	}
25500Sstevel@tonic-gate 
25510Sstevel@tonic-gate 	/* else do it the long way */
25520Sstevel@tonic-gate slow_unlock:
25534574Sraf 	return (mutex_unlock_internal(mp, 0));
25540Sstevel@tonic-gate }
25550Sstevel@tonic-gate 
25560Sstevel@tonic-gate /*
25570Sstevel@tonic-gate  * Internally to the library, almost all mutex lock/unlock actions
25580Sstevel@tonic-gate  * go through these lmutex_ functions, to protect critical regions.
25596812Sraf  * We replicate a bit of code from mutex_lock() and mutex_unlock()
25600Sstevel@tonic-gate  * to make these functions faster since we know that the mutex type
25610Sstevel@tonic-gate  * of all internal locks is USYNC_THREAD.  We also know that internal
25620Sstevel@tonic-gate  * locking can never fail, so we panic if it does.
25630Sstevel@tonic-gate  */
25640Sstevel@tonic-gate void
25650Sstevel@tonic-gate lmutex_lock(mutex_t *mp)
25660Sstevel@tonic-gate {
25670Sstevel@tonic-gate 	ulwp_t *self = curthread;
25680Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
25690Sstevel@tonic-gate 
25700Sstevel@tonic-gate 	ASSERT(mp->mutex_type == USYNC_THREAD);
25710Sstevel@tonic-gate 
25720Sstevel@tonic-gate 	enter_critical(self);
25730Sstevel@tonic-gate 	/*
25740Sstevel@tonic-gate 	 * Optimize the case of no lock statistics and only a single thread.
25750Sstevel@tonic-gate 	 * (Most likely a traditional single-threaded application.)
25760Sstevel@tonic-gate 	 */
25770Sstevel@tonic-gate 	if (udp->uberflags.uf_all == 0) {
25780Sstevel@tonic-gate 		/*
25790Sstevel@tonic-gate 		 * Only one thread exists; the mutex must be free.
25800Sstevel@tonic-gate 		 */
25810Sstevel@tonic-gate 		ASSERT(mp->mutex_lockw == 0);
25820Sstevel@tonic-gate 		mp->mutex_lockw = LOCKSET;
25830Sstevel@tonic-gate 		mp->mutex_owner = (uintptr_t)self;
25840Sstevel@tonic-gate 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
25850Sstevel@tonic-gate 	} else {
25860Sstevel@tonic-gate 		tdb_mutex_stats_t *msp = MUTEX_STATS(mp, udp);
25870Sstevel@tonic-gate 
25880Sstevel@tonic-gate 		if (!self->ul_schedctl_called)
25890Sstevel@tonic-gate 			(void) setup_schedctl();
25900Sstevel@tonic-gate 
25910Sstevel@tonic-gate 		if (set_lock_byte(&mp->mutex_lockw) == 0) {
25920Sstevel@tonic-gate 			mp->mutex_owner = (uintptr_t)self;
25930Sstevel@tonic-gate 			DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
25944613Sraf 		} else if (mutex_trylock_adaptive(mp, 1) != 0) {
25950Sstevel@tonic-gate 			(void) mutex_lock_queue(self, msp, mp, NULL);
25960Sstevel@tonic-gate 		}
25970Sstevel@tonic-gate 
25980Sstevel@tonic-gate 		if (msp)
25990Sstevel@tonic-gate 			record_begin_hold(msp);
26000Sstevel@tonic-gate 	}
26010Sstevel@tonic-gate }
26020Sstevel@tonic-gate 
26030Sstevel@tonic-gate void
26040Sstevel@tonic-gate lmutex_unlock(mutex_t *mp)
26050Sstevel@tonic-gate {
26060Sstevel@tonic-gate 	ulwp_t *self = curthread;
26070Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
26080Sstevel@tonic-gate 
26090Sstevel@tonic-gate 	ASSERT(mp->mutex_type == USYNC_THREAD);
26100Sstevel@tonic-gate 
26110Sstevel@tonic-gate 	/*
26120Sstevel@tonic-gate 	 * Optimize the case of no lock statistics and only a single thread.
26130Sstevel@tonic-gate 	 * (Most likely a traditional single-threaded application.)
26140Sstevel@tonic-gate 	 */
26150Sstevel@tonic-gate 	if (udp->uberflags.uf_all == 0) {
26160Sstevel@tonic-gate 		/*
26170Sstevel@tonic-gate 		 * Only one thread exists so there can be no waiters.
26180Sstevel@tonic-gate 		 */
26190Sstevel@tonic-gate 		mp->mutex_owner = 0;
26200Sstevel@tonic-gate 		mp->mutex_lockword = 0;
26210Sstevel@tonic-gate 		DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
26220Sstevel@tonic-gate 	} else {
26230Sstevel@tonic-gate 		tdb_mutex_stats_t *msp = MUTEX_STATS(mp, udp);
26240Sstevel@tonic-gate 		lwpid_t lwpid;
26250Sstevel@tonic-gate 
26260Sstevel@tonic-gate 		if (msp)
26270Sstevel@tonic-gate 			(void) record_hold_time(msp);
26284574Sraf 		if ((lwpid = mutex_unlock_queue(mp, 0)) != 0) {
26290Sstevel@tonic-gate 			(void) __lwp_unpark(lwpid);
26300Sstevel@tonic-gate 			preempt(self);
26310Sstevel@tonic-gate 		}
26320Sstevel@tonic-gate 	}
26330Sstevel@tonic-gate 	exit_critical(self);
26340Sstevel@tonic-gate }
26350Sstevel@tonic-gate 
26362248Sraf /*
26372248Sraf  * For specialized code in libc, like the asynchronous i/o code,
26382248Sraf  * the following sig_*() locking primitives are used in order
26392248Sraf  * to make the code asynchronous signal safe.  Signals are
26402248Sraf  * deferred while locks acquired by these functions are held.
26412248Sraf  */
26422248Sraf void
26432248Sraf sig_mutex_lock(mutex_t *mp)
26442248Sraf {
26452248Sraf 	sigoff(curthread);
26466515Sraf 	(void) mutex_lock(mp);
26472248Sraf }
26482248Sraf 
26492248Sraf void
26502248Sraf sig_mutex_unlock(mutex_t *mp)
26512248Sraf {
26526515Sraf 	(void) mutex_unlock(mp);
26532248Sraf 	sigon(curthread);
26542248Sraf }
26552248Sraf 
26562248Sraf int
26572248Sraf sig_mutex_trylock(mutex_t *mp)
26582248Sraf {
26592248Sraf 	int error;
26602248Sraf 
26612248Sraf 	sigoff(curthread);
26626515Sraf 	if ((error = mutex_trylock(mp)) != 0)
26632248Sraf 		sigon(curthread);
26642248Sraf 	return (error);
26652248Sraf }
26662248Sraf 
26672248Sraf /*
26682248Sraf  * sig_cond_wait() is a cancellation point.
26692248Sraf  */
26702248Sraf int
26712248Sraf sig_cond_wait(cond_t *cv, mutex_t *mp)
26722248Sraf {
26732248Sraf 	int error;
26742248Sraf 
26752248Sraf 	ASSERT(curthread->ul_sigdefer != 0);
26766515Sraf 	pthread_testcancel();
26775891Sraf 	error = __cond_wait(cv, mp);
26782248Sraf 	if (error == EINTR && curthread->ul_cursig) {
26792248Sraf 		sig_mutex_unlock(mp);
26802248Sraf 		/* take the deferred signal here */
26812248Sraf 		sig_mutex_lock(mp);
26822248Sraf 	}
26836515Sraf 	pthread_testcancel();
26842248Sraf 	return (error);
26852248Sraf }
26862248Sraf 
26872248Sraf /*
26882248Sraf  * sig_cond_reltimedwait() is a cancellation point.
26892248Sraf  */
26902248Sraf int
26912248Sraf sig_cond_reltimedwait(cond_t *cv, mutex_t *mp, const timespec_t *ts)
26922248Sraf {
26932248Sraf 	int error;
26942248Sraf 
26952248Sraf 	ASSERT(curthread->ul_sigdefer != 0);
26966515Sraf 	pthread_testcancel();
26975891Sraf 	error = __cond_reltimedwait(cv, mp, ts);
26982248Sraf 	if (error == EINTR && curthread->ul_cursig) {
26992248Sraf 		sig_mutex_unlock(mp);
27002248Sraf 		/* take the deferred signal here */
27012248Sraf 		sig_mutex_lock(mp);
27022248Sraf 	}
27036515Sraf 	pthread_testcancel();
27042248Sraf 	return (error);
27052248Sraf }
27062248Sraf 
27075891Sraf /*
27085891Sraf  * For specialized code in libc, like the stdio code.
27095891Sraf  * the following cancel_safe_*() locking primitives are used in
27105891Sraf  * order to make the code cancellation-safe.  Cancellation is
27115891Sraf  * deferred while locks acquired by these functions are held.
27125891Sraf  */
27135891Sraf void
27145891Sraf cancel_safe_mutex_lock(mutex_t *mp)
27155891Sraf {
27166515Sraf 	(void) mutex_lock(mp);
27175891Sraf 	curthread->ul_libc_locks++;
27185891Sraf }
27195891Sraf 
27205891Sraf int
27215891Sraf cancel_safe_mutex_trylock(mutex_t *mp)
27225891Sraf {
27235891Sraf 	int error;
27245891Sraf 
27256515Sraf 	if ((error = mutex_trylock(mp)) == 0)
27265891Sraf 		curthread->ul_libc_locks++;
27275891Sraf 	return (error);
27285891Sraf }
27295891Sraf 
27305891Sraf void
27315891Sraf cancel_safe_mutex_unlock(mutex_t *mp)
27325891Sraf {
27335891Sraf 	ulwp_t *self = curthread;
27345891Sraf 
27355891Sraf 	ASSERT(self->ul_libc_locks != 0);
27365891Sraf 
27376515Sraf 	(void) mutex_unlock(mp);
27385891Sraf 
27395891Sraf 	/*
27405891Sraf 	 * Decrement the count of locks held by cancel_safe_mutex_lock().
27415891Sraf 	 * If we are then in a position to terminate cleanly and
27425891Sraf 	 * if there is a pending cancellation and cancellation
27435891Sraf 	 * is not disabled and we received EINTR from a recent
27445891Sraf 	 * system call then perform the cancellation action now.
27455891Sraf 	 */
27465891Sraf 	if (--self->ul_libc_locks == 0 &&
27475891Sraf 	    !(self->ul_vfork | self->ul_nocancel |
27485891Sraf 	    self->ul_critical | self->ul_sigdefer) &&
27495891Sraf 	    cancel_active())
27506812Sraf 		pthread_exit(PTHREAD_CANCELED);
27515891Sraf }
27525891Sraf 
27530Sstevel@tonic-gate static int
27540Sstevel@tonic-gate shared_mutex_held(mutex_t *mparg)
27550Sstevel@tonic-gate {
27560Sstevel@tonic-gate 	/*
27574574Sraf 	 * The 'volatile' is necessary to make sure the compiler doesn't
27584574Sraf 	 * reorder the tests of the various components of the mutex.
27594574Sraf 	 * They must be tested in this order:
27604574Sraf 	 *	mutex_lockw
27614574Sraf 	 *	mutex_owner
27624574Sraf 	 *	mutex_ownerpid
27634574Sraf 	 * This relies on the fact that everywhere mutex_lockw is cleared,
27644574Sraf 	 * mutex_owner and mutex_ownerpid are cleared before mutex_lockw
27654574Sraf 	 * is cleared, and that everywhere mutex_lockw is set, mutex_owner
27664574Sraf 	 * and mutex_ownerpid are set after mutex_lockw is set, and that
27674574Sraf 	 * mutex_lockw is set or cleared with a memory barrier.
27680Sstevel@tonic-gate 	 */
27690Sstevel@tonic-gate 	volatile mutex_t *mp = (volatile mutex_t *)mparg;
27700Sstevel@tonic-gate 	ulwp_t *self = curthread;
27710Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
27720Sstevel@tonic-gate 
27734574Sraf 	return (MUTEX_OWNED(mp, self) && mp->mutex_ownerpid == udp->pid);
27740Sstevel@tonic-gate }
27750Sstevel@tonic-gate 
27766812Sraf #pragma weak _mutex_held = mutex_held
27770Sstevel@tonic-gate int
27786812Sraf mutex_held(mutex_t *mparg)
27790Sstevel@tonic-gate {
27804574Sraf 	volatile mutex_t *mp = (volatile mutex_t *)mparg;
27814574Sraf 
27824574Sraf 	if (mparg->mutex_type & USYNC_PROCESS)
27834574Sraf 		return (shared_mutex_held(mparg));
27840Sstevel@tonic-gate 	return (MUTEX_OWNED(mp, curthread));
27850Sstevel@tonic-gate }
27860Sstevel@tonic-gate 
27876812Sraf #pragma weak pthread_mutex_destroy = mutex_destroy
27886812Sraf #pragma weak _mutex_destroy = mutex_destroy
27890Sstevel@tonic-gate int
27906812Sraf mutex_destroy(mutex_t *mp)
27910Sstevel@tonic-gate {
27924574Sraf 	if (mp->mutex_type & USYNC_PROCESS)
27934574Sraf 		forget_lock(mp);
27946515Sraf 	(void) memset(mp, 0, sizeof (*mp));
27950Sstevel@tonic-gate 	tdb_sync_obj_deregister(mp);
27960Sstevel@tonic-gate 	return (0);
27970Sstevel@tonic-gate }
27980Sstevel@tonic-gate 
27996812Sraf #pragma weak pthread_mutex_consistent_np = mutex_consistent
28004574Sraf int
28016812Sraf mutex_consistent(mutex_t *mp)
28024574Sraf {
28034574Sraf 	/*
28044574Sraf 	 * Do this only for an inconsistent, initialized robust lock
28054574Sraf 	 * that we hold.  For all other cases, return EINVAL.
28064574Sraf 	 */
28076812Sraf 	if (mutex_held(mp) &&
28084574Sraf 	    (mp->mutex_type & LOCK_ROBUST) &&
28094574Sraf 	    (mp->mutex_flag & LOCK_INITED) &&
28104574Sraf 	    (mp->mutex_flag & (LOCK_OWNERDEAD | LOCK_UNMAPPED))) {
28114574Sraf 		mp->mutex_flag &= ~(LOCK_OWNERDEAD | LOCK_UNMAPPED);
28124574Sraf 		mp->mutex_rcount = 0;
28134574Sraf 		return (0);
28144574Sraf 	}
28154574Sraf 	return (EINVAL);
28164574Sraf }
28174574Sraf 
28180Sstevel@tonic-gate /*
28190Sstevel@tonic-gate  * Spin locks are separate from ordinary mutexes,
28200Sstevel@tonic-gate  * but we use the same data structure for them.
28210Sstevel@tonic-gate  */
28220Sstevel@tonic-gate 
28230Sstevel@tonic-gate int
28246812Sraf pthread_spin_init(pthread_spinlock_t *lock, int pshared)
28250Sstevel@tonic-gate {
28260Sstevel@tonic-gate 	mutex_t *mp = (mutex_t *)lock;
28270Sstevel@tonic-gate 
28286515Sraf 	(void) memset(mp, 0, sizeof (*mp));
28290Sstevel@tonic-gate 	if (pshared == PTHREAD_PROCESS_SHARED)
28300Sstevel@tonic-gate 		mp->mutex_type = USYNC_PROCESS;
28310Sstevel@tonic-gate 	else
28320Sstevel@tonic-gate 		mp->mutex_type = USYNC_THREAD;
28330Sstevel@tonic-gate 	mp->mutex_flag = LOCK_INITED;
28340Sstevel@tonic-gate 	mp->mutex_magic = MUTEX_MAGIC;
28357255Sraf 
28367255Sraf 	/*
28377255Sraf 	 * This should be at the beginning of the function,
28387255Sraf 	 * but for the sake of old broken applications that
28397255Sraf 	 * do not have proper alignment for their mutexes
28407255Sraf 	 * (and don't check the return code from pthread_spin_init),
28417255Sraf 	 * we put it here, after initializing the mutex regardless.
28427255Sraf 	 */
28437255Sraf 	if (((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1)) &&
28447255Sraf 	    curthread->ul_misaligned == 0)
28457255Sraf 		return (EINVAL);
28467255Sraf 
28470Sstevel@tonic-gate 	return (0);
28480Sstevel@tonic-gate }
28490Sstevel@tonic-gate 
28500Sstevel@tonic-gate int
28516812Sraf pthread_spin_destroy(pthread_spinlock_t *lock)
28520Sstevel@tonic-gate {
28536515Sraf 	(void) memset(lock, 0, sizeof (*lock));
28540Sstevel@tonic-gate 	return (0);
28550Sstevel@tonic-gate }
28560Sstevel@tonic-gate 
28570Sstevel@tonic-gate int
28586812Sraf pthread_spin_trylock(pthread_spinlock_t *lock)
28590Sstevel@tonic-gate {
28600Sstevel@tonic-gate 	mutex_t *mp = (mutex_t *)lock;
28610Sstevel@tonic-gate 	ulwp_t *self = curthread;
28620Sstevel@tonic-gate 	int error = 0;
28630Sstevel@tonic-gate 
28640Sstevel@tonic-gate 	no_preempt(self);
28650Sstevel@tonic-gate 	if (set_lock_byte(&mp->mutex_lockw) != 0)
28660Sstevel@tonic-gate 		error = EBUSY;
28670Sstevel@tonic-gate 	else {
28680Sstevel@tonic-gate 		mp->mutex_owner = (uintptr_t)self;
28690Sstevel@tonic-gate 		if (mp->mutex_type == USYNC_PROCESS)
28700Sstevel@tonic-gate 			mp->mutex_ownerpid = self->ul_uberdata->pid;
28710Sstevel@tonic-gate 		DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, 0);
28720Sstevel@tonic-gate 	}
28730Sstevel@tonic-gate 	preempt(self);
28740Sstevel@tonic-gate 	return (error);
28750Sstevel@tonic-gate }
28760Sstevel@tonic-gate 
28770Sstevel@tonic-gate int
28786812Sraf pthread_spin_lock(pthread_spinlock_t *lock)
28790Sstevel@tonic-gate {
28804574Sraf 	mutex_t *mp = (mutex_t *)lock;
28814574Sraf 	ulwp_t *self = curthread;
28824574Sraf 	volatile uint8_t *lockp = (volatile uint8_t *)&mp->mutex_lockw;
28834574Sraf 	int count = 0;
28844574Sraf 
28854574Sraf 	ASSERT(!self->ul_critical || self->ul_bindflags);
28864574Sraf 
28874574Sraf 	DTRACE_PROBE1(plockstat, mutex__spin, mp);
28884574Sraf 
28890Sstevel@tonic-gate 	/*
28900Sstevel@tonic-gate 	 * We don't care whether the owner is running on a processor.
28910Sstevel@tonic-gate 	 * We just spin because that's what this interface requires.
28920Sstevel@tonic-gate 	 */
28930Sstevel@tonic-gate 	for (;;) {
28940Sstevel@tonic-gate 		if (*lockp == 0) {	/* lock byte appears to be clear */
28954574Sraf 			no_preempt(self);
28964574Sraf 			if (set_lock_byte(lockp) == 0)
28974574Sraf 				break;
28984574Sraf 			preempt(self);
28990Sstevel@tonic-gate 		}
29005629Sraf 		if (count < INT_MAX)
29015629Sraf 			count++;
29020Sstevel@tonic-gate 		SMT_PAUSE();
29030Sstevel@tonic-gate 	}
29044574Sraf 	mp->mutex_owner = (uintptr_t)self;
29054574Sraf 	if (mp->mutex_type == USYNC_PROCESS)
29064574Sraf 		mp->mutex_ownerpid = self->ul_uberdata->pid;
29074574Sraf 	preempt(self);
29085629Sraf 	if (count) {
29095629Sraf 		DTRACE_PROBE2(plockstat, mutex__spun, 1, count);
29105629Sraf 	}
29114574Sraf 	DTRACE_PROBE3(plockstat, mutex__acquire, mp, 0, count);
29124574Sraf 	return (0);
29130Sstevel@tonic-gate }
29140Sstevel@tonic-gate 
29150Sstevel@tonic-gate int
29166812Sraf pthread_spin_unlock(pthread_spinlock_t *lock)
29170Sstevel@tonic-gate {
29180Sstevel@tonic-gate 	mutex_t *mp = (mutex_t *)lock;
29190Sstevel@tonic-gate 	ulwp_t *self = curthread;
29200Sstevel@tonic-gate 
29210Sstevel@tonic-gate 	no_preempt(self);
29220Sstevel@tonic-gate 	mp->mutex_owner = 0;
29230Sstevel@tonic-gate 	mp->mutex_ownerpid = 0;
29240Sstevel@tonic-gate 	DTRACE_PROBE2(plockstat, mutex__release, mp, 0);
29254570Sraf 	(void) atomic_swap_32(&mp->mutex_lockword, 0);
29260Sstevel@tonic-gate 	preempt(self);
29270Sstevel@tonic-gate 	return (0);
29280Sstevel@tonic-gate }
29290Sstevel@tonic-gate 
29305629Sraf #define	INITIAL_LOCKS	8	/* initial size of ul_heldlocks.array */
29314574Sraf 
29324574Sraf /*
29334574Sraf  * Find/allocate an entry for 'lock' in our array of held locks.
29344574Sraf  */
29354574Sraf static mutex_t **
29364574Sraf find_lock_entry(mutex_t *lock)
29374574Sraf {
29384574Sraf 	ulwp_t *self = curthread;
29394574Sraf 	mutex_t **remembered = NULL;
29404574Sraf 	mutex_t **lockptr;
29414574Sraf 	uint_t nlocks;
29424574Sraf 
29434574Sraf 	if ((nlocks = self->ul_heldlockcnt) != 0)
29444574Sraf 		lockptr = self->ul_heldlocks.array;
29454574Sraf 	else {
29464574Sraf 		nlocks = 1;
29474574Sraf 		lockptr = &self->ul_heldlocks.single;
29484574Sraf 	}
29494574Sraf 
29504574Sraf 	for (; nlocks; nlocks--, lockptr++) {
29514574Sraf 		if (*lockptr == lock)
29524574Sraf 			return (lockptr);
29534574Sraf 		if (*lockptr == NULL && remembered == NULL)
29544574Sraf 			remembered = lockptr;
29554574Sraf 	}
29564574Sraf 	if (remembered != NULL) {
29574574Sraf 		*remembered = lock;
29584574Sraf 		return (remembered);
29594574Sraf 	}
29604574Sraf 
29614574Sraf 	/*
29624574Sraf 	 * No entry available.  Allocate more space, converting
29634574Sraf 	 * the single entry into an array of entries if necessary.
29644574Sraf 	 */
29654574Sraf 	if ((nlocks = self->ul_heldlockcnt) == 0) {
29664574Sraf 		/*
29674574Sraf 		 * Initial allocation of the array.
29684574Sraf 		 * Convert the single entry into an array.
29694574Sraf 		 */
29704574Sraf 		self->ul_heldlockcnt = nlocks = INITIAL_LOCKS;
29714574Sraf 		lockptr = lmalloc(nlocks * sizeof (mutex_t *));
29724574Sraf 		/*
29734574Sraf 		 * The single entry becomes the first entry in the array.
29744574Sraf 		 */
29754574Sraf 		*lockptr = self->ul_heldlocks.single;
29764574Sraf 		self->ul_heldlocks.array = lockptr;
29774574Sraf 		/*
29784574Sraf 		 * Return the next available entry in the array.
29794574Sraf 		 */
29804574Sraf 		*++lockptr = lock;
29814574Sraf 		return (lockptr);
29824574Sraf 	}
29834574Sraf 	/*
29844574Sraf 	 * Reallocate the array, double the size each time.
29854574Sraf 	 */
29864574Sraf 	lockptr = lmalloc(nlocks * 2 * sizeof (mutex_t *));
29876515Sraf 	(void) memcpy(lockptr, self->ul_heldlocks.array,
29884574Sraf 	    nlocks * sizeof (mutex_t *));
29894574Sraf 	lfree(self->ul_heldlocks.array, nlocks * sizeof (mutex_t *));
29904574Sraf 	self->ul_heldlocks.array = lockptr;
29914574Sraf 	self->ul_heldlockcnt *= 2;
29924574Sraf 	/*
29934574Sraf 	 * Return the next available entry in the newly allocated array.
29944574Sraf 	 */
29954574Sraf 	*(lockptr += nlocks) = lock;
29964574Sraf 	return (lockptr);
29974574Sraf }
29984574Sraf 
29994574Sraf /*
30004574Sraf  * Insert 'lock' into our list of held locks.
30014574Sraf  * Currently only used for LOCK_ROBUST mutexes.
30024574Sraf  */
30034574Sraf void
30044574Sraf remember_lock(mutex_t *lock)
30054574Sraf {
30064574Sraf 	(void) find_lock_entry(lock);
30074574Sraf }
30084574Sraf 
30094574Sraf /*
30104574Sraf  * Remove 'lock' from our list of held locks.
30114574Sraf  * Currently only used for LOCK_ROBUST mutexes.
30124574Sraf  */
30134574Sraf void
30144574Sraf forget_lock(mutex_t *lock)
30154574Sraf {
30164574Sraf 	*find_lock_entry(lock) = NULL;
30174574Sraf }
30184574Sraf 
30194574Sraf /*
30204574Sraf  * Free the array of held locks.
30214574Sraf  */
30224574Sraf void
30234574Sraf heldlock_free(ulwp_t *ulwp)
30244574Sraf {
30254574Sraf 	uint_t nlocks;
30264574Sraf 
30274574Sraf 	if ((nlocks = ulwp->ul_heldlockcnt) != 0)
30284574Sraf 		lfree(ulwp->ul_heldlocks.array, nlocks * sizeof (mutex_t *));
30294574Sraf 	ulwp->ul_heldlockcnt = 0;
30304574Sraf 	ulwp->ul_heldlocks.array = NULL;
30314574Sraf }
30324574Sraf 
30334574Sraf /*
30344574Sraf  * Mark all held LOCK_ROBUST mutexes LOCK_OWNERDEAD.
30354574Sraf  * Called from _thrp_exit() to deal with abandoned locks.
30364574Sraf  */
30374574Sraf void
30384574Sraf heldlock_exit(void)
30394574Sraf {
30404574Sraf 	ulwp_t *self = curthread;
30414574Sraf 	mutex_t **lockptr;
30424574Sraf 	uint_t nlocks;
30434574Sraf 	mutex_t *mp;
30444574Sraf 
30454574Sraf 	if ((nlocks = self->ul_heldlockcnt) != 0)
30464574Sraf 		lockptr = self->ul_heldlocks.array;
30474574Sraf 	else {
30484574Sraf 		nlocks = 1;
30494574Sraf 		lockptr = &self->ul_heldlocks.single;
30504574Sraf 	}
30514574Sraf 
30524574Sraf 	for (; nlocks; nlocks--, lockptr++) {
30534574Sraf 		/*
30544574Sraf 		 * The kernel takes care of transitioning held
30554574Sraf 		 * LOCK_PRIO_INHERIT mutexes to LOCK_OWNERDEAD.
30564574Sraf 		 * We avoid that case here.
30574574Sraf 		 */
30584574Sraf 		if ((mp = *lockptr) != NULL &&
30596812Sraf 		    mutex_held(mp) &&
30604574Sraf 		    (mp->mutex_type & (LOCK_ROBUST | LOCK_PRIO_INHERIT)) ==
30614574Sraf 		    LOCK_ROBUST) {
30624574Sraf 			mp->mutex_rcount = 0;
30634574Sraf 			if (!(mp->mutex_flag & LOCK_UNMAPPED))
30644574Sraf 				mp->mutex_flag |= LOCK_OWNERDEAD;
30654574Sraf 			(void) mutex_unlock_internal(mp, 1);
30664574Sraf 		}
30674574Sraf 	}
30684574Sraf 
30694574Sraf 	heldlock_free(self);
30704574Sraf }
30714574Sraf 
30726812Sraf #pragma weak _cond_init = cond_init
30730Sstevel@tonic-gate /* ARGSUSED2 */
30740Sstevel@tonic-gate int
30756812Sraf cond_init(cond_t *cvp, int type, void *arg)
30760Sstevel@tonic-gate {
30770Sstevel@tonic-gate 	if (type != USYNC_THREAD && type != USYNC_PROCESS)
30780Sstevel@tonic-gate 		return (EINVAL);
30796515Sraf 	(void) memset(cvp, 0, sizeof (*cvp));
30800Sstevel@tonic-gate 	cvp->cond_type = (uint16_t)type;
30810Sstevel@tonic-gate 	cvp->cond_magic = COND_MAGIC;
30827255Sraf 
30837255Sraf 	/*
30847255Sraf 	 * This should be at the beginning of the function,
30857255Sraf 	 * but for the sake of old broken applications that
30867255Sraf 	 * do not have proper alignment for their condvars
30877255Sraf 	 * (and don't check the return code from cond_init),
30887255Sraf 	 * we put it here, after initializing the condvar regardless.
30897255Sraf 	 */
30907255Sraf 	if (((uintptr_t)cvp & (_LONG_LONG_ALIGNMENT - 1)) &&
30917255Sraf 	    curthread->ul_misaligned == 0)
30927255Sraf 		return (EINVAL);
30937255Sraf 
30940Sstevel@tonic-gate 	return (0);
30950Sstevel@tonic-gate }
30960Sstevel@tonic-gate 
30970Sstevel@tonic-gate /*
30980Sstevel@tonic-gate  * cond_sleep_queue(): utility function for cond_wait_queue().
30990Sstevel@tonic-gate  *
31000Sstevel@tonic-gate  * Go to sleep on a condvar sleep queue, expect to be waked up
31010Sstevel@tonic-gate  * by someone calling cond_signal() or cond_broadcast() or due
31020Sstevel@tonic-gate  * to receiving a UNIX signal or being cancelled, or just simply
31030Sstevel@tonic-gate  * due to a spurious wakeup (like someome calling forkall()).
31040Sstevel@tonic-gate  *
31050Sstevel@tonic-gate  * The associated mutex is *not* reacquired before returning.
31060Sstevel@tonic-gate  * That must be done by the caller of cond_sleep_queue().
31070Sstevel@tonic-gate  */
31084574Sraf static int
31090Sstevel@tonic-gate cond_sleep_queue(cond_t *cvp, mutex_t *mp, timespec_t *tsp)
31100Sstevel@tonic-gate {
31110Sstevel@tonic-gate 	ulwp_t *self = curthread;
31120Sstevel@tonic-gate 	queue_head_t *qp;
31130Sstevel@tonic-gate 	queue_head_t *mqp;
31140Sstevel@tonic-gate 	lwpid_t lwpid;
31150Sstevel@tonic-gate 	int signalled;
31160Sstevel@tonic-gate 	int error;
31176247Sraf 	int cv_wake;
31184574Sraf 	int release_all;
31190Sstevel@tonic-gate 
31200Sstevel@tonic-gate 	/*
31210Sstevel@tonic-gate 	 * Put ourself on the CV sleep queue, unlock the mutex, then
31220Sstevel@tonic-gate 	 * park ourself and unpark a candidate lwp to grab the mutex.
31230Sstevel@tonic-gate 	 * We must go onto the CV sleep queue before dropping the
31240Sstevel@tonic-gate 	 * mutex in order to guarantee atomicity of the operation.
31250Sstevel@tonic-gate 	 */
31260Sstevel@tonic-gate 	self->ul_sp = stkptr();
31270Sstevel@tonic-gate 	qp = queue_lock(cvp, CV);
31286247Sraf 	enqueue(qp, self, 0);
31290Sstevel@tonic-gate 	cvp->cond_waiters_user = 1;
31300Sstevel@tonic-gate 	self->ul_cvmutex = mp;
31316247Sraf 	self->ul_cv_wake = cv_wake = (tsp != NULL);
31320Sstevel@tonic-gate 	self->ul_signalled = 0;
31334574Sraf 	if (mp->mutex_flag & LOCK_OWNERDEAD) {
31344574Sraf 		mp->mutex_flag &= ~LOCK_OWNERDEAD;
31354574Sraf 		mp->mutex_flag |= LOCK_NOTRECOVERABLE;
31364574Sraf 	}
31374574Sraf 	release_all = ((mp->mutex_flag & LOCK_NOTRECOVERABLE) != 0);
31384574Sraf 	lwpid = mutex_unlock_queue(mp, release_all);
31390Sstevel@tonic-gate 	for (;;) {
31400Sstevel@tonic-gate 		set_parking_flag(self, 1);
31410Sstevel@tonic-gate 		queue_unlock(qp);
31420Sstevel@tonic-gate 		if (lwpid != 0) {
31430Sstevel@tonic-gate 			lwpid = preempt_unpark(self, lwpid);
31440Sstevel@tonic-gate 			preempt(self);
31450Sstevel@tonic-gate 		}
31460Sstevel@tonic-gate 		/*
31470Sstevel@tonic-gate 		 * We may have a deferred signal present,
31480Sstevel@tonic-gate 		 * in which case we should return EINTR.
31490Sstevel@tonic-gate 		 * Also, we may have received a SIGCANCEL; if so
31500Sstevel@tonic-gate 		 * and we are cancelable we should return EINTR.
31510Sstevel@tonic-gate 		 * We force an immediate EINTR return from
31520Sstevel@tonic-gate 		 * __lwp_park() by turning our parking flag off.
31530Sstevel@tonic-gate 		 */
31540Sstevel@tonic-gate 		if (self->ul_cursig != 0 ||
31550Sstevel@tonic-gate 		    (self->ul_cancelable && self->ul_cancel_pending))
31560Sstevel@tonic-gate 			set_parking_flag(self, 0);
31570Sstevel@tonic-gate 		/*
31580Sstevel@tonic-gate 		 * __lwp_park() will return the residual time in tsp
31590Sstevel@tonic-gate 		 * if we are unparked before the timeout expires.
31600Sstevel@tonic-gate 		 */
31610Sstevel@tonic-gate 		error = __lwp_park(tsp, lwpid);
31620Sstevel@tonic-gate 		set_parking_flag(self, 0);
31630Sstevel@tonic-gate 		lwpid = 0;	/* unpark the other lwp only once */
31640Sstevel@tonic-gate 		/*
31650Sstevel@tonic-gate 		 * We were waked up by cond_signal(), cond_broadcast(),
31660Sstevel@tonic-gate 		 * by an interrupt or timeout (EINTR or ETIME),
31670Sstevel@tonic-gate 		 * or we may just have gotten a spurious wakeup.
31680Sstevel@tonic-gate 		 */
31690Sstevel@tonic-gate 		qp = queue_lock(cvp, CV);
31706247Sraf 		if (!cv_wake)
31716247Sraf 			mqp = queue_lock(mp, MX);
31720Sstevel@tonic-gate 		if (self->ul_sleepq == NULL)
31730Sstevel@tonic-gate 			break;
31740Sstevel@tonic-gate 		/*
31750Sstevel@tonic-gate 		 * We are on either the condvar sleep queue or the
31761893Sraf 		 * mutex sleep queue.  Break out of the sleep if we
31771893Sraf 		 * were interrupted or we timed out (EINTR or ETIME).
31780Sstevel@tonic-gate 		 * Else this is a spurious wakeup; continue the loop.
31790Sstevel@tonic-gate 		 */
31806247Sraf 		if (!cv_wake && self->ul_sleepq == mqp) { /* mutex queue */
31811893Sraf 			if (error) {
31826247Sraf 				mp->mutex_waiters = dequeue_self(mqp);
31831893Sraf 				break;
31841893Sraf 			}
31851893Sraf 			tsp = NULL;	/* no more timeout */
31861893Sraf 		} else if (self->ul_sleepq == qp) {	/* condvar queue */
31870Sstevel@tonic-gate 			if (error) {
31886247Sraf 				cvp->cond_waiters_user = dequeue_self(qp);
31890Sstevel@tonic-gate 				break;
31900Sstevel@tonic-gate 			}
31910Sstevel@tonic-gate 			/*
31920Sstevel@tonic-gate 			 * Else a spurious wakeup on the condvar queue.
31930Sstevel@tonic-gate 			 * __lwp_park() has already adjusted the timeout.
31940Sstevel@tonic-gate 			 */
31950Sstevel@tonic-gate 		} else {
31960Sstevel@tonic-gate 			thr_panic("cond_sleep_queue(): thread not on queue");
31970Sstevel@tonic-gate 		}
31986247Sraf 		if (!cv_wake)
31996247Sraf 			queue_unlock(mqp);
32000Sstevel@tonic-gate 	}
32010Sstevel@tonic-gate 
32020Sstevel@tonic-gate 	self->ul_sp = 0;
32036247Sraf 	self->ul_cv_wake = 0;
32046247Sraf 	ASSERT(self->ul_cvmutex == NULL);
32050Sstevel@tonic-gate 	ASSERT(self->ul_sleepq == NULL && self->ul_link == NULL &&
32060Sstevel@tonic-gate 	    self->ul_wchan == NULL);
32070Sstevel@tonic-gate 
32080Sstevel@tonic-gate 	signalled = self->ul_signalled;
32090Sstevel@tonic-gate 	self->ul_signalled = 0;
32100Sstevel@tonic-gate 	queue_unlock(qp);
32116247Sraf 	if (!cv_wake)
32126247Sraf 		queue_unlock(mqp);
32130Sstevel@tonic-gate 
32140Sstevel@tonic-gate 	/*
32150Sstevel@tonic-gate 	 * If we were concurrently cond_signal()d and any of:
32160Sstevel@tonic-gate 	 * received a UNIX signal, were cancelled, or got a timeout,
32170Sstevel@tonic-gate 	 * then perform another cond_signal() to avoid consuming it.
32180Sstevel@tonic-gate 	 */
32190Sstevel@tonic-gate 	if (error && signalled)
32206812Sraf 		(void) cond_signal(cvp);
32210Sstevel@tonic-gate 
32220Sstevel@tonic-gate 	return (error);
32230Sstevel@tonic-gate }
32240Sstevel@tonic-gate 
32257255Sraf static void
32267255Sraf cond_wait_check_alignment(cond_t *cvp, mutex_t *mp)
32277255Sraf {
32287255Sraf 	if ((uintptr_t)mp & (_LONG_LONG_ALIGNMENT - 1))
32297255Sraf 		lock_error(mp, "cond_wait", cvp, "mutex is misaligned");
32307255Sraf 	if ((uintptr_t)cvp & (_LONG_LONG_ALIGNMENT - 1))
32317255Sraf 		lock_error(mp, "cond_wait", cvp, "condvar is misaligned");
32327255Sraf }
32337255Sraf 
32340Sstevel@tonic-gate int
32355629Sraf cond_wait_queue(cond_t *cvp, mutex_t *mp, timespec_t *tsp)
32360Sstevel@tonic-gate {
32370Sstevel@tonic-gate 	ulwp_t *self = curthread;
32380Sstevel@tonic-gate 	int error;
32394574Sraf 	int merror;
32400Sstevel@tonic-gate 
32417255Sraf 	if (self->ul_error_detection && self->ul_misaligned == 0)
32427255Sraf 		cond_wait_check_alignment(cvp, mp);
32437255Sraf 
32440Sstevel@tonic-gate 	/*
32450Sstevel@tonic-gate 	 * The old thread library was programmed to defer signals
32460Sstevel@tonic-gate 	 * while in cond_wait() so that the associated mutex would
32470Sstevel@tonic-gate 	 * be guaranteed to be held when the application signal
32480Sstevel@tonic-gate 	 * handler was invoked.
32490Sstevel@tonic-gate 	 *
32500Sstevel@tonic-gate 	 * We do not behave this way by default; the state of the
32510Sstevel@tonic-gate 	 * associated mutex in the signal handler is undefined.
32520Sstevel@tonic-gate 	 *
32530Sstevel@tonic-gate 	 * To accommodate applications that depend on the old
32540Sstevel@tonic-gate 	 * behavior, the _THREAD_COND_WAIT_DEFER environment
32550Sstevel@tonic-gate 	 * variable can be set to 1 and we will behave in the
32560Sstevel@tonic-gate 	 * old way with respect to cond_wait().
32570Sstevel@tonic-gate 	 */
32580Sstevel@tonic-gate 	if (self->ul_cond_wait_defer)
32590Sstevel@tonic-gate 		sigoff(self);
32600Sstevel@tonic-gate 
32610Sstevel@tonic-gate 	error = cond_sleep_queue(cvp, mp, tsp);
32620Sstevel@tonic-gate 
32630Sstevel@tonic-gate 	/*
32640Sstevel@tonic-gate 	 * Reacquire the mutex.
32650Sstevel@tonic-gate 	 */
32665629Sraf 	if ((merror = mutex_lock_impl(mp, NULL)) != 0)
32674574Sraf 		error = merror;
32680Sstevel@tonic-gate 
32690Sstevel@tonic-gate 	/*
32700Sstevel@tonic-gate 	 * Take any deferred signal now, after we have reacquired the mutex.
32710Sstevel@tonic-gate 	 */
32720Sstevel@tonic-gate 	if (self->ul_cond_wait_defer)
32730Sstevel@tonic-gate 		sigon(self);
32740Sstevel@tonic-gate 
32750Sstevel@tonic-gate 	return (error);
32760Sstevel@tonic-gate }
32770Sstevel@tonic-gate 
32780Sstevel@tonic-gate /*
32790Sstevel@tonic-gate  * cond_sleep_kernel(): utility function for cond_wait_kernel().
32800Sstevel@tonic-gate  * See the comment ahead of cond_sleep_queue(), above.
32810Sstevel@tonic-gate  */
32824574Sraf static int
32830Sstevel@tonic-gate cond_sleep_kernel(cond_t *cvp, mutex_t *mp, timespec_t *tsp)
32840Sstevel@tonic-gate {
32850Sstevel@tonic-gate 	int mtype = mp->mutex_type;
32860Sstevel@tonic-gate 	ulwp_t *self = curthread;
32870Sstevel@tonic-gate 	int error;
32880Sstevel@tonic-gate 
32894574Sraf 	if ((mtype & LOCK_PRIO_PROTECT) && _ceil_mylist_del(mp))
32904574Sraf 		_ceil_prio_waive();
32910Sstevel@tonic-gate 
32920Sstevel@tonic-gate 	self->ul_sp = stkptr();
32930Sstevel@tonic-gate 	self->ul_wchan = cvp;
3294*7907SRoger.Faulkner@Sun.COM 	sigoff(self);
32950Sstevel@tonic-gate 	mp->mutex_owner = 0;
32966057Sraf 	/* mp->mutex_ownerpid is cleared by ___lwp_cond_wait() */
32976247Sraf 	if (mtype & LOCK_PRIO_INHERIT) {
32980Sstevel@tonic-gate 		mp->mutex_lockw = LOCKCLEAR;
32996247Sraf 		self->ul_pilocks--;
33006247Sraf 	}
33010Sstevel@tonic-gate 	/*
33020Sstevel@tonic-gate 	 * ___lwp_cond_wait() returns immediately with EINTR if
33030Sstevel@tonic-gate 	 * set_parking_flag(self,0) is called on this lwp before it
33040Sstevel@tonic-gate 	 * goes to sleep in the kernel.  sigacthandler() calls this
33050Sstevel@tonic-gate 	 * when a deferred signal is noted.  This assures that we don't
33060Sstevel@tonic-gate 	 * get stuck in ___lwp_cond_wait() with all signals blocked
33070Sstevel@tonic-gate 	 * due to taking a deferred signal before going to sleep.
33080Sstevel@tonic-gate 	 */
33090Sstevel@tonic-gate 	set_parking_flag(self, 1);
33100Sstevel@tonic-gate 	if (self->ul_cursig != 0 ||
33110Sstevel@tonic-gate 	    (self->ul_cancelable && self->ul_cancel_pending))
33120Sstevel@tonic-gate 		set_parking_flag(self, 0);
33130Sstevel@tonic-gate 	error = ___lwp_cond_wait(cvp, mp, tsp, 1);
33140Sstevel@tonic-gate 	set_parking_flag(self, 0);
3315*7907SRoger.Faulkner@Sun.COM 	sigon(self);
33160Sstevel@tonic-gate 	self->ul_sp = 0;
33170Sstevel@tonic-gate 	self->ul_wchan = NULL;
33180Sstevel@tonic-gate 	return (error);
33190Sstevel@tonic-gate }
33200Sstevel@tonic-gate 
33210Sstevel@tonic-gate int
33220Sstevel@tonic-gate cond_wait_kernel(cond_t *cvp, mutex_t *mp, timespec_t *tsp)
33230Sstevel@tonic-gate {
33240Sstevel@tonic-gate 	ulwp_t *self = curthread;
33250Sstevel@tonic-gate 	int error;
33260Sstevel@tonic-gate 	int merror;
33270Sstevel@tonic-gate 
33287255Sraf 	if (self->ul_error_detection && self->ul_misaligned == 0)
33297255Sraf 		cond_wait_check_alignment(cvp, mp);
33307255Sraf 
33310Sstevel@tonic-gate 	/*
33320Sstevel@tonic-gate 	 * See the large comment in cond_wait_queue(), above.
33330Sstevel@tonic-gate 	 */
33340Sstevel@tonic-gate 	if (self->ul_cond_wait_defer)
33350Sstevel@tonic-gate 		sigoff(self);
33360Sstevel@tonic-gate 
33370Sstevel@tonic-gate 	error = cond_sleep_kernel(cvp, mp, tsp);
33380Sstevel@tonic-gate 
33390Sstevel@tonic-gate 	/*
33400Sstevel@tonic-gate 	 * Override the return code from ___lwp_cond_wait()
33410Sstevel@tonic-gate 	 * with any non-zero return code from mutex_lock().
33420Sstevel@tonic-gate 	 * This addresses robust lock failures in particular;
33430Sstevel@tonic-gate 	 * the caller must see the EOWNERDEAD or ENOTRECOVERABLE
33440Sstevel@tonic-gate 	 * errors in order to take corrective action.
33450Sstevel@tonic-gate 	 */
33465629Sraf 	if ((merror = mutex_lock_impl(mp, NULL)) != 0)
33470Sstevel@tonic-gate 		error = merror;
33480Sstevel@tonic-gate 
33490Sstevel@tonic-gate 	/*
33500Sstevel@tonic-gate 	 * Take any deferred signal now, after we have reacquired the mutex.
33510Sstevel@tonic-gate 	 */
33520Sstevel@tonic-gate 	if (self->ul_cond_wait_defer)
33530Sstevel@tonic-gate 		sigon(self);
33540Sstevel@tonic-gate 
33550Sstevel@tonic-gate 	return (error);
33560Sstevel@tonic-gate }
33570Sstevel@tonic-gate 
33580Sstevel@tonic-gate /*
33596812Sraf  * Common code for cond_wait() and cond_timedwait()
33600Sstevel@tonic-gate  */
33610Sstevel@tonic-gate int
33620Sstevel@tonic-gate cond_wait_common(cond_t *cvp, mutex_t *mp, timespec_t *tsp)
33630Sstevel@tonic-gate {
33640Sstevel@tonic-gate 	int mtype = mp->mutex_type;
33650Sstevel@tonic-gate 	hrtime_t begin_sleep = 0;
33660Sstevel@tonic-gate 	ulwp_t *self = curthread;
33670Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
33680Sstevel@tonic-gate 	tdb_cond_stats_t *csp = COND_STATS(cvp, udp);
33690Sstevel@tonic-gate 	tdb_mutex_stats_t *msp = MUTEX_STATS(mp, udp);
33700Sstevel@tonic-gate 	uint8_t rcount;
33710Sstevel@tonic-gate 	int error = 0;
33720Sstevel@tonic-gate 
33730Sstevel@tonic-gate 	/*
33740Sstevel@tonic-gate 	 * The SUSV3 Posix spec for pthread_cond_timedwait() states:
33750Sstevel@tonic-gate 	 *	Except in the case of [ETIMEDOUT], all these error checks
33760Sstevel@tonic-gate 	 *	shall act as if they were performed immediately at the
33770Sstevel@tonic-gate 	 *	beginning of processing for the function and shall cause
33780Sstevel@tonic-gate 	 *	an error return, in effect, prior to modifying the state
33790Sstevel@tonic-gate 	 *	of the mutex specified by mutex or the condition variable
33800Sstevel@tonic-gate 	 *	specified by cond.
33810Sstevel@tonic-gate 	 * Therefore, we must return EINVAL now if the timout is invalid.
33820Sstevel@tonic-gate 	 */
33830Sstevel@tonic-gate 	if (tsp != NULL &&
33840Sstevel@tonic-gate 	    (tsp->tv_sec < 0 || (ulong_t)tsp->tv_nsec >= NANOSEC))
33850Sstevel@tonic-gate 		return (EINVAL);
33860Sstevel@tonic-gate 
33870Sstevel@tonic-gate 	if (__td_event_report(self, TD_SLEEP, udp)) {
33880Sstevel@tonic-gate 		self->ul_sp = stkptr();
33890Sstevel@tonic-gate 		self->ul_wchan = cvp;
33900Sstevel@tonic-gate 		self->ul_td_evbuf.eventnum = TD_SLEEP;
33910Sstevel@tonic-gate 		self->ul_td_evbuf.eventdata = cvp;
33920Sstevel@tonic-gate 		tdb_event(TD_SLEEP, udp);
33930Sstevel@tonic-gate 		self->ul_sp = 0;
33940Sstevel@tonic-gate 	}
33950Sstevel@tonic-gate 	if (csp) {
33960Sstevel@tonic-gate 		if (tsp)
33970Sstevel@tonic-gate 			tdb_incr(csp->cond_timedwait);
33980Sstevel@tonic-gate 		else
33990Sstevel@tonic-gate 			tdb_incr(csp->cond_wait);
34000Sstevel@tonic-gate 	}
34010Sstevel@tonic-gate 	if (msp)
34020Sstevel@tonic-gate 		begin_sleep = record_hold_time(msp);
34030Sstevel@tonic-gate 	else if (csp)
34040Sstevel@tonic-gate 		begin_sleep = gethrtime();
34050Sstevel@tonic-gate 
34060Sstevel@tonic-gate 	if (self->ul_error_detection) {
34076812Sraf 		if (!mutex_held(mp))
34080Sstevel@tonic-gate 			lock_error(mp, "cond_wait", cvp, NULL);
34090Sstevel@tonic-gate 		if ((mtype & LOCK_RECURSIVE) && mp->mutex_rcount != 0)
34100Sstevel@tonic-gate 			lock_error(mp, "recursive mutex in cond_wait",
34115629Sraf 			    cvp, NULL);
34120Sstevel@tonic-gate 		if (cvp->cond_type & USYNC_PROCESS) {
34134574Sraf 			if (!(mtype & USYNC_PROCESS))
34140Sstevel@tonic-gate 				lock_error(mp, "cond_wait", cvp,
34155629Sraf 				    "condvar process-shared, "
34165629Sraf 				    "mutex process-private");
34170Sstevel@tonic-gate 		} else {
34184574Sraf 			if (mtype & USYNC_PROCESS)
34190Sstevel@tonic-gate 				lock_error(mp, "cond_wait", cvp,
34205629Sraf 				    "condvar process-private, "
34215629Sraf 				    "mutex process-shared");
34220Sstevel@tonic-gate 		}
34230Sstevel@tonic-gate 	}
34240Sstevel@tonic-gate 
34250Sstevel@tonic-gate 	/*
34260Sstevel@tonic-gate 	 * We deal with recursive mutexes by completely
34270Sstevel@tonic-gate 	 * dropping the lock and restoring the recursion
34280Sstevel@tonic-gate 	 * count after waking up.  This is arguably wrong,
34290Sstevel@tonic-gate 	 * but it obeys the principle of least astonishment.
34300Sstevel@tonic-gate 	 */
34310Sstevel@tonic-gate 	rcount = mp->mutex_rcount;
34320Sstevel@tonic-gate 	mp->mutex_rcount = 0;
34334574Sraf 	if ((mtype &
34344574Sraf 	    (USYNC_PROCESS | LOCK_PRIO_INHERIT | LOCK_PRIO_PROTECT)) |
34350Sstevel@tonic-gate 	    (cvp->cond_type & USYNC_PROCESS))
34360Sstevel@tonic-gate 		error = cond_wait_kernel(cvp, mp, tsp);
34370Sstevel@tonic-gate 	else
34385629Sraf 		error = cond_wait_queue(cvp, mp, tsp);
34390Sstevel@tonic-gate 	mp->mutex_rcount = rcount;
34400Sstevel@tonic-gate 
34410Sstevel@tonic-gate 	if (csp) {
34420Sstevel@tonic-gate 		hrtime_t lapse = gethrtime() - begin_sleep;
34430Sstevel@tonic-gate 		if (tsp == NULL)
34440Sstevel@tonic-gate 			csp->cond_wait_sleep_time += lapse;
34450Sstevel@tonic-gate 		else {
34460Sstevel@tonic-gate 			csp->cond_timedwait_sleep_time += lapse;
34470Sstevel@tonic-gate 			if (error == ETIME)
34480Sstevel@tonic-gate 				tdb_incr(csp->cond_timedwait_timeout);
34490Sstevel@tonic-gate 		}
34500Sstevel@tonic-gate 	}
34510Sstevel@tonic-gate 	return (error);
34520Sstevel@tonic-gate }
34530Sstevel@tonic-gate 
34540Sstevel@tonic-gate /*
34556812Sraf  * cond_wait() is a cancellation point but __cond_wait() is not.
34566812Sraf  * Internally, libc calls the non-cancellation version.
34575891Sraf  * Other libraries need to use pthread_setcancelstate(), as appropriate,
34585891Sraf  * since __cond_wait() is not exported from libc.
34590Sstevel@tonic-gate  */
34600Sstevel@tonic-gate int
34615891Sraf __cond_wait(cond_t *cvp, mutex_t *mp)
34620Sstevel@tonic-gate {
34630Sstevel@tonic-gate 	ulwp_t *self = curthread;
34640Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
34650Sstevel@tonic-gate 	uberflags_t *gflags;
34660Sstevel@tonic-gate 
34670Sstevel@tonic-gate 	/*
34680Sstevel@tonic-gate 	 * Optimize the common case of USYNC_THREAD plus
34690Sstevel@tonic-gate 	 * no error detection, no lock statistics, and no event tracing.
34700Sstevel@tonic-gate 	 */
34710Sstevel@tonic-gate 	if ((gflags = self->ul_schedctl_called) != NULL &&
34720Sstevel@tonic-gate 	    (cvp->cond_type | mp->mutex_type | gflags->uf_trs_ted |
34730Sstevel@tonic-gate 	    self->ul_td_events_enable |
34740Sstevel@tonic-gate 	    udp->tdb.tdb_ev_global_mask.event_bits[0]) == 0)
34755629Sraf 		return (cond_wait_queue(cvp, mp, NULL));
34760Sstevel@tonic-gate 
34770Sstevel@tonic-gate 	/*
34780Sstevel@tonic-gate 	 * Else do it the long way.
34790Sstevel@tonic-gate 	 */
34800Sstevel@tonic-gate 	return (cond_wait_common(cvp, mp, NULL));
34810Sstevel@tonic-gate }
34820Sstevel@tonic-gate 
34836812Sraf #pragma weak _cond_wait = cond_wait
34840Sstevel@tonic-gate int
34856812Sraf cond_wait(cond_t *cvp, mutex_t *mp)
34860Sstevel@tonic-gate {
34870Sstevel@tonic-gate 	int error;
34880Sstevel@tonic-gate 
34890Sstevel@tonic-gate 	_cancelon();
34905891Sraf 	error = __cond_wait(cvp, mp);
34910Sstevel@tonic-gate 	if (error == EINTR)
34920Sstevel@tonic-gate 		_canceloff();
34930Sstevel@tonic-gate 	else
34940Sstevel@tonic-gate 		_canceloff_nocancel();
34950Sstevel@tonic-gate 	return (error);
34960Sstevel@tonic-gate }
34970Sstevel@tonic-gate 
34985891Sraf /*
34995891Sraf  * pthread_cond_wait() is a cancellation point.
35005891Sraf  */
35010Sstevel@tonic-gate int
35026812Sraf pthread_cond_wait(pthread_cond_t *_RESTRICT_KYWD cvp,
35036812Sraf 	pthread_mutex_t *_RESTRICT_KYWD mp)
35040Sstevel@tonic-gate {
35050Sstevel@tonic-gate 	int error;
35060Sstevel@tonic-gate 
35076812Sraf 	error = cond_wait((cond_t *)cvp, (mutex_t *)mp);
35080Sstevel@tonic-gate 	return ((error == EINTR)? 0 : error);
35090Sstevel@tonic-gate }
35100Sstevel@tonic-gate 
35110Sstevel@tonic-gate /*
35126812Sraf  * cond_timedwait() is a cancellation point but __cond_timedwait() is not.
35130Sstevel@tonic-gate  */
35140Sstevel@tonic-gate int
35155891Sraf __cond_timedwait(cond_t *cvp, mutex_t *mp, const timespec_t *abstime)
35160Sstevel@tonic-gate {
35170Sstevel@tonic-gate 	clockid_t clock_id = cvp->cond_clockid;
35180Sstevel@tonic-gate 	timespec_t reltime;
35190Sstevel@tonic-gate 	int error;
35200Sstevel@tonic-gate 
35210Sstevel@tonic-gate 	if (clock_id != CLOCK_REALTIME && clock_id != CLOCK_HIGHRES)
35220Sstevel@tonic-gate 		clock_id = CLOCK_REALTIME;
35230Sstevel@tonic-gate 	abstime_to_reltime(clock_id, abstime, &reltime);
35240Sstevel@tonic-gate 	error = cond_wait_common(cvp, mp, &reltime);
35250Sstevel@tonic-gate 	if (error == ETIME && clock_id == CLOCK_HIGHRES) {
35260Sstevel@tonic-gate 		/*
35270Sstevel@tonic-gate 		 * Don't return ETIME if we didn't really get a timeout.
35280Sstevel@tonic-gate 		 * This can happen if we return because someone resets
35290Sstevel@tonic-gate 		 * the system clock.  Just return zero in this case,
35300Sstevel@tonic-gate 		 * giving a spurious wakeup but not a timeout.
35310Sstevel@tonic-gate 		 */
35320Sstevel@tonic-gate 		if ((hrtime_t)(uint32_t)abstime->tv_sec * NANOSEC +
35330Sstevel@tonic-gate 		    abstime->tv_nsec > gethrtime())
35340Sstevel@tonic-gate 			error = 0;
35350Sstevel@tonic-gate 	}
35360Sstevel@tonic-gate 	return (error);
35370Sstevel@tonic-gate }
35380Sstevel@tonic-gate 
35390Sstevel@tonic-gate int
35406812Sraf cond_timedwait(cond_t *cvp, mutex_t *mp, const timespec_t *abstime)
35410Sstevel@tonic-gate {
35420Sstevel@tonic-gate 	int error;
35430Sstevel@tonic-gate 
35440Sstevel@tonic-gate 	_cancelon();
35455891Sraf 	error = __cond_timedwait(cvp, mp, abstime);
35460Sstevel@tonic-gate 	if (error == EINTR)
35470Sstevel@tonic-gate 		_canceloff();
35480Sstevel@tonic-gate 	else
35490Sstevel@tonic-gate 		_canceloff_nocancel();
35500Sstevel@tonic-gate 	return (error);
35510Sstevel@tonic-gate }
35520Sstevel@tonic-gate 
35535891Sraf /*
35545891Sraf  * pthread_cond_timedwait() is a cancellation point.
35555891Sraf  */
35560Sstevel@tonic-gate int
35576812Sraf pthread_cond_timedwait(pthread_cond_t *_RESTRICT_KYWD cvp,
35586812Sraf 	pthread_mutex_t *_RESTRICT_KYWD mp,
35596812Sraf 	const struct timespec *_RESTRICT_KYWD abstime)
35600Sstevel@tonic-gate {
35610Sstevel@tonic-gate 	int error;
35620Sstevel@tonic-gate 
35636812Sraf 	error = cond_timedwait((cond_t *)cvp, (mutex_t *)mp, abstime);
35640Sstevel@tonic-gate 	if (error == ETIME)
35650Sstevel@tonic-gate 		error = ETIMEDOUT;
35660Sstevel@tonic-gate 	else if (error == EINTR)
35670Sstevel@tonic-gate 		error = 0;
35680Sstevel@tonic-gate 	return (error);
35690Sstevel@tonic-gate }
35700Sstevel@tonic-gate 
35710Sstevel@tonic-gate /*
35726812Sraf  * cond_reltimedwait() is a cancellation point but __cond_reltimedwait() is not.
35730Sstevel@tonic-gate  */
35740Sstevel@tonic-gate int
35755891Sraf __cond_reltimedwait(cond_t *cvp, mutex_t *mp, const timespec_t *reltime)
35760Sstevel@tonic-gate {
35770Sstevel@tonic-gate 	timespec_t tslocal = *reltime;
35780Sstevel@tonic-gate 
35790Sstevel@tonic-gate 	return (cond_wait_common(cvp, mp, &tslocal));
35800Sstevel@tonic-gate }
35810Sstevel@tonic-gate 
35820Sstevel@tonic-gate int
35836812Sraf cond_reltimedwait(cond_t *cvp, mutex_t *mp, const timespec_t *reltime)
35840Sstevel@tonic-gate {
35850Sstevel@tonic-gate 	int error;
35860Sstevel@tonic-gate 
35870Sstevel@tonic-gate 	_cancelon();
35885891Sraf 	error = __cond_reltimedwait(cvp, mp, reltime);
35890Sstevel@tonic-gate 	if (error == EINTR)
35900Sstevel@tonic-gate 		_canceloff();
35910Sstevel@tonic-gate 	else
35920Sstevel@tonic-gate 		_canceloff_nocancel();
35930Sstevel@tonic-gate 	return (error);
35940Sstevel@tonic-gate }
35950Sstevel@tonic-gate 
35960Sstevel@tonic-gate int
35976812Sraf pthread_cond_reltimedwait_np(pthread_cond_t *_RESTRICT_KYWD cvp,
35986812Sraf 	pthread_mutex_t *_RESTRICT_KYWD mp,
35996812Sraf 	const struct timespec *_RESTRICT_KYWD reltime)
36000Sstevel@tonic-gate {
36010Sstevel@tonic-gate 	int error;
36020Sstevel@tonic-gate 
36036812Sraf 	error = cond_reltimedwait((cond_t *)cvp, (mutex_t *)mp, reltime);
36040Sstevel@tonic-gate 	if (error == ETIME)
36050Sstevel@tonic-gate 		error = ETIMEDOUT;
36060Sstevel@tonic-gate 	else if (error == EINTR)
36070Sstevel@tonic-gate 		error = 0;
36080Sstevel@tonic-gate 	return (error);
36090Sstevel@tonic-gate }
36100Sstevel@tonic-gate 
36116812Sraf #pragma weak pthread_cond_signal = cond_signal
36126812Sraf #pragma weak _cond_signal = cond_signal
36130Sstevel@tonic-gate int
36146812Sraf cond_signal(cond_t *cvp)
36150Sstevel@tonic-gate {
36160Sstevel@tonic-gate 	ulwp_t *self = curthread;
36170Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
36180Sstevel@tonic-gate 	tdb_cond_stats_t *csp = COND_STATS(cvp, udp);
36190Sstevel@tonic-gate 	int error = 0;
36206247Sraf 	int more;
36216247Sraf 	lwpid_t lwpid;
36220Sstevel@tonic-gate 	queue_head_t *qp;
36230Sstevel@tonic-gate 	mutex_t *mp;
36240Sstevel@tonic-gate 	queue_head_t *mqp;
36250Sstevel@tonic-gate 	ulwp_t **ulwpp;
36260Sstevel@tonic-gate 	ulwp_t *ulwp;
36276247Sraf 	ulwp_t *prev;
36280Sstevel@tonic-gate 
36290Sstevel@tonic-gate 	if (csp)
36300Sstevel@tonic-gate 		tdb_incr(csp->cond_signal);
36310Sstevel@tonic-gate 
36320Sstevel@tonic-gate 	if (cvp->cond_waiters_kernel)	/* someone sleeping in the kernel? */
36336812Sraf 		error = _lwp_cond_signal(cvp);
36340Sstevel@tonic-gate 
36350Sstevel@tonic-gate 	if (!cvp->cond_waiters_user)	/* no one sleeping at user-level */
36360Sstevel@tonic-gate 		return (error);
36370Sstevel@tonic-gate 
36380Sstevel@tonic-gate 	/*
36390Sstevel@tonic-gate 	 * Move someone from the condvar sleep queue to the mutex sleep
36400Sstevel@tonic-gate 	 * queue for the mutex that he will acquire on being waked up.
36410Sstevel@tonic-gate 	 * We can do this only if we own the mutex he will acquire.
36420Sstevel@tonic-gate 	 * If we do not own the mutex, or if his ul_cv_wake flag
36430Sstevel@tonic-gate 	 * is set, just dequeue and unpark him.
36440Sstevel@tonic-gate 	 */
36450Sstevel@tonic-gate 	qp = queue_lock(cvp, CV);
36466247Sraf 	ulwpp = queue_slot(qp, &prev, &more);
36476247Sraf 	cvp->cond_waiters_user = more;
36486247Sraf 	if (ulwpp == NULL) {	/* no one on the sleep queue */
36490Sstevel@tonic-gate 		queue_unlock(qp);
36500Sstevel@tonic-gate 		return (error);
36510Sstevel@tonic-gate 	}
36526247Sraf 	ulwp = *ulwpp;
36530Sstevel@tonic-gate 
36540Sstevel@tonic-gate 	/*
36550Sstevel@tonic-gate 	 * Inform the thread that he was the recipient of a cond_signal().
36560Sstevel@tonic-gate 	 * This lets him deal with cond_signal() and, concurrently,
36570Sstevel@tonic-gate 	 * one or more of a cancellation, a UNIX signal, or a timeout.
36580Sstevel@tonic-gate 	 * These latter conditions must not consume a cond_signal().
36590Sstevel@tonic-gate 	 */
36600Sstevel@tonic-gate 	ulwp->ul_signalled = 1;
36610Sstevel@tonic-gate 
36620Sstevel@tonic-gate 	/*
36630Sstevel@tonic-gate 	 * Dequeue the waiter but leave his ul_sleepq non-NULL
36640Sstevel@tonic-gate 	 * while we move him to the mutex queue so that he can
36650Sstevel@tonic-gate 	 * deal properly with spurious wakeups.
36660Sstevel@tonic-gate 	 */
36676247Sraf 	queue_unlink(qp, ulwpp, prev);
36680Sstevel@tonic-gate 
36690Sstevel@tonic-gate 	mp = ulwp->ul_cvmutex;		/* the mutex he will acquire */
36700Sstevel@tonic-gate 	ulwp->ul_cvmutex = NULL;
36710Sstevel@tonic-gate 	ASSERT(mp != NULL);
36720Sstevel@tonic-gate 
36730Sstevel@tonic-gate 	if (ulwp->ul_cv_wake || !MUTEX_OWNED(mp, self)) {
36746247Sraf 		/* just wake him up */
36756247Sraf 		lwpid = ulwp->ul_lwpid;
36760Sstevel@tonic-gate 		no_preempt(self);
36770Sstevel@tonic-gate 		ulwp->ul_sleepq = NULL;
36780Sstevel@tonic-gate 		ulwp->ul_wchan = NULL;
36790Sstevel@tonic-gate 		queue_unlock(qp);
36800Sstevel@tonic-gate 		(void) __lwp_unpark(lwpid);
36810Sstevel@tonic-gate 		preempt(self);
36820Sstevel@tonic-gate 	} else {
36836247Sraf 		/* move him to the mutex queue */
36840Sstevel@tonic-gate 		mqp = queue_lock(mp, MX);
36856247Sraf 		enqueue(mqp, ulwp, 0);
36860Sstevel@tonic-gate 		mp->mutex_waiters = 1;
36870Sstevel@tonic-gate 		queue_unlock(mqp);
36880Sstevel@tonic-gate 		queue_unlock(qp);
36890Sstevel@tonic-gate 	}
36900Sstevel@tonic-gate 
36910Sstevel@tonic-gate 	return (error);
36920Sstevel@tonic-gate }
36930Sstevel@tonic-gate 
36944570Sraf /*
36954574Sraf  * Utility function called by mutex_wakeup_all(), cond_broadcast(),
36964574Sraf  * and rw_queue_release() to (re)allocate a big buffer to hold the
36974574Sraf  * lwpids of all the threads to be set running after they are removed
36984574Sraf  * from their sleep queues.  Since we are holding a queue lock, we
36994574Sraf  * cannot call any function that might acquire a lock.  mmap(), munmap(),
37004574Sraf  * lwp_unpark_all() are simple system calls and are safe in this regard.
37014570Sraf  */
37024570Sraf lwpid_t *
37034570Sraf alloc_lwpids(lwpid_t *lwpid, int *nlwpid_ptr, int *maxlwps_ptr)
37044570Sraf {
37054570Sraf 	/*
37064570Sraf 	 * Allocate NEWLWPS ids on the first overflow.
37074570Sraf 	 * Double the allocation each time after that.
37084570Sraf 	 */
37094570Sraf 	int nlwpid = *nlwpid_ptr;
37104570Sraf 	int maxlwps = *maxlwps_ptr;
37114570Sraf 	int first_allocation;
37124570Sraf 	int newlwps;
37134570Sraf 	void *vaddr;
37144570Sraf 
37154570Sraf 	ASSERT(nlwpid == maxlwps);
37164570Sraf 
37174570Sraf 	first_allocation = (maxlwps == MAXLWPS);
37184570Sraf 	newlwps = first_allocation? NEWLWPS : 2 * maxlwps;
37196515Sraf 	vaddr = mmap(NULL, newlwps * sizeof (lwpid_t),
37204570Sraf 	    PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, (off_t)0);
37214570Sraf 
37224570Sraf 	if (vaddr == MAP_FAILED) {
37234570Sraf 		/*
37244570Sraf 		 * Let's hope this never happens.
37254570Sraf 		 * If it does, then we have a terrible
37264570Sraf 		 * thundering herd on our hands.
37274570Sraf 		 */
37284570Sraf 		(void) __lwp_unpark_all(lwpid, nlwpid);
37294570Sraf 		*nlwpid_ptr = 0;
37304570Sraf 	} else {
37316515Sraf 		(void) memcpy(vaddr, lwpid, maxlwps * sizeof (lwpid_t));
37324570Sraf 		if (!first_allocation)
37336515Sraf 			(void) munmap((caddr_t)lwpid,
37344570Sraf 			    maxlwps * sizeof (lwpid_t));
37354570Sraf 		lwpid = vaddr;
37364570Sraf 		*maxlwps_ptr = newlwps;
37374570Sraf 	}
37384570Sraf 
37394570Sraf 	return (lwpid);
37404570Sraf }
37410Sstevel@tonic-gate 
37426812Sraf #pragma weak pthread_cond_broadcast = cond_broadcast
37436812Sraf #pragma weak _cond_broadcast = cond_broadcast
37440Sstevel@tonic-gate int
37456812Sraf cond_broadcast(cond_t *cvp)
37460Sstevel@tonic-gate {
37470Sstevel@tonic-gate 	ulwp_t *self = curthread;
37480Sstevel@tonic-gate 	uberdata_t *udp = self->ul_uberdata;
37490Sstevel@tonic-gate 	tdb_cond_stats_t *csp = COND_STATS(cvp, udp);
37500Sstevel@tonic-gate 	int error = 0;
37510Sstevel@tonic-gate 	queue_head_t *qp;
37526247Sraf 	queue_root_t *qrp;
37530Sstevel@tonic-gate 	mutex_t *mp;
37540Sstevel@tonic-gate 	mutex_t *mp_cache = NULL;
37554570Sraf 	queue_head_t *mqp = NULL;
37560Sstevel@tonic-gate 	ulwp_t *ulwp;
37574570Sraf 	int nlwpid = 0;
37584570Sraf 	int maxlwps = MAXLWPS;
37590Sstevel@tonic-gate 	lwpid_t buffer[MAXLWPS];
37600Sstevel@tonic-gate 	lwpid_t *lwpid = buffer;
37610Sstevel@tonic-gate 
37620Sstevel@tonic-gate 	if (csp)
37630Sstevel@tonic-gate 		tdb_incr(csp->cond_broadcast);
37640Sstevel@tonic-gate 
37650Sstevel@tonic-gate 	if (cvp->cond_waiters_kernel)	/* someone sleeping in the kernel? */
37666812Sraf 		error = _lwp_cond_broadcast(cvp);
37670Sstevel@tonic-gate 
37680Sstevel@tonic-gate 	if (!cvp->cond_waiters_user)	/* no one sleeping at user-level */
37690Sstevel@tonic-gate 		return (error);
37700Sstevel@tonic-gate 
37710Sstevel@tonic-gate 	/*
37720Sstevel@tonic-gate 	 * Move everyone from the condvar sleep queue to the mutex sleep
37730Sstevel@tonic-gate 	 * queue for the mutex that they will acquire on being waked up.
37740Sstevel@tonic-gate 	 * We can do this only if we own the mutex they will acquire.
37750Sstevel@tonic-gate 	 * If we do not own the mutex, or if their ul_cv_wake flag
37760Sstevel@tonic-gate 	 * is set, just dequeue and unpark them.
37770Sstevel@tonic-gate 	 *
37780Sstevel@tonic-gate 	 * We keep track of lwpids that are to be unparked in lwpid[].
37790Sstevel@tonic-gate 	 * __lwp_unpark_all() is called to unpark all of them after
37800Sstevel@tonic-gate 	 * they have been removed from the sleep queue and the sleep
37810Sstevel@tonic-gate 	 * queue lock has been dropped.  If we run out of space in our
37820Sstevel@tonic-gate 	 * on-stack buffer, we need to allocate more but we can't call
37830Sstevel@tonic-gate 	 * lmalloc() because we are holding a queue lock when the overflow
37840Sstevel@tonic-gate 	 * occurs and lmalloc() acquires a lock.  We can't use alloca()
37854570Sraf 	 * either because the application may have allocated a small
37864570Sraf 	 * stack and we don't want to overrun the stack.  So we call
37874570Sraf 	 * alloc_lwpids() to allocate a bigger buffer using the mmap()
37880Sstevel@tonic-gate 	 * system call directly since that path acquires no locks.
37890Sstevel@tonic-gate 	 */
37900Sstevel@tonic-gate 	qp = queue_lock(cvp, CV);
37910Sstevel@tonic-gate 	cvp->cond_waiters_user = 0;
37926247Sraf 	for (;;) {
37936247Sraf 		if ((qrp = qp->qh_root) == NULL ||
37946247Sraf 		    (ulwp = qrp->qr_head) == NULL)
37956247Sraf 			break;
37966247Sraf 		ASSERT(ulwp->ul_wchan == cvp);
37976247Sraf 		queue_unlink(qp, &qrp->qr_head, NULL);
37980Sstevel@tonic-gate 		mp = ulwp->ul_cvmutex;		/* his mutex */
37990Sstevel@tonic-gate 		ulwp->ul_cvmutex = NULL;
38000Sstevel@tonic-gate 		ASSERT(mp != NULL);
38010Sstevel@tonic-gate 		if (ulwp->ul_cv_wake || !MUTEX_OWNED(mp, self)) {
38026247Sraf 			/* just wake him up */
38030Sstevel@tonic-gate 			ulwp->ul_sleepq = NULL;
38040Sstevel@tonic-gate 			ulwp->ul_wchan = NULL;
38054570Sraf 			if (nlwpid == maxlwps)
38064570Sraf 				lwpid = alloc_lwpids(lwpid, &nlwpid, &maxlwps);
38070Sstevel@tonic-gate 			lwpid[nlwpid++] = ulwp->ul_lwpid;
38080Sstevel@tonic-gate 		} else {
38096247Sraf 			/* move him to the mutex queue */
38100Sstevel@tonic-gate 			if (mp != mp_cache) {
38110Sstevel@tonic-gate 				mp_cache = mp;
38124570Sraf 				if (mqp != NULL)
38134570Sraf 					queue_unlock(mqp);
38144570Sraf 				mqp = queue_lock(mp, MX);
38150Sstevel@tonic-gate 			}
38166247Sraf 			enqueue(mqp, ulwp, 0);
38170Sstevel@tonic-gate 			mp->mutex_waiters = 1;
38180Sstevel@tonic-gate 		}
38190Sstevel@tonic-gate 	}
38204570Sraf 	if (mqp != NULL)
38214570Sraf 		queue_unlock(mqp);
38224570Sraf 	if (nlwpid == 0) {
38234570Sraf 		queue_unlock(qp);
38244570Sraf 	} else {
38254570Sraf 		no_preempt(self);
38264570Sraf 		queue_unlock(qp);
38270Sstevel@tonic-gate 		if (nlwpid == 1)
38280Sstevel@tonic-gate 			(void) __lwp_unpark(lwpid[0]);
38290Sstevel@tonic-gate 		else
38300Sstevel@tonic-gate 			(void) __lwp_unpark_all(lwpid, nlwpid);
38314570Sraf 		preempt(self);
38320Sstevel@tonic-gate 	}
38330Sstevel@tonic-gate 	if (lwpid != buffer)
38346515Sraf 		(void) munmap((caddr_t)lwpid, maxlwps * sizeof (lwpid_t));
38350Sstevel@tonic-gate 	return (error);
38360Sstevel@tonic-gate }
38370Sstevel@tonic-gate 
38386812Sraf #pragma weak pthread_cond_destroy = cond_destroy
38390Sstevel@tonic-gate int
38406812Sraf cond_destroy(cond_t *cvp)
38410Sstevel@tonic-gate {
38420Sstevel@tonic-gate 	cvp->cond_magic = 0;
38430Sstevel@tonic-gate 	tdb_sync_obj_deregister(cvp);
38440Sstevel@tonic-gate 	return (0);
38450Sstevel@tonic-gate }
38460Sstevel@tonic-gate 
38470Sstevel@tonic-gate #if defined(THREAD_DEBUG)
38480Sstevel@tonic-gate void
38490Sstevel@tonic-gate assert_no_libc_locks_held(void)
38500Sstevel@tonic-gate {
38510Sstevel@tonic-gate 	ASSERT(!curthread->ul_critical || curthread->ul_bindflags);
38520Sstevel@tonic-gate }
38530Sstevel@tonic-gate 
38540Sstevel@tonic-gate /* protected by link_lock */
38550Sstevel@tonic-gate uint64_t spin_lock_spin;
38560Sstevel@tonic-gate uint64_t spin_lock_spin2;
38570Sstevel@tonic-gate uint64_t spin_lock_sleep;
38580Sstevel@tonic-gate uint64_t spin_lock_wakeup;
38590Sstevel@tonic-gate 
38600Sstevel@tonic-gate /*
38610Sstevel@tonic-gate  * Record spin lock statistics.
38620Sstevel@tonic-gate  * Called by a thread exiting itself in thrp_exit().
38630Sstevel@tonic-gate  * Also called via atexit() from the thread calling
38640Sstevel@tonic-gate  * exit() to do all the other threads as well.
38650Sstevel@tonic-gate  */
38660Sstevel@tonic-gate void
38670Sstevel@tonic-gate record_spin_locks(ulwp_t *ulwp)
38680Sstevel@tonic-gate {
38690Sstevel@tonic-gate 	spin_lock_spin += ulwp->ul_spin_lock_spin;
38700Sstevel@tonic-gate 	spin_lock_spin2 += ulwp->ul_spin_lock_spin2;
38710Sstevel@tonic-gate 	spin_lock_sleep += ulwp->ul_spin_lock_sleep;
38720Sstevel@tonic-gate 	spin_lock_wakeup += ulwp->ul_spin_lock_wakeup;
38730Sstevel@tonic-gate 	ulwp->ul_spin_lock_spin = 0;
38740Sstevel@tonic-gate 	ulwp->ul_spin_lock_spin2 = 0;
38750Sstevel@tonic-gate 	ulwp->ul_spin_lock_sleep = 0;
38760Sstevel@tonic-gate 	ulwp->ul_spin_lock_wakeup = 0;
38770Sstevel@tonic-gate }
38780Sstevel@tonic-gate 
38790Sstevel@tonic-gate /*
38800Sstevel@tonic-gate  * atexit function:  dump the queue statistics to stderr.
38810Sstevel@tonic-gate  */
38820Sstevel@tonic-gate #include <stdio.h>
38830Sstevel@tonic-gate void
38840Sstevel@tonic-gate dump_queue_statistics(void)
38850Sstevel@tonic-gate {
38860Sstevel@tonic-gate 	uberdata_t *udp = curthread->ul_uberdata;
38870Sstevel@tonic-gate 	queue_head_t *qp;
38880Sstevel@tonic-gate 	int qn;
38890Sstevel@tonic-gate 	uint64_t spin_lock_total = 0;
38900Sstevel@tonic-gate 
38910Sstevel@tonic-gate 	if (udp->queue_head == NULL || thread_queue_dump == 0)
38920Sstevel@tonic-gate 		return;
38930Sstevel@tonic-gate 
38940Sstevel@tonic-gate 	if (fprintf(stderr, "\n%5d mutex queues:\n", QHASHSIZE) < 0 ||
38956247Sraf 	    fprintf(stderr, "queue#   lockcount    max qlen    max hlen\n") < 0)
38960Sstevel@tonic-gate 		return;
38970Sstevel@tonic-gate 	for (qn = 0, qp = udp->queue_head; qn < QHASHSIZE; qn++, qp++) {
38980Sstevel@tonic-gate 		if (qp->qh_lockcount == 0)
38990Sstevel@tonic-gate 			continue;
39000Sstevel@tonic-gate 		spin_lock_total += qp->qh_lockcount;
39016247Sraf 		if (fprintf(stderr, "%5d %12llu%12u%12u\n", qn,
39026247Sraf 		    (u_longlong_t)qp->qh_lockcount,
39036247Sraf 		    qp->qh_qmax, qp->qh_hmax) < 0)
39045629Sraf 			return;
39050Sstevel@tonic-gate 	}
39060Sstevel@tonic-gate 
39070Sstevel@tonic-gate 	if (fprintf(stderr, "\n%5d condvar queues:\n", QHASHSIZE) < 0 ||
39086247Sraf 	    fprintf(stderr, "queue#   lockcount    max qlen    max hlen\n") < 0)
39090Sstevel@tonic-gate 		return;
39100Sstevel@tonic-gate 	for (qn = 0; qn < QHASHSIZE; qn++, qp++) {
39110Sstevel@tonic-gate 		if (qp->qh_lockcount == 0)
39120Sstevel@tonic-gate 			continue;
39130Sstevel@tonic-gate 		spin_lock_total += qp->qh_lockcount;
39146247Sraf 		if (fprintf(stderr, "%5d %12llu%12u%12u\n", qn,
39156247Sraf 		    (u_longlong_t)qp->qh_lockcount,
39166247Sraf 		    qp->qh_qmax, qp->qh_hmax) < 0)
39175629Sraf 			return;
39180Sstevel@tonic-gate 	}
39190Sstevel@tonic-gate 
39200Sstevel@tonic-gate 	(void) fprintf(stderr, "\n  spin_lock_total  = %10llu\n",
39215629Sraf 	    (u_longlong_t)spin_lock_total);
39220Sstevel@tonic-gate 	(void) fprintf(stderr, "  spin_lock_spin   = %10llu\n",
39235629Sraf 	    (u_longlong_t)spin_lock_spin);
39240Sstevel@tonic-gate 	(void) fprintf(stderr, "  spin_lock_spin2  = %10llu\n",
39255629Sraf 	    (u_longlong_t)spin_lock_spin2);
39260Sstevel@tonic-gate 	(void) fprintf(stderr, "  spin_lock_sleep  = %10llu\n",
39275629Sraf 	    (u_longlong_t)spin_lock_sleep);
39280Sstevel@tonic-gate 	(void) fprintf(stderr, "  spin_lock_wakeup = %10llu\n",
39295629Sraf 	    (u_longlong_t)spin_lock_wakeup);
39300Sstevel@tonic-gate }
39316247Sraf #endif
3932