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