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