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