subr_turnstile.c revision 166188
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 166188 2007-01-23 08:46:51Z jeff $");
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		critical_enter();
425		propagate_priority(td);
426		critical_exit();
427	} else
428		mtx_unlock_spin(&tc->tc_lock);
429}
430
431/*
432 * Set the owner of the lock this turnstile is attached to.
433 */
434static void
435turnstile_setowner(struct turnstile *ts, struct thread *owner)
436{
437
438	mtx_assert(&td_contested_lock, MA_OWNED);
439	MPASS(ts->ts_owner == NULL);
440
441	/* A shared lock might not have an owner. */
442	if (owner == NULL)
443		return;
444
445	MPASS(owner->td_proc->p_magic == P_MAGIC);
446	ts->ts_owner = owner;
447	LIST_INSERT_HEAD(&owner->td_contested, ts, ts_link);
448}
449
450/*
451 * Malloc a turnstile for a new thread, initialize it and return it.
452 */
453struct turnstile *
454turnstile_alloc(void)
455{
456	struct turnstile *ts;
457
458	ts = malloc(sizeof(struct turnstile), M_TURNSTILE, M_WAITOK | M_ZERO);
459	TAILQ_INIT(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]);
460	TAILQ_INIT(&ts->ts_blocked[TS_SHARED_QUEUE]);
461	TAILQ_INIT(&ts->ts_pending);
462	LIST_INIT(&ts->ts_free);
463	return (ts);
464}
465
466/*
467 * Free a turnstile when a thread is destroyed.
468 */
469void
470turnstile_free(struct turnstile *ts)
471{
472
473	MPASS(ts != NULL);
474	MPASS(TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]));
475	MPASS(TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]));
476	MPASS(TAILQ_EMPTY(&ts->ts_pending));
477	free(ts, M_TURNSTILE);
478}
479
480/*
481 * Lock the turnstile chain associated with the specified lock.
482 */
483void
484turnstile_lock(struct lock_object *lock)
485{
486	struct turnstile_chain *tc;
487
488	tc = TC_LOOKUP(lock);
489	mtx_lock_spin(&tc->tc_lock);
490}
491
492/*
493 * Look up the turnstile for a lock in the hash table locking the associated
494 * turnstile chain along the way.  If no turnstile is found in the hash
495 * table, NULL is returned.
496 */
497struct turnstile *
498turnstile_lookup(struct lock_object *lock)
499{
500	struct turnstile_chain *tc;
501	struct turnstile *ts;
502
503	tc = TC_LOOKUP(lock);
504	mtx_assert(&tc->tc_lock, MA_OWNED);
505	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
506		if (ts->ts_lockobj == lock)
507			return (ts);
508	return (NULL);
509}
510
511/*
512 * Unlock the turnstile chain associated with a given lock.
513 */
514void
515turnstile_release(struct lock_object *lock)
516{
517	struct turnstile_chain *tc;
518
519	tc = TC_LOOKUP(lock);
520	mtx_unlock_spin(&tc->tc_lock);
521}
522
523/*
524 * Return a pointer to the thread waiting on this turnstile with the
525 * most important priority or NULL if the turnstile has no waiters.
526 */
527static struct thread *
528turnstile_first_waiter(struct turnstile *ts)
529{
530	struct thread *std, *xtd;
531
532	std = TAILQ_FIRST(&ts->ts_blocked[TS_SHARED_QUEUE]);
533	xtd = TAILQ_FIRST(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]);
534	if (xtd == NULL || (std != NULL && std->td_priority < xtd->td_priority))
535		return (std);
536	return (xtd);
537}
538
539/*
540 * Take ownership of a turnstile and adjust the priority of the new
541 * owner appropriately.
542 */
543void
544turnstile_claim(struct lock_object *lock)
545{
546	struct turnstile_chain *tc;
547	struct turnstile *ts;
548	struct thread *td, *owner;
549
550	tc = TC_LOOKUP(lock);
551	mtx_assert(&tc->tc_lock, MA_OWNED);
552	ts = turnstile_lookup(lock);
553	MPASS(ts != NULL);
554
555	owner = curthread;
556	mtx_lock_spin(&td_contested_lock);
557	turnstile_setowner(ts, owner);
558	mtx_unlock_spin(&td_contested_lock);
559
560	td = turnstile_first_waiter(ts);
561	MPASS(td != NULL);
562	MPASS(td->td_proc->p_magic == P_MAGIC);
563	mtx_unlock_spin(&tc->tc_lock);
564
565	/*
566	 * Update the priority of the new owner if needed.
567	 */
568	mtx_lock_spin(&sched_lock);
569	if (td->td_priority < owner->td_priority)
570		sched_lend_prio(owner, td->td_priority);
571	mtx_unlock_spin(&sched_lock);
572}
573
574/*
575 * Block the current thread on the turnstile assicated with 'lock'.  This
576 * function will context switch and not return until this thread has been
577 * woken back up.  This function must be called with the appropriate
578 * turnstile chain locked and will return with it unlocked.
579 */
580void
581turnstile_wait(struct lock_object *lock, struct thread *owner, int queue)
582{
583	struct turnstile_chain *tc;
584	struct turnstile *ts;
585	struct thread *td, *td1;
586
587	td = curthread;
588	tc = TC_LOOKUP(lock);
589	mtx_assert(&tc->tc_lock, MA_OWNED);
590	MPASS(td->td_turnstile != NULL);
591	if (queue == TS_SHARED_QUEUE)
592		MPASS(owner != NULL);
593	if (owner)
594		MPASS(owner->td_proc->p_magic == P_MAGIC);
595	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
596
597	/* Look up the turnstile associated with the lock 'lock'. */
598	ts = turnstile_lookup(lock);
599
600	/*
601	 * If the lock does not already have a turnstile, use this thread's
602	 * turnstile.  Otherwise insert the current thread into the
603	 * turnstile already in use by this lock.
604	 */
605	if (ts == NULL) {
606#ifdef TURNSTILE_PROFILING
607		tc->tc_depth++;
608		if (tc->tc_depth > tc->tc_max_depth) {
609			tc->tc_max_depth = tc->tc_depth;
610			if (tc->tc_max_depth > turnstile_max_depth)
611				turnstile_max_depth = tc->tc_max_depth;
612		}
613#endif
614		ts = td->td_turnstile;
615		LIST_INSERT_HEAD(&tc->tc_turnstiles, ts, ts_hash);
616		KASSERT(TAILQ_EMPTY(&ts->ts_pending),
617		    ("thread's turnstile has pending threads"));
618		KASSERT(TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]),
619		    ("thread's turnstile has exclusive waiters"));
620		KASSERT(TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]),
621		    ("thread's turnstile has shared waiters"));
622		KASSERT(LIST_EMPTY(&ts->ts_free),
623		    ("thread's turnstile has a non-empty free list"));
624		KASSERT(ts->ts_lockobj == NULL, ("stale ts_lockobj pointer"));
625		ts->ts_lockobj = lock;
626		mtx_lock_spin(&td_contested_lock);
627		TAILQ_INSERT_TAIL(&ts->ts_blocked[queue], td, td_lockq);
628		turnstile_setowner(ts, owner);
629		mtx_unlock_spin(&td_contested_lock);
630	} else {
631		TAILQ_FOREACH(td1, &ts->ts_blocked[queue], td_lockq)
632			if (td1->td_priority > td->td_priority)
633				break;
634		mtx_lock_spin(&td_contested_lock);
635		if (td1 != NULL)
636			TAILQ_INSERT_BEFORE(td1, td, td_lockq);
637		else
638			TAILQ_INSERT_TAIL(&ts->ts_blocked[queue], td, td_lockq);
639		MPASS(owner == ts->ts_owner);
640		mtx_unlock_spin(&td_contested_lock);
641		MPASS(td->td_turnstile != NULL);
642		LIST_INSERT_HEAD(&ts->ts_free, td->td_turnstile, ts_hash);
643	}
644	td->td_turnstile = NULL;
645	mtx_unlock_spin(&tc->tc_lock);
646
647	mtx_lock_spin(&sched_lock);
648	/*
649	 * Handle race condition where a thread on another CPU that owns
650	 * lock 'lock' could have woken us in between us dropping the
651	 * turnstile chain lock and acquiring the sched_lock.
652	 */
653	if (td->td_flags & TDF_TSNOBLOCK) {
654		td->td_flags &= ~TDF_TSNOBLOCK;
655		mtx_unlock_spin(&sched_lock);
656		return;
657	}
658
659#ifdef notyet
660	/*
661	 * If we're borrowing an interrupted thread's VM context, we
662	 * must clean up before going to sleep.
663	 */
664	if (td->td_ithd != NULL) {
665		struct ithd *it = td->td_ithd;
666
667		if (it->it_interrupted) {
668			if (LOCK_LOG_TEST(lock, 0))
669				CTR3(KTR_LOCK, "%s: %p interrupted %p",
670				    __func__, it, it->it_interrupted);
671			intr_thd_fixup(it);
672		}
673	}
674#endif
675
676	/* Save who we are blocked on and switch. */
677	td->td_tsqueue = queue;
678	td->td_blocked = ts;
679	td->td_lockname = lock->lo_name;
680	TD_SET_LOCK(td);
681	critical_enter();
682	propagate_priority(td);
683	critical_exit();
684
685	if (LOCK_LOG_TEST(lock, 0))
686		CTR4(KTR_LOCK, "%s: td %d blocked on [%p] %s", __func__,
687		    td->td_tid, lock, lock->lo_name);
688
689	mi_switch(SW_VOL, NULL);
690
691	if (LOCK_LOG_TEST(lock, 0))
692		CTR4(KTR_LOCK, "%s: td %d free from blocked on [%p] %s",
693		    __func__, td->td_tid, lock, lock->lo_name);
694
695	mtx_unlock_spin(&sched_lock);
696}
697
698/*
699 * Pick the highest priority thread on this turnstile and put it on the
700 * pending list.  This must be called with the turnstile chain locked.
701 */
702int
703turnstile_signal(struct turnstile *ts, int queue)
704{
705	struct turnstile_chain *tc;
706	struct thread *td;
707	int empty;
708
709	MPASS(ts != NULL);
710	MPASS(curthread->td_proc->p_magic == P_MAGIC);
711	MPASS(ts->ts_owner == curthread ||
712	    (queue == TS_EXCLUSIVE_QUEUE && ts->ts_owner == NULL));
713	tc = TC_LOOKUP(ts->ts_lockobj);
714	mtx_assert(&tc->tc_lock, MA_OWNED);
715	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
716
717	/*
718	 * Pick the highest priority thread blocked on this lock and
719	 * move it to the pending list.
720	 */
721	td = TAILQ_FIRST(&ts->ts_blocked[queue]);
722	MPASS(td->td_proc->p_magic == P_MAGIC);
723	mtx_lock_spin(&td_contested_lock);
724	TAILQ_REMOVE(&ts->ts_blocked[queue], td, td_lockq);
725	mtx_unlock_spin(&td_contested_lock);
726	TAILQ_INSERT_TAIL(&ts->ts_pending, td, td_lockq);
727
728	/*
729	 * If the turnstile is now empty, remove it from its chain and
730	 * give it to the about-to-be-woken thread.  Otherwise take a
731	 * turnstile from the free list and give it to the thread.
732	 */
733	empty = TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) &&
734	    TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]);
735	if (empty) {
736		MPASS(LIST_EMPTY(&ts->ts_free));
737#ifdef TURNSTILE_PROFILING
738		tc->tc_depth--;
739#endif
740	} else
741		ts = LIST_FIRST(&ts->ts_free);
742	MPASS(ts != NULL);
743	LIST_REMOVE(ts, ts_hash);
744	td->td_turnstile = ts;
745
746	return (empty);
747}
748
749/*
750 * Put all blocked threads on the pending list.  This must be called with
751 * the turnstile chain locked.
752 */
753void
754turnstile_broadcast(struct turnstile *ts, int queue)
755{
756	struct turnstile_chain *tc;
757	struct turnstile *ts1;
758	struct thread *td;
759
760	MPASS(ts != NULL);
761	MPASS(curthread->td_proc->p_magic == P_MAGIC);
762	MPASS(ts->ts_owner == curthread ||
763	    (queue == TS_EXCLUSIVE_QUEUE && ts->ts_owner == NULL));
764	tc = TC_LOOKUP(ts->ts_lockobj);
765	mtx_assert(&tc->tc_lock, MA_OWNED);
766	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
767
768	/*
769	 * Transfer the blocked list to the pending list.
770	 */
771	mtx_lock_spin(&td_contested_lock);
772	TAILQ_CONCAT(&ts->ts_pending, &ts->ts_blocked[queue], td_lockq);
773	mtx_unlock_spin(&td_contested_lock);
774
775	/*
776	 * Give a turnstile to each thread.  The last thread gets
777	 * this turnstile if the turnstile is empty.
778	 */
779	TAILQ_FOREACH(td, &ts->ts_pending, td_lockq) {
780		if (LIST_EMPTY(&ts->ts_free)) {
781			MPASS(TAILQ_NEXT(td, td_lockq) == NULL);
782			ts1 = ts;
783#ifdef TURNSTILE_PROFILING
784			tc->tc_depth--;
785#endif
786		} else
787			ts1 = LIST_FIRST(&ts->ts_free);
788		MPASS(ts1 != NULL);
789		LIST_REMOVE(ts1, ts_hash);
790		td->td_turnstile = ts1;
791	}
792}
793
794/*
795 * Wakeup all threads on the pending list and adjust the priority of the
796 * current thread appropriately.  This must be called with the turnstile
797 * chain locked.
798 */
799void
800turnstile_unpend(struct turnstile *ts, int owner_type)
801{
802	TAILQ_HEAD( ,thread) pending_threads;
803	struct turnstile_chain *tc;
804	struct thread *td;
805	u_char cp, pri;
806
807	MPASS(ts != NULL);
808	MPASS(ts->ts_owner == curthread ||
809	    (owner_type == TS_SHARED_LOCK && ts->ts_owner == NULL));
810	tc = TC_LOOKUP(ts->ts_lockobj);
811	mtx_assert(&tc->tc_lock, MA_OWNED);
812	MPASS(!TAILQ_EMPTY(&ts->ts_pending));
813
814	/*
815	 * Move the list of pending threads out of the turnstile and
816	 * into a local variable.
817	 */
818	TAILQ_INIT(&pending_threads);
819	TAILQ_CONCAT(&pending_threads, &ts->ts_pending, td_lockq);
820#ifdef INVARIANTS
821	if (TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) &&
822	    TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]))
823		ts->ts_lockobj = NULL;
824#endif
825
826	/*
827	 * Remove the turnstile from this thread's list of contested locks
828	 * since this thread doesn't own it anymore.  New threads will
829	 * not be blocking on the turnstile until it is claimed by a new
830	 * owner.  There might not be a current owner if this is a shared
831	 * lock.
832	 */
833	if (ts->ts_owner != NULL) {
834		mtx_lock_spin(&td_contested_lock);
835		ts->ts_owner = NULL;
836		LIST_REMOVE(ts, ts_link);
837		mtx_unlock_spin(&td_contested_lock);
838	}
839	critical_enter();
840	mtx_unlock_spin(&tc->tc_lock);
841
842	/*
843	 * Adjust the priority of curthread based on other contested
844	 * locks it owns.  Don't lower the priority below the base
845	 * priority however.
846	 */
847	td = curthread;
848	pri = PRI_MAX;
849	mtx_lock_spin(&sched_lock);
850	mtx_lock_spin(&td_contested_lock);
851	LIST_FOREACH(ts, &td->td_contested, ts_link) {
852		cp = turnstile_first_waiter(ts)->td_priority;
853		if (cp < pri)
854			pri = cp;
855	}
856	mtx_unlock_spin(&td_contested_lock);
857	sched_unlend_prio(td, pri);
858
859	/*
860	 * Wake up all the pending threads.  If a thread is not blocked
861	 * on a lock, then it is currently executing on another CPU in
862	 * turnstile_wait() or sitting on a run queue waiting to resume
863	 * in turnstile_wait().  Set a flag to force it to try to acquire
864	 * the lock again instead of blocking.
865	 */
866	while (!TAILQ_EMPTY(&pending_threads)) {
867		td = TAILQ_FIRST(&pending_threads);
868		TAILQ_REMOVE(&pending_threads, td, td_lockq);
869		MPASS(td->td_proc->p_magic == P_MAGIC);
870		if (TD_ON_LOCK(td)) {
871			td->td_blocked = NULL;
872			td->td_lockname = NULL;
873#ifdef INVARIANTS
874			td->td_tsqueue = 0xff;
875#endif
876			TD_CLR_LOCK(td);
877			MPASS(TD_CAN_RUN(td));
878			sched_add(td, SRQ_BORING);
879		} else {
880			td->td_flags |= TDF_TSNOBLOCK;
881			MPASS(TD_IS_RUNNING(td) || TD_ON_RUNQ(td));
882		}
883	}
884	critical_exit();
885	mtx_unlock_spin(&sched_lock);
886}
887
888/*
889 * Give up ownership of a turnstile.  This must be called with the
890 * turnstile chain locked.
891 */
892void
893turnstile_disown(struct turnstile *ts)
894{
895	struct turnstile_chain *tc;
896	struct thread *td;
897	u_char cp, pri;
898
899	MPASS(ts != NULL);
900	MPASS(ts->ts_owner == curthread);
901	tc = TC_LOOKUP(ts->ts_lockobj);
902	mtx_assert(&tc->tc_lock, MA_OWNED);
903	MPASS(TAILQ_EMPTY(&ts->ts_pending));
904	MPASS(!TAILQ_EMPTY(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE]) ||
905	    !TAILQ_EMPTY(&ts->ts_blocked[TS_SHARED_QUEUE]));
906
907	/*
908	 * Remove the turnstile from this thread's list of contested locks
909	 * since this thread doesn't own it anymore.  New threads will
910	 * not be blocking on the turnstile until it is claimed by a new
911	 * owner.
912	 */
913	mtx_lock_spin(&td_contested_lock);
914	ts->ts_owner = NULL;
915	LIST_REMOVE(ts, ts_link);
916	mtx_unlock_spin(&td_contested_lock);
917	mtx_unlock_spin(&tc->tc_lock);
918
919	/*
920	 * Adjust the priority of curthread based on other contested
921	 * locks it owns.  Don't lower the priority below the base
922	 * priority however.
923	 */
924	td = curthread;
925	pri = PRI_MAX;
926	mtx_lock_spin(&sched_lock);
927	mtx_lock_spin(&td_contested_lock);
928	LIST_FOREACH(ts, &td->td_contested, ts_link) {
929		cp = turnstile_first_waiter(ts)->td_priority;
930		if (cp < pri)
931			pri = cp;
932	}
933	mtx_unlock_spin(&td_contested_lock);
934	sched_unlend_prio(td, pri);
935	mtx_unlock_spin(&sched_lock);
936}
937
938/*
939 * Return the first thread in a turnstile.
940 */
941struct thread *
942turnstile_head(struct turnstile *ts, int queue)
943{
944#ifdef INVARIANTS
945	struct turnstile_chain *tc;
946
947	MPASS(ts != NULL);
948	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
949	tc = TC_LOOKUP(ts->ts_lockobj);
950	mtx_assert(&tc->tc_lock, MA_OWNED);
951#endif
952	return (TAILQ_FIRST(&ts->ts_blocked[queue]));
953}
954
955/*
956 * Returns true if a sub-queue of a turnstile is empty.
957 */
958int
959turnstile_empty(struct turnstile *ts, int queue)
960{
961#ifdef INVARIANTS
962	struct turnstile_chain *tc;
963
964	MPASS(ts != NULL);
965	MPASS(queue == TS_SHARED_QUEUE || queue == TS_EXCLUSIVE_QUEUE);
966	tc = TC_LOOKUP(ts->ts_lockobj);
967	mtx_assert(&tc->tc_lock, MA_OWNED);
968#endif
969	return (TAILQ_EMPTY(&ts->ts_blocked[queue]));
970}
971
972#ifdef DDB
973static void
974print_thread(struct thread *td, const char *prefix)
975{
976
977	db_printf("%s%p (tid %d, pid %d, \"%s\")\n", prefix, td, td->td_tid,
978	    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
979	    td->td_proc->p_comm);
980}
981
982static void
983print_queue(struct threadqueue *queue, const char *header, const char *prefix)
984{
985	struct thread *td;
986
987	db_printf("%s:\n", header);
988	if (TAILQ_EMPTY(queue)) {
989		db_printf("%sempty\n", prefix);
990		return;
991	}
992	TAILQ_FOREACH(td, queue, td_lockq) {
993		print_thread(td, prefix);
994	}
995}
996
997DB_SHOW_COMMAND(turnstile, db_show_turnstile)
998{
999	struct turnstile_chain *tc;
1000	struct turnstile *ts;
1001	struct lock_object *lock;
1002	int i;
1003
1004	if (!have_addr)
1005		return;
1006
1007	/*
1008	 * First, see if there is an active turnstile for the lock indicated
1009	 * by the address.
1010	 */
1011	lock = (struct lock_object *)addr;
1012	tc = TC_LOOKUP(lock);
1013	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
1014		if (ts->ts_lockobj == lock)
1015			goto found;
1016
1017	/*
1018	 * Second, see if there is an active turnstile at the address
1019	 * indicated.
1020	 */
1021	for (i = 0; i < TC_TABLESIZE; i++)
1022		LIST_FOREACH(ts, &turnstile_chains[i].tc_turnstiles, ts_hash) {
1023			if (ts == (struct turnstile *)addr)
1024				goto found;
1025		}
1026
1027	db_printf("Unable to locate a turnstile via %p\n", (void *)addr);
1028	return;
1029found:
1030	lock = ts->ts_lockobj;
1031	db_printf("Lock: %p - (%s) %s\n", lock, LOCK_CLASS(lock)->lc_name,
1032	    lock->lo_name);
1033	if (ts->ts_owner)
1034		print_thread(ts->ts_owner, "Lock Owner: ");
1035	else
1036		db_printf("Lock Owner: none\n");
1037	print_queue(&ts->ts_blocked[TS_SHARED_QUEUE], "Shared Waiters", "\t");
1038	print_queue(&ts->ts_blocked[TS_EXCLUSIVE_QUEUE], "Exclusive Waiters",
1039	    "\t");
1040	print_queue(&ts->ts_pending, "Pending Threads", "\t");
1041
1042}
1043
1044/*
1045 * Show all the threads a particular thread is waiting on based on
1046 * non-sleepable and non-spin locks.
1047 */
1048static void
1049print_lockchain(struct thread *td, const char *prefix)
1050{
1051	struct lock_object *lock;
1052	struct lock_class *class;
1053	struct turnstile *ts;
1054
1055	/*
1056	 * Follow the chain.  We keep walking as long as the thread is
1057	 * blocked on a turnstile that has an owner.
1058	 */
1059	while (!db_pager_quit) {
1060		db_printf("%sthread %d (pid %d, %s) ", prefix, td->td_tid,
1061		    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
1062		    td->td_proc->p_comm);
1063		switch (td->td_state) {
1064		case TDS_INACTIVE:
1065			db_printf("is inactive\n");
1066			return;
1067		case TDS_CAN_RUN:
1068			db_printf("can run\n");
1069			return;
1070		case TDS_RUNQ:
1071			db_printf("is on a run queue\n");
1072			return;
1073		case TDS_RUNNING:
1074			db_printf("running on CPU %d\n", td->td_oncpu);
1075			return;
1076		case TDS_INHIBITED:
1077			if (TD_ON_LOCK(td)) {
1078				ts = td->td_blocked;
1079				lock = ts->ts_lockobj;
1080				class = LOCK_CLASS(lock);
1081				db_printf("blocked on lock %p (%s) \"%s\"\n",
1082				    lock, class->lc_name, lock->lo_name);
1083				if (ts->ts_owner == NULL)
1084					return;
1085				td = ts->ts_owner;
1086				break;
1087			}
1088			db_printf("inhibited\n");
1089			return;
1090		default:
1091			db_printf("??? (%#x)\n", td->td_state);
1092			return;
1093		}
1094	}
1095}
1096
1097DB_SHOW_COMMAND(lockchain, db_show_lockchain)
1098{
1099	struct thread *td;
1100
1101	/* Figure out which thread to start with. */
1102	if (have_addr)
1103		td = db_lookup_thread(addr, TRUE);
1104	else
1105		td = kdb_thread;
1106
1107	print_lockchain(td, "");
1108}
1109
1110DB_SHOW_COMMAND(allchains, db_show_allchains)
1111{
1112	struct thread *td;
1113	struct proc *p;
1114	int i;
1115
1116	i = 1;
1117	FOREACH_PROC_IN_SYSTEM(p) {
1118		FOREACH_THREAD_IN_PROC(p, td) {
1119			if (TD_ON_LOCK(td) && LIST_EMPTY(&td->td_contested)) {
1120				db_printf("chain %d:\n", i++);
1121				print_lockchain(td, " ");
1122			}
1123			if (db_pager_quit)
1124				return;
1125		}
1126	}
1127}
1128
1129/*
1130 * Show all the threads a particular thread is waiting on based on
1131 * sleepable locks.
1132 */
1133static void
1134print_sleepchain(struct thread *td, const char *prefix)
1135{
1136	struct thread *owner;
1137
1138	/*
1139	 * Follow the chain.  We keep walking as long as the thread is
1140	 * blocked on a sleep lock that has an owner.
1141	 */
1142	while (!db_pager_quit) {
1143		db_printf("%sthread %d (pid %d, %s) ", prefix, td->td_tid,
1144		    td->td_proc->p_pid, td->td_name[0] != '\0' ? td->td_name :
1145		    td->td_proc->p_comm);
1146		switch (td->td_state) {
1147		case TDS_INACTIVE:
1148			db_printf("is inactive\n");
1149			return;
1150		case TDS_CAN_RUN:
1151			db_printf("can run\n");
1152			return;
1153		case TDS_RUNQ:
1154			db_printf("is on a run queue\n");
1155			return;
1156		case TDS_RUNNING:
1157			db_printf("running on CPU %d\n", td->td_oncpu);
1158			return;
1159		case TDS_INHIBITED:
1160			if (TD_ON_SLEEPQ(td)) {
1161				if (lockmgr_chain(td, &owner) ||
1162				    sx_chain(td, &owner)) {
1163					if (owner == NULL)
1164						return;
1165					td = owner;
1166					break;
1167				}
1168				db_printf("sleeping on %p \"%s\"\n",
1169				    td->td_wchan, td->td_wmesg);
1170				return;
1171			}
1172			db_printf("inhibited\n");
1173			return;
1174		default:
1175			db_printf("??? (%#x)\n", td->td_state);
1176			return;
1177		}
1178	}
1179}
1180
1181DB_SHOW_COMMAND(sleepchain, db_show_sleepchain)
1182{
1183	struct thread *td;
1184
1185	/* Figure out which thread to start with. */
1186	if (have_addr)
1187		td = db_lookup_thread(addr, TRUE);
1188	else
1189		td = kdb_thread;
1190
1191	print_sleepchain(td, "");
1192}
1193
1194static void	print_waiters(struct turnstile *ts, int indent);
1195
1196static void
1197print_waiter(struct thread *td, int indent)
1198{
1199	struct turnstile *ts;
1200	int i;
1201
1202	if (db_pager_quit)
1203		return;
1204	for (i = 0; i < indent; i++)
1205		db_printf(" ");
1206	print_thread(td, "thread ");
1207	LIST_FOREACH(ts, &td->td_contested, ts_link)
1208		print_waiters(ts, indent + 1);
1209}
1210
1211static void
1212print_waiters(struct turnstile *ts, int indent)
1213{
1214	struct lock_object *lock;
1215	struct lock_class *class;
1216	struct thread *td;
1217	int i;
1218
1219	if (db_pager_quit)
1220		return;
1221	lock = ts->ts_lockobj;
1222	class = LOCK_CLASS(lock);
1223	for (i = 0; i < indent; i++)
1224		db_printf(" ");
1225	db_printf("lock %p (%s) \"%s\"\n", lock, class->lc_name, lock->lo_name);
1226	TAILQ_FOREACH(td, &ts->ts_blocked[TS_EXCLUSIVE_QUEUE], td_lockq)
1227		print_waiter(td, indent + 1);
1228	TAILQ_FOREACH(td, &ts->ts_blocked[TS_SHARED_QUEUE], td_lockq)
1229		print_waiter(td, indent + 1);
1230	TAILQ_FOREACH(td, &ts->ts_pending, td_lockq)
1231		print_waiter(td, indent + 1);
1232}
1233
1234DB_SHOW_COMMAND(locktree, db_show_locktree)
1235{
1236	struct lock_object *lock;
1237	struct lock_class *class;
1238	struct turnstile_chain *tc;
1239	struct turnstile *ts;
1240
1241	if (!have_addr)
1242		return;
1243	lock = (struct lock_object *)addr;
1244	tc = TC_LOOKUP(lock);
1245	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
1246		if (ts->ts_lockobj == lock)
1247			break;
1248	if (ts == NULL) {
1249		class = LOCK_CLASS(lock);
1250		db_printf("lock %p (%s) \"%s\"\n", lock, class->lc_name,
1251		    lock->lo_name);
1252	} else
1253		print_waiters(ts, 0);
1254}
1255#endif
1256