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