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