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