subr_turnstile.c revision 161337
1/*-
2 * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 * 3. Berkeley Software Design Inc's name may not be used to endorse or
13 *    promote products derived from this software without specific prior
14 *    written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
29 *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
30 */
31
32/*
33 * Implementation of turnstiles used to hold queue of threads blocked on
34 * non-sleepable locks.  Sleepable locks use condition variables to
35 * implement their queues.  Turnstiles differ from a sleep queue in that
36 * turnstile queue's are assigned to a lock held by an owning thread.  Thus,
37 * when one thread is enqueued onto a turnstile, it can lend its priority
38 * to the owning thread.
39 *
40 * We wish to avoid bloating locks with an embedded turnstile and we do not
41 * want to use back-pointers in the locks for the same reason.  Thus, we
42 * use a similar approach to that of Solaris 7 as described in Solaris
43 * Internals by Jim Mauro and Richard McDougall.  Turnstiles are looked up
44 * in a hash table based on the address of the lock.  Each entry in the
45 * hash table is a linked-lists of turnstiles and is called a turnstile
46 * chain.  Each chain contains a spin mutex that protects all of the
47 * turnstiles in the chain.
48 *
49 * Each time a thread is created, a turnstile is malloc'd and attached to
50 * that thread.  When a thread blocks on a lock, if it is the first thread
51 * to block, it lends its turnstile to the lock.  If the lock already has
52 * a turnstile, then it gives its turnstile to the lock's turnstile's free
53 * list.  When a thread is woken up, it takes a turnstile from the free list
54 * if there are any other waiters.  If it is the only thread blocked on the
55 * lock, then it reclaims the turnstile associated with the lock and removes
56 * it from the hash table.
57 */
58
59#include <sys/cdefs.h>
60__FBSDID("$FreeBSD: head/sys/kern/subr_turnstile.c 161337 2006-08-15 18:29:01Z jhb $");
61
62#include "opt_ddb.h"
63#include "opt_turnstile_profiling.h"
64
65#include <sys/param.h>
66#include <sys/systm.h>
67#include <sys/kernel.h>
68#include <sys/ktr.h>
69#include <sys/lock.h>
70#include <sys/malloc.h>
71#include <sys/mutex.h>
72#include <sys/proc.h>
73#include <sys/queue.h>
74#include <sys/sched.h>
75#include <sys/sysctl.h>
76#include <sys/turnstile.h>
77
78#ifdef DDB
79#include <sys/kdb.h>
80#include <ddb/ddb.h>
81#include <sys/lockmgr.h>
82#include <sys/sx.h>
83#endif
84
85/*
86 * Constants for the hash table of turnstile chains.  TC_SHIFT is a magic
87 * number chosen because the sleep queue's use the same value for the
88 * shift.  Basically, we ignore the lower 8 bits of the address.
89 * TC_TABLESIZE must be a power of two for TC_MASK to work properly.
90 */
91#define	TC_TABLESIZE	128			/* Must be power of 2. */
92#define	TC_MASK		(TC_TABLESIZE - 1)
93#define	TC_SHIFT	8
94#define	TC_HASH(lock)	(((uintptr_t)(lock) >> TC_SHIFT) & TC_MASK)
95#define	TC_LOOKUP(lock)	&turnstile_chains[TC_HASH(lock)]
96
97/*
98 * There are three different lists of turnstiles as follows.  The list
99 * connected by ts_link entries is a per-thread list of all the turnstiles
100 * attached to locks that we own.  This is used to fixup our priority when
101 * a lock is released.  The other two lists use the ts_hash entries.  The
102 * first of these two is the turnstile chain list that a turnstile is on
103 * when it is attached to a lock.  The second list to use ts_hash is the
104 * free list hung off of a turnstile that is attached to a lock.
105 *
106 * Each turnstile contains three lists of threads.  The two ts_blocked lists
107 * are linked list of threads blocked on the turnstile's lock.  One list is
108 * for exclusive waiters, and the other is for shared waiters.  The
109 * ts_pending list is a linked list of threads previously awakened by
110 * turnstile_signal() or turnstile_wait() that are waiting to be put on
111 * the run queue.
112 *
113 * Locking key:
114 *  c - turnstile chain lock
115 *  q - td_contested lock
116 */
117struct turnstile {
118	struct threadqueue ts_blocked[2];	/* (c + q) Blocked threads. */
119	struct threadqueue ts_pending;		/* (c) Pending threads. */
120	LIST_ENTRY(turnstile) ts_hash;		/* (c) Chain and free list. */
121	LIST_ENTRY(turnstile) ts_link;		/* (q) Contested locks. */
122	LIST_HEAD(, turnstile) ts_free;		/* (c) Free turnstiles. */
123	struct lock_object *ts_lockobj;		/* (c) Lock we reference. */
124	struct thread *ts_owner;		/* (c + q) Who owns the lock. */
125};
126
127struct turnstile_chain {
128	LIST_HEAD(, turnstile) tc_turnstiles;	/* List of turnstiles. */
129	struct mtx tc_lock;			/* Spin lock for this chain. */
130#ifdef TURNSTILE_PROFILING
131	u_int	tc_depth;			/* Length of tc_queues. */
132	u_int	tc_max_depth;			/* Max length of tc_queues. */
133#endif
134};
135
136#ifdef TURNSTILE_PROFILING
137u_int turnstile_max_depth;
138SYSCTL_NODE(_debug, OID_AUTO, turnstile, CTLFLAG_RD, 0, "turnstile profiling");
139SYSCTL_NODE(_debug_turnstile, OID_AUTO, chains, CTLFLAG_RD, 0,
140    "turnstile chain stats");
141SYSCTL_UINT(_debug_turnstile, OID_AUTO, max_depth, CTLFLAG_RD,
142    &turnstile_max_depth, 0, "maxmimum depth achieved of a single chain");
143#endif
144static struct mtx td_contested_lock;
145static struct turnstile_chain turnstile_chains[TC_TABLESIZE];
146
147static MALLOC_DEFINE(M_TURNSTILE, "turnstiles", "turnstiles");
148
149/*
150 * Prototypes for non-exported routines.
151 */
152static void	init_turnstile0(void *dummy);
153#ifdef TURNSTILE_PROFILING
154static void	init_turnstile_profiling(void *arg);
155#endif
156static void	propagate_priority(struct thread *td);
157static int	turnstile_adjust_thread(struct turnstile *ts,
158		    struct thread *td);
159static struct thread *turnstile_first_waiter(struct turnstile *ts);
160static void	turnstile_setowner(struct turnstile *ts, struct thread *owner);
161
162/*
163 * Walks the chain of turnstiles and their owners to propagate the priority
164 * of the thread being blocked to all the threads holding locks that have to
165 * release their locks before this thread can run again.
166 */
167static void
168propagate_priority(struct thread *td)
169{
170	struct turnstile_chain *tc;
171	struct turnstile *ts;
172	int pri;
173
174	mtx_assert(&sched_lock, MA_OWNED);
175	pri = td->td_priority;
176	ts = td->td_blocked;
177	for (;;) {
178		td = ts->ts_owner;
179
180		if (td == NULL) {
181			/*
182			 * This might be a read lock with no owner.  There's
183			 * not much we can do, so just bail.
184			 */
185			return;
186		}
187
188		MPASS(td->td_proc != NULL);
189		MPASS(td->td_proc->p_magic == P_MAGIC);
190
191		/*
192		 * If the thread is asleep, then we are probably about
193		 * to deadlock.  To make debugging this easier, just
194		 * panic and tell the user which thread misbehaved so
195		 * they can hopefully get a stack trace from the truly
196		 * misbehaving thread.
197		 */
198		if (TD_IS_SLEEPING(td)) {
199			printf(
200		"Sleeping thread (tid %d, pid %d) owns a non-sleepable lock\n",
201			    td->td_tid, td->td_proc->p_pid);
202#ifdef DDB
203			db_trace_thread(td, -1);
204#endif
205			panic("sleeping thread");
206		}
207
208		/*
209		 * If this thread already has higher priority than the
210		 * thread that is being blocked, we are finished.
211		 */
212		if (td->td_priority <= pri)
213			return;
214
215		/*
216		 * Bump this thread's priority.
217		 */
218		sched_lend_prio(td, pri);
219
220		/*
221		 * If lock holder is actually running or on the run queue
222		 * then we are done.
223		 */
224		if (TD_IS_RUNNING(td) || TD_ON_RUNQ(td)) {
225			MPASS(td->td_blocked == NULL);
226			return;
227		}
228
229#ifndef SMP
230		/*
231		 * For UP, we check to see if td is curthread (this shouldn't
232		 * ever happen however as it would mean we are in a deadlock.)
233		 */
234		KASSERT(td != curthread, ("Deadlock detected"));
235#endif
236
237		/*
238		 * If we aren't blocked on a lock, we should be.
239		 */
240		KASSERT(TD_ON_LOCK(td), (
241		    "thread %d(%s):%d holds %s but isn't blocked on a lock\n",
242		    td->td_tid, td->td_proc->p_comm, td->td_state,
243		    ts->ts_lockobj->lo_name));
244
245		/*
246		 * Pick up the lock that td is blocked on.
247		 */
248		ts = td->td_blocked;
249		MPASS(ts != NULL);
250		tc = TC_LOOKUP(ts->ts_lockobj);
251		mtx_lock_spin(&tc->tc_lock);
252
253		/* Resort td on the list if needed. */
254		if (!turnstile_adjust_thread(ts, td)) {
255			mtx_unlock_spin(&tc->tc_lock);
256			return;
257		}
258		mtx_unlock_spin(&tc->tc_lock);
259	}
260}
261
262/*
263 * Adjust the thread's position on a turnstile after its priority has been
264 * changed.
265 */
266static int
267turnstile_adjust_thread(struct turnstile *ts, struct thread *td)
268{
269	struct turnstile_chain *tc;
270	struct thread *td1, *td2;
271	int queue;
272
273	mtx_assert(&sched_lock, MA_OWNED);
274	MPASS(TD_ON_LOCK(td));
275
276	/*
277	 * This thread may not be blocked on this turnstile anymore
278	 * but instead might already be woken up on another CPU
279	 * that is waiting on sched_lock in turnstile_unpend() to
280	 * finish waking this thread up.  We can detect this case
281	 * by checking to see if this thread has been given a
282	 * turnstile by either turnstile_signal() or
283	 * turnstile_broadcast().  In this case, treat the thread as
284	 * if it was already running.
285	 */
286	if (td->td_turnstile != NULL)
287		return (0);
288
289	/*
290	 * Check if the thread needs to be moved on the blocked chain.
291	 * It needs to be moved if either its priority is lower than
292	 * the previous thread or higher than the next thread.
293	 */
294	tc = TC_LOOKUP(ts->ts_lockobj);
295	mtx_assert(&tc->tc_lock, MA_OWNED);
296	td1 = TAILQ_PREV(td, threadqueue, td_lockq);
297	td2 = TAILQ_NEXT(td, td_lockq);
298	if ((td1 != NULL && td->td_priority < td1->td_priority) ||
299	    (td2 != NULL && td->td_priority > td2->td_priority)) {
300
301		/*
302		 * Remove thread from blocked chain and determine where
303		 * it should be moved to.
304		 */
305		queue = td->td_tsqueue;
306		MPASS(queue == TS_EXCLUSIVE_QUEUE || queue == TS_SHARED_QUEUE);
307		mtx_lock_spin(&td_contested_lock);
308		TAILQ_REMOVE(&ts->ts_blocked[queue], td, td_lockq);
309		TAILQ_FOREACH(td1, &ts->ts_blocked[queue], td_lockq) {
310			MPASS(td1->td_proc->p_magic == P_MAGIC);
311			if (td1->td_priority > td->td_priority)
312				break;
313		}
314
315		if (td1 == NULL)
316			TAILQ_INSERT_TAIL(&ts->ts_blocked[queue], td, td_lockq);
317		else
318			TAILQ_INSERT_BEFORE(td1, td, td_lockq);
319		mtx_unlock_spin(&td_contested_lock);
320		if (td1 == NULL)
321			CTR3(KTR_LOCK,
322		    "turnstile_adjust_thread: td %d put at tail on [%p] %s",
323			    td->td_tid, ts->ts_lockobj, ts->ts_lockobj->lo_name);
324		else
325			CTR4(KTR_LOCK,
326		    "turnstile_adjust_thread: td %d moved before %d on [%p] %s",
327			    td->td_tid, td1->td_tid, ts->ts_lockobj,
328			    ts->ts_lockobj->lo_name);
329	}
330	return (1);
331}
332
333/*
334 * Early initialization of turnstiles.  This is not done via a SYSINIT()
335 * since this needs to be initialized very early when mutexes are first
336 * initialized.
337 */
338void
339init_turnstiles(void)
340{
341	int i;
342
343	for (i = 0; i < TC_TABLESIZE; i++) {
344		LIST_INIT(&turnstile_chains[i].tc_turnstiles);
345		mtx_init(&turnstile_chains[i].tc_lock, "turnstile chain",
346		    NULL, MTX_SPIN);
347	}
348	mtx_init(&td_contested_lock, "td_contested", NULL, MTX_SPIN);
349	LIST_INIT(&thread0.td_contested);
350	thread0.td_turnstile = NULL;
351}
352
353#ifdef TURNSTILE_PROFILING
354static void
355init_turnstile_profiling(void *arg)
356{
357	struct sysctl_oid *chain_oid;
358	char chain_name[10];
359	int i;
360
361	for (i = 0; i < TC_TABLESIZE; i++) {
362		snprintf(chain_name, sizeof(chain_name), "%d", i);
363		chain_oid = SYSCTL_ADD_NODE(NULL,
364		    SYSCTL_STATIC_CHILDREN(_debug_turnstile_chains), OID_AUTO,
365		    chain_name, CTLFLAG_RD, NULL, "turnstile chain stats");
366		SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
367		    "depth", CTLFLAG_RD, &turnstile_chains[i].tc_depth, 0,
368		    NULL);
369		SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
370		    "max_depth", CTLFLAG_RD, &turnstile_chains[i].tc_max_depth,
371		    0, NULL);
372	}
373}
374SYSINIT(turnstile_profiling, SI_SUB_LOCK, SI_ORDER_ANY,
375    init_turnstile_profiling, NULL);
376#endif
377
378static void
379init_turnstile0(void *dummy)
380{
381
382	thread0.td_turnstile = turnstile_alloc();
383}
384SYSINIT(turnstile0, SI_SUB_LOCK, SI_ORDER_ANY, init_turnstile0, NULL);
385
386/*
387 * Update a thread on the turnstile list after it's priority has been changed.
388 * The old priority is passed in as an argument.
389 */
390void
391turnstile_adjust(struct thread *td, u_char oldpri)
392{
393	struct turnstile_chain *tc;
394	struct turnstile *ts;
395
396	mtx_assert(&sched_lock, MA_OWNED);
397	MPASS(TD_ON_LOCK(td));
398
399	/*
400	 * Pick up the lock that td is blocked on.
401	 */
402	ts = td->td_blocked;
403	MPASS(ts != NULL);
404	tc = TC_LOOKUP(ts->ts_lockobj);
405	mtx_lock_spin(&tc->tc_lock);
406
407	/* Resort the turnstile on the list. */
408	if (!turnstile_adjust_thread(ts, td)) {
409		mtx_unlock_spin(&tc->tc_lock);
410		return;
411	}
412
413	/*
414	 * If our priority was lowered and we are at the head of the
415	 * turnstile, then propagate our new priority up the chain.
416	 * Note that we currently don't try to revoke lent priorities
417	 * when our priority goes up.
418	 */
419	MPASS(td->td_tsqueue == TS_EXCLUSIVE_QUEUE ||
420	    td->td_tsqueue == TS_SHARED_QUEUE);
421	if (td == TAILQ_FIRST(&ts->ts_blocked[td->td_tsqueue]) &&
422	    td->td_priority < oldpri) {
423		mtx_unlock_spin(&tc->tc_lock);
424		propagate_priority(td);
425	} else
426		mtx_unlock_spin(&tc->tc_lock);
427}
428
429/*
430 * Set the owner of the lock this turnstile is attached to.
431 */
432static void
433turnstile_setowner(struct turnstile *ts, struct thread *owner)
434{
435
436	mtx_assert(&td_contested_lock, MA_OWNED);
437	MPASS(ts->ts_owner == NULL);
438
439	/* A shared lock might not have an owner. */
440	if (owner == NULL)
441		return;
442
443	MPASS(owner->td_proc->p_magic == P_MAGIC);
444	ts->ts_owner = owner;
445	LIST_INSERT_HEAD(&owner->td_contested, ts, ts_link);
446}
447
448/*
449 * Malloc a turnstile for a new thread, initialize it and return it.
450 */
451struct turnstile *
452turnstile_alloc(void)
453{
454	struct turnstile *ts;
455
456	ts = malloc(sizeof(struct turnstile), M_TURNSTILE, M_WAITOK | M_ZERO);
457	TAILQ_INIT(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]);
458	TAILQ_INIT(&ts->ts_blocked[TS_SHARED_QUEUE]);
459	TAILQ_INIT(&ts->ts_pending);
460	LIST_INIT(&ts->ts_free);
461	return (ts);
462}
463
464/*
465 * Free a turnstile when a thread is destroyed.
466 */
467void
468turnstile_free(struct turnstile *ts)
469{
470
471	MPASS(ts != NULL);
472	MPASS(TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]));
473	MPASS(TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]));
474	MPASS(TAILQ_EMPTY(&ts->ts_pending));
475	free(ts, M_TURNSTILE);
476}
477
478/*
479 * Lock the turnstile chain associated with the specified lock.
480 */
481void
482turnstile_lock(struct lock_object *lock)
483{
484	struct turnstile_chain *tc;
485
486	tc = TC_LOOKUP(lock);
487	mtx_lock_spin(&tc->tc_lock);
488}
489
490/*
491 * Look up the turnstile for a lock in the hash table locking the associated
492 * turnstile chain along the way.  If no turnstile is found in the hash
493 * table, NULL is returned.
494 */
495struct turnstile *
496turnstile_lookup(struct lock_object *lock)
497{
498	struct turnstile_chain *tc;
499	struct turnstile *ts;
500
501	tc = TC_LOOKUP(lock);
502	mtx_assert(&tc->tc_lock, MA_OWNED);
503	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
504		if (ts->ts_lockobj == lock)
505			return (ts);
506	return (NULL);
507}
508
509/*
510 * Unlock the turnstile chain associated with a given lock.
511 */
512void
513turnstile_release(struct lock_object *lock)
514{
515	struct turnstile_chain *tc;
516
517	tc = TC_LOOKUP(lock);
518	mtx_unlock_spin(&tc->tc_lock);
519}
520
521/*
522 * Return a pointer to the thread waiting on this turnstile with the
523 * most important priority or NULL if the turnstile has no waiters.
524 */
525static struct thread *
526turnstile_first_waiter(struct turnstile *ts)
527{
528	struct thread *std, *xtd;
529
530	std = TAILQ_FIRST(&ts->ts_blocked[TS_SHARED_QUEUE]);
531	xtd = TAILQ_FIRST(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]);
532	if (xtd == NULL || (std != NULL && std->td_priority < xtd->td_priority))
533		return (std);
534	return (xtd);
535}
536
537/*
538 * Take ownership of a turnstile and adjust the priority of the new
539 * owner appropriately.
540 */
541void
542turnstile_claim(struct lock_object *lock)
543{
544	struct turnstile_chain *tc;
545	struct turnstile *ts;
546	struct thread *td, *owner;
547
548	tc = TC_LOOKUP(lock);
549	mtx_assert(&tc->tc_lock, MA_OWNED);
550	ts = turnstile_lookup(lock);
551	MPASS(ts != NULL);
552
553	owner = curthread;
554	mtx_lock_spin(&td_contested_lock);
555	turnstile_setowner(ts, owner);
556	mtx_unlock_spin(&td_contested_lock);
557
558	td = turnstile_first_waiter(ts);
559	MPASS(td != NULL);
560	MPASS(td->td_proc->p_magic == P_MAGIC);
561	mtx_unlock_spin(&tc->tc_lock);
562
563	/*
564	 * Update the priority of the new owner if needed.
565	 */
566	mtx_lock_spin(&sched_lock);
567	if (td->td_priority < owner->td_priority)
568		sched_lend_prio(owner, td->td_priority);
569	mtx_unlock_spin(&sched_lock);
570}
571
572/*
573 * Block the current thread on the turnstile assicated with 'lock'.  This
574 * function will context switch and not return until this thread has been
575 * woken back up.  This function must be called with the appropriate
576 * turnstile chain locked and will return with it unlocked.
577 */
578void
579turnstile_wait(struct lock_object *lock, struct thread *owner, int queue)
580{
581	struct turnstile_chain *tc;
582	struct turnstile *ts;
583	struct thread *td, *td1;
584
585	td = curthread;
586	tc = TC_LOOKUP(lock);
587	mtx_assert(&tc->tc_lock, MA_OWNED);
588	MPASS(td->td_turnstile != NULL);
589	if (queue == TS_SHARED_QUEUE)
590		MPASS(owner != NULL);
591	if (owner)
592		MPASS(owner->td_proc->p_magic == P_MAGIC);
593	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
594
595	/* Look up the turnstile associated with the lock 'lock'. */
596	ts = turnstile_lookup(lock);
597
598	/*
599	 * If the lock does not already have a turnstile, use this thread's
600	 * turnstile.  Otherwise insert the current thread into the
601	 * turnstile already in use by this lock.
602	 */
603	if (ts == NULL) {
604#ifdef TURNSTILE_PROFILING
605		tc->tc_depth++;
606		if (tc->tc_depth > tc->tc_max_depth) {
607			tc->tc_max_depth = tc->tc_depth;
608			if (tc->tc_max_depth > turnstile_max_depth)
609				turnstile_max_depth = tc->tc_max_depth;
610		}
611#endif
612		ts = td->td_turnstile;
613		LIST_INSERT_HEAD(&tc->tc_turnstiles, ts, ts_hash);
614		KASSERT(TAILQ_EMPTY(&ts->ts_pending),
615		    ("thread's turnstile has pending threads"));
616		KASSERT(TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]),
617		    ("thread's turnstile has exclusive waiters"));
618		KASSERT(TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]),
619		    ("thread's turnstile has shared waiters"));
620		KASSERT(LIST_EMPTY(&ts->ts_free),
621		    ("thread's turnstile has a non-empty free list"));
622		KASSERT(ts->ts_lockobj == NULL, ("stale ts_lockobj pointer"));
623		ts->ts_lockobj = lock;
624		mtx_lock_spin(&td_contested_lock);
625		TAILQ_INSERT_TAIL(&ts->ts_blocked[queue], td, td_lockq);
626		turnstile_setowner(ts, owner);
627		mtx_unlock_spin(&td_contested_lock);
628	} else {
629		TAILQ_FOREACH(td1, &ts->ts_blocked[queue], td_lockq)
630			if (td1->td_priority > td->td_priority)
631				break;
632		mtx_lock_spin(&td_contested_lock);
633		if (td1 != NULL)
634			TAILQ_INSERT_BEFORE(td1, td, td_lockq);
635		else
636			TAILQ_INSERT_TAIL(&ts->ts_blocked[queue], td, td_lockq);
637		MPASS(owner == ts->ts_owner);
638		mtx_unlock_spin(&td_contested_lock);
639		MPASS(td->td_turnstile != NULL);
640		LIST_INSERT_HEAD(&ts->ts_free, td->td_turnstile, ts_hash);
641	}
642	td->td_turnstile = NULL;
643	mtx_unlock_spin(&tc->tc_lock);
644
645	mtx_lock_spin(&sched_lock);
646	/*
647	 * Handle race condition where a thread on another CPU that owns
648	 * lock 'lock' could have woken us in between us dropping the
649	 * turnstile chain lock and acquiring the sched_lock.
650	 */
651	if (td->td_flags & TDF_TSNOBLOCK) {
652		td->td_flags &= ~TDF_TSNOBLOCK;
653		mtx_unlock_spin(&sched_lock);
654		return;
655	}
656
657#ifdef notyet
658	/*
659	 * If we're borrowing an interrupted thread's VM context, we
660	 * must clean up before going to sleep.
661	 */
662	if (td->td_ithd != NULL) {
663		struct ithd *it = td->td_ithd;
664
665		if (it->it_interrupted) {
666			if (LOCK_LOG_TEST(lock, 0))
667				CTR3(KTR_LOCK, "%s: %p interrupted %p",
668				    __func__, it, it->it_interrupted);
669			intr_thd_fixup(it);
670		}
671	}
672#endif
673
674	/* Save who we are blocked on and switch. */
675	td->td_tsqueue = queue;
676	td->td_blocked = ts;
677	td->td_lockname = lock->lo_name;
678	TD_SET_LOCK(td);
679	propagate_priority(td);
680
681	if (LOCK_LOG_TEST(lock, 0))
682		CTR4(KTR_LOCK, "%s: td %d blocked on [%p] %s", __func__,
683		    td->td_tid, lock, lock->lo_name);
684
685	mi_switch(SW_VOL, NULL);
686
687	if (LOCK_LOG_TEST(lock, 0))
688		CTR4(KTR_LOCK, "%s: td %d free from blocked on [%p] %s",
689		    __func__, td->td_tid, lock, lock->lo_name);
690
691	mtx_unlock_spin(&sched_lock);
692}
693
694/*
695 * Pick the highest priority thread on this turnstile and put it on the
696 * pending list.  This must be called with the turnstile chain locked.
697 */
698int
699turnstile_signal(struct turnstile *ts, int queue)
700{
701	struct turnstile_chain *tc;
702	struct thread *td;
703	int empty;
704
705	MPASS(ts != NULL);
706	MPASS(curthread->td_proc->p_magic == P_MAGIC);
707	MPASS(ts->ts_owner == curthread ||
708	    (queue == TS_EXCLUSIVE_QUEUE && ts->ts_owner == NULL));
709	tc = TC_LOOKUP(ts->ts_lockobj);
710	mtx_assert(&tc->tc_lock, MA_OWNED);
711	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
712
713	/*
714	 * Pick the highest priority thread blocked on this lock and
715	 * move it to the pending list.
716	 */
717	td = TAILQ_FIRST(&ts->ts_blocked[queue]);
718	MPASS(td->td_proc->p_magic == P_MAGIC);
719	mtx_lock_spin(&td_contested_lock);
720	TAILQ_REMOVE(&ts->ts_blocked[queue], td, td_lockq);
721	mtx_unlock_spin(&td_contested_lock);
722	TAILQ_INSERT_TAIL(&ts->ts_pending, td, td_lockq);
723
724	/*
725	 * If the turnstile is now empty, remove it from its chain and
726	 * give it to the about-to-be-woken thread.  Otherwise take a
727	 * turnstile from the free list and give it to the thread.
728	 */
729	empty = TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) &&
730	    TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]);
731	if (empty) {
732		MPASS(LIST_EMPTY(&ts->ts_free));
733#ifdef TURNSTILE_PROFILING
734		tc->tc_depth--;
735#endif
736	} else
737		ts = LIST_FIRST(&ts->ts_free);
738	MPASS(ts != NULL);
739	LIST_REMOVE(ts, ts_hash);
740	td->td_turnstile = ts;
741
742	return (empty);
743}
744
745/*
746 * Put all blocked threads on the pending list.  This must be called with
747 * the turnstile chain locked.
748 */
749void
750turnstile_broadcast(struct turnstile *ts, int queue)
751{
752	struct turnstile_chain *tc;
753	struct turnstile *ts1;
754	struct thread *td;
755
756	MPASS(ts != NULL);
757	MPASS(curthread->td_proc->p_magic == P_MAGIC);
758	MPASS(ts->ts_owner == curthread ||
759	    (queue == TS_EXCLUSIVE_QUEUE && ts->ts_owner == NULL));
760	tc = TC_LOOKUP(ts->ts_lockobj);
761	mtx_assert(&tc->tc_lock, MA_OWNED);
762	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
763
764	/*
765	 * Transfer the blocked list to the pending list.
766	 */
767	mtx_lock_spin(&td_contested_lock);
768	TAILQ_CONCAT(&ts->ts_pending, &ts->ts_blocked[queue], td_lockq);
769	mtx_unlock_spin(&td_contested_lock);
770
771	/*
772	 * Give a turnstile to each thread.  The last thread gets
773	 * this turnstile if the turnstile is empty.
774	 */
775	TAILQ_FOREACH(td, &ts->ts_pending, td_lockq) {
776		if (LIST_EMPTY(&ts->ts_free)) {
777			MPASS(TAILQ_NEXT(td, td_lockq) == NULL);
778			ts1 = ts;
779#ifdef TURNSTILE_PROFILING
780			tc->tc_depth--;
781#endif
782		} else
783			ts1 = LIST_FIRST(&ts->ts_free);
784		MPASS(ts1 != NULL);
785		LIST_REMOVE(ts1, ts_hash);
786		td->td_turnstile = ts1;
787	}
788}
789
790/*
791 * Wakeup all threads on the pending list and adjust the priority of the
792 * current thread appropriately.  This must be called with the turnstile
793 * chain locked.
794 */
795void
796turnstile_unpend(struct turnstile *ts, int owner_type)
797{
798	TAILQ_HEAD( ,thread) pending_threads;
799	struct turnstile_chain *tc;
800	struct thread *td;
801	u_char cp, pri;
802
803	MPASS(ts != NULL);
804	MPASS(ts->ts_owner == curthread ||
805	    (owner_type == TS_SHARED_LOCK && ts->ts_owner == NULL));
806	tc = TC_LOOKUP(ts->ts_lockobj);
807	mtx_assert(&tc->tc_lock, MA_OWNED);
808	MPASS(!TAILQ_EMPTY(&ts->ts_pending));
809
810	/*
811	 * Move the list of pending threads out of the turnstile and
812	 * into a local variable.
813	 */
814	TAILQ_INIT(&pending_threads);
815	TAILQ_CONCAT(&pending_threads, &ts->ts_pending, td_lockq);
816#ifdef INVARIANTS
817	if (TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) &&
818	    TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]))
819		ts->ts_lockobj = NULL;
820#endif
821
822	/*
823	 * Remove the turnstile from this thread's list of contested locks
824	 * since this thread doesn't own it anymore.  New threads will
825	 * not be blocking on the turnstile until it is claimed by a new
826	 * owner.  There might not be a current owner if this is a shared
827	 * lock.
828	 */
829	if (ts->ts_owner != NULL) {
830		mtx_lock_spin(&td_contested_lock);
831		ts->ts_owner = NULL;
832		LIST_REMOVE(ts, ts_link);
833		mtx_unlock_spin(&td_contested_lock);
834	}
835	critical_enter();
836	mtx_unlock_spin(&tc->tc_lock);
837
838	/*
839	 * Adjust the priority of curthread based on other contested
840	 * locks it owns.  Don't lower the priority below the base
841	 * priority however.
842	 */
843	td = curthread;
844	pri = PRI_MAX;
845	mtx_lock_spin(&sched_lock);
846	mtx_lock_spin(&td_contested_lock);
847	LIST_FOREACH(ts, &td->td_contested, ts_link) {
848		cp = turnstile_first_waiter(ts)->td_priority;
849		if (cp < pri)
850			pri = cp;
851	}
852	mtx_unlock_spin(&td_contested_lock);
853	sched_unlend_prio(td, pri);
854
855	/*
856	 * Wake up all the pending threads.  If a thread is not blocked
857	 * on a lock, then it is currently executing on another CPU in
858	 * turnstile_wait() or sitting on a run queue waiting to resume
859	 * in turnstile_wait().  Set a flag to force it to try to acquire
860	 * the lock again instead of blocking.
861	 */
862	while (!TAILQ_EMPTY(&pending_threads)) {
863		td = TAILQ_FIRST(&pending_threads);
864		TAILQ_REMOVE(&pending_threads, td, td_lockq);
865		MPASS(td->td_proc->p_magic == P_MAGIC);
866		if (TD_ON_LOCK(td)) {
867			td->td_blocked = NULL;
868			td->td_lockname = NULL;
869#ifdef INVARIANTS
870			td->td_tsqueue = 0xff;
871#endif
872			TD_CLR_LOCK(td);
873			MPASS(TD_CAN_RUN(td));
874			setrunqueue(td, SRQ_BORING);
875		} else {
876			td->td_flags |= TDF_TSNOBLOCK;
877			MPASS(TD_IS_RUNNING(td) || TD_ON_RUNQ(td));
878		}
879	}
880	critical_exit();
881	mtx_unlock_spin(&sched_lock);
882}
883
884/*
885 * Give up ownership of a turnstile.  This must be called with the
886 * turnstile chain locked.
887 */
888void
889turnstile_disown(struct turnstile *ts)
890{
891	struct turnstile_chain *tc;
892	struct thread *td;
893	u_char cp, pri;
894
895	MPASS(ts != NULL);
896	MPASS(ts->ts_owner == curthread);
897	tc = TC_LOOKUP(ts->ts_lockobj);
898	mtx_assert(&tc->tc_lock, MA_OWNED);
899	MPASS(TAILQ_EMPTY(&ts->ts_pending));
900	MPASS(!TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) ||
901	    !TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]));
902
903	/*
904	 * Remove the turnstile from this thread's list of contested locks
905	 * since this thread doesn't own it anymore.  New threads will
906	 * not be blocking on the turnstile until it is claimed by a new
907	 * owner.
908	 */
909	mtx_lock_spin(&td_contested_lock);
910	ts->ts_owner = NULL;
911	LIST_REMOVE(ts, ts_link);
912	mtx_unlock_spin(&td_contested_lock);
913	mtx_unlock_spin(&tc->tc_lock);
914
915	/*
916	 * Adjust the priority of curthread based on other contested
917	 * locks it owns.  Don't lower the priority below the base
918	 * priority however.
919	 */
920	td = curthread;
921	pri = PRI_MAX;
922	mtx_lock_spin(&sched_lock);
923	mtx_lock_spin(&td_contested_lock);
924	LIST_FOREACH(ts, &td->td_contested, ts_link) {
925		cp = turnstile_first_waiter(ts)->td_priority;
926		if (cp < pri)
927			pri = cp;
928	}
929	mtx_unlock_spin(&td_contested_lock);
930	sched_unlend_prio(td, pri);
931	mtx_unlock_spin(&sched_lock);
932}
933
934/*
935 * Return the first thread in a turnstile.
936 */
937struct thread *
938turnstile_head(struct turnstile *ts, int queue)
939{
940#ifdef INVARIANTS
941	struct turnstile_chain *tc;
942
943	MPASS(ts != NULL);
944	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
945	tc = TC_LOOKUP(ts->ts_lockobj);
946	mtx_assert(&tc->tc_lock, MA_OWNED);
947#endif
948	return (TAILQ_FIRST(&ts->ts_blocked[queue]));
949}
950
951/*
952 * Returns true if a sub-queue of a turnstile is empty.
953 */
954int
955turnstile_empty(struct turnstile *ts, int queue)
956{
957#ifdef INVARIANTS
958	struct turnstile_chain *tc;
959
960	MPASS(ts != NULL);
961	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
962	tc = TC_LOOKUP(ts->ts_lockobj);
963	mtx_assert(&tc->tc_lock, MA_OWNED);
964#endif
965	return (TAILQ_EMPTY(&ts->ts_blocked[queue]));
966}
967
968#ifdef DDB
969static void
970print_thread(struct thread *td, const char *prefix)
971{
972
973	db_printf("%s%p (tid %d, pid %d, \"%s\")\n", prefix, td, td->td_tid,
974	    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
975	    td->td_proc->p_comm);
976}
977
978static void
979print_queue(struct threadqueue *queue, const char *header, const char *prefix)
980{
981	struct thread *td;
982
983	db_printf("%s:\n", header);
984	if (TAILQ_EMPTY(queue)) {
985		db_printf("%sempty\n", prefix);
986		return;
987	}
988	TAILQ_FOREACH(td, queue, td_lockq) {
989		print_thread(td, prefix);
990	}
991}
992
993DB_SHOW_COMMAND(turnstile, db_show_turnstile)
994{
995	struct turnstile_chain *tc;
996	struct turnstile *ts;
997	struct lock_object *lock;
998	int i;
999
1000	if (!have_addr)
1001		return;
1002
1003	/*
1004	 * First, see if there is an active turnstile for the lock indicated
1005	 * by the address.
1006	 */
1007	lock = (struct lock_object *)addr;
1008	tc = TC_LOOKUP(lock);
1009	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
1010		if (ts->ts_lockobj == lock)
1011			goto found;
1012
1013	/*
1014	 * Second, see if there is an active turnstile at the address
1015	 * indicated.
1016	 */
1017	for (i = 0; i < TC_TABLESIZE; i++)
1018		LIST_FOREACH(ts, &turnstile_chains[i].tc_turnstiles, ts_hash) {
1019			if (ts == (struct turnstile *)addr)
1020				goto found;
1021		}
1022
1023	db_printf("Unable to locate a turnstile via %p\n", (void *)addr);
1024	return;
1025found:
1026	lock = ts->ts_lockobj;
1027	db_printf("Lock: %p - (%s) %s\n", lock, LOCK_CLASS(lock)->lc_name,
1028	    lock->lo_name);
1029	if (ts->ts_owner)
1030		print_thread(ts->ts_owner, "Lock Owner: ");
1031	else
1032		db_printf("Lock Owner: none\n");
1033	print_queue(&ts->ts_blocked[TS_SHARED_QUEUE], "Shared Waiters", "\t");
1034	print_queue(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE], "Exclusive Waiters",
1035	    "\t");
1036	print_queue(&ts->ts_pending, "Pending Threads", "\t");
1037
1038}
1039
1040/*
1041 * Show all the threads a particular thread is waiting on based on
1042 * non-sleepable and non-spin locks.
1043 */
1044static void
1045print_lockchain(struct thread *td, const char *prefix)
1046{
1047	struct lock_object *lock;
1048	struct lock_class *class;
1049	struct turnstile *ts;
1050
1051	/*
1052	 * Follow the chain.  We keep walking as long as the thread is
1053	 * blocked on a turnstile that has an owner.
1054	 */
1055	while (!db_pager_quit) {
1056		db_printf("%sthread %d (pid %d, %s) ", prefix, td->td_tid,
1057		    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
1058		    td->td_proc->p_comm);
1059		switch (td->td_state) {
1060		case TDS_INACTIVE:
1061			db_printf("is inactive\n");
1062			return;
1063		case TDS_CAN_RUN:
1064			db_printf("can run\n");
1065			return;
1066		case TDS_RUNQ:
1067			db_printf("is on a run queue\n");
1068			return;
1069		case TDS_RUNNING:
1070			db_printf("running on CPU %d\n", td->td_oncpu);
1071			return;
1072		case TDS_INHIBITED:
1073			if (TD_ON_LOCK(td)) {
1074				ts = td->td_blocked;
1075				lock = ts->ts_lockobj;
1076				class = LOCK_CLASS(lock);
1077				db_printf("blocked on lock %p (%s) \"%s\"\n",
1078				    lock, class->lc_name, lock->lo_name);
1079				if (ts->ts_owner == NULL)
1080					return;
1081				td = ts->ts_owner;
1082				break;
1083			}
1084			db_printf("inhibited\n");
1085			return;
1086		default:
1087			db_printf("??? (%#x)\n", td->td_state);
1088			return;
1089		}
1090	}
1091}
1092
1093DB_SHOW_COMMAND(lockchain, db_show_lockchain)
1094{
1095	struct thread *td;
1096
1097	/* Figure out which thread to start with. */
1098	if (have_addr)
1099		td = db_lookup_thread(addr, TRUE);
1100	else
1101		td = kdb_thread;
1102
1103	print_lockchain(td, "");
1104}
1105
1106DB_SHOW_COMMAND(allchains, db_show_allchains)
1107{
1108	struct thread *td;
1109	struct proc *p;
1110	int i;
1111
1112	i = 1;
1113	LIST_FOREACH(p, &allproc, p_list) {
1114		FOREACH_THREAD_IN_PROC(p, td) {
1115			if (TD_ON_LOCK(td) && LIST_EMPTY(&td->td_contested)) {
1116				db_printf("chain %d:\n", i++);
1117				print_lockchain(td, " ");
1118			}
1119			if (db_pager_quit)
1120				return;
1121		}
1122	}
1123}
1124
1125/*
1126 * Show all the threads a particular thread is waiting on based on
1127 * sleepable locks.
1128 */
1129static void
1130print_sleepchain(struct thread *td, const char *prefix)
1131{
1132	struct thread *owner;
1133
1134	/*
1135	 * Follow the chain.  We keep walking as long as the thread is
1136	 * blocked on a sleep lock that has an owner.
1137	 */
1138	while (!db_pager_quit) {
1139		db_printf("%sthread %d (pid %d, %s) ", prefix, td->td_tid,
1140		    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
1141		    td->td_proc->p_comm);
1142		switch (td->td_state) {
1143		case TDS_INACTIVE:
1144			db_printf("is inactive\n");
1145			return;
1146		case TDS_CAN_RUN:
1147			db_printf("can run\n");
1148			return;
1149		case TDS_RUNQ:
1150			db_printf("is on a run queue\n");
1151			return;
1152		case TDS_RUNNING:
1153			db_printf("running on CPU %d\n", td->td_oncpu);
1154			return;
1155		case TDS_INHIBITED:
1156			if (TD_ON_SLEEPQ(td)) {
1157				if (lockmgr_chain(td, &owner) ||
1158				    sx_chain(td, &owner)) {
1159					if (owner == NULL)
1160						return;
1161					td = owner;
1162					break;
1163				}
1164				db_printf("sleeping on %p \"%s\"\n",
1165				    td->td_wchan, td->td_wmesg);
1166				return;
1167			}
1168			db_printf("inhibited\n");
1169			return;
1170		default:
1171			db_printf("??? (%#x)\n", td->td_state);
1172			return;
1173		}
1174	}
1175}
1176
1177DB_SHOW_COMMAND(sleepchain, db_show_sleepchain)
1178{
1179	struct thread *td;
1180
1181	/* Figure out which thread to start with. */
1182	if (have_addr)
1183		td = db_lookup_thread(addr, TRUE);
1184	else
1185		td = kdb_thread;
1186
1187	print_sleepchain(td, "");
1188}
1189
1190static void	print_waiters(struct turnstile *ts, int indent);
1191
1192static void
1193print_waiter(struct thread *td, int indent)
1194{
1195	struct turnstile *ts;
1196	int i;
1197
1198	if (db_pager_quit)
1199		return;
1200	for (i = 0; i < indent; i++)
1201		db_printf(" ");
1202	print_thread(td, "thread ");
1203	LIST_FOREACH(ts, &td->td_contested, ts_link)
1204		print_waiters(ts, indent + 1);
1205}
1206
1207static void
1208print_waiters(struct turnstile *ts, int indent)
1209{
1210	struct lock_object *lock;
1211	struct lock_class *class;
1212	struct thread *td;
1213	int i;
1214
1215	if (db_pager_quit)
1216		return;
1217	lock = ts->ts_lockobj;
1218	class = LOCK_CLASS(lock);
1219	for (i = 0; i < indent; i++)
1220		db_printf(" ");
1221	db_printf("lock %p (%s) \"%s\"\n", lock, class->lc_name, lock->lo_name);
1222	TAILQ_FOREACH(td, &ts->ts_blocked[TS_EXCLUSIVE_QUEUE], td_lockq)
1223		print_waiter(td, indent + 1);
1224	TAILQ_FOREACH(td, &ts->ts_blocked[TS_SHARED_QUEUE], td_lockq)
1225		print_waiter(td, indent + 1);
1226	TAILQ_FOREACH(td, &ts->ts_pending, td_lockq)
1227		print_waiter(td, indent + 1);
1228}
1229
1230DB_SHOW_COMMAND(locktree, db_show_locktree)
1231{
1232	struct lock_object *lock;
1233	struct lock_class *class;
1234	struct turnstile_chain *tc;
1235	struct turnstile *ts;
1236
1237	if (!have_addr)
1238		return;
1239	lock = (struct lock_object *)addr;
1240	tc = TC_LOOKUP(lock);
1241	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
1242		if (ts->ts_lockobj == lock)
1243			break;
1244	if (ts == NULL) {
1245		class = LOCK_CLASS(lock);
1246		db_printf("lock %p (%s) \"%s\"\n", lock, class->lc_name,
1247		    lock->lo_name);
1248	} else
1249		print_waiters(ts, 0);
1250}
1251#endif
1252