subr_witness.c revision 148896
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 the `witness' lock verifier.  Originally implemented for
34 * mutexes in BSD/OS.  Extended to handle generic lock objects and lock
35 * classes in FreeBSD.
36 */
37
38/*
39 *	Main Entry: witness
40 *	Pronunciation: 'wit-n&s
41 *	Function: noun
42 *	Etymology: Middle English witnesse, from Old English witnes knowledge,
43 *	    testimony, witness, from 2wit
44 *	Date: before 12th century
45 *	1 : attestation of a fact or event : TESTIMONY
46 *	2 : one that gives evidence; specifically : one who testifies in
47 *	    a cause or before a judicial tribunal
48 *	3 : one asked to be present at a transaction so as to be able to
49 *	    testify to its having taken place
50 *	4 : one who has personal knowledge of something
51 *	5 a : something serving as evidence or proof : SIGN
52 *	  b : public affirmation by word or example of usually
53 *	      religious faith or conviction <the heroic witness to divine
54 *	      life -- Pilot>
55 *	6 capitalized : a member of the Jehovah's Witnesses
56 */
57
58/*
59 * Special rules concerning Giant and lock orders:
60 *
61 * 1) Giant must be acquired before any other mutexes.  Stated another way,
62 *    no other mutex may be held when Giant is acquired.
63 *
64 * 2) Giant must be released when blocking on a sleepable lock.
65 *
66 * This rule is less obvious, but is a result of Giant providing the same
67 * semantics as spl().  Basically, when a thread sleeps, it must release
68 * Giant.  When a thread blocks on a sleepable lock, it sleeps.  Hence rule
69 * 2).
70 *
71 * 3) Giant may be acquired before or after sleepable locks.
72 *
73 * This rule is also not quite as obvious.  Giant may be acquired after
74 * a sleepable lock because it is a non-sleepable lock and non-sleepable
75 * locks may always be acquired while holding a sleepable lock.  The second
76 * case, Giant before a sleepable lock, follows from rule 2) above.  Suppose
77 * you have two threads T1 and T2 and a sleepable lock X.  Suppose that T1
78 * acquires X and blocks on Giant.  Then suppose that T2 acquires Giant and
79 * blocks on X.  When T2 blocks on X, T2 will release Giant allowing T1 to
80 * execute.  Thus, acquiring Giant both before and after a sleepable lock
81 * will not result in a lock order reversal.
82 */
83
84#include <sys/cdefs.h>
85__FBSDID("$FreeBSD: head/sys/kern/subr_witness.c 148896 2005-08-09 13:27:50Z rwatson $");
86
87#include "opt_ddb.h"
88#include "opt_witness.h"
89
90#include <sys/param.h>
91#include <sys/bus.h>
92#include <sys/kdb.h>
93#include <sys/kernel.h>
94#include <sys/ktr.h>
95#include <sys/lock.h>
96#include <sys/malloc.h>
97#include <sys/mutex.h>
98#include <sys/proc.h>
99#include <sys/sysctl.h>
100#include <sys/systm.h>
101
102#include <ddb/ddb.h>
103
104#include <machine/stdarg.h>
105
106/* Define this to check for blessed mutexes */
107#undef BLESSING
108
109#define WITNESS_COUNT 1024
110#define WITNESS_CHILDCOUNT (WITNESS_COUNT * 4)
111/*
112 * XXX: This is somewhat bogus, as we assume here that at most 1024 threads
113 * will hold LOCK_NCHILDREN * 2 locks.  We handle failure ok, and we should
114 * probably be safe for the most part, but it's still a SWAG.
115 */
116#define LOCK_CHILDCOUNT (MAXCPU + 1024) * 2
117
118#define	WITNESS_NCHILDREN 6
119
120struct witness_child_list_entry;
121
122struct witness {
123	const	char *w_name;
124	struct	lock_class *w_class;
125	STAILQ_ENTRY(witness) w_list;		/* List of all witnesses. */
126	STAILQ_ENTRY(witness) w_typelist;	/* Witnesses of a type. */
127	struct	witness_child_list_entry *w_children;	/* Great evilness... */
128	const	char *w_file;
129	int	w_line;
130	u_int	w_level;
131	u_int	w_refcount;
132	u_char	w_Giant_squawked:1;
133	u_char	w_other_squawked:1;
134	u_char	w_same_squawked:1;
135	u_char	w_displayed:1;
136};
137
138struct witness_child_list_entry {
139	struct	witness_child_list_entry *wcl_next;
140	struct	witness *wcl_children[WITNESS_NCHILDREN];
141	u_int	wcl_count;
142};
143
144STAILQ_HEAD(witness_list, witness);
145
146#ifdef BLESSING
147struct witness_blessed {
148	const	char *b_lock1;
149	const	char *b_lock2;
150};
151#endif
152
153struct witness_order_list_entry {
154	const	char *w_name;
155	struct	lock_class *w_class;
156};
157
158#ifdef BLESSING
159static int	blessed(struct witness *, struct witness *);
160#endif
161static int	depart(struct witness *w);
162static struct	witness *enroll(const char *description,
163				struct lock_class *lock_class);
164static int	insertchild(struct witness *parent, struct witness *child);
165static int	isitmychild(struct witness *parent, struct witness *child);
166static int	isitmydescendant(struct witness *parent, struct witness *child);
167static int	itismychild(struct witness *parent, struct witness *child);
168static int	rebalancetree(struct witness_list *list);
169static void	removechild(struct witness *parent, struct witness *child);
170static int	reparentchildren(struct witness *newparent,
171		    struct witness *oldparent);
172static int	sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
173static void	witness_displaydescendants(void(*)(const char *fmt, ...),
174					   struct witness *, int indent);
175static const char *fixup_filename(const char *file);
176static void	witness_leveldescendents(struct witness *parent, int level);
177static void	witness_levelall(void);
178static struct	witness *witness_get(void);
179static void	witness_free(struct witness *m);
180static struct	witness_child_list_entry *witness_child_get(void);
181static void	witness_child_free(struct witness_child_list_entry *wcl);
182static struct	lock_list_entry *witness_lock_list_get(void);
183static void	witness_lock_list_free(struct lock_list_entry *lle);
184static struct	lock_instance *find_instance(struct lock_list_entry *lock_list,
185					     struct lock_object *lock);
186static void	witness_list_lock(struct lock_instance *instance);
187#ifdef DDB
188static void	witness_list(struct thread *td);
189static void	witness_display_list(void(*prnt)(const char *fmt, ...),
190				     struct witness_list *list);
191static void	witness_display(void(*)(const char *fmt, ...));
192#endif
193
194SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW, 0, "Witness Locking");
195
196/*
197 * If set to 0, witness is disabled.  If set to 1, witness performs full lock
198 * order checking for all locks.  If set to 2 or higher, then witness skips
199 * the full lock order check if the lock being acquired is at a higher level
200 * (i.e. farther down in the tree) than the current lock.  This last mode is
201 * somewhat experimental and not considered fully safe.  At runtime, this
202 * value may be set to 0 to turn off witness.  witness is not allowed be
203 * turned on once it is turned off, however.
204 */
205static int witness_watch = 1;
206TUNABLE_INT("debug.witness.watch", &witness_watch);
207SYSCTL_PROC(_debug_witness, OID_AUTO, watch, CTLFLAG_RW | CTLTYPE_INT, NULL, 0,
208    sysctl_debug_witness_watch, "I", "witness is watching lock operations");
209
210#ifdef KDB
211/*
212 * When KDB is enabled and witness_kdb is set to 1, it will cause the system
213 * to drop into kdebug() when:
214 *	- a lock heirarchy violation occurs
215 *	- locks are held when going to sleep.
216 */
217#ifdef WITNESS_KDB
218int	witness_kdb = 1;
219#else
220int	witness_kdb = 0;
221#endif
222TUNABLE_INT("debug.witness.kdb", &witness_kdb);
223SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RW, &witness_kdb, 0, "");
224
225/*
226 * When KDB is enabled and witness_trace is set to 1, it will cause the system
227 * to print a stack trace:
228 *	- a lock heirarchy violation occurs
229 *	- locks are held when going to sleep.
230 */
231int	witness_trace = 1;
232TUNABLE_INT("debug.witness.trace", &witness_trace);
233SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RW, &witness_trace, 0, "");
234#endif /* KDB */
235
236#ifdef WITNESS_SKIPSPIN
237int	witness_skipspin = 1;
238#else
239int	witness_skipspin = 0;
240#endif
241TUNABLE_INT("debug.witness.skipspin", &witness_skipspin);
242SYSCTL_INT(_debug_witness, OID_AUTO, skipspin, CTLFLAG_RDTUN,
243    &witness_skipspin, 0, "");
244
245static struct mtx w_mtx;
246static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
247static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
248static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
249static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
250static struct witness_child_list_entry *w_child_free = NULL;
251static struct lock_list_entry *w_lock_list_free = NULL;
252
253static struct witness w_data[WITNESS_COUNT];
254static struct witness_child_list_entry w_childdata[WITNESS_CHILDCOUNT];
255static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
256
257static struct witness_order_list_entry order_lists[] = {
258	{ "proctree", &lock_class_sx },
259	{ "allproc", &lock_class_sx },
260	{ "Giant", &lock_class_mtx_sleep },
261	{ "filedesc structure", &lock_class_mtx_sleep },
262	{ "pipe mutex", &lock_class_mtx_sleep },
263	{ "sigio lock", &lock_class_mtx_sleep },
264	{ "process group", &lock_class_mtx_sleep },
265	{ "process lock", &lock_class_mtx_sleep },
266	{ "session", &lock_class_mtx_sleep },
267	{ "uidinfo hash", &lock_class_mtx_sleep },
268	{ "uidinfo struct", &lock_class_mtx_sleep },
269	{ "allprison", &lock_class_mtx_sleep },
270	{ NULL, NULL },
271	/*
272	 * Sockets
273	 */
274	{ "filedesc structure", &lock_class_mtx_sleep },
275	{ "accept", &lock_class_mtx_sleep },
276	{ "so_snd", &lock_class_mtx_sleep },
277	{ "so_rcv", &lock_class_mtx_sleep },
278	{ "sellck", &lock_class_mtx_sleep },
279	{ NULL, NULL },
280	/*
281	 * Routing
282	 */
283	{ "so_rcv", &lock_class_mtx_sleep },
284	{ "radix node head", &lock_class_mtx_sleep },
285	{ "rtentry", &lock_class_mtx_sleep },
286	{ "ifaddr", &lock_class_mtx_sleep },
287	{ NULL, NULL },
288	/*
289	 * Multicast - protocol locks before interface locks, after UDP locks.
290	 */
291	{ "udpinp", &lock_class_mtx_sleep },
292	{ "in_multi_mtx", &lock_class_mtx_sleep },
293	{ "igmp_mtx", &lock_class_mtx_sleep },
294	{ "if_addr_mtx", &lock_class_mtx_sleep },
295	{ NULL, NULL },
296	/*
297	 * UNIX Domain Sockets
298	 */
299	{ "unp", &lock_class_mtx_sleep },
300	{ "so_snd", &lock_class_mtx_sleep },
301	{ NULL, NULL },
302	/*
303	 * UDP/IP
304	 */
305	{ "udp", &lock_class_mtx_sleep },
306	{ "udpinp", &lock_class_mtx_sleep },
307	{ "so_snd", &lock_class_mtx_sleep },
308	{ NULL, NULL },
309	/*
310	 * TCP/IP
311	 */
312	{ "tcp", &lock_class_mtx_sleep },
313	{ "tcpinp", &lock_class_mtx_sleep },
314	{ "so_snd", &lock_class_mtx_sleep },
315	{ NULL, NULL },
316	/*
317	 * SLIP
318	 */
319	{ "slip_mtx", &lock_class_mtx_sleep },
320	{ "slip sc_mtx", &lock_class_mtx_sleep },
321	{ NULL, NULL },
322	/*
323	 * netatalk
324	 */
325	{ "ddp_list_mtx", &lock_class_mtx_sleep },
326	{ "ddp_mtx", &lock_class_mtx_sleep },
327	{ NULL, NULL },
328	/*
329	 * BPF
330	 */
331	{ "bpf global lock", &lock_class_mtx_sleep },
332	{ "bpf interface lock", &lock_class_mtx_sleep },
333	{ "bpf cdev lock", &lock_class_mtx_sleep },
334	{ NULL, NULL },
335	/*
336	 * NFS server
337	 */
338	{ "nfsd_mtx", &lock_class_mtx_sleep },
339	{ "so_snd", &lock_class_mtx_sleep },
340	{ NULL, NULL },
341	/*
342	 * CDEV
343	 */
344	{ "system map", &lock_class_mtx_sleep },
345	{ "vm page queue mutex", &lock_class_mtx_sleep },
346	{ "vnode interlock", &lock_class_mtx_sleep },
347	{ "cdev", &lock_class_mtx_sleep },
348	{ NULL, NULL },
349	/*
350	 * spin locks
351	 */
352#ifdef SMP
353	{ "ap boot", &lock_class_mtx_spin },
354#endif
355	{ "sio", &lock_class_mtx_spin },
356#ifdef __i386__
357	{ "cy", &lock_class_mtx_spin },
358#endif
359	{ "uart_hwmtx", &lock_class_mtx_spin },
360	{ "sabtty", &lock_class_mtx_spin },
361	{ "zstty", &lock_class_mtx_spin },
362	{ "ng_node", &lock_class_mtx_spin },
363	{ "ng_worklist", &lock_class_mtx_spin },
364	{ "taskqueue_fast", &lock_class_mtx_spin },
365	{ "intr table", &lock_class_mtx_spin },
366	{ "ithread table lock", &lock_class_mtx_spin },
367	{ "sleepq chain", &lock_class_mtx_spin },
368	{ "sched lock", &lock_class_mtx_spin },
369	{ "turnstile chain", &lock_class_mtx_spin },
370	{ "td_contested", &lock_class_mtx_spin },
371	{ "callout", &lock_class_mtx_spin },
372	{ "entropy harvest mutex", &lock_class_mtx_spin },
373	/*
374	 * leaf locks
375	 */
376	{ "allpmaps", &lock_class_mtx_spin },
377	{ "vm page queue free mutex", &lock_class_mtx_spin },
378	{ "icu", &lock_class_mtx_spin },
379#ifdef SMP
380	{ "smp rendezvous", &lock_class_mtx_spin },
381#if defined(__i386__) || defined(__amd64__)
382	{ "tlb", &lock_class_mtx_spin },
383#endif
384#ifdef __sparc64__
385	{ "ipi", &lock_class_mtx_spin },
386	{ "rtc_mtx", &lock_class_mtx_spin },
387#endif
388#endif
389	{ "clk", &lock_class_mtx_spin },
390	{ "mutex profiling lock", &lock_class_mtx_spin },
391	{ "kse zombie lock", &lock_class_mtx_spin },
392	{ "ALD Queue", &lock_class_mtx_spin },
393#ifdef __ia64__
394	{ "MCA spin lock", &lock_class_mtx_spin },
395#endif
396#if defined(__i386__) || defined(__amd64__)
397	{ "pcicfg", &lock_class_mtx_spin },
398	{ "NDIS thread lock", &lock_class_mtx_spin },
399#endif
400	{ "tw_osl_io_lock", &lock_class_mtx_spin },
401	{ "tw_osl_q_lock", &lock_class_mtx_spin },
402	{ "tw_cl_io_lock", &lock_class_mtx_spin },
403	{ "tw_cl_intr_lock", &lock_class_mtx_spin },
404	{ "tw_cl_gen_lock", &lock_class_mtx_spin },
405	{ NULL, NULL },
406	{ NULL, NULL }
407};
408
409#ifdef BLESSING
410/*
411 * Pairs of locks which have been blessed
412 * Don't complain about order problems with blessed locks
413 */
414static struct witness_blessed blessed_list[] = {
415};
416static int blessed_count =
417	sizeof(blessed_list) / sizeof(struct witness_blessed);
418#endif
419
420/*
421 * List of all locks in the system.
422 */
423TAILQ_HEAD(, lock_object) all_locks = TAILQ_HEAD_INITIALIZER(all_locks);
424
425static struct mtx all_mtx = {
426	{ &lock_class_mtx_sleep,	/* mtx_object.lo_class */
427	  "All locks list",		/* mtx_object.lo_name */
428	  "All locks list",		/* mtx_object.lo_type */
429	  LO_INITIALIZED,		/* mtx_object.lo_flags */
430	  { NULL, NULL },		/* mtx_object.lo_list */
431	  NULL },			/* mtx_object.lo_witness */
432	MTX_UNOWNED, 0			/* mtx_lock, mtx_recurse */
433};
434
435/*
436 * This global is set to 0 once it becomes safe to use the witness code.
437 */
438static int witness_cold = 1;
439
440/*
441 * Global variables for book keeping.
442 */
443static int lock_cur_cnt;
444static int lock_max_cnt;
445
446/*
447 * The WITNESS-enabled diagnostic code.
448 */
449static void
450witness_initialize(void *dummy __unused)
451{
452	struct lock_object *lock;
453	struct witness_order_list_entry *order;
454	struct witness *w, *w1;
455	int i;
456
457	/*
458	 * We have to release Giant before initializing its witness
459	 * structure so that WITNESS doesn't get confused.
460	 */
461	mtx_unlock(&Giant);
462	mtx_assert(&Giant, MA_NOTOWNED);
463
464	CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
465	TAILQ_INSERT_HEAD(&all_locks, &all_mtx.mtx_object, lo_list);
466	mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
467	    MTX_NOWITNESS);
468	for (i = 0; i < WITNESS_COUNT; i++)
469		witness_free(&w_data[i]);
470	for (i = 0; i < WITNESS_CHILDCOUNT; i++)
471		witness_child_free(&w_childdata[i]);
472	for (i = 0; i < LOCK_CHILDCOUNT; i++)
473		witness_lock_list_free(&w_locklistdata[i]);
474
475	/* First add in all the specified order lists. */
476	for (order = order_lists; order->w_name != NULL; order++) {
477		w = enroll(order->w_name, order->w_class);
478		if (w == NULL)
479			continue;
480		w->w_file = "order list";
481		for (order++; order->w_name != NULL; order++) {
482			w1 = enroll(order->w_name, order->w_class);
483			if (w1 == NULL)
484				continue;
485			w1->w_file = "order list";
486			if (!itismychild(w, w1))
487				panic("Not enough memory for static orders!");
488			w = w1;
489		}
490	}
491
492	/* Iterate through all locks and add them to witness. */
493	mtx_lock(&all_mtx);
494	TAILQ_FOREACH(lock, &all_locks, lo_list) {
495		if (lock->lo_flags & LO_WITNESS)
496			lock->lo_witness = enroll(lock->lo_type,
497			    lock->lo_class);
498		else
499			lock->lo_witness = NULL;
500	}
501	mtx_unlock(&all_mtx);
502
503	/* Mark the witness code as being ready for use. */
504	atomic_store_rel_int(&witness_cold, 0);
505
506	mtx_lock(&Giant);
507}
508SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize, NULL)
509
510static int
511sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
512{
513	int error, value;
514
515	value = witness_watch;
516	error = sysctl_handle_int(oidp, &value, 0, req);
517	if (error != 0 || req->newptr == NULL)
518		return (error);
519	error = suser(req->td);
520	if (error != 0)
521		return (error);
522	if (value == witness_watch)
523		return (0);
524	if (value != 0)
525		return (EINVAL);
526	witness_watch = 0;
527	return (0);
528}
529
530void
531witness_init(struct lock_object *lock)
532{
533	struct lock_class *class;
534
535	class = lock->lo_class;
536	if (lock->lo_flags & LO_INITIALIZED)
537		panic("%s: lock (%s) %s is already initialized", __func__,
538		    class->lc_name, lock->lo_name);
539	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
540	    (class->lc_flags & LC_RECURSABLE) == 0)
541		panic("%s: lock (%s) %s can not be recursable", __func__,
542		    class->lc_name, lock->lo_name);
543	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
544	    (class->lc_flags & LC_SLEEPABLE) == 0)
545		panic("%s: lock (%s) %s can not be sleepable", __func__,
546		    class->lc_name, lock->lo_name);
547	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
548	    (class->lc_flags & LC_UPGRADABLE) == 0)
549		panic("%s: lock (%s) %s can not be upgradable", __func__,
550		    class->lc_name, lock->lo_name);
551
552	mtx_lock(&all_mtx);
553	TAILQ_INSERT_TAIL(&all_locks, lock, lo_list);
554	lock->lo_flags |= LO_INITIALIZED;
555	lock_cur_cnt++;
556	if (lock_cur_cnt > lock_max_cnt)
557		lock_max_cnt = lock_cur_cnt;
558	mtx_unlock(&all_mtx);
559	if (!witness_cold && witness_watch != 0 && panicstr == NULL &&
560	    (lock->lo_flags & LO_WITNESS) != 0)
561		lock->lo_witness = enroll(lock->lo_type, class);
562	else
563		lock->lo_witness = NULL;
564}
565
566void
567witness_destroy(struct lock_object *lock)
568{
569	struct witness *w;
570
571	if (witness_cold)
572		panic("lock (%s) %s destroyed while witness_cold",
573		    lock->lo_class->lc_name, lock->lo_name);
574	if ((lock->lo_flags & LO_INITIALIZED) == 0)
575		panic("%s: lock (%s) %s is not initialized", __func__,
576		    lock->lo_class->lc_name, lock->lo_name);
577
578	/* XXX: need to verify that no one holds the lock */
579	w = lock->lo_witness;
580	if (w != NULL) {
581		mtx_lock_spin(&w_mtx);
582		MPASS(w->w_refcount > 0);
583		w->w_refcount--;
584
585		/*
586		 * Lock is already released if we have an allocation failure
587		 * and depart() fails.
588		 */
589		if (w->w_refcount != 0 || depart(w))
590			mtx_unlock_spin(&w_mtx);
591	}
592
593	mtx_lock(&all_mtx);
594	lock_cur_cnt--;
595	TAILQ_REMOVE(&all_locks, lock, lo_list);
596	lock->lo_flags &= ~LO_INITIALIZED;
597	mtx_unlock(&all_mtx);
598}
599
600#ifdef DDB
601static void
602witness_display_list(void(*prnt)(const char *fmt, ...),
603		     struct witness_list *list)
604{
605	struct witness *w;
606
607	STAILQ_FOREACH(w, list, w_typelist) {
608		if (w->w_file == NULL || w->w_level > 0)
609			continue;
610		/*
611		 * This lock has no anscestors, display its descendants.
612		 */
613		witness_displaydescendants(prnt, w, 0);
614	}
615}
616
617static void
618witness_display(void(*prnt)(const char *fmt, ...))
619{
620	struct witness *w;
621
622	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
623	witness_levelall();
624
625	/* Clear all the displayed flags. */
626	STAILQ_FOREACH(w, &w_all, w_list) {
627		w->w_displayed = 0;
628	}
629
630	/*
631	 * First, handle sleep locks which have been acquired at least
632	 * once.
633	 */
634	prnt("Sleep locks:\n");
635	witness_display_list(prnt, &w_sleep);
636
637	/*
638	 * Now do spin locks which have been acquired at least once.
639	 */
640	prnt("\nSpin locks:\n");
641	witness_display_list(prnt, &w_spin);
642
643	/*
644	 * Finally, any locks which have not been acquired yet.
645	 */
646	prnt("\nLocks which were never acquired:\n");
647	STAILQ_FOREACH(w, &w_all, w_list) {
648		if (w->w_file != NULL || w->w_refcount == 0)
649			continue;
650		prnt("%s\n", w->w_name);
651	}
652}
653#endif /* DDB */
654
655/* Trim useless garbage from filenames. */
656static const char *
657fixup_filename(const char *file)
658{
659
660	if (file == NULL)
661		return (NULL);
662	while (strncmp(file, "../", 3) == 0)
663		file += 3;
664	return (file);
665}
666
667int
668witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
669{
670
671	if (witness_watch == 0 || panicstr != NULL)
672		return (0);
673
674	/* Require locks that witness knows about. */
675	if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
676	    lock2->lo_witness == NULL)
677		return (EINVAL);
678
679	MPASS(!mtx_owned(&w_mtx));
680	mtx_lock_spin(&w_mtx);
681
682	/*
683	 * If we already have either an explicit or implied lock order that
684	 * is the other way around, then return an error.
685	 */
686	if (isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
687		mtx_unlock_spin(&w_mtx);
688		return (EDOOFUS);
689	}
690
691	/* Try to add the new order. */
692	CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
693	    lock2->lo_type, lock1->lo_type);
694	if (!itismychild(lock1->lo_witness, lock2->lo_witness))
695		return (ENOMEM);
696	mtx_unlock_spin(&w_mtx);
697	return (0);
698}
699
700void
701witness_checkorder(struct lock_object *lock, int flags, const char *file,
702    int line)
703{
704	struct lock_list_entry **lock_list, *lle;
705	struct lock_instance *lock1, *lock2;
706	struct lock_class *class;
707	struct witness *w, *w1;
708	struct thread *td;
709	int i, j;
710
711	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
712	    panicstr != NULL)
713		return;
714
715	/*
716	 * Try locks do not block if they fail to acquire the lock, thus
717	 * there is no danger of deadlocks or of switching while holding a
718	 * spin lock if we acquire a lock via a try operation.  This
719	 * function shouldn't even be called for try locks, so panic if
720	 * that happens.
721	 */
722	if (flags & LOP_TRYLOCK)
723		panic("%s should not be called for try lock operations",
724		    __func__);
725
726	w = lock->lo_witness;
727	class = lock->lo_class;
728	td = curthread;
729	file = fixup_filename(file);
730
731	if (class->lc_flags & LC_SLEEPLOCK) {
732		/*
733		 * Since spin locks include a critical section, this check
734		 * implicitly enforces a lock order of all sleep locks before
735		 * all spin locks.
736		 */
737		if (td->td_critnest != 0 && !kdb_active)
738			panic("blockable sleep lock (%s) %s @ %s:%d",
739			    class->lc_name, lock->lo_name, file, line);
740
741		/*
742		 * If this is the first lock acquired then just return as
743		 * no order checking is needed.
744		 */
745		if (td->td_sleeplocks == NULL)
746			return;
747		lock_list = &td->td_sleeplocks;
748	} else {
749		/*
750		 * If this is the first lock, just return as no order
751		 * checking is needed.  We check this in both if clauses
752		 * here as unifying the check would require us to use a
753		 * critical section to ensure we don't migrate while doing
754		 * the check.  Note that if this is not the first lock, we
755		 * are already in a critical section and are safe for the
756		 * rest of the check.
757		 */
758		if (PCPU_GET(spinlocks) == NULL)
759			return;
760		lock_list = PCPU_PTR(spinlocks);
761	}
762
763	/*
764	 * Check to see if we are recursing on a lock we already own.  If
765	 * so, make sure that we don't mismatch exclusive and shared lock
766	 * acquires.
767	 */
768	lock1 = find_instance(*lock_list, lock);
769	if (lock1 != NULL) {
770		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
771		    (flags & LOP_EXCLUSIVE) == 0) {
772			printf("shared lock of (%s) %s @ %s:%d\n",
773			    class->lc_name, lock->lo_name, file, line);
774			printf("while exclusively locked from %s:%d\n",
775			    lock1->li_file, lock1->li_line);
776			panic("share->excl");
777		}
778		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
779		    (flags & LOP_EXCLUSIVE) != 0) {
780			printf("exclusive lock of (%s) %s @ %s:%d\n",
781			    class->lc_name, lock->lo_name, file, line);
782			printf("while share locked from %s:%d\n",
783			    lock1->li_file, lock1->li_line);
784			panic("excl->share");
785		}
786		return;
787	}
788
789	/*
790	 * Try locks do not block if they fail to acquire the lock, thus
791	 * there is no danger of deadlocks or of switching while holding a
792	 * spin lock if we acquire a lock via a try operation.
793	 */
794	if (flags & LOP_TRYLOCK)
795		return;
796
797	/*
798	 * Check for duplicate locks of the same type.  Note that we only
799	 * have to check for this on the last lock we just acquired.  Any
800	 * other cases will be caught as lock order violations.
801	 */
802	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
803	w1 = lock1->li_lock->lo_witness;
804	if (w1 == w) {
805		if (w->w_same_squawked || (lock->lo_flags & LO_DUPOK) ||
806		    (flags & LOP_DUPOK))
807			return;
808		w->w_same_squawked = 1;
809		printf("acquiring duplicate lock of same type: \"%s\"\n",
810			lock->lo_type);
811		printf(" 1st %s @ %s:%d\n", lock1->li_lock->lo_name,
812		    lock1->li_file, lock1->li_line);
813		printf(" 2nd %s @ %s:%d\n", lock->lo_name, file, line);
814#ifdef KDB
815		goto debugger;
816#else
817		return;
818#endif
819	}
820	MPASS(!mtx_owned(&w_mtx));
821	mtx_lock_spin(&w_mtx);
822	/*
823	 * If we have a known higher number just say ok
824	 */
825	if (witness_watch > 1 && w->w_level > w1->w_level) {
826		mtx_unlock_spin(&w_mtx);
827		return;
828	}
829	/*
830	 * If we know that the the lock we are acquiring comes after
831	 * the lock we most recently acquired in the lock order tree,
832	 * then there is no need for any further checks.
833	 */
834	if (isitmydescendant(w1, w)) {
835		mtx_unlock_spin(&w_mtx);
836		return;
837	}
838	for (j = 0, lle = *lock_list; lle != NULL; lle = lle->ll_next) {
839		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
840
841			MPASS(j < WITNESS_COUNT);
842			lock1 = &lle->ll_children[i];
843			w1 = lock1->li_lock->lo_witness;
844
845			/*
846			 * If this lock doesn't undergo witness checking,
847			 * then skip it.
848			 */
849			if (w1 == NULL) {
850				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
851				    ("lock missing witness structure"));
852				continue;
853			}
854			/*
855			 * If we are locking Giant and this is a sleepable
856			 * lock, then skip it.
857			 */
858			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
859			    lock == &Giant.mtx_object)
860				continue;
861			/*
862			 * If we are locking a sleepable lock and this lock
863			 * is Giant, then skip it.
864			 */
865			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
866			    lock1->li_lock == &Giant.mtx_object)
867				continue;
868			/*
869			 * If we are locking a sleepable lock and this lock
870			 * isn't sleepable, we want to treat it as a lock
871			 * order violation to enfore a general lock order of
872			 * sleepable locks before non-sleepable locks.
873			 */
874			if (!((lock->lo_flags & LO_SLEEPABLE) != 0 &&
875			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
876			    /*
877			     * Check the lock order hierarchy for a reveresal.
878			     */
879			    if (!isitmydescendant(w, w1))
880				continue;
881			/*
882			 * We have a lock order violation, check to see if it
883			 * is allowed or has already been yelled about.
884			 */
885			mtx_unlock_spin(&w_mtx);
886#ifdef BLESSING
887			/*
888			 * If the lock order is blessed, just bail.  We don't
889			 * look for other lock order violations though, which
890			 * may be a bug.
891			 */
892			if (blessed(w, w1))
893				return;
894#endif
895			if (lock1->li_lock == &Giant.mtx_object) {
896				if (w1->w_Giant_squawked)
897					return;
898				else
899					w1->w_Giant_squawked = 1;
900			} else {
901				if (w1->w_other_squawked)
902					return;
903				else
904					w1->w_other_squawked = 1;
905			}
906			/*
907			 * Ok, yell about it.
908			 */
909			printf("lock order reversal\n");
910			/*
911			 * Try to locate an earlier lock with
912			 * witness w in our list.
913			 */
914			do {
915				lock2 = &lle->ll_children[i];
916				MPASS(lock2->li_lock != NULL);
917				if (lock2->li_lock->lo_witness == w)
918					break;
919				if (i == 0 && lle->ll_next != NULL) {
920					lle = lle->ll_next;
921					i = lle->ll_count - 1;
922					MPASS(i >= 0 && i < LOCK_NCHILDREN);
923				} else
924					i--;
925			} while (i >= 0);
926			if (i < 0) {
927				printf(" 1st %p %s (%s) @ %s:%d\n",
928				    lock1->li_lock, lock1->li_lock->lo_name,
929				    lock1->li_lock->lo_type, lock1->li_file,
930				    lock1->li_line);
931				printf(" 2nd %p %s (%s) @ %s:%d\n", lock,
932				    lock->lo_name, lock->lo_type, file, line);
933			} else {
934				printf(" 1st %p %s (%s) @ %s:%d\n",
935				    lock2->li_lock, lock2->li_lock->lo_name,
936				    lock2->li_lock->lo_type, lock2->li_file,
937				    lock2->li_line);
938				printf(" 2nd %p %s (%s) @ %s:%d\n",
939				    lock1->li_lock, lock1->li_lock->lo_name,
940				    lock1->li_lock->lo_type, lock1->li_file,
941				    lock1->li_line);
942				printf(" 3rd %p %s (%s) @ %s:%d\n", lock,
943				    lock->lo_name, lock->lo_type, file, line);
944			}
945#ifdef KDB
946			goto debugger;
947#else
948			return;
949#endif
950		}
951	}
952	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
953	/*
954	 * If requested, build a new lock order.  However, don't build a new
955	 * relationship between a sleepable lock and Giant if it is in the
956	 * wrong direction.  The correct lock order is that sleepable locks
957	 * always come before Giant.
958	 */
959	if (flags & LOP_NEWORDER &&
960	    !(lock1->li_lock == &Giant.mtx_object &&
961	    (lock->lo_flags & LO_SLEEPABLE) != 0)) {
962		CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
963		    lock->lo_type, lock1->li_lock->lo_type);
964		if (!itismychild(lock1->li_lock->lo_witness, w))
965			/* Witness is dead. */
966			return;
967	}
968	mtx_unlock_spin(&w_mtx);
969	return;
970
971#ifdef KDB
972debugger:
973	if (witness_trace)
974		kdb_backtrace();
975	if (witness_kdb)
976		kdb_enter(__func__);
977#endif
978}
979
980void
981witness_lock(struct lock_object *lock, int flags, const char *file, int line)
982{
983	struct lock_list_entry **lock_list, *lle;
984	struct lock_instance *instance;
985	struct witness *w;
986	struct thread *td;
987
988	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
989	    panicstr != NULL)
990		return;
991	w = lock->lo_witness;
992	td = curthread;
993	file = fixup_filename(file);
994
995	/* Determine lock list for this lock. */
996	if (lock->lo_class->lc_flags & LC_SLEEPLOCK)
997		lock_list = &td->td_sleeplocks;
998	else
999		lock_list = PCPU_PTR(spinlocks);
1000
1001	/* Check to see if we are recursing on a lock we already own. */
1002	instance = find_instance(*lock_list, lock);
1003	if (instance != NULL) {
1004		instance->li_flags++;
1005		CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1006		    td->td_proc->p_pid, lock->lo_name,
1007		    instance->li_flags & LI_RECURSEMASK);
1008		instance->li_file = file;
1009		instance->li_line = line;
1010		return;
1011	}
1012
1013	/* Update per-witness last file and line acquire. */
1014	w->w_file = file;
1015	w->w_line = line;
1016
1017	/* Find the next open lock instance in the list and fill it. */
1018	lle = *lock_list;
1019	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1020		lle = witness_lock_list_get();
1021		if (lle == NULL)
1022			return;
1023		lle->ll_next = *lock_list;
1024		CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1025		    td->td_proc->p_pid, lle);
1026		*lock_list = lle;
1027	}
1028	instance = &lle->ll_children[lle->ll_count++];
1029	instance->li_lock = lock;
1030	instance->li_line = line;
1031	instance->li_file = file;
1032	if ((flags & LOP_EXCLUSIVE) != 0)
1033		instance->li_flags = LI_EXCLUSIVE;
1034	else
1035		instance->li_flags = 0;
1036	CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1037	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1038}
1039
1040void
1041witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1042{
1043	struct lock_instance *instance;
1044	struct lock_class *class;
1045
1046	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1047	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1048		return;
1049	class = lock->lo_class;
1050	file = fixup_filename(file);
1051	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1052		panic("upgrade of non-upgradable lock (%s) %s @ %s:%d",
1053		    class->lc_name, lock->lo_name, file, line);
1054	if ((flags & LOP_TRYLOCK) == 0)
1055		panic("non-try upgrade of lock (%s) %s @ %s:%d", class->lc_name,
1056		    lock->lo_name, file, line);
1057	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1058		panic("upgrade of non-sleep lock (%s) %s @ %s:%d",
1059		    class->lc_name, lock->lo_name, file, line);
1060	instance = find_instance(curthread->td_sleeplocks, lock);
1061	if (instance == NULL)
1062		panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1063		    class->lc_name, lock->lo_name, file, line);
1064	if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1065		panic("upgrade of exclusive lock (%s) %s @ %s:%d",
1066		    class->lc_name, lock->lo_name, file, line);
1067	if ((instance->li_flags & LI_RECURSEMASK) != 0)
1068		panic("upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1069		    class->lc_name, lock->lo_name,
1070		    instance->li_flags & LI_RECURSEMASK, file, line);
1071	instance->li_flags |= LI_EXCLUSIVE;
1072}
1073
1074void
1075witness_downgrade(struct lock_object *lock, int flags, const char *file,
1076    int line)
1077{
1078	struct lock_instance *instance;
1079	struct lock_class *class;
1080
1081	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1082	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1083		return;
1084	class = lock->lo_class;
1085	file = fixup_filename(file);
1086	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1087		panic("downgrade of non-upgradable lock (%s) %s @ %s:%d",
1088		    class->lc_name, lock->lo_name, file, line);
1089	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1090		panic("downgrade of non-sleep lock (%s) %s @ %s:%d",
1091		    class->lc_name, lock->lo_name, file, line);
1092	instance = find_instance(curthread->td_sleeplocks, lock);
1093	if (instance == NULL)
1094		panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1095		    class->lc_name, lock->lo_name, file, line);
1096	if ((instance->li_flags & LI_EXCLUSIVE) == 0)
1097		panic("downgrade of shared lock (%s) %s @ %s:%d",
1098		    class->lc_name, lock->lo_name, file, line);
1099	if ((instance->li_flags & LI_RECURSEMASK) != 0)
1100		panic("downgrade of recursed lock (%s) %s r=%d @ %s:%d",
1101		    class->lc_name, lock->lo_name,
1102		    instance->li_flags & LI_RECURSEMASK, file, line);
1103	instance->li_flags &= ~LI_EXCLUSIVE;
1104}
1105
1106void
1107witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
1108{
1109	struct lock_list_entry **lock_list, *lle;
1110	struct lock_instance *instance;
1111	struct lock_class *class;
1112	struct thread *td;
1113	register_t s;
1114	int i, j;
1115
1116	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
1117	    panicstr != NULL)
1118		return;
1119	td = curthread;
1120	class = lock->lo_class;
1121	file = fixup_filename(file);
1122
1123	/* Find lock instance associated with this lock. */
1124	if (class->lc_flags & LC_SLEEPLOCK)
1125		lock_list = &td->td_sleeplocks;
1126	else
1127		lock_list = PCPU_PTR(spinlocks);
1128	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
1129		for (i = 0; i < (*lock_list)->ll_count; i++) {
1130			instance = &(*lock_list)->ll_children[i];
1131			if (instance->li_lock == lock)
1132				goto found;
1133		}
1134	panic("lock (%s) %s not locked @ %s:%d", class->lc_name, lock->lo_name,
1135	    file, line);
1136found:
1137
1138	/* First, check for shared/exclusive mismatches. */
1139	if ((instance->li_flags & LI_EXCLUSIVE) != 0 &&
1140	    (flags & LOP_EXCLUSIVE) == 0) {
1141		printf("shared unlock of (%s) %s @ %s:%d\n", class->lc_name,
1142		    lock->lo_name, file, line);
1143		printf("while exclusively locked from %s:%d\n",
1144		    instance->li_file, instance->li_line);
1145		panic("excl->ushare");
1146	}
1147	if ((instance->li_flags & LI_EXCLUSIVE) == 0 &&
1148	    (flags & LOP_EXCLUSIVE) != 0) {
1149		printf("exclusive unlock of (%s) %s @ %s:%d\n", class->lc_name,
1150		    lock->lo_name, file, line);
1151		printf("while share locked from %s:%d\n", instance->li_file,
1152		    instance->li_line);
1153		panic("share->uexcl");
1154	}
1155
1156	/* If we are recursed, unrecurse. */
1157	if ((instance->li_flags & LI_RECURSEMASK) > 0) {
1158		CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
1159		    td->td_proc->p_pid, instance->li_lock->lo_name,
1160		    instance->li_flags);
1161		instance->li_flags--;
1162		return;
1163	}
1164
1165	/* Otherwise, remove this item from the list. */
1166	s = intr_disable();
1167	CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
1168	    td->td_proc->p_pid, instance->li_lock->lo_name,
1169	    (*lock_list)->ll_count - 1);
1170	for (j = i; j < (*lock_list)->ll_count - 1; j++)
1171		(*lock_list)->ll_children[j] =
1172		    (*lock_list)->ll_children[j + 1];
1173	(*lock_list)->ll_count--;
1174	intr_restore(s);
1175
1176	/* If this lock list entry is now empty, free it. */
1177	if ((*lock_list)->ll_count == 0) {
1178		lle = *lock_list;
1179		*lock_list = lle->ll_next;
1180		CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
1181		    td->td_proc->p_pid, lle);
1182		witness_lock_list_free(lle);
1183	}
1184}
1185
1186/*
1187 * Warn if any locks other than 'lock' are held.  Flags can be passed in to
1188 * exempt Giant and sleepable locks from the checks as well.  If any
1189 * non-exempt locks are held, then a supplied message is printed to the
1190 * console along with a list of the offending locks.  If indicated in the
1191 * flags then a failure results in a panic as well.
1192 */
1193int
1194witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1195{
1196	struct lock_list_entry *lle;
1197	struct lock_instance *lock1;
1198	struct thread *td;
1199	va_list ap;
1200	int i, n;
1201
1202	if (witness_cold || witness_watch == 0 || panicstr != NULL)
1203		return (0);
1204	n = 0;
1205	td = curthread;
1206	for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1207		for (i = lle->ll_count - 1; i >= 0; i--) {
1208			lock1 = &lle->ll_children[i];
1209			if (lock1->li_lock == lock)
1210				continue;
1211			if (flags & WARN_GIANTOK &&
1212			    lock1->li_lock == &Giant.mtx_object)
1213				continue;
1214			if (flags & WARN_SLEEPOK &&
1215			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1216				continue;
1217			if (n == 0) {
1218				va_start(ap, fmt);
1219				vprintf(fmt, ap);
1220				va_end(ap);
1221				printf(" with the following");
1222				if (flags & WARN_SLEEPOK)
1223					printf(" non-sleepable");
1224				printf(" locks held:\n");
1225			}
1226			n++;
1227			witness_list_lock(lock1);
1228		}
1229	if (PCPU_GET(spinlocks) != NULL) {
1230		/*
1231		 * Since we already hold a spinlock preemption is
1232		 * already blocked.
1233		 */
1234		if (n == 0) {
1235			va_start(ap, fmt);
1236			vprintf(fmt, ap);
1237			va_end(ap);
1238			printf(" with the following");
1239			if (flags & WARN_SLEEPOK)
1240				printf(" non-sleepable");
1241			printf(" locks held:\n");
1242		}
1243		n += witness_list_locks(PCPU_PTR(spinlocks));
1244	}
1245	if (flags & WARN_PANIC && n)
1246		panic("witness_warn");
1247#ifdef KDB
1248	else if (witness_kdb && n)
1249		kdb_enter(__func__);
1250	else if (witness_trace && n)
1251		kdb_backtrace();
1252#endif
1253	return (n);
1254}
1255
1256const char *
1257witness_file(struct lock_object *lock)
1258{
1259	struct witness *w;
1260
1261	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1262		return ("?");
1263	w = lock->lo_witness;
1264	return (w->w_file);
1265}
1266
1267int
1268witness_line(struct lock_object *lock)
1269{
1270	struct witness *w;
1271
1272	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1273		return (0);
1274	w = lock->lo_witness;
1275	return (w->w_line);
1276}
1277
1278static struct witness *
1279enroll(const char *description, struct lock_class *lock_class)
1280{
1281	struct witness *w;
1282
1283	if (witness_watch == 0 || panicstr != NULL)
1284		return (NULL);
1285	if ((lock_class->lc_flags & LC_SPINLOCK) && witness_skipspin)
1286		return (NULL);
1287	mtx_lock_spin(&w_mtx);
1288	STAILQ_FOREACH(w, &w_all, w_list) {
1289		if (w->w_name == description || (w->w_refcount > 0 &&
1290		    strcmp(description, w->w_name) == 0)) {
1291			w->w_refcount++;
1292			mtx_unlock_spin(&w_mtx);
1293			if (lock_class != w->w_class)
1294				panic(
1295				"lock (%s) %s does not match earlier (%s) lock",
1296				    description, lock_class->lc_name,
1297				    w->w_class->lc_name);
1298			return (w);
1299		}
1300	}
1301	/*
1302	 * This isn't quite right, as witness_cold is still 0 while we
1303	 * enroll all the locks initialized before witness_initialize().
1304	 */
1305	if ((lock_class->lc_flags & LC_SPINLOCK) && !witness_cold) {
1306		mtx_unlock_spin(&w_mtx);
1307		panic("spin lock %s not in order list", description);
1308	}
1309	if ((w = witness_get()) == NULL)
1310		return (NULL);
1311	w->w_name = description;
1312	w->w_class = lock_class;
1313	w->w_refcount = 1;
1314	STAILQ_INSERT_HEAD(&w_all, w, w_list);
1315	if (lock_class->lc_flags & LC_SPINLOCK)
1316		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1317	else if (lock_class->lc_flags & LC_SLEEPLOCK)
1318		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1319	else {
1320		mtx_unlock_spin(&w_mtx);
1321		panic("lock class %s is not sleep or spin",
1322		    lock_class->lc_name);
1323	}
1324	mtx_unlock_spin(&w_mtx);
1325	return (w);
1326}
1327
1328/* Don't let the door bang you on the way out... */
1329static int
1330depart(struct witness *w)
1331{
1332	struct witness_child_list_entry *wcl, *nwcl;
1333	struct witness_list *list;
1334	struct witness *parent;
1335
1336	MPASS(w->w_refcount == 0);
1337	if (w->w_class->lc_flags & LC_SLEEPLOCK)
1338		list = &w_sleep;
1339	else
1340		list = &w_spin;
1341	/*
1342	 * First, we run through the entire tree looking for any
1343	 * witnesses that the outgoing witness is a child of.  For
1344	 * each parent that we find, we reparent all the direct
1345	 * children of the outgoing witness to its parent.
1346	 */
1347	STAILQ_FOREACH(parent, list, w_typelist) {
1348		if (!isitmychild(parent, w))
1349			continue;
1350		removechild(parent, w);
1351		if (!reparentchildren(parent, w))
1352			return (0);
1353	}
1354
1355	/*
1356	 * Now we go through and free up the child list of the
1357	 * outgoing witness.
1358	 */
1359	for (wcl = w->w_children; wcl != NULL; wcl = nwcl) {
1360		nwcl = wcl->wcl_next;
1361		witness_child_free(wcl);
1362	}
1363
1364	/*
1365	 * Detach from various lists and free.
1366	 */
1367	STAILQ_REMOVE(list, w, witness, w_typelist);
1368	STAILQ_REMOVE(&w_all, w, witness, w_list);
1369	witness_free(w);
1370
1371	/* Finally, fixup the tree. */
1372	return (rebalancetree(list));
1373}
1374
1375/*
1376 * Prune an entire lock order tree.  We look for cases where a lock
1377 * is now both a descendant and a direct child of a given lock.  In
1378 * that case, we want to remove the direct child link from the tree.
1379 *
1380 * Returns false if insertchild() fails.
1381 */
1382static int
1383rebalancetree(struct witness_list *list)
1384{
1385	struct witness *child, *parent;
1386
1387	STAILQ_FOREACH(child, list, w_typelist) {
1388		STAILQ_FOREACH(parent, list, w_typelist) {
1389			if (!isitmychild(parent, child))
1390				continue;
1391			removechild(parent, child);
1392			if (isitmydescendant(parent, child))
1393				continue;
1394			if (!insertchild(parent, child))
1395				return (0);
1396		}
1397	}
1398	witness_levelall();
1399	return (1);
1400}
1401
1402/*
1403 * Add "child" as a direct child of "parent".  Returns false if
1404 * we fail due to out of memory.
1405 */
1406static int
1407insertchild(struct witness *parent, struct witness *child)
1408{
1409	struct witness_child_list_entry **wcl;
1410
1411	MPASS(child != NULL && parent != NULL);
1412
1413	/*
1414	 * Insert "child" after "parent"
1415	 */
1416	wcl = &parent->w_children;
1417	while (*wcl != NULL && (*wcl)->wcl_count == WITNESS_NCHILDREN)
1418		wcl = &(*wcl)->wcl_next;
1419	if (*wcl == NULL) {
1420		*wcl = witness_child_get();
1421		if (*wcl == NULL)
1422			return (0);
1423	}
1424	(*wcl)->wcl_children[(*wcl)->wcl_count++] = child;
1425
1426	return (1);
1427}
1428
1429/*
1430 * Make all the direct descendants of oldparent be direct descendants
1431 * of newparent.
1432 */
1433static int
1434reparentchildren(struct witness *newparent, struct witness *oldparent)
1435{
1436	struct witness_child_list_entry *wcl;
1437	int i;
1438
1439	/* Avoid making a witness a child of itself. */
1440	MPASS(!isitmychild(oldparent, newparent));
1441
1442	for (wcl = oldparent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1443		for (i = 0; i < wcl->wcl_count; i++)
1444			if (!insertchild(newparent, wcl->wcl_children[i]))
1445				return (0);
1446	return (1);
1447}
1448
1449static int
1450itismychild(struct witness *parent, struct witness *child)
1451{
1452	struct witness_list *list;
1453
1454	MPASS(child != NULL && parent != NULL);
1455	if ((parent->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) !=
1456	    (child->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)))
1457		panic(
1458		"%s: parent (%s) and child (%s) are not the same lock type",
1459		    __func__, parent->w_class->lc_name,
1460		    child->w_class->lc_name);
1461
1462	if (!insertchild(parent, child))
1463		return (0);
1464
1465	if (parent->w_class->lc_flags & LC_SLEEPLOCK)
1466		list = &w_sleep;
1467	else
1468		list = &w_spin;
1469	return (rebalancetree(list));
1470}
1471
1472static void
1473removechild(struct witness *parent, struct witness *child)
1474{
1475	struct witness_child_list_entry **wcl, *wcl1;
1476	int i;
1477
1478	for (wcl = &parent->w_children; *wcl != NULL; wcl = &(*wcl)->wcl_next)
1479		for (i = 0; i < (*wcl)->wcl_count; i++)
1480			if ((*wcl)->wcl_children[i] == child)
1481				goto found;
1482	return;
1483found:
1484	(*wcl)->wcl_count--;
1485	if ((*wcl)->wcl_count > i)
1486		(*wcl)->wcl_children[i] =
1487		    (*wcl)->wcl_children[(*wcl)->wcl_count];
1488	MPASS((*wcl)->wcl_children[i] != NULL);
1489	if ((*wcl)->wcl_count != 0)
1490		return;
1491	wcl1 = *wcl;
1492	*wcl = wcl1->wcl_next;
1493	witness_child_free(wcl1);
1494}
1495
1496static int
1497isitmychild(struct witness *parent, struct witness *child)
1498{
1499	struct witness_child_list_entry *wcl;
1500	int i;
1501
1502	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1503		for (i = 0; i < wcl->wcl_count; i++) {
1504			if (wcl->wcl_children[i] == child)
1505				return (1);
1506		}
1507	}
1508	return (0);
1509}
1510
1511static int
1512isitmydescendant(struct witness *parent, struct witness *child)
1513{
1514	struct witness_child_list_entry *wcl;
1515	int i, j;
1516
1517	if (isitmychild(parent, child))
1518		return (1);
1519	j = 0;
1520	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1521		MPASS(j < 1000);
1522		for (i = 0; i < wcl->wcl_count; i++) {
1523			if (isitmydescendant(wcl->wcl_children[i], child))
1524				return (1);
1525		}
1526		j++;
1527	}
1528	return (0);
1529}
1530
1531static void
1532witness_levelall (void)
1533{
1534	struct witness_list *list;
1535	struct witness *w, *w1;
1536
1537	/*
1538	 * First clear all levels.
1539	 */
1540	STAILQ_FOREACH(w, &w_all, w_list) {
1541		w->w_level = 0;
1542	}
1543
1544	/*
1545	 * Look for locks with no parent and level all their descendants.
1546	 */
1547	STAILQ_FOREACH(w, &w_all, w_list) {
1548		/*
1549		 * This is just an optimization, technically we could get
1550		 * away just walking the all list each time.
1551		 */
1552		if (w->w_class->lc_flags & LC_SLEEPLOCK)
1553			list = &w_sleep;
1554		else
1555			list = &w_spin;
1556		STAILQ_FOREACH(w1, list, w_typelist) {
1557			if (isitmychild(w1, w))
1558				goto skip;
1559		}
1560		witness_leveldescendents(w, 0);
1561	skip:
1562		;	/* silence GCC 3.x */
1563	}
1564}
1565
1566static void
1567witness_leveldescendents(struct witness *parent, int level)
1568{
1569	struct witness_child_list_entry *wcl;
1570	int i;
1571
1572	if (parent->w_level < level)
1573		parent->w_level = level;
1574	level++;
1575	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1576		for (i = 0; i < wcl->wcl_count; i++)
1577			witness_leveldescendents(wcl->wcl_children[i], level);
1578}
1579
1580static void
1581witness_displaydescendants(void(*prnt)(const char *fmt, ...),
1582			   struct witness *parent, int indent)
1583{
1584	struct witness_child_list_entry *wcl;
1585	int i, level;
1586
1587	level = parent->w_level;
1588	prnt("%-2d", level);
1589	for (i = 0; i < indent; i++)
1590		prnt(" ");
1591	if (parent->w_refcount > 0)
1592		prnt("%s", parent->w_name);
1593	else
1594		prnt("(dead)");
1595	if (parent->w_displayed) {
1596		prnt(" -- (already displayed)\n");
1597		return;
1598	}
1599	parent->w_displayed = 1;
1600	if (parent->w_refcount > 0) {
1601		if (parent->w_file != NULL)
1602			prnt(" -- last acquired @ %s:%d", parent->w_file,
1603			    parent->w_line);
1604	}
1605	prnt("\n");
1606	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1607		for (i = 0; i < wcl->wcl_count; i++)
1608			    witness_displaydescendants(prnt,
1609				wcl->wcl_children[i], indent + 1);
1610}
1611
1612#ifdef BLESSING
1613static int
1614blessed(struct witness *w1, struct witness *w2)
1615{
1616	int i;
1617	struct witness_blessed *b;
1618
1619	for (i = 0; i < blessed_count; i++) {
1620		b = &blessed_list[i];
1621		if (strcmp(w1->w_name, b->b_lock1) == 0) {
1622			if (strcmp(w2->w_name, b->b_lock2) == 0)
1623				return (1);
1624			continue;
1625		}
1626		if (strcmp(w1->w_name, b->b_lock2) == 0)
1627			if (strcmp(w2->w_name, b->b_lock1) == 0)
1628				return (1);
1629	}
1630	return (0);
1631}
1632#endif
1633
1634static struct witness *
1635witness_get(void)
1636{
1637	struct witness *w;
1638
1639	if (witness_watch == 0) {
1640		mtx_unlock_spin(&w_mtx);
1641		return (NULL);
1642	}
1643	if (STAILQ_EMPTY(&w_free)) {
1644		witness_watch = 0;
1645		mtx_unlock_spin(&w_mtx);
1646		printf("%s: witness exhausted\n", __func__);
1647		return (NULL);
1648	}
1649	w = STAILQ_FIRST(&w_free);
1650	STAILQ_REMOVE_HEAD(&w_free, w_list);
1651	bzero(w, sizeof(*w));
1652	return (w);
1653}
1654
1655static void
1656witness_free(struct witness *w)
1657{
1658
1659	STAILQ_INSERT_HEAD(&w_free, w, w_list);
1660}
1661
1662static struct witness_child_list_entry *
1663witness_child_get(void)
1664{
1665	struct witness_child_list_entry *wcl;
1666
1667	if (witness_watch == 0) {
1668		mtx_unlock_spin(&w_mtx);
1669		return (NULL);
1670	}
1671	wcl = w_child_free;
1672	if (wcl == NULL) {
1673		witness_watch = 0;
1674		mtx_unlock_spin(&w_mtx);
1675		printf("%s: witness exhausted\n", __func__);
1676		return (NULL);
1677	}
1678	w_child_free = wcl->wcl_next;
1679	bzero(wcl, sizeof(*wcl));
1680	return (wcl);
1681}
1682
1683static void
1684witness_child_free(struct witness_child_list_entry *wcl)
1685{
1686
1687	wcl->wcl_next = w_child_free;
1688	w_child_free = wcl;
1689}
1690
1691static struct lock_list_entry *
1692witness_lock_list_get(void)
1693{
1694	struct lock_list_entry *lle;
1695
1696	if (witness_watch == 0)
1697		return (NULL);
1698	mtx_lock_spin(&w_mtx);
1699	lle = w_lock_list_free;
1700	if (lle == NULL) {
1701		witness_watch = 0;
1702		mtx_unlock_spin(&w_mtx);
1703		printf("%s: witness exhausted\n", __func__);
1704		return (NULL);
1705	}
1706	w_lock_list_free = lle->ll_next;
1707	mtx_unlock_spin(&w_mtx);
1708	bzero(lle, sizeof(*lle));
1709	return (lle);
1710}
1711
1712static void
1713witness_lock_list_free(struct lock_list_entry *lle)
1714{
1715
1716	mtx_lock_spin(&w_mtx);
1717	lle->ll_next = w_lock_list_free;
1718	w_lock_list_free = lle;
1719	mtx_unlock_spin(&w_mtx);
1720}
1721
1722static struct lock_instance *
1723find_instance(struct lock_list_entry *lock_list, struct lock_object *lock)
1724{
1725	struct lock_list_entry *lle;
1726	struct lock_instance *instance;
1727	int i;
1728
1729	for (lle = lock_list; lle != NULL; lle = lle->ll_next)
1730		for (i = lle->ll_count - 1; i >= 0; i--) {
1731			instance = &lle->ll_children[i];
1732			if (instance->li_lock == lock)
1733				return (instance);
1734		}
1735	return (NULL);
1736}
1737
1738static void
1739witness_list_lock(struct lock_instance *instance)
1740{
1741	struct lock_object *lock;
1742
1743	lock = instance->li_lock;
1744	printf("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
1745	    "exclusive" : "shared", lock->lo_class->lc_name, lock->lo_name);
1746	if (lock->lo_type != lock->lo_name)
1747		printf(" (%s)", lock->lo_type);
1748	printf(" r = %d (%p) locked @ %s:%d\n",
1749	    instance->li_flags & LI_RECURSEMASK, lock, instance->li_file,
1750	    instance->li_line);
1751}
1752
1753#ifdef DDB
1754static int
1755witness_thread_has_locks(struct thread *td)
1756{
1757
1758	return (td->td_sleeplocks != NULL);
1759}
1760
1761static int
1762witness_proc_has_locks(struct proc *p)
1763{
1764	struct thread *td;
1765
1766	FOREACH_THREAD_IN_PROC(p, td) {
1767		if (witness_thread_has_locks(td))
1768			return (1);
1769	}
1770	return (0);
1771}
1772#endif
1773
1774int
1775witness_list_locks(struct lock_list_entry **lock_list)
1776{
1777	struct lock_list_entry *lle;
1778	int i, nheld;
1779
1780	nheld = 0;
1781	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
1782		for (i = lle->ll_count - 1; i >= 0; i--) {
1783			witness_list_lock(&lle->ll_children[i]);
1784			nheld++;
1785		}
1786	return (nheld);
1787}
1788
1789/*
1790 * This is a bit risky at best.  We call this function when we have timed
1791 * out acquiring a spin lock, and we assume that the other CPU is stuck
1792 * with this lock held.  So, we go groveling around in the other CPU's
1793 * per-cpu data to try to find the lock instance for this spin lock to
1794 * see when it was last acquired.
1795 */
1796void
1797witness_display_spinlock(struct lock_object *lock, struct thread *owner)
1798{
1799	struct lock_instance *instance;
1800	struct pcpu *pc;
1801
1802	if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
1803		return;
1804	pc = pcpu_find(owner->td_oncpu);
1805	instance = find_instance(pc->pc_spinlocks, lock);
1806	if (instance != NULL)
1807		witness_list_lock(instance);
1808}
1809
1810void
1811witness_save(struct lock_object *lock, const char **filep, int *linep)
1812{
1813	struct lock_instance *instance;
1814
1815	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1816	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1817		return;
1818	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1819		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1820		    lock->lo_class->lc_name, lock->lo_name);
1821	instance = find_instance(curthread->td_sleeplocks, lock);
1822	if (instance == NULL)
1823		panic("%s: lock (%s) %s not locked", __func__,
1824		    lock->lo_class->lc_name, lock->lo_name);
1825	*filep = instance->li_file;
1826	*linep = instance->li_line;
1827}
1828
1829void
1830witness_restore(struct lock_object *lock, const char *file, int line)
1831{
1832	struct lock_instance *instance;
1833
1834	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1835	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1836		return;
1837	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1838		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1839		    lock->lo_class->lc_name, lock->lo_name);
1840	instance = find_instance(curthread->td_sleeplocks, lock);
1841	if (instance == NULL)
1842		panic("%s: lock (%s) %s not locked", __func__,
1843		    lock->lo_class->lc_name, lock->lo_name);
1844	lock->lo_witness->w_file = file;
1845	lock->lo_witness->w_line = line;
1846	instance->li_file = file;
1847	instance->li_line = line;
1848}
1849
1850void
1851witness_assert(struct lock_object *lock, int flags, const char *file, int line)
1852{
1853#ifdef INVARIANT_SUPPORT
1854	struct lock_instance *instance;
1855
1856	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1857		return;
1858	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) != 0)
1859		instance = find_instance(curthread->td_sleeplocks, lock);
1860	else if ((lock->lo_class->lc_flags & LC_SPINLOCK) != 0)
1861		instance = find_instance(PCPU_GET(spinlocks), lock);
1862	else {
1863		panic("Lock (%s) %s is not sleep or spin!",
1864		    lock->lo_class->lc_name, lock->lo_name);
1865	}
1866	file = fixup_filename(file);
1867	switch (flags) {
1868	case LA_UNLOCKED:
1869		if (instance != NULL)
1870			panic("Lock (%s) %s locked @ %s:%d.",
1871			    lock->lo_class->lc_name, lock->lo_name, file, line);
1872		break;
1873	case LA_LOCKED:
1874	case LA_LOCKED | LA_RECURSED:
1875	case LA_LOCKED | LA_NOTRECURSED:
1876	case LA_SLOCKED:
1877	case LA_SLOCKED | LA_RECURSED:
1878	case LA_SLOCKED | LA_NOTRECURSED:
1879	case LA_XLOCKED:
1880	case LA_XLOCKED | LA_RECURSED:
1881	case LA_XLOCKED | LA_NOTRECURSED:
1882		if (instance == NULL) {
1883			panic("Lock (%s) %s not locked @ %s:%d.",
1884			    lock->lo_class->lc_name, lock->lo_name, file, line);
1885			break;
1886		}
1887		if ((flags & LA_XLOCKED) != 0 &&
1888		    (instance->li_flags & LI_EXCLUSIVE) == 0)
1889			panic("Lock (%s) %s not exclusively locked @ %s:%d.",
1890			    lock->lo_class->lc_name, lock->lo_name, file, line);
1891		if ((flags & LA_SLOCKED) != 0 &&
1892		    (instance->li_flags & LI_EXCLUSIVE) != 0)
1893			panic("Lock (%s) %s exclusively locked @ %s:%d.",
1894			    lock->lo_class->lc_name, lock->lo_name, file, line);
1895		if ((flags & LA_RECURSED) != 0 &&
1896		    (instance->li_flags & LI_RECURSEMASK) == 0)
1897			panic("Lock (%s) %s not recursed @ %s:%d.",
1898			    lock->lo_class->lc_name, lock->lo_name, file, line);
1899		if ((flags & LA_NOTRECURSED) != 0 &&
1900		    (instance->li_flags & LI_RECURSEMASK) != 0)
1901			panic("Lock (%s) %s recursed @ %s:%d.",
1902			    lock->lo_class->lc_name, lock->lo_name, file, line);
1903		break;
1904	default:
1905		panic("Invalid lock assertion at %s:%d.", file, line);
1906
1907	}
1908#endif	/* INVARIANT_SUPPORT */
1909}
1910
1911#ifdef DDB
1912static void
1913witness_list(struct thread *td)
1914{
1915
1916	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1917	KASSERT(kdb_active, ("%s: not in the debugger", __func__));
1918
1919	if (witness_watch == 0)
1920		return;
1921
1922	witness_list_locks(&td->td_sleeplocks);
1923
1924	/*
1925	 * We only handle spinlocks if td == curthread.  This is somewhat broken
1926	 * if td is currently executing on some other CPU and holds spin locks
1927	 * as we won't display those locks.  If we had a MI way of getting
1928	 * the per-cpu data for a given cpu then we could use
1929	 * td->td_oncpu to get the list of spinlocks for this thread
1930	 * and "fix" this.
1931	 *
1932	 * That still wouldn't really fix this unless we locked sched_lock
1933	 * or stopped the other CPU to make sure it wasn't changing the list
1934	 * out from under us.  It is probably best to just not try to handle
1935	 * threads on other CPU's for now.
1936	 */
1937	if (td == curthread && PCPU_GET(spinlocks) != NULL)
1938		witness_list_locks(PCPU_PTR(spinlocks));
1939}
1940
1941DB_SHOW_COMMAND(locks, db_witness_list)
1942{
1943	struct thread *td;
1944	pid_t pid;
1945	struct proc *p;
1946
1947	if (have_addr) {
1948		pid = (addr % 16) + ((addr >> 4) % 16) * 10 +
1949		    ((addr >> 8) % 16) * 100 + ((addr >> 12) % 16) * 1000 +
1950		    ((addr >> 16) % 16) * 10000;
1951		/* sx_slock(&allproc_lock); */
1952		FOREACH_PROC_IN_SYSTEM(p) {
1953			if (p->p_pid == pid)
1954				break;
1955		}
1956		/* sx_sunlock(&allproc_lock); */
1957		if (p == NULL) {
1958			db_printf("pid %d not found\n", pid);
1959			return;
1960		}
1961		FOREACH_THREAD_IN_PROC(p, td) {
1962			witness_list(td);
1963		}
1964	} else {
1965		td = curthread;
1966		witness_list(td);
1967	}
1968}
1969
1970DB_SHOW_COMMAND(alllocks, db_witness_list_all)
1971{
1972	struct thread *td;
1973	struct proc *p;
1974
1975	/*
1976	 * It would be nice to list only threads and processes that actually
1977	 * held sleep locks, but that information is currently not exported
1978	 * by WITNESS.
1979	 */
1980	FOREACH_PROC_IN_SYSTEM(p) {
1981		if (!witness_proc_has_locks(p))
1982			continue;
1983		FOREACH_THREAD_IN_PROC(p, td) {
1984			if (!witness_thread_has_locks(td))
1985				continue;
1986			printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
1987			    p->p_comm, td, td->td_tid);
1988			witness_list(td);
1989		}
1990	}
1991}
1992
1993DB_SHOW_COMMAND(witness, db_witness_display)
1994{
1995
1996	witness_display(db_printf);
1997}
1998#endif
1999