xref: /freebsd/sys/kern/subr_witness.c (revision 2a2234c0f41da33b8cfc938e46b54a8234b64135)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2008 Isilon Systems, Inc.
5  * Copyright (c) 2008 Ilya Maykov <ivmaykov@gmail.com>
6  * Copyright (c) 1998 Berkeley Software Design, Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Berkeley Software Design Inc's name may not be used to endorse or
18  *    promote products derived from this software without specific prior
19  *    written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
34  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
35  */
36 
37 /*
38  * Implementation of the `witness' lock verifier.  Originally implemented for
39  * mutexes in BSD/OS.  Extended to handle generic lock objects and lock
40  * classes in FreeBSD.
41  */
42 
43 /*
44  *	Main Entry: witness
45  *	Pronunciation: 'wit-n&s
46  *	Function: noun
47  *	Etymology: Middle English witnesse, from Old English witnes knowledge,
48  *	    testimony, witness, from 2wit
49  *	Date: before 12th century
50  *	1 : attestation of a fact or event : TESTIMONY
51  *	2 : one that gives evidence; specifically : one who testifies in
52  *	    a cause or before a judicial tribunal
53  *	3 : one asked to be present at a transaction so as to be able to
54  *	    testify to its having taken place
55  *	4 : one who has personal knowledge of something
56  *	5 a : something serving as evidence or proof : SIGN
57  *	  b : public affirmation by word or example of usually
58  *	      religious faith or conviction <the heroic witness to divine
59  *	      life -- Pilot>
60  *	6 capitalized : a member of the Jehovah's Witnesses
61  */
62 
63 /*
64  * Special rules concerning Giant and lock orders:
65  *
66  * 1) Giant must be acquired before any other mutexes.  Stated another way,
67  *    no other mutex may be held when Giant is acquired.
68  *
69  * 2) Giant must be released when blocking on a sleepable lock.
70  *
71  * This rule is less obvious, but is a result of Giant providing the same
72  * semantics as spl().  Basically, when a thread sleeps, it must release
73  * Giant.  When a thread blocks on a sleepable lock, it sleeps.  Hence rule
74  * 2).
75  *
76  * 3) Giant may be acquired before or after sleepable locks.
77  *
78  * This rule is also not quite as obvious.  Giant may be acquired after
79  * a sleepable lock because it is a non-sleepable lock and non-sleepable
80  * locks may always be acquired while holding a sleepable lock.  The second
81  * case, Giant before a sleepable lock, follows from rule 2) above.  Suppose
82  * you have two threads T1 and T2 and a sleepable lock X.  Suppose that T1
83  * acquires X and blocks on Giant.  Then suppose that T2 acquires Giant and
84  * blocks on X.  When T2 blocks on X, T2 will release Giant allowing T1 to
85  * execute.  Thus, acquiring Giant both before and after a sleepable lock
86  * will not result in a lock order reversal.
87  */
88 
89 #include <sys/cdefs.h>
90 __FBSDID("$FreeBSD$");
91 
92 #include "opt_ddb.h"
93 #include "opt_hwpmc_hooks.h"
94 #include "opt_stack.h"
95 #include "opt_witness.h"
96 
97 #include <sys/param.h>
98 #include <sys/bus.h>
99 #include <sys/kdb.h>
100 #include <sys/kernel.h>
101 #include <sys/ktr.h>
102 #include <sys/lock.h>
103 #include <sys/malloc.h>
104 #include <sys/mutex.h>
105 #include <sys/priv.h>
106 #include <sys/proc.h>
107 #include <sys/sbuf.h>
108 #include <sys/sched.h>
109 #include <sys/stack.h>
110 #include <sys/sysctl.h>
111 #include <sys/syslog.h>
112 #include <sys/systm.h>
113 
114 #ifdef DDB
115 #include <ddb/ddb.h>
116 #endif
117 
118 #include <machine/stdarg.h>
119 
120 #if !defined(DDB) && !defined(STACK)
121 #error "DDB or STACK options are required for WITNESS"
122 #endif
123 
124 /* Note that these traces do not work with KTR_ALQ. */
125 #if 0
126 #define	KTR_WITNESS	KTR_SUBSYS
127 #else
128 #define	KTR_WITNESS	0
129 #endif
130 
131 #define	LI_RECURSEMASK	0x0000ffff	/* Recursion depth of lock instance. */
132 #define	LI_EXCLUSIVE	0x00010000	/* Exclusive lock instance. */
133 #define	LI_NORELEASE	0x00020000	/* Lock not allowed to be released. */
134 
135 /* Define this to check for blessed mutexes */
136 #undef BLESSING
137 
138 #ifndef WITNESS_COUNT
139 #define	WITNESS_COUNT 		1536
140 #endif
141 #define	WITNESS_HASH_SIZE	251	/* Prime, gives load factor < 2 */
142 #define	WITNESS_PENDLIST	(512 + (MAXCPU * 4))
143 
144 /* Allocate 256 KB of stack data space */
145 #define	WITNESS_LO_DATA_COUNT	2048
146 
147 /* Prime, gives load factor of ~2 at full load */
148 #define	WITNESS_LO_HASH_SIZE	1021
149 
150 /*
151  * XXX: This is somewhat bogus, as we assume here that at most 2048 threads
152  * will hold LOCK_NCHILDREN locks.  We handle failure ok, and we should
153  * probably be safe for the most part, but it's still a SWAG.
154  */
155 #define	LOCK_NCHILDREN	5
156 #define	LOCK_CHILDCOUNT	2048
157 
158 #define	MAX_W_NAME	64
159 
160 #define	FULLGRAPH_SBUF_SIZE	512
161 
162 /*
163  * These flags go in the witness relationship matrix and describe the
164  * relationship between any two struct witness objects.
165  */
166 #define	WITNESS_UNRELATED        0x00    /* No lock order relation. */
167 #define	WITNESS_PARENT           0x01    /* Parent, aka direct ancestor. */
168 #define	WITNESS_ANCESTOR         0x02    /* Direct or indirect ancestor. */
169 #define	WITNESS_CHILD            0x04    /* Child, aka direct descendant. */
170 #define	WITNESS_DESCENDANT       0x08    /* Direct or indirect descendant. */
171 #define	WITNESS_ANCESTOR_MASK    (WITNESS_PARENT | WITNESS_ANCESTOR)
172 #define	WITNESS_DESCENDANT_MASK  (WITNESS_CHILD | WITNESS_DESCENDANT)
173 #define	WITNESS_RELATED_MASK						\
174 	(WITNESS_ANCESTOR_MASK | WITNESS_DESCENDANT_MASK)
175 #define	WITNESS_REVERSAL         0x10    /* A lock order reversal has been
176 					  * observed. */
177 #define	WITNESS_RESERVED1        0x20    /* Unused flag, reserved. */
178 #define	WITNESS_RESERVED2        0x40    /* Unused flag, reserved. */
179 #define	WITNESS_LOCK_ORDER_KNOWN 0x80    /* This lock order is known. */
180 
181 /* Descendant to ancestor flags */
182 #define	WITNESS_DTOA(x)	(((x) & WITNESS_RELATED_MASK) >> 2)
183 
184 /* Ancestor to descendant flags */
185 #define	WITNESS_ATOD(x)	(((x) & WITNESS_RELATED_MASK) << 2)
186 
187 #define	WITNESS_INDEX_ASSERT(i)						\
188 	MPASS((i) > 0 && (i) <= w_max_used_index && (i) < witness_count)
189 
190 static MALLOC_DEFINE(M_WITNESS, "Witness", "Witness");
191 
192 /*
193  * Lock instances.  A lock instance is the data associated with a lock while
194  * it is held by witness.  For example, a lock instance will hold the
195  * recursion count of a lock.  Lock instances are held in lists.  Spin locks
196  * are held in a per-cpu list while sleep locks are held in per-thread list.
197  */
198 struct lock_instance {
199 	struct lock_object	*li_lock;
200 	const char		*li_file;
201 	int			li_line;
202 	u_int			li_flags;
203 };
204 
205 /*
206  * A simple list type used to build the list of locks held by a thread
207  * or CPU.  We can't simply embed the list in struct lock_object since a
208  * lock may be held by more than one thread if it is a shared lock.  Locks
209  * are added to the head of the list, so we fill up each list entry from
210  * "the back" logically.  To ease some of the arithmetic, we actually fill
211  * in each list entry the normal way (children[0] then children[1], etc.) but
212  * when we traverse the list we read children[count-1] as the first entry
213  * down to children[0] as the final entry.
214  */
215 struct lock_list_entry {
216 	struct lock_list_entry	*ll_next;
217 	struct lock_instance	ll_children[LOCK_NCHILDREN];
218 	u_int			ll_count;
219 };
220 
221 /*
222  * The main witness structure. One of these per named lock type in the system
223  * (for example, "vnode interlock").
224  */
225 struct witness {
226 	char  			w_name[MAX_W_NAME];
227 	uint32_t 		w_index;  /* Index in the relationship matrix */
228 	struct lock_class	*w_class;
229 	STAILQ_ENTRY(witness) 	w_list;		/* List of all witnesses. */
230 	STAILQ_ENTRY(witness) 	w_typelist;	/* Witnesses of a type. */
231 	struct witness		*w_hash_next; /* Linked list in hash buckets. */
232 	const char		*w_file; /* File where last acquired */
233 	uint32_t 		w_line; /* Line where last acquired */
234 	uint32_t 		w_refcount;
235 	uint16_t 		w_num_ancestors; /* direct/indirect
236 						  * ancestor count */
237 	uint16_t 		w_num_descendants; /* direct/indirect
238 						    * descendant count */
239 	int16_t 		w_ddb_level;
240 	unsigned		w_displayed:1;
241 	unsigned		w_reversed:1;
242 };
243 
244 STAILQ_HEAD(witness_list, witness);
245 
246 /*
247  * The witness hash table. Keys are witness names (const char *), elements are
248  * witness objects (struct witness *).
249  */
250 struct witness_hash {
251 	struct witness	*wh_array[WITNESS_HASH_SIZE];
252 	uint32_t	wh_size;
253 	uint32_t	wh_count;
254 };
255 
256 /*
257  * Key type for the lock order data hash table.
258  */
259 struct witness_lock_order_key {
260 	uint16_t	from;
261 	uint16_t	to;
262 };
263 
264 struct witness_lock_order_data {
265 	struct stack			wlod_stack;
266 	struct witness_lock_order_key	wlod_key;
267 	struct witness_lock_order_data	*wlod_next;
268 };
269 
270 /*
271  * The witness lock order data hash table. Keys are witness index tuples
272  * (struct witness_lock_order_key), elements are lock order data objects
273  * (struct witness_lock_order_data).
274  */
275 struct witness_lock_order_hash {
276 	struct witness_lock_order_data	*wloh_array[WITNESS_LO_HASH_SIZE];
277 	u_int	wloh_size;
278 	u_int	wloh_count;
279 };
280 
281 #ifdef BLESSING
282 struct witness_blessed {
283 	const char	*b_lock1;
284 	const char	*b_lock2;
285 };
286 #endif
287 
288 struct witness_pendhelp {
289 	const char		*wh_type;
290 	struct lock_object	*wh_lock;
291 };
292 
293 struct witness_order_list_entry {
294 	const char		*w_name;
295 	struct lock_class	*w_class;
296 };
297 
298 /*
299  * Returns 0 if one of the locks is a spin lock and the other is not.
300  * Returns 1 otherwise.
301  */
302 static __inline int
303 witness_lock_type_equal(struct witness *w1, struct witness *w2)
304 {
305 
306 	return ((w1->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) ==
307 		(w2->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)));
308 }
309 
310 static __inline int
311 witness_lock_order_key_equal(const struct witness_lock_order_key *a,
312     const struct witness_lock_order_key *b)
313 {
314 
315 	return (a->from == b->from && a->to == b->to);
316 }
317 
318 static int	_isitmyx(struct witness *w1, struct witness *w2, int rmask,
319 		    const char *fname);
320 static void	adopt(struct witness *parent, struct witness *child);
321 #ifdef BLESSING
322 static int	blessed(struct witness *, struct witness *);
323 #endif
324 static void	depart(struct witness *w);
325 static struct witness	*enroll(const char *description,
326 			    struct lock_class *lock_class);
327 static struct lock_instance	*find_instance(struct lock_list_entry *list,
328 				    const struct lock_object *lock);
329 static int	isitmychild(struct witness *parent, struct witness *child);
330 static int	isitmydescendant(struct witness *parent, struct witness *child);
331 static void	itismychild(struct witness *parent, struct witness *child);
332 static int	sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS);
333 static int	sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
334 static int	sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS);
335 static int	sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS);
336 static void	witness_add_fullgraph(struct sbuf *sb, struct witness *parent);
337 #ifdef DDB
338 static void	witness_ddb_compute_levels(void);
339 static void	witness_ddb_display(int(*)(const char *fmt, ...));
340 static void	witness_ddb_display_descendants(int(*)(const char *fmt, ...),
341 		    struct witness *, int indent);
342 static void	witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
343 		    struct witness_list *list);
344 static void	witness_ddb_level_descendants(struct witness *parent, int l);
345 static void	witness_ddb_list(struct thread *td);
346 #endif
347 static void	witness_debugger(int cond, const char *msg);
348 static void	witness_free(struct witness *m);
349 static struct witness	*witness_get(void);
350 static uint32_t	witness_hash_djb2(const uint8_t *key, uint32_t size);
351 static struct witness	*witness_hash_get(const char *key);
352 static void	witness_hash_put(struct witness *w);
353 static void	witness_init_hash_tables(void);
354 static void	witness_increment_graph_generation(void);
355 static void	witness_lock_list_free(struct lock_list_entry *lle);
356 static struct lock_list_entry	*witness_lock_list_get(void);
357 static int	witness_lock_order_add(struct witness *parent,
358 		    struct witness *child);
359 static int	witness_lock_order_check(struct witness *parent,
360 		    struct witness *child);
361 static struct witness_lock_order_data	*witness_lock_order_get(
362 					    struct witness *parent,
363 					    struct witness *child);
364 static void	witness_list_lock(struct lock_instance *instance,
365 		    int (*prnt)(const char *fmt, ...));
366 static int	witness_output(const char *fmt, ...) __printflike(1, 2);
367 static int	witness_voutput(const char *fmt, va_list ap) __printflike(1, 0);
368 static void	witness_setflag(struct lock_object *lock, int flag, int set);
369 
370 static SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW, NULL,
371     "Witness Locking");
372 
373 /*
374  * If set to 0, lock order checking is disabled.  If set to -1,
375  * witness is completely disabled.  Otherwise witness performs full
376  * lock order checking for all locks.  At runtime, lock order checking
377  * may be toggled.  However, witness cannot be reenabled once it is
378  * completely disabled.
379  */
380 static int witness_watch = 1;
381 SYSCTL_PROC(_debug_witness, OID_AUTO, watch, CTLFLAG_RWTUN | CTLTYPE_INT, NULL, 0,
382     sysctl_debug_witness_watch, "I", "witness is watching lock operations");
383 
384 #ifdef KDB
385 /*
386  * When KDB is enabled and witness_kdb is 1, it will cause the system
387  * to drop into kdebug() when:
388  *	- a lock hierarchy violation occurs
389  *	- locks are held when going to sleep.
390  */
391 #ifdef WITNESS_KDB
392 int	witness_kdb = 1;
393 #else
394 int	witness_kdb = 0;
395 #endif
396 SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RWTUN, &witness_kdb, 0, "");
397 #endif /* KDB */
398 
399 #if defined(DDB) || defined(KDB)
400 /*
401  * When DDB or KDB is enabled and witness_trace is 1, it will cause the system
402  * to print a stack trace:
403  *	- a lock hierarchy violation occurs
404  *	- locks are held when going to sleep.
405  */
406 int	witness_trace = 1;
407 SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RWTUN, &witness_trace, 0, "");
408 #endif /* DDB || KDB */
409 
410 #ifdef WITNESS_SKIPSPIN
411 int	witness_skipspin = 1;
412 #else
413 int	witness_skipspin = 0;
414 #endif
415 SYSCTL_INT(_debug_witness, OID_AUTO, skipspin, CTLFLAG_RDTUN, &witness_skipspin, 0, "");
416 
417 int badstack_sbuf_size;
418 
419 int witness_count = WITNESS_COUNT;
420 SYSCTL_INT(_debug_witness, OID_AUTO, witness_count, CTLFLAG_RDTUN,
421     &witness_count, 0, "");
422 
423 /*
424  * Output channel for witness messages.  By default we print to the console.
425  */
426 enum witness_channel {
427 	WITNESS_CONSOLE,
428 	WITNESS_LOG,
429 	WITNESS_NONE,
430 };
431 
432 static enum witness_channel witness_channel = WITNESS_CONSOLE;
433 SYSCTL_PROC(_debug_witness, OID_AUTO, output_channel, CTLTYPE_STRING |
434     CTLFLAG_RWTUN, NULL, 0, sysctl_debug_witness_channel, "A",
435     "Output channel for warnings");
436 
437 /*
438  * Call this to print out the relations between locks.
439  */
440 SYSCTL_PROC(_debug_witness, OID_AUTO, fullgraph, CTLTYPE_STRING | CTLFLAG_RD,
441     NULL, 0, sysctl_debug_witness_fullgraph, "A", "Show locks relation graphs");
442 
443 /*
444  * Call this to print out the witness faulty stacks.
445  */
446 SYSCTL_PROC(_debug_witness, OID_AUTO, badstacks, CTLTYPE_STRING | CTLFLAG_RD,
447     NULL, 0, sysctl_debug_witness_badstacks, "A", "Show bad witness stacks");
448 
449 static struct mtx w_mtx;
450 
451 /* w_list */
452 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
453 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
454 
455 /* w_typelist */
456 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
457 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
458 
459 /* lock list */
460 static struct lock_list_entry *w_lock_list_free = NULL;
461 static struct witness_pendhelp pending_locks[WITNESS_PENDLIST];
462 static u_int pending_cnt;
463 
464 static int w_free_cnt, w_spin_cnt, w_sleep_cnt;
465 SYSCTL_INT(_debug_witness, OID_AUTO, free_cnt, CTLFLAG_RD, &w_free_cnt, 0, "");
466 SYSCTL_INT(_debug_witness, OID_AUTO, spin_cnt, CTLFLAG_RD, &w_spin_cnt, 0, "");
467 SYSCTL_INT(_debug_witness, OID_AUTO, sleep_cnt, CTLFLAG_RD, &w_sleep_cnt, 0,
468     "");
469 
470 static struct witness *w_data;
471 static uint8_t **w_rmatrix;
472 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
473 static struct witness_hash w_hash;	/* The witness hash table. */
474 
475 /* The lock order data hash */
476 static struct witness_lock_order_data w_lodata[WITNESS_LO_DATA_COUNT];
477 static struct witness_lock_order_data *w_lofree = NULL;
478 static struct witness_lock_order_hash w_lohash;
479 static int w_max_used_index = 0;
480 static unsigned int w_generation = 0;
481 static const char w_notrunning[] = "Witness not running\n";
482 static const char w_stillcold[] = "Witness is still cold\n";
483 #ifdef __i386__
484 static const char w_notallowed[] = "The sysctl is disabled on the arch\n";
485 #endif
486 
487 static struct witness_order_list_entry order_lists[] = {
488 	/*
489 	 * sx locks
490 	 */
491 	{ "proctree", &lock_class_sx },
492 	{ "allproc", &lock_class_sx },
493 	{ "allprison", &lock_class_sx },
494 	{ NULL, NULL },
495 	/*
496 	 * Various mutexes
497 	 */
498 	{ "Giant", &lock_class_mtx_sleep },
499 	{ "pipe mutex", &lock_class_mtx_sleep },
500 	{ "sigio lock", &lock_class_mtx_sleep },
501 	{ "process group", &lock_class_mtx_sleep },
502 	{ "process lock", &lock_class_mtx_sleep },
503 	{ "session", &lock_class_mtx_sleep },
504 	{ "uidinfo hash", &lock_class_rw },
505 #ifdef	HWPMC_HOOKS
506 	{ "pmc-sleep", &lock_class_mtx_sleep },
507 #endif
508 	{ "time lock", &lock_class_mtx_sleep },
509 	{ NULL, NULL },
510 	/*
511 	 * umtx
512 	 */
513 	{ "umtx lock", &lock_class_mtx_sleep },
514 	{ NULL, NULL },
515 	/*
516 	 * Sockets
517 	 */
518 	{ "accept", &lock_class_mtx_sleep },
519 	{ "so_snd", &lock_class_mtx_sleep },
520 	{ "so_rcv", &lock_class_mtx_sleep },
521 	{ "sellck", &lock_class_mtx_sleep },
522 	{ NULL, NULL },
523 	/*
524 	 * Routing
525 	 */
526 	{ "so_rcv", &lock_class_mtx_sleep },
527 	{ "radix node head", &lock_class_rw },
528 	{ "rtentry", &lock_class_mtx_sleep },
529 	{ "ifaddr", &lock_class_mtx_sleep },
530 	{ NULL, NULL },
531 	/*
532 	 * IPv4 multicast:
533 	 * protocol locks before interface locks, after UDP locks.
534 	 */
535 	{ "udpinp", &lock_class_rw },
536 	{ "in_multi_mtx", &lock_class_mtx_sleep },
537 	{ "igmp_mtx", &lock_class_mtx_sleep },
538 	{ "if_addr_lock", &lock_class_rw },
539 	{ NULL, NULL },
540 	/*
541 	 * IPv6 multicast:
542 	 * protocol locks before interface locks, after UDP locks.
543 	 */
544 	{ "udpinp", &lock_class_rw },
545 	{ "in6_multi_mtx", &lock_class_mtx_sleep },
546 	{ "mld_mtx", &lock_class_mtx_sleep },
547 	{ "if_addr_lock", &lock_class_rw },
548 	{ NULL, NULL },
549 	/*
550 	 * UNIX Domain Sockets
551 	 */
552 	{ "unp_link_rwlock", &lock_class_rw },
553 	{ "unp_list_lock", &lock_class_mtx_sleep },
554 	{ "unp", &lock_class_mtx_sleep },
555 	{ "so_snd", &lock_class_mtx_sleep },
556 	{ NULL, NULL },
557 	/*
558 	 * UDP/IP
559 	 */
560 	{ "udp", &lock_class_rw },
561 	{ "udpinp", &lock_class_rw },
562 	{ "so_snd", &lock_class_mtx_sleep },
563 	{ NULL, NULL },
564 	/*
565 	 * TCP/IP
566 	 */
567 	{ "tcp", &lock_class_rw },
568 	{ "tcpinp", &lock_class_rw },
569 	{ "so_snd", &lock_class_mtx_sleep },
570 	{ NULL, NULL },
571 	/*
572 	 * BPF
573 	 */
574 	{ "bpf global lock", &lock_class_sx },
575 	{ "bpf interface lock", &lock_class_rw },
576 	{ "bpf cdev lock", &lock_class_mtx_sleep },
577 	{ NULL, NULL },
578 	/*
579 	 * NFS server
580 	 */
581 	{ "nfsd_mtx", &lock_class_mtx_sleep },
582 	{ "so_snd", &lock_class_mtx_sleep },
583 	{ NULL, NULL },
584 
585 	/*
586 	 * IEEE 802.11
587 	 */
588 	{ "802.11 com lock", &lock_class_mtx_sleep},
589 	{ NULL, NULL },
590 	/*
591 	 * Network drivers
592 	 */
593 	{ "network driver", &lock_class_mtx_sleep},
594 	{ NULL, NULL },
595 
596 	/*
597 	 * Netgraph
598 	 */
599 	{ "ng_node", &lock_class_mtx_sleep },
600 	{ "ng_worklist", &lock_class_mtx_sleep },
601 	{ NULL, NULL },
602 	/*
603 	 * CDEV
604 	 */
605 	{ "vm map (system)", &lock_class_mtx_sleep },
606 	{ "vm pagequeue", &lock_class_mtx_sleep },
607 	{ "vnode interlock", &lock_class_mtx_sleep },
608 	{ "cdev", &lock_class_mtx_sleep },
609 	{ NULL, NULL },
610 	/*
611 	 * VM
612 	 */
613 	{ "vm map (user)", &lock_class_sx },
614 	{ "vm object", &lock_class_rw },
615 	{ "vm page", &lock_class_mtx_sleep },
616 	{ "vm pagequeue", &lock_class_mtx_sleep },
617 	{ "pmap pv global", &lock_class_rw },
618 	{ "pmap", &lock_class_mtx_sleep },
619 	{ "pmap pv list", &lock_class_rw },
620 	{ "vm page free queue", &lock_class_mtx_sleep },
621 	{ NULL, NULL },
622 	/*
623 	 * kqueue/VFS interaction
624 	 */
625 	{ "kqueue", &lock_class_mtx_sleep },
626 	{ "struct mount mtx", &lock_class_mtx_sleep },
627 	{ "vnode interlock", &lock_class_mtx_sleep },
628 	{ NULL, NULL },
629 	/*
630 	 * VFS namecache
631 	 */
632 	{ "ncvn", &lock_class_mtx_sleep },
633 	{ "ncbuc", &lock_class_rw },
634 	{ "vnode interlock", &lock_class_mtx_sleep },
635 	{ "ncneg", &lock_class_mtx_sleep },
636 	{ NULL, NULL },
637 	/*
638 	 * ZFS locking
639 	 */
640 	{ "dn->dn_mtx", &lock_class_sx },
641 	{ "dr->dt.di.dr_mtx", &lock_class_sx },
642 	{ "db->db_mtx", &lock_class_sx },
643 	{ NULL, NULL },
644 	/*
645 	 * TCP log locks
646 	 */
647 	{ "TCP ID tree", &lock_class_rw },
648 	{ "tcp log id bucket", &lock_class_mtx_sleep },
649 	{ "tcpinp", &lock_class_rw },
650 	{ "TCP log expireq", &lock_class_mtx_sleep },
651 	{ NULL, NULL },
652 	/*
653 	 * spin locks
654 	 */
655 #ifdef SMP
656 	{ "ap boot", &lock_class_mtx_spin },
657 #endif
658 	{ "rm.mutex_mtx", &lock_class_mtx_spin },
659 	{ "sio", &lock_class_mtx_spin },
660 #ifdef __i386__
661 	{ "cy", &lock_class_mtx_spin },
662 #endif
663 #ifdef __sparc64__
664 	{ "pcib_mtx", &lock_class_mtx_spin },
665 	{ "rtc_mtx", &lock_class_mtx_spin },
666 #endif
667 	{ "scc_hwmtx", &lock_class_mtx_spin },
668 	{ "uart_hwmtx", &lock_class_mtx_spin },
669 	{ "fast_taskqueue", &lock_class_mtx_spin },
670 	{ "intr table", &lock_class_mtx_spin },
671 #ifdef	HWPMC_HOOKS
672 	{ "pmc-per-proc", &lock_class_mtx_spin },
673 #endif
674 	{ "process slock", &lock_class_mtx_spin },
675 	{ "syscons video lock", &lock_class_mtx_spin },
676 	{ "sleepq chain", &lock_class_mtx_spin },
677 	{ "rm_spinlock", &lock_class_mtx_spin },
678 	{ "turnstile chain", &lock_class_mtx_spin },
679 	{ "turnstile lock", &lock_class_mtx_spin },
680 	{ "sched lock", &lock_class_mtx_spin },
681 	{ "td_contested", &lock_class_mtx_spin },
682 	{ "callout", &lock_class_mtx_spin },
683 	{ "entropy harvest mutex", &lock_class_mtx_spin },
684 #ifdef SMP
685 	{ "smp rendezvous", &lock_class_mtx_spin },
686 #endif
687 #ifdef __powerpc__
688 	{ "tlb0", &lock_class_mtx_spin },
689 #endif
690 	/*
691 	 * leaf locks
692 	 */
693 	{ "intrcnt", &lock_class_mtx_spin },
694 	{ "icu", &lock_class_mtx_spin },
695 #if defined(SMP) && defined(__sparc64__)
696 	{ "ipi", &lock_class_mtx_spin },
697 #endif
698 #ifdef __i386__
699 	{ "allpmaps", &lock_class_mtx_spin },
700 	{ "descriptor tables", &lock_class_mtx_spin },
701 #endif
702 	{ "clk", &lock_class_mtx_spin },
703 	{ "cpuset", &lock_class_mtx_spin },
704 	{ "mprof lock", &lock_class_mtx_spin },
705 	{ "zombie lock", &lock_class_mtx_spin },
706 	{ "ALD Queue", &lock_class_mtx_spin },
707 #if defined(__i386__) || defined(__amd64__)
708 	{ "pcicfg", &lock_class_mtx_spin },
709 	{ "NDIS thread lock", &lock_class_mtx_spin },
710 #endif
711 	{ "tw_osl_io_lock", &lock_class_mtx_spin },
712 	{ "tw_osl_q_lock", &lock_class_mtx_spin },
713 	{ "tw_cl_io_lock", &lock_class_mtx_spin },
714 	{ "tw_cl_intr_lock", &lock_class_mtx_spin },
715 	{ "tw_cl_gen_lock", &lock_class_mtx_spin },
716 #ifdef	HWPMC_HOOKS
717 	{ "pmc-leaf", &lock_class_mtx_spin },
718 #endif
719 	{ "blocked lock", &lock_class_mtx_spin },
720 	{ NULL, NULL },
721 	{ NULL, NULL }
722 };
723 
724 #ifdef BLESSING
725 /*
726  * Pairs of locks which have been blessed
727  * Don't complain about order problems with blessed locks
728  */
729 static struct witness_blessed blessed_list[] = {
730 };
731 #endif
732 
733 /*
734  * This global is set to 0 once it becomes safe to use the witness code.
735  */
736 static int witness_cold = 1;
737 
738 /*
739  * This global is set to 1 once the static lock orders have been enrolled
740  * so that a warning can be issued for any spin locks enrolled later.
741  */
742 static int witness_spin_warn = 0;
743 
744 /* Trim useless garbage from filenames. */
745 static const char *
746 fixup_filename(const char *file)
747 {
748 
749 	if (file == NULL)
750 		return (NULL);
751 	while (strncmp(file, "../", 3) == 0)
752 		file += 3;
753 	return (file);
754 }
755 
756 /*
757  * Calculate the size of early witness structures.
758  */
759 int
760 witness_startup_count(void)
761 {
762 	int sz;
763 
764 	sz = sizeof(struct witness) * witness_count;
765 	sz += sizeof(*w_rmatrix) * (witness_count + 1);
766 	sz += sizeof(*w_rmatrix[0]) * (witness_count + 1) *
767 	    (witness_count + 1);
768 
769 	return (sz);
770 }
771 
772 /*
773  * The WITNESS-enabled diagnostic code.  Note that the witness code does
774  * assume that the early boot is single-threaded at least until after this
775  * routine is completed.
776  */
777 void
778 witness_startup(void *mem)
779 {
780 	struct lock_object *lock;
781 	struct witness_order_list_entry *order;
782 	struct witness *w, *w1;
783 	uintptr_t p;
784 	int i;
785 
786 	p = (uintptr_t)mem;
787 	w_data = (void *)p;
788 	p += sizeof(struct witness) * witness_count;
789 
790 	w_rmatrix = (void *)p;
791 	p += sizeof(*w_rmatrix) * (witness_count + 1);
792 
793 	for (i = 0; i < witness_count + 1; i++) {
794 		w_rmatrix[i] = (void *)p;
795 		p += sizeof(*w_rmatrix[i]) * (witness_count + 1);
796 	}
797 	badstack_sbuf_size = witness_count * 256;
798 
799 	/*
800 	 * We have to release Giant before initializing its witness
801 	 * structure so that WITNESS doesn't get confused.
802 	 */
803 	mtx_unlock(&Giant);
804 	mtx_assert(&Giant, MA_NOTOWNED);
805 
806 	CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
807 	mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
808 	    MTX_NOWITNESS | MTX_NOPROFILE);
809 	for (i = witness_count - 1; i >= 0; i--) {
810 		w = &w_data[i];
811 		memset(w, 0, sizeof(*w));
812 		w_data[i].w_index = i;	/* Witness index never changes. */
813 		witness_free(w);
814 	}
815 	KASSERT(STAILQ_FIRST(&w_free)->w_index == 0,
816 	    ("%s: Invalid list of free witness objects", __func__));
817 
818 	/* Witness with index 0 is not used to aid in debugging. */
819 	STAILQ_REMOVE_HEAD(&w_free, w_list);
820 	w_free_cnt--;
821 
822 	for (i = 0; i < witness_count; i++) {
823 		memset(w_rmatrix[i], 0, sizeof(*w_rmatrix[i]) *
824 		    (witness_count + 1));
825 	}
826 
827 	for (i = 0; i < LOCK_CHILDCOUNT; i++)
828 		witness_lock_list_free(&w_locklistdata[i]);
829 	witness_init_hash_tables();
830 
831 	/* First add in all the specified order lists. */
832 	for (order = order_lists; order->w_name != NULL; order++) {
833 		w = enroll(order->w_name, order->w_class);
834 		if (w == NULL)
835 			continue;
836 		w->w_file = "order list";
837 		for (order++; order->w_name != NULL; order++) {
838 			w1 = enroll(order->w_name, order->w_class);
839 			if (w1 == NULL)
840 				continue;
841 			w1->w_file = "order list";
842 			itismychild(w, w1);
843 			w = w1;
844 		}
845 	}
846 	witness_spin_warn = 1;
847 
848 	/* Iterate through all locks and add them to witness. */
849 	for (i = 0; pending_locks[i].wh_lock != NULL; i++) {
850 		lock = pending_locks[i].wh_lock;
851 		KASSERT(lock->lo_flags & LO_WITNESS,
852 		    ("%s: lock %s is on pending list but not LO_WITNESS",
853 		    __func__, lock->lo_name));
854 		lock->lo_witness = enroll(pending_locks[i].wh_type,
855 		    LOCK_CLASS(lock));
856 	}
857 
858 	/* Mark the witness code as being ready for use. */
859 	witness_cold = 0;
860 
861 	mtx_lock(&Giant);
862 }
863 
864 void
865 witness_init(struct lock_object *lock, const char *type)
866 {
867 	struct lock_class *class;
868 
869 	/* Various sanity checks. */
870 	class = LOCK_CLASS(lock);
871 	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
872 	    (class->lc_flags & LC_RECURSABLE) == 0)
873 		kassert_panic("%s: lock (%s) %s can not be recursable",
874 		    __func__, class->lc_name, lock->lo_name);
875 	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
876 	    (class->lc_flags & LC_SLEEPABLE) == 0)
877 		kassert_panic("%s: lock (%s) %s can not be sleepable",
878 		    __func__, class->lc_name, lock->lo_name);
879 	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
880 	    (class->lc_flags & LC_UPGRADABLE) == 0)
881 		kassert_panic("%s: lock (%s) %s can not be upgradable",
882 		    __func__, class->lc_name, lock->lo_name);
883 
884 	/*
885 	 * If we shouldn't watch this lock, then just clear lo_witness.
886 	 * Otherwise, if witness_cold is set, then it is too early to
887 	 * enroll this lock, so defer it to witness_initialize() by adding
888 	 * it to the pending_locks list.  If it is not too early, then enroll
889 	 * the lock now.
890 	 */
891 	if (witness_watch < 1 || panicstr != NULL ||
892 	    (lock->lo_flags & LO_WITNESS) == 0)
893 		lock->lo_witness = NULL;
894 	else if (witness_cold) {
895 		pending_locks[pending_cnt].wh_lock = lock;
896 		pending_locks[pending_cnt++].wh_type = type;
897 		if (pending_cnt > WITNESS_PENDLIST)
898 			panic("%s: pending locks list is too small, "
899 			    "increase WITNESS_PENDLIST\n",
900 			    __func__);
901 	} else
902 		lock->lo_witness = enroll(type, class);
903 }
904 
905 void
906 witness_destroy(struct lock_object *lock)
907 {
908 	struct lock_class *class;
909 	struct witness *w;
910 
911 	class = LOCK_CLASS(lock);
912 
913 	if (witness_cold)
914 		panic("lock (%s) %s destroyed while witness_cold",
915 		    class->lc_name, lock->lo_name);
916 
917 	/* XXX: need to verify that no one holds the lock */
918 	if ((lock->lo_flags & LO_WITNESS) == 0 || lock->lo_witness == NULL)
919 		return;
920 	w = lock->lo_witness;
921 
922 	mtx_lock_spin(&w_mtx);
923 	MPASS(w->w_refcount > 0);
924 	w->w_refcount--;
925 
926 	if (w->w_refcount == 0)
927 		depart(w);
928 	mtx_unlock_spin(&w_mtx);
929 }
930 
931 #ifdef DDB
932 static void
933 witness_ddb_compute_levels(void)
934 {
935 	struct witness *w;
936 
937 	/*
938 	 * First clear all levels.
939 	 */
940 	STAILQ_FOREACH(w, &w_all, w_list)
941 		w->w_ddb_level = -1;
942 
943 	/*
944 	 * Look for locks with no parents and level all their descendants.
945 	 */
946 	STAILQ_FOREACH(w, &w_all, w_list) {
947 
948 		/* If the witness has ancestors (is not a root), skip it. */
949 		if (w->w_num_ancestors > 0)
950 			continue;
951 		witness_ddb_level_descendants(w, 0);
952 	}
953 }
954 
955 static void
956 witness_ddb_level_descendants(struct witness *w, int l)
957 {
958 	int i;
959 
960 	if (w->w_ddb_level >= l)
961 		return;
962 
963 	w->w_ddb_level = l;
964 	l++;
965 
966 	for (i = 1; i <= w_max_used_index; i++) {
967 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
968 			witness_ddb_level_descendants(&w_data[i], l);
969 	}
970 }
971 
972 static void
973 witness_ddb_display_descendants(int(*prnt)(const char *fmt, ...),
974     struct witness *w, int indent)
975 {
976 	int i;
977 
978  	for (i = 0; i < indent; i++)
979  		prnt(" ");
980 	prnt("%s (type: %s, depth: %d, active refs: %d)",
981 	     w->w_name, w->w_class->lc_name,
982 	     w->w_ddb_level, w->w_refcount);
983  	if (w->w_displayed) {
984  		prnt(" -- (already displayed)\n");
985  		return;
986  	}
987  	w->w_displayed = 1;
988 	if (w->w_file != NULL && w->w_line != 0)
989 		prnt(" -- last acquired @ %s:%d\n", fixup_filename(w->w_file),
990 		    w->w_line);
991 	else
992 		prnt(" -- never acquired\n");
993 	indent++;
994 	WITNESS_INDEX_ASSERT(w->w_index);
995 	for (i = 1; i <= w_max_used_index; i++) {
996 		if (db_pager_quit)
997 			return;
998 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
999 			witness_ddb_display_descendants(prnt, &w_data[i],
1000 			    indent);
1001 	}
1002 }
1003 
1004 static void
1005 witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
1006     struct witness_list *list)
1007 {
1008 	struct witness *w;
1009 
1010 	STAILQ_FOREACH(w, list, w_typelist) {
1011 		if (w->w_file == NULL || w->w_ddb_level > 0)
1012 			continue;
1013 
1014 		/* This lock has no anscestors - display its descendants. */
1015 		witness_ddb_display_descendants(prnt, w, 0);
1016 		if (db_pager_quit)
1017 			return;
1018 	}
1019 }
1020 
1021 static void
1022 witness_ddb_display(int(*prnt)(const char *fmt, ...))
1023 {
1024 	struct witness *w;
1025 
1026 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1027 	witness_ddb_compute_levels();
1028 
1029 	/* Clear all the displayed flags. */
1030 	STAILQ_FOREACH(w, &w_all, w_list)
1031 		w->w_displayed = 0;
1032 
1033 	/*
1034 	 * First, handle sleep locks which have been acquired at least
1035 	 * once.
1036 	 */
1037 	prnt("Sleep locks:\n");
1038 	witness_ddb_display_list(prnt, &w_sleep);
1039 	if (db_pager_quit)
1040 		return;
1041 
1042 	/*
1043 	 * Now do spin locks which have been acquired at least once.
1044 	 */
1045 	prnt("\nSpin locks:\n");
1046 	witness_ddb_display_list(prnt, &w_spin);
1047 	if (db_pager_quit)
1048 		return;
1049 
1050 	/*
1051 	 * Finally, any locks which have not been acquired yet.
1052 	 */
1053 	prnt("\nLocks which were never acquired:\n");
1054 	STAILQ_FOREACH(w, &w_all, w_list) {
1055 		if (w->w_file != NULL || w->w_refcount == 0)
1056 			continue;
1057 		prnt("%s (type: %s, depth: %d)\n", w->w_name,
1058 		    w->w_class->lc_name, w->w_ddb_level);
1059 		if (db_pager_quit)
1060 			return;
1061 	}
1062 }
1063 #endif /* DDB */
1064 
1065 int
1066 witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
1067 {
1068 
1069 	if (witness_watch == -1 || panicstr != NULL)
1070 		return (0);
1071 
1072 	/* Require locks that witness knows about. */
1073 	if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
1074 	    lock2->lo_witness == NULL)
1075 		return (EINVAL);
1076 
1077 	mtx_assert(&w_mtx, MA_NOTOWNED);
1078 	mtx_lock_spin(&w_mtx);
1079 
1080 	/*
1081 	 * If we already have either an explicit or implied lock order that
1082 	 * is the other way around, then return an error.
1083 	 */
1084 	if (witness_watch &&
1085 	    isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
1086 		mtx_unlock_spin(&w_mtx);
1087 		return (EDOOFUS);
1088 	}
1089 
1090 	/* Try to add the new order. */
1091 	CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1092 	    lock2->lo_witness->w_name, lock1->lo_witness->w_name);
1093 	itismychild(lock1->lo_witness, lock2->lo_witness);
1094 	mtx_unlock_spin(&w_mtx);
1095 	return (0);
1096 }
1097 
1098 void
1099 witness_checkorder(struct lock_object *lock, int flags, const char *file,
1100     int line, struct lock_object *interlock)
1101 {
1102 	struct lock_list_entry *lock_list, *lle;
1103 	struct lock_instance *lock1, *lock2, *plock;
1104 	struct lock_class *class, *iclass;
1105 	struct witness *w, *w1;
1106 	struct thread *td;
1107 	int i, j;
1108 
1109 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL ||
1110 	    panicstr != NULL)
1111 		return;
1112 
1113 	w = lock->lo_witness;
1114 	class = LOCK_CLASS(lock);
1115 	td = curthread;
1116 
1117 	if (class->lc_flags & LC_SLEEPLOCK) {
1118 
1119 		/*
1120 		 * Since spin locks include a critical section, this check
1121 		 * implicitly enforces a lock order of all sleep locks before
1122 		 * all spin locks.
1123 		 */
1124 		if (td->td_critnest != 0 && !kdb_active)
1125 			kassert_panic("acquiring blockable sleep lock with "
1126 			    "spinlock or critical section held (%s) %s @ %s:%d",
1127 			    class->lc_name, lock->lo_name,
1128 			    fixup_filename(file), line);
1129 
1130 		/*
1131 		 * If this is the first lock acquired then just return as
1132 		 * no order checking is needed.
1133 		 */
1134 		lock_list = td->td_sleeplocks;
1135 		if (lock_list == NULL || lock_list->ll_count == 0)
1136 			return;
1137 	} else {
1138 
1139 		/*
1140 		 * If this is the first lock, just return as no order
1141 		 * checking is needed.  Avoid problems with thread
1142 		 * migration pinning the thread while checking if
1143 		 * spinlocks are held.  If at least one spinlock is held
1144 		 * the thread is in a safe path and it is allowed to
1145 		 * unpin it.
1146 		 */
1147 		sched_pin();
1148 		lock_list = PCPU_GET(spinlocks);
1149 		if (lock_list == NULL || lock_list->ll_count == 0) {
1150 			sched_unpin();
1151 			return;
1152 		}
1153 		sched_unpin();
1154 	}
1155 
1156 	/*
1157 	 * Check to see if we are recursing on a lock we already own.  If
1158 	 * so, make sure that we don't mismatch exclusive and shared lock
1159 	 * acquires.
1160 	 */
1161 	lock1 = find_instance(lock_list, lock);
1162 	if (lock1 != NULL) {
1163 		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
1164 		    (flags & LOP_EXCLUSIVE) == 0) {
1165 			witness_output("shared lock of (%s) %s @ %s:%d\n",
1166 			    class->lc_name, lock->lo_name,
1167 			    fixup_filename(file), line);
1168 			witness_output("while exclusively locked from %s:%d\n",
1169 			    fixup_filename(lock1->li_file), lock1->li_line);
1170 			kassert_panic("excl->share");
1171 		}
1172 		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
1173 		    (flags & LOP_EXCLUSIVE) != 0) {
1174 			witness_output("exclusive lock of (%s) %s @ %s:%d\n",
1175 			    class->lc_name, lock->lo_name,
1176 			    fixup_filename(file), line);
1177 			witness_output("while share locked from %s:%d\n",
1178 			    fixup_filename(lock1->li_file), lock1->li_line);
1179 			kassert_panic("share->excl");
1180 		}
1181 		return;
1182 	}
1183 
1184 	/* Warn if the interlock is not locked exactly once. */
1185 	if (interlock != NULL) {
1186 		iclass = LOCK_CLASS(interlock);
1187 		lock1 = find_instance(lock_list, interlock);
1188 		if (lock1 == NULL)
1189 			kassert_panic("interlock (%s) %s not locked @ %s:%d",
1190 			    iclass->lc_name, interlock->lo_name,
1191 			    fixup_filename(file), line);
1192 		else if ((lock1->li_flags & LI_RECURSEMASK) != 0)
1193 			kassert_panic("interlock (%s) %s recursed @ %s:%d",
1194 			    iclass->lc_name, interlock->lo_name,
1195 			    fixup_filename(file), line);
1196 	}
1197 
1198 	/*
1199 	 * Find the previously acquired lock, but ignore interlocks.
1200 	 */
1201 	plock = &lock_list->ll_children[lock_list->ll_count - 1];
1202 	if (interlock != NULL && plock->li_lock == interlock) {
1203 		if (lock_list->ll_count > 1)
1204 			plock =
1205 			    &lock_list->ll_children[lock_list->ll_count - 2];
1206 		else {
1207 			lle = lock_list->ll_next;
1208 
1209 			/*
1210 			 * The interlock is the only lock we hold, so
1211 			 * simply return.
1212 			 */
1213 			if (lle == NULL)
1214 				return;
1215 			plock = &lle->ll_children[lle->ll_count - 1];
1216 		}
1217 	}
1218 
1219 	/*
1220 	 * Try to perform most checks without a lock.  If this succeeds we
1221 	 * can skip acquiring the lock and return success.  Otherwise we redo
1222 	 * the check with the lock held to handle races with concurrent updates.
1223 	 */
1224 	w1 = plock->li_lock->lo_witness;
1225 	if (witness_lock_order_check(w1, w))
1226 		return;
1227 
1228 	mtx_lock_spin(&w_mtx);
1229 	if (witness_lock_order_check(w1, w)) {
1230 		mtx_unlock_spin(&w_mtx);
1231 		return;
1232 	}
1233 	witness_lock_order_add(w1, w);
1234 
1235 	/*
1236 	 * Check for duplicate locks of the same type.  Note that we only
1237 	 * have to check for this on the last lock we just acquired.  Any
1238 	 * other cases will be caught as lock order violations.
1239 	 */
1240 	if (w1 == w) {
1241 		i = w->w_index;
1242 		if (!(lock->lo_flags & LO_DUPOK) && !(flags & LOP_DUPOK) &&
1243 		    !(w_rmatrix[i][i] & WITNESS_REVERSAL)) {
1244 		    w_rmatrix[i][i] |= WITNESS_REVERSAL;
1245 			w->w_reversed = 1;
1246 			mtx_unlock_spin(&w_mtx);
1247 			witness_output(
1248 			    "acquiring duplicate lock of same type: \"%s\"\n",
1249 			    w->w_name);
1250 			witness_output(" 1st %s @ %s:%d\n", plock->li_lock->lo_name,
1251 			    fixup_filename(plock->li_file), plock->li_line);
1252 			witness_output(" 2nd %s @ %s:%d\n", lock->lo_name,
1253 			    fixup_filename(file), line);
1254 			witness_debugger(1, __func__);
1255 		} else
1256 			mtx_unlock_spin(&w_mtx);
1257 		return;
1258 	}
1259 	mtx_assert(&w_mtx, MA_OWNED);
1260 
1261 	/*
1262 	 * If we know that the lock we are acquiring comes after
1263 	 * the lock we most recently acquired in the lock order tree,
1264 	 * then there is no need for any further checks.
1265 	 */
1266 	if (isitmychild(w1, w))
1267 		goto out;
1268 
1269 	for (j = 0, lle = lock_list; lle != NULL; lle = lle->ll_next) {
1270 		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
1271 
1272 			MPASS(j < LOCK_CHILDCOUNT * LOCK_NCHILDREN);
1273 			lock1 = &lle->ll_children[i];
1274 
1275 			/*
1276 			 * Ignore the interlock.
1277 			 */
1278 			if (interlock == lock1->li_lock)
1279 				continue;
1280 
1281 			/*
1282 			 * If this lock doesn't undergo witness checking,
1283 			 * then skip it.
1284 			 */
1285 			w1 = lock1->li_lock->lo_witness;
1286 			if (w1 == NULL) {
1287 				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
1288 				    ("lock missing witness structure"));
1289 				continue;
1290 			}
1291 
1292 			/*
1293 			 * If we are locking Giant and this is a sleepable
1294 			 * lock, then skip it.
1295 			 */
1296 			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
1297 			    lock == &Giant.lock_object)
1298 				continue;
1299 
1300 			/*
1301 			 * If we are locking a sleepable lock and this lock
1302 			 * is Giant, then skip it.
1303 			 */
1304 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1305 			    lock1->li_lock == &Giant.lock_object)
1306 				continue;
1307 
1308 			/*
1309 			 * If we are locking a sleepable lock and this lock
1310 			 * isn't sleepable, we want to treat it as a lock
1311 			 * order violation to enfore a general lock order of
1312 			 * sleepable locks before non-sleepable locks.
1313 			 */
1314 			if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1315 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1316 				goto reversal;
1317 
1318 			/*
1319 			 * If we are locking Giant and this is a non-sleepable
1320 			 * lock, then treat it as a reversal.
1321 			 */
1322 			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0 &&
1323 			    lock == &Giant.lock_object)
1324 				goto reversal;
1325 
1326 			/*
1327 			 * Check the lock order hierarchy for a reveresal.
1328 			 */
1329 			if (!isitmydescendant(w, w1))
1330 				continue;
1331 		reversal:
1332 
1333 			/*
1334 			 * We have a lock order violation, check to see if it
1335 			 * is allowed or has already been yelled about.
1336 			 */
1337 #ifdef BLESSING
1338 
1339 			/*
1340 			 * If the lock order is blessed, just bail.  We don't
1341 			 * look for other lock order violations though, which
1342 			 * may be a bug.
1343 			 */
1344 			if (blessed(w, w1))
1345 				goto out;
1346 #endif
1347 
1348 			/* Bail if this violation is known */
1349 			if (w_rmatrix[w1->w_index][w->w_index] & WITNESS_REVERSAL)
1350 				goto out;
1351 
1352 			/* Record this as a violation */
1353 			w_rmatrix[w1->w_index][w->w_index] |= WITNESS_REVERSAL;
1354 			w_rmatrix[w->w_index][w1->w_index] |= WITNESS_REVERSAL;
1355 			w->w_reversed = w1->w_reversed = 1;
1356 			witness_increment_graph_generation();
1357 			mtx_unlock_spin(&w_mtx);
1358 
1359 #ifdef WITNESS_NO_VNODE
1360 			/*
1361 			 * There are known LORs between VNODE locks. They are
1362 			 * not an indication of a bug. VNODE locks are flagged
1363 			 * as such (LO_IS_VNODE) and we don't yell if the LOR
1364 			 * is between 2 VNODE locks.
1365 			 */
1366 			if ((lock->lo_flags & LO_IS_VNODE) != 0 &&
1367 			    (lock1->li_lock->lo_flags & LO_IS_VNODE) != 0)
1368 				return;
1369 #endif
1370 
1371 			/*
1372 			 * Ok, yell about it.
1373 			 */
1374 			if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1375 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1376 				witness_output(
1377 		"lock order reversal: (sleepable after non-sleepable)\n");
1378 			else if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0
1379 			    && lock == &Giant.lock_object)
1380 				witness_output(
1381 		"lock order reversal: (Giant after non-sleepable)\n");
1382 			else
1383 				witness_output("lock order reversal:\n");
1384 
1385 			/*
1386 			 * Try to locate an earlier lock with
1387 			 * witness w in our list.
1388 			 */
1389 			do {
1390 				lock2 = &lle->ll_children[i];
1391 				MPASS(lock2->li_lock != NULL);
1392 				if (lock2->li_lock->lo_witness == w)
1393 					break;
1394 				if (i == 0 && lle->ll_next != NULL) {
1395 					lle = lle->ll_next;
1396 					i = lle->ll_count - 1;
1397 					MPASS(i >= 0 && i < LOCK_NCHILDREN);
1398 				} else
1399 					i--;
1400 			} while (i >= 0);
1401 			if (i < 0) {
1402 				witness_output(" 1st %p %s (%s) @ %s:%d\n",
1403 				    lock1->li_lock, lock1->li_lock->lo_name,
1404 				    w1->w_name, fixup_filename(lock1->li_file),
1405 				    lock1->li_line);
1406 				witness_output(" 2nd %p %s (%s) @ %s:%d\n", lock,
1407 				    lock->lo_name, w->w_name,
1408 				    fixup_filename(file), line);
1409 			} else {
1410 				witness_output(" 1st %p %s (%s) @ %s:%d\n",
1411 				    lock2->li_lock, lock2->li_lock->lo_name,
1412 				    lock2->li_lock->lo_witness->w_name,
1413 				    fixup_filename(lock2->li_file),
1414 				    lock2->li_line);
1415 				witness_output(" 2nd %p %s (%s) @ %s:%d\n",
1416 				    lock1->li_lock, lock1->li_lock->lo_name,
1417 				    w1->w_name, fixup_filename(lock1->li_file),
1418 				    lock1->li_line);
1419 				witness_output(" 3rd %p %s (%s) @ %s:%d\n", lock,
1420 				    lock->lo_name, w->w_name,
1421 				    fixup_filename(file), line);
1422 			}
1423 			witness_debugger(1, __func__);
1424 			return;
1425 		}
1426 	}
1427 
1428 	/*
1429 	 * If requested, build a new lock order.  However, don't build a new
1430 	 * relationship between a sleepable lock and Giant if it is in the
1431 	 * wrong direction.  The correct lock order is that sleepable locks
1432 	 * always come before Giant.
1433 	 */
1434 	if (flags & LOP_NEWORDER &&
1435 	    !(plock->li_lock == &Giant.lock_object &&
1436 	    (lock->lo_flags & LO_SLEEPABLE) != 0)) {
1437 		CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1438 		    w->w_name, plock->li_lock->lo_witness->w_name);
1439 		itismychild(plock->li_lock->lo_witness, w);
1440 	}
1441 out:
1442 	mtx_unlock_spin(&w_mtx);
1443 }
1444 
1445 void
1446 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
1447 {
1448 	struct lock_list_entry **lock_list, *lle;
1449 	struct lock_instance *instance;
1450 	struct witness *w;
1451 	struct thread *td;
1452 
1453 	if (witness_cold || witness_watch == -1 || lock->lo_witness == NULL ||
1454 	    panicstr != NULL)
1455 		return;
1456 	w = lock->lo_witness;
1457 	td = curthread;
1458 
1459 	/* Determine lock list for this lock. */
1460 	if (LOCK_CLASS(lock)->lc_flags & LC_SLEEPLOCK)
1461 		lock_list = &td->td_sleeplocks;
1462 	else
1463 		lock_list = PCPU_PTR(spinlocks);
1464 
1465 	/* Check to see if we are recursing on a lock we already own. */
1466 	instance = find_instance(*lock_list, lock);
1467 	if (instance != NULL) {
1468 		instance->li_flags++;
1469 		CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1470 		    td->td_proc->p_pid, lock->lo_name,
1471 		    instance->li_flags & LI_RECURSEMASK);
1472 		instance->li_file = file;
1473 		instance->li_line = line;
1474 		return;
1475 	}
1476 
1477 	/* Update per-witness last file and line acquire. */
1478 	w->w_file = file;
1479 	w->w_line = line;
1480 
1481 	/* Find the next open lock instance in the list and fill it. */
1482 	lle = *lock_list;
1483 	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1484 		lle = witness_lock_list_get();
1485 		if (lle == NULL)
1486 			return;
1487 		lle->ll_next = *lock_list;
1488 		CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1489 		    td->td_proc->p_pid, lle);
1490 		*lock_list = lle;
1491 	}
1492 	instance = &lle->ll_children[lle->ll_count++];
1493 	instance->li_lock = lock;
1494 	instance->li_line = line;
1495 	instance->li_file = file;
1496 	if ((flags & LOP_EXCLUSIVE) != 0)
1497 		instance->li_flags = LI_EXCLUSIVE;
1498 	else
1499 		instance->li_flags = 0;
1500 	CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1501 	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1502 }
1503 
1504 void
1505 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1506 {
1507 	struct lock_instance *instance;
1508 	struct lock_class *class;
1509 
1510 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1511 	if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1512 		return;
1513 	class = LOCK_CLASS(lock);
1514 	if (witness_watch) {
1515 		if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1516 			kassert_panic(
1517 			    "upgrade of non-upgradable lock (%s) %s @ %s:%d",
1518 			    class->lc_name, lock->lo_name,
1519 			    fixup_filename(file), line);
1520 		if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1521 			kassert_panic(
1522 			    "upgrade of non-sleep lock (%s) %s @ %s:%d",
1523 			    class->lc_name, lock->lo_name,
1524 			    fixup_filename(file), line);
1525 	}
1526 	instance = find_instance(curthread->td_sleeplocks, lock);
1527 	if (instance == NULL) {
1528 		kassert_panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1529 		    class->lc_name, lock->lo_name,
1530 		    fixup_filename(file), line);
1531 		return;
1532 	}
1533 	if (witness_watch) {
1534 		if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1535 			kassert_panic(
1536 			    "upgrade of exclusive lock (%s) %s @ %s:%d",
1537 			    class->lc_name, lock->lo_name,
1538 			    fixup_filename(file), line);
1539 		if ((instance->li_flags & LI_RECURSEMASK) != 0)
1540 			kassert_panic(
1541 			    "upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1542 			    class->lc_name, lock->lo_name,
1543 			    instance->li_flags & LI_RECURSEMASK,
1544 			    fixup_filename(file), line);
1545 	}
1546 	instance->li_flags |= LI_EXCLUSIVE;
1547 }
1548 
1549 void
1550 witness_downgrade(struct lock_object *lock, int flags, const char *file,
1551     int line)
1552 {
1553 	struct lock_instance *instance;
1554 	struct lock_class *class;
1555 
1556 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1557 	if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1558 		return;
1559 	class = LOCK_CLASS(lock);
1560 	if (witness_watch) {
1561 		if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1562 			kassert_panic(
1563 			    "downgrade of non-upgradable lock (%s) %s @ %s:%d",
1564 			    class->lc_name, lock->lo_name,
1565 			    fixup_filename(file), line);
1566 		if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1567 			kassert_panic(
1568 			    "downgrade of non-sleep lock (%s) %s @ %s:%d",
1569 			    class->lc_name, lock->lo_name,
1570 			    fixup_filename(file), line);
1571 	}
1572 	instance = find_instance(curthread->td_sleeplocks, lock);
1573 	if (instance == NULL) {
1574 		kassert_panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1575 		    class->lc_name, lock->lo_name,
1576 		    fixup_filename(file), line);
1577 		return;
1578 	}
1579 	if (witness_watch) {
1580 		if ((instance->li_flags & LI_EXCLUSIVE) == 0)
1581 			kassert_panic(
1582 			    "downgrade of shared lock (%s) %s @ %s:%d",
1583 			    class->lc_name, lock->lo_name,
1584 			    fixup_filename(file), line);
1585 		if ((instance->li_flags & LI_RECURSEMASK) != 0)
1586 			kassert_panic(
1587 			    "downgrade of recursed lock (%s) %s r=%d @ %s:%d",
1588 			    class->lc_name, lock->lo_name,
1589 			    instance->li_flags & LI_RECURSEMASK,
1590 			    fixup_filename(file), line);
1591 	}
1592 	instance->li_flags &= ~LI_EXCLUSIVE;
1593 }
1594 
1595 void
1596 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
1597 {
1598 	struct lock_list_entry **lock_list, *lle;
1599 	struct lock_instance *instance;
1600 	struct lock_class *class;
1601 	struct thread *td;
1602 	register_t s;
1603 	int i, j;
1604 
1605 	if (witness_cold || lock->lo_witness == NULL || panicstr != NULL)
1606 		return;
1607 	td = curthread;
1608 	class = LOCK_CLASS(lock);
1609 
1610 	/* Find lock instance associated with this lock. */
1611 	if (class->lc_flags & LC_SLEEPLOCK)
1612 		lock_list = &td->td_sleeplocks;
1613 	else
1614 		lock_list = PCPU_PTR(spinlocks);
1615 	lle = *lock_list;
1616 	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
1617 		for (i = 0; i < (*lock_list)->ll_count; i++) {
1618 			instance = &(*lock_list)->ll_children[i];
1619 			if (instance->li_lock == lock)
1620 				goto found;
1621 		}
1622 
1623 	/*
1624 	 * When disabling WITNESS through witness_watch we could end up in
1625 	 * having registered locks in the td_sleeplocks queue.
1626 	 * We have to make sure we flush these queues, so just search for
1627 	 * eventual register locks and remove them.
1628 	 */
1629 	if (witness_watch > 0) {
1630 		kassert_panic("lock (%s) %s not locked @ %s:%d", class->lc_name,
1631 		    lock->lo_name, fixup_filename(file), line);
1632 		return;
1633 	} else {
1634 		return;
1635 	}
1636 found:
1637 
1638 	/* First, check for shared/exclusive mismatches. */
1639 	if ((instance->li_flags & LI_EXCLUSIVE) != 0 && witness_watch > 0 &&
1640 	    (flags & LOP_EXCLUSIVE) == 0) {
1641 		witness_output("shared unlock of (%s) %s @ %s:%d\n",
1642 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
1643 		witness_output("while exclusively locked from %s:%d\n",
1644 		    fixup_filename(instance->li_file), instance->li_line);
1645 		kassert_panic("excl->ushare");
1646 	}
1647 	if ((instance->li_flags & LI_EXCLUSIVE) == 0 && witness_watch > 0 &&
1648 	    (flags & LOP_EXCLUSIVE) != 0) {
1649 		witness_output("exclusive unlock of (%s) %s @ %s:%d\n",
1650 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
1651 		witness_output("while share locked from %s:%d\n",
1652 		    fixup_filename(instance->li_file),
1653 		    instance->li_line);
1654 		kassert_panic("share->uexcl");
1655 	}
1656 	/* If we are recursed, unrecurse. */
1657 	if ((instance->li_flags & LI_RECURSEMASK) > 0) {
1658 		CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
1659 		    td->td_proc->p_pid, instance->li_lock->lo_name,
1660 		    instance->li_flags);
1661 		instance->li_flags--;
1662 		return;
1663 	}
1664 	/* The lock is now being dropped, check for NORELEASE flag */
1665 	if ((instance->li_flags & LI_NORELEASE) != 0 && witness_watch > 0) {
1666 		witness_output("forbidden unlock of (%s) %s @ %s:%d\n",
1667 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
1668 		kassert_panic("lock marked norelease");
1669 	}
1670 
1671 	/* Otherwise, remove this item from the list. */
1672 	s = intr_disable();
1673 	CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
1674 	    td->td_proc->p_pid, instance->li_lock->lo_name,
1675 	    (*lock_list)->ll_count - 1);
1676 	for (j = i; j < (*lock_list)->ll_count - 1; j++)
1677 		(*lock_list)->ll_children[j] =
1678 		    (*lock_list)->ll_children[j + 1];
1679 	(*lock_list)->ll_count--;
1680 	intr_restore(s);
1681 
1682 	/*
1683 	 * In order to reduce contention on w_mtx, we want to keep always an
1684 	 * head object into lists so that frequent allocation from the
1685 	 * free witness pool (and subsequent locking) is avoided.
1686 	 * In order to maintain the current code simple, when the head
1687 	 * object is totally unloaded it means also that we do not have
1688 	 * further objects in the list, so the list ownership needs to be
1689 	 * hand over to another object if the current head needs to be freed.
1690 	 */
1691 	if ((*lock_list)->ll_count == 0) {
1692 		if (*lock_list == lle) {
1693 			if (lle->ll_next == NULL)
1694 				return;
1695 		} else
1696 			lle = *lock_list;
1697 		*lock_list = lle->ll_next;
1698 		CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
1699 		    td->td_proc->p_pid, lle);
1700 		witness_lock_list_free(lle);
1701 	}
1702 }
1703 
1704 void
1705 witness_thread_exit(struct thread *td)
1706 {
1707 	struct lock_list_entry *lle;
1708 	int i, n;
1709 
1710 	lle = td->td_sleeplocks;
1711 	if (lle == NULL || panicstr != NULL)
1712 		return;
1713 	if (lle->ll_count != 0) {
1714 		for (n = 0; lle != NULL; lle = lle->ll_next)
1715 			for (i = lle->ll_count - 1; i >= 0; i--) {
1716 				if (n == 0)
1717 					witness_output(
1718 		    "Thread %p exiting with the following locks held:\n", td);
1719 				n++;
1720 				witness_list_lock(&lle->ll_children[i],
1721 				    witness_output);
1722 
1723 			}
1724 		kassert_panic(
1725 		    "Thread %p cannot exit while holding sleeplocks\n", td);
1726 	}
1727 	witness_lock_list_free(lle);
1728 }
1729 
1730 /*
1731  * Warn if any locks other than 'lock' are held.  Flags can be passed in to
1732  * exempt Giant and sleepable locks from the checks as well.  If any
1733  * non-exempt locks are held, then a supplied message is printed to the
1734  * output channel along with a list of the offending locks.  If indicated in the
1735  * flags then a failure results in a panic as well.
1736  */
1737 int
1738 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1739 {
1740 	struct lock_list_entry *lock_list, *lle;
1741 	struct lock_instance *lock1;
1742 	struct thread *td;
1743 	va_list ap;
1744 	int i, n;
1745 
1746 	if (witness_cold || witness_watch < 1 || panicstr != NULL)
1747 		return (0);
1748 	n = 0;
1749 	td = curthread;
1750 	for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1751 		for (i = lle->ll_count - 1; i >= 0; i--) {
1752 			lock1 = &lle->ll_children[i];
1753 			if (lock1->li_lock == lock)
1754 				continue;
1755 			if (flags & WARN_GIANTOK &&
1756 			    lock1->li_lock == &Giant.lock_object)
1757 				continue;
1758 			if (flags & WARN_SLEEPOK &&
1759 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1760 				continue;
1761 			if (n == 0) {
1762 				va_start(ap, fmt);
1763 				vprintf(fmt, ap);
1764 				va_end(ap);
1765 				printf(" with the following %slocks held:\n",
1766 				    (flags & WARN_SLEEPOK) != 0 ?
1767 				    "non-sleepable " : "");
1768 			}
1769 			n++;
1770 			witness_list_lock(lock1, printf);
1771 		}
1772 
1773 	/*
1774 	 * Pin the thread in order to avoid problems with thread migration.
1775 	 * Once that all verifies are passed about spinlocks ownership,
1776 	 * the thread is in a safe path and it can be unpinned.
1777 	 */
1778 	sched_pin();
1779 	lock_list = PCPU_GET(spinlocks);
1780 	if (lock_list != NULL && lock_list->ll_count != 0) {
1781 		sched_unpin();
1782 
1783 		/*
1784 		 * We should only have one spinlock and as long as
1785 		 * the flags cannot match for this locks class,
1786 		 * check if the first spinlock is the one curthread
1787 		 * should hold.
1788 		 */
1789 		lock1 = &lock_list->ll_children[lock_list->ll_count - 1];
1790 		if (lock_list->ll_count == 1 && lock_list->ll_next == NULL &&
1791 		    lock1->li_lock == lock && n == 0)
1792 			return (0);
1793 
1794 		va_start(ap, fmt);
1795 		vprintf(fmt, ap);
1796 		va_end(ap);
1797 		printf(" with the following %slocks held:\n",
1798 		    (flags & WARN_SLEEPOK) != 0 ?  "non-sleepable " : "");
1799 		n += witness_list_locks(&lock_list, printf);
1800 	} else
1801 		sched_unpin();
1802 	if (flags & WARN_PANIC && n)
1803 		kassert_panic("%s", __func__);
1804 	else
1805 		witness_debugger(n, __func__);
1806 	return (n);
1807 }
1808 
1809 const char *
1810 witness_file(struct lock_object *lock)
1811 {
1812 	struct witness *w;
1813 
1814 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1815 		return ("?");
1816 	w = lock->lo_witness;
1817 	return (w->w_file);
1818 }
1819 
1820 int
1821 witness_line(struct lock_object *lock)
1822 {
1823 	struct witness *w;
1824 
1825 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1826 		return (0);
1827 	w = lock->lo_witness;
1828 	return (w->w_line);
1829 }
1830 
1831 static struct witness *
1832 enroll(const char *description, struct lock_class *lock_class)
1833 {
1834 	struct witness *w;
1835 
1836 	MPASS(description != NULL);
1837 
1838 	if (witness_watch == -1 || panicstr != NULL)
1839 		return (NULL);
1840 	if ((lock_class->lc_flags & LC_SPINLOCK)) {
1841 		if (witness_skipspin)
1842 			return (NULL);
1843 	} else if ((lock_class->lc_flags & LC_SLEEPLOCK) == 0) {
1844 		kassert_panic("lock class %s is not sleep or spin",
1845 		    lock_class->lc_name);
1846 		return (NULL);
1847 	}
1848 
1849 	mtx_lock_spin(&w_mtx);
1850 	w = witness_hash_get(description);
1851 	if (w)
1852 		goto found;
1853 	if ((w = witness_get()) == NULL)
1854 		return (NULL);
1855 	MPASS(strlen(description) < MAX_W_NAME);
1856 	strcpy(w->w_name, description);
1857 	w->w_class = lock_class;
1858 	w->w_refcount = 1;
1859 	STAILQ_INSERT_HEAD(&w_all, w, w_list);
1860 	if (lock_class->lc_flags & LC_SPINLOCK) {
1861 		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1862 		w_spin_cnt++;
1863 	} else if (lock_class->lc_flags & LC_SLEEPLOCK) {
1864 		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1865 		w_sleep_cnt++;
1866 	}
1867 
1868 	/* Insert new witness into the hash */
1869 	witness_hash_put(w);
1870 	witness_increment_graph_generation();
1871 	mtx_unlock_spin(&w_mtx);
1872 	return (w);
1873 found:
1874 	w->w_refcount++;
1875 	if (w->w_refcount == 1)
1876 		w->w_class = lock_class;
1877 	mtx_unlock_spin(&w_mtx);
1878 	if (lock_class != w->w_class)
1879 		kassert_panic(
1880 		    "lock (%s) %s does not match earlier (%s) lock",
1881 		    description, lock_class->lc_name,
1882 		    w->w_class->lc_name);
1883 	return (w);
1884 }
1885 
1886 static void
1887 depart(struct witness *w)
1888 {
1889 
1890 	MPASS(w->w_refcount == 0);
1891 	if (w->w_class->lc_flags & LC_SLEEPLOCK) {
1892 		w_sleep_cnt--;
1893 	} else {
1894 		w_spin_cnt--;
1895 	}
1896 	/*
1897 	 * Set file to NULL as it may point into a loadable module.
1898 	 */
1899 	w->w_file = NULL;
1900 	w->w_line = 0;
1901 	witness_increment_graph_generation();
1902 }
1903 
1904 
1905 static void
1906 adopt(struct witness *parent, struct witness *child)
1907 {
1908 	int pi, ci, i, j;
1909 
1910 	if (witness_cold == 0)
1911 		mtx_assert(&w_mtx, MA_OWNED);
1912 
1913 	/* If the relationship is already known, there's no work to be done. */
1914 	if (isitmychild(parent, child))
1915 		return;
1916 
1917 	/* When the structure of the graph changes, bump up the generation. */
1918 	witness_increment_graph_generation();
1919 
1920 	/*
1921 	 * The hard part ... create the direct relationship, then propagate all
1922 	 * indirect relationships.
1923 	 */
1924 	pi = parent->w_index;
1925 	ci = child->w_index;
1926 	WITNESS_INDEX_ASSERT(pi);
1927 	WITNESS_INDEX_ASSERT(ci);
1928 	MPASS(pi != ci);
1929 	w_rmatrix[pi][ci] |= WITNESS_PARENT;
1930 	w_rmatrix[ci][pi] |= WITNESS_CHILD;
1931 
1932 	/*
1933 	 * If parent was not already an ancestor of child,
1934 	 * then we increment the descendant and ancestor counters.
1935 	 */
1936 	if ((w_rmatrix[pi][ci] & WITNESS_ANCESTOR) == 0) {
1937 		parent->w_num_descendants++;
1938 		child->w_num_ancestors++;
1939 	}
1940 
1941 	/*
1942 	 * Find each ancestor of 'pi'. Note that 'pi' itself is counted as
1943 	 * an ancestor of 'pi' during this loop.
1944 	 */
1945 	for (i = 1; i <= w_max_used_index; i++) {
1946 		if ((w_rmatrix[i][pi] & WITNESS_ANCESTOR_MASK) == 0 &&
1947 		    (i != pi))
1948 			continue;
1949 
1950 		/* Find each descendant of 'i' and mark it as a descendant. */
1951 		for (j = 1; j <= w_max_used_index; j++) {
1952 
1953 			/*
1954 			 * Skip children that are already marked as
1955 			 * descendants of 'i'.
1956 			 */
1957 			if (w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK)
1958 				continue;
1959 
1960 			/*
1961 			 * We are only interested in descendants of 'ci'. Note
1962 			 * that 'ci' itself is counted as a descendant of 'ci'.
1963 			 */
1964 			if ((w_rmatrix[ci][j] & WITNESS_ANCESTOR_MASK) == 0 &&
1965 			    (j != ci))
1966 				continue;
1967 			w_rmatrix[i][j] |= WITNESS_ANCESTOR;
1968 			w_rmatrix[j][i] |= WITNESS_DESCENDANT;
1969 			w_data[i].w_num_descendants++;
1970 			w_data[j].w_num_ancestors++;
1971 
1972 			/*
1973 			 * Make sure we aren't marking a node as both an
1974 			 * ancestor and descendant. We should have caught
1975 			 * this as a lock order reversal earlier.
1976 			 */
1977 			if ((w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK) &&
1978 			    (w_rmatrix[i][j] & WITNESS_DESCENDANT_MASK)) {
1979 				printf("witness rmatrix paradox! [%d][%d]=%d "
1980 				    "both ancestor and descendant\n",
1981 				    i, j, w_rmatrix[i][j]);
1982 				kdb_backtrace();
1983 				printf("Witness disabled.\n");
1984 				witness_watch = -1;
1985 			}
1986 			if ((w_rmatrix[j][i] & WITNESS_ANCESTOR_MASK) &&
1987 			    (w_rmatrix[j][i] & WITNESS_DESCENDANT_MASK)) {
1988 				printf("witness rmatrix paradox! [%d][%d]=%d "
1989 				    "both ancestor and descendant\n",
1990 				    j, i, w_rmatrix[j][i]);
1991 				kdb_backtrace();
1992 				printf("Witness disabled.\n");
1993 				witness_watch = -1;
1994 			}
1995 		}
1996 	}
1997 }
1998 
1999 static void
2000 itismychild(struct witness *parent, struct witness *child)
2001 {
2002 	int unlocked;
2003 
2004 	MPASS(child != NULL && parent != NULL);
2005 	if (witness_cold == 0)
2006 		mtx_assert(&w_mtx, MA_OWNED);
2007 
2008 	if (!witness_lock_type_equal(parent, child)) {
2009 		if (witness_cold == 0) {
2010 			unlocked = 1;
2011 			mtx_unlock_spin(&w_mtx);
2012 		} else {
2013 			unlocked = 0;
2014 		}
2015 		kassert_panic(
2016 		    "%s: parent \"%s\" (%s) and child \"%s\" (%s) are not "
2017 		    "the same lock type", __func__, parent->w_name,
2018 		    parent->w_class->lc_name, child->w_name,
2019 		    child->w_class->lc_name);
2020 		if (unlocked)
2021 			mtx_lock_spin(&w_mtx);
2022 	}
2023 	adopt(parent, child);
2024 }
2025 
2026 /*
2027  * Generic code for the isitmy*() functions. The rmask parameter is the
2028  * expected relationship of w1 to w2.
2029  */
2030 static int
2031 _isitmyx(struct witness *w1, struct witness *w2, int rmask, const char *fname)
2032 {
2033 	unsigned char r1, r2;
2034 	int i1, i2;
2035 
2036 	i1 = w1->w_index;
2037 	i2 = w2->w_index;
2038 	WITNESS_INDEX_ASSERT(i1);
2039 	WITNESS_INDEX_ASSERT(i2);
2040 	r1 = w_rmatrix[i1][i2] & WITNESS_RELATED_MASK;
2041 	r2 = w_rmatrix[i2][i1] & WITNESS_RELATED_MASK;
2042 
2043 	/* The flags on one better be the inverse of the flags on the other */
2044 	if (!((WITNESS_ATOD(r1) == r2 && WITNESS_DTOA(r2) == r1) ||
2045 	    (WITNESS_DTOA(r1) == r2 && WITNESS_ATOD(r2) == r1))) {
2046 		/* Don't squawk if we're potentially racing with an update. */
2047 		if (!mtx_owned(&w_mtx))
2048 			return (0);
2049 		printf("%s: rmatrix mismatch between %s (index %d) and %s "
2050 		    "(index %d): w_rmatrix[%d][%d] == %hhx but "
2051 		    "w_rmatrix[%d][%d] == %hhx\n",
2052 		    fname, w1->w_name, i1, w2->w_name, i2, i1, i2, r1,
2053 		    i2, i1, r2);
2054 		kdb_backtrace();
2055 		printf("Witness disabled.\n");
2056 		witness_watch = -1;
2057 	}
2058 	return (r1 & rmask);
2059 }
2060 
2061 /*
2062  * Checks if @child is a direct child of @parent.
2063  */
2064 static int
2065 isitmychild(struct witness *parent, struct witness *child)
2066 {
2067 
2068 	return (_isitmyx(parent, child, WITNESS_PARENT, __func__));
2069 }
2070 
2071 /*
2072  * Checks if @descendant is a direct or inderect descendant of @ancestor.
2073  */
2074 static int
2075 isitmydescendant(struct witness *ancestor, struct witness *descendant)
2076 {
2077 
2078 	return (_isitmyx(ancestor, descendant, WITNESS_ANCESTOR_MASK,
2079 	    __func__));
2080 }
2081 
2082 #ifdef BLESSING
2083 static int
2084 blessed(struct witness *w1, struct witness *w2)
2085 {
2086 	int i;
2087 	struct witness_blessed *b;
2088 
2089 	for (i = 0; i < nitems(blessed_list); i++) {
2090 		b = &blessed_list[i];
2091 		if (strcmp(w1->w_name, b->b_lock1) == 0) {
2092 			if (strcmp(w2->w_name, b->b_lock2) == 0)
2093 				return (1);
2094 			continue;
2095 		}
2096 		if (strcmp(w1->w_name, b->b_lock2) == 0)
2097 			if (strcmp(w2->w_name, b->b_lock1) == 0)
2098 				return (1);
2099 	}
2100 	return (0);
2101 }
2102 #endif
2103 
2104 static struct witness *
2105 witness_get(void)
2106 {
2107 	struct witness *w;
2108 	int index;
2109 
2110 	if (witness_cold == 0)
2111 		mtx_assert(&w_mtx, MA_OWNED);
2112 
2113 	if (witness_watch == -1) {
2114 		mtx_unlock_spin(&w_mtx);
2115 		return (NULL);
2116 	}
2117 	if (STAILQ_EMPTY(&w_free)) {
2118 		witness_watch = -1;
2119 		mtx_unlock_spin(&w_mtx);
2120 		printf("WITNESS: unable to allocate a new witness object\n");
2121 		return (NULL);
2122 	}
2123 	w = STAILQ_FIRST(&w_free);
2124 	STAILQ_REMOVE_HEAD(&w_free, w_list);
2125 	w_free_cnt--;
2126 	index = w->w_index;
2127 	MPASS(index > 0 && index == w_max_used_index+1 &&
2128 	    index < witness_count);
2129 	bzero(w, sizeof(*w));
2130 	w->w_index = index;
2131 	if (index > w_max_used_index)
2132 		w_max_used_index = index;
2133 	return (w);
2134 }
2135 
2136 static void
2137 witness_free(struct witness *w)
2138 {
2139 
2140 	STAILQ_INSERT_HEAD(&w_free, w, w_list);
2141 	w_free_cnt++;
2142 }
2143 
2144 static struct lock_list_entry *
2145 witness_lock_list_get(void)
2146 {
2147 	struct lock_list_entry *lle;
2148 
2149 	if (witness_watch == -1)
2150 		return (NULL);
2151 	mtx_lock_spin(&w_mtx);
2152 	lle = w_lock_list_free;
2153 	if (lle == NULL) {
2154 		witness_watch = -1;
2155 		mtx_unlock_spin(&w_mtx);
2156 		printf("%s: witness exhausted\n", __func__);
2157 		return (NULL);
2158 	}
2159 	w_lock_list_free = lle->ll_next;
2160 	mtx_unlock_spin(&w_mtx);
2161 	bzero(lle, sizeof(*lle));
2162 	return (lle);
2163 }
2164 
2165 static void
2166 witness_lock_list_free(struct lock_list_entry *lle)
2167 {
2168 
2169 	mtx_lock_spin(&w_mtx);
2170 	lle->ll_next = w_lock_list_free;
2171 	w_lock_list_free = lle;
2172 	mtx_unlock_spin(&w_mtx);
2173 }
2174 
2175 static struct lock_instance *
2176 find_instance(struct lock_list_entry *list, const struct lock_object *lock)
2177 {
2178 	struct lock_list_entry *lle;
2179 	struct lock_instance *instance;
2180 	int i;
2181 
2182 	for (lle = list; lle != NULL; lle = lle->ll_next)
2183 		for (i = lle->ll_count - 1; i >= 0; i--) {
2184 			instance = &lle->ll_children[i];
2185 			if (instance->li_lock == lock)
2186 				return (instance);
2187 		}
2188 	return (NULL);
2189 }
2190 
2191 static void
2192 witness_list_lock(struct lock_instance *instance,
2193     int (*prnt)(const char *fmt, ...))
2194 {
2195 	struct lock_object *lock;
2196 
2197 	lock = instance->li_lock;
2198 	prnt("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
2199 	    "exclusive" : "shared", LOCK_CLASS(lock)->lc_name, lock->lo_name);
2200 	if (lock->lo_witness->w_name != lock->lo_name)
2201 		prnt(" (%s)", lock->lo_witness->w_name);
2202 	prnt(" r = %d (%p) locked @ %s:%d\n",
2203 	    instance->li_flags & LI_RECURSEMASK, lock,
2204 	    fixup_filename(instance->li_file), instance->li_line);
2205 }
2206 
2207 static int
2208 witness_output(const char *fmt, ...)
2209 {
2210 	va_list ap;
2211 	int ret;
2212 
2213 	va_start(ap, fmt);
2214 	ret = witness_voutput(fmt, ap);
2215 	va_end(ap);
2216 	return (ret);
2217 }
2218 
2219 static int
2220 witness_voutput(const char *fmt, va_list ap)
2221 {
2222 	int ret;
2223 
2224 	ret = 0;
2225 	switch (witness_channel) {
2226 	case WITNESS_CONSOLE:
2227 		ret = vprintf(fmt, ap);
2228 		break;
2229 	case WITNESS_LOG:
2230 		vlog(LOG_NOTICE, fmt, ap);
2231 		break;
2232 	case WITNESS_NONE:
2233 		break;
2234 	}
2235 	return (ret);
2236 }
2237 
2238 #ifdef DDB
2239 static int
2240 witness_thread_has_locks(struct thread *td)
2241 {
2242 
2243 	if (td->td_sleeplocks == NULL)
2244 		return (0);
2245 	return (td->td_sleeplocks->ll_count != 0);
2246 }
2247 
2248 static int
2249 witness_proc_has_locks(struct proc *p)
2250 {
2251 	struct thread *td;
2252 
2253 	FOREACH_THREAD_IN_PROC(p, td) {
2254 		if (witness_thread_has_locks(td))
2255 			return (1);
2256 	}
2257 	return (0);
2258 }
2259 #endif
2260 
2261 int
2262 witness_list_locks(struct lock_list_entry **lock_list,
2263     int (*prnt)(const char *fmt, ...))
2264 {
2265 	struct lock_list_entry *lle;
2266 	int i, nheld;
2267 
2268 	nheld = 0;
2269 	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
2270 		for (i = lle->ll_count - 1; i >= 0; i--) {
2271 			witness_list_lock(&lle->ll_children[i], prnt);
2272 			nheld++;
2273 		}
2274 	return (nheld);
2275 }
2276 
2277 /*
2278  * This is a bit risky at best.  We call this function when we have timed
2279  * out acquiring a spin lock, and we assume that the other CPU is stuck
2280  * with this lock held.  So, we go groveling around in the other CPU's
2281  * per-cpu data to try to find the lock instance for this spin lock to
2282  * see when it was last acquired.
2283  */
2284 void
2285 witness_display_spinlock(struct lock_object *lock, struct thread *owner,
2286     int (*prnt)(const char *fmt, ...))
2287 {
2288 	struct lock_instance *instance;
2289 	struct pcpu *pc;
2290 
2291 	if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
2292 		return;
2293 	pc = pcpu_find(owner->td_oncpu);
2294 	instance = find_instance(pc->pc_spinlocks, lock);
2295 	if (instance != NULL)
2296 		witness_list_lock(instance, prnt);
2297 }
2298 
2299 void
2300 witness_save(struct lock_object *lock, const char **filep, int *linep)
2301 {
2302 	struct lock_list_entry *lock_list;
2303 	struct lock_instance *instance;
2304 	struct lock_class *class;
2305 
2306 	/*
2307 	 * This function is used independently in locking code to deal with
2308 	 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2309 	 * is gone.
2310 	 */
2311 	if (SCHEDULER_STOPPED())
2312 		return;
2313 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2314 	if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2315 		return;
2316 	class = LOCK_CLASS(lock);
2317 	if (class->lc_flags & LC_SLEEPLOCK)
2318 		lock_list = curthread->td_sleeplocks;
2319 	else {
2320 		if (witness_skipspin)
2321 			return;
2322 		lock_list = PCPU_GET(spinlocks);
2323 	}
2324 	instance = find_instance(lock_list, lock);
2325 	if (instance == NULL) {
2326 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2327 		    class->lc_name, lock->lo_name);
2328 		return;
2329 	}
2330 	*filep = instance->li_file;
2331 	*linep = instance->li_line;
2332 }
2333 
2334 void
2335 witness_restore(struct lock_object *lock, const char *file, int line)
2336 {
2337 	struct lock_list_entry *lock_list;
2338 	struct lock_instance *instance;
2339 	struct lock_class *class;
2340 
2341 	/*
2342 	 * This function is used independently in locking code to deal with
2343 	 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2344 	 * is gone.
2345 	 */
2346 	if (SCHEDULER_STOPPED())
2347 		return;
2348 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2349 	if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2350 		return;
2351 	class = LOCK_CLASS(lock);
2352 	if (class->lc_flags & LC_SLEEPLOCK)
2353 		lock_list = curthread->td_sleeplocks;
2354 	else {
2355 		if (witness_skipspin)
2356 			return;
2357 		lock_list = PCPU_GET(spinlocks);
2358 	}
2359 	instance = find_instance(lock_list, lock);
2360 	if (instance == NULL)
2361 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2362 		    class->lc_name, lock->lo_name);
2363 	lock->lo_witness->w_file = file;
2364 	lock->lo_witness->w_line = line;
2365 	if (instance == NULL)
2366 		return;
2367 	instance->li_file = file;
2368 	instance->li_line = line;
2369 }
2370 
2371 void
2372 witness_assert(const struct lock_object *lock, int flags, const char *file,
2373     int line)
2374 {
2375 #ifdef INVARIANT_SUPPORT
2376 	struct lock_instance *instance;
2377 	struct lock_class *class;
2378 
2379 	if (lock->lo_witness == NULL || witness_watch < 1 || panicstr != NULL)
2380 		return;
2381 	class = LOCK_CLASS(lock);
2382 	if ((class->lc_flags & LC_SLEEPLOCK) != 0)
2383 		instance = find_instance(curthread->td_sleeplocks, lock);
2384 	else if ((class->lc_flags & LC_SPINLOCK) != 0)
2385 		instance = find_instance(PCPU_GET(spinlocks), lock);
2386 	else {
2387 		kassert_panic("Lock (%s) %s is not sleep or spin!",
2388 		    class->lc_name, lock->lo_name);
2389 		return;
2390 	}
2391 	switch (flags) {
2392 	case LA_UNLOCKED:
2393 		if (instance != NULL)
2394 			kassert_panic("Lock (%s) %s locked @ %s:%d.",
2395 			    class->lc_name, lock->lo_name,
2396 			    fixup_filename(file), line);
2397 		break;
2398 	case LA_LOCKED:
2399 	case LA_LOCKED | LA_RECURSED:
2400 	case LA_LOCKED | LA_NOTRECURSED:
2401 	case LA_SLOCKED:
2402 	case LA_SLOCKED | LA_RECURSED:
2403 	case LA_SLOCKED | LA_NOTRECURSED:
2404 	case LA_XLOCKED:
2405 	case LA_XLOCKED | LA_RECURSED:
2406 	case LA_XLOCKED | LA_NOTRECURSED:
2407 		if (instance == NULL) {
2408 			kassert_panic("Lock (%s) %s not locked @ %s:%d.",
2409 			    class->lc_name, lock->lo_name,
2410 			    fixup_filename(file), line);
2411 			break;
2412 		}
2413 		if ((flags & LA_XLOCKED) != 0 &&
2414 		    (instance->li_flags & LI_EXCLUSIVE) == 0)
2415 			kassert_panic(
2416 			    "Lock (%s) %s not exclusively locked @ %s:%d.",
2417 			    class->lc_name, lock->lo_name,
2418 			    fixup_filename(file), line);
2419 		if ((flags & LA_SLOCKED) != 0 &&
2420 		    (instance->li_flags & LI_EXCLUSIVE) != 0)
2421 			kassert_panic(
2422 			    "Lock (%s) %s exclusively locked @ %s:%d.",
2423 			    class->lc_name, lock->lo_name,
2424 			    fixup_filename(file), line);
2425 		if ((flags & LA_RECURSED) != 0 &&
2426 		    (instance->li_flags & LI_RECURSEMASK) == 0)
2427 			kassert_panic("Lock (%s) %s not recursed @ %s:%d.",
2428 			    class->lc_name, lock->lo_name,
2429 			    fixup_filename(file), line);
2430 		if ((flags & LA_NOTRECURSED) != 0 &&
2431 		    (instance->li_flags & LI_RECURSEMASK) != 0)
2432 			kassert_panic("Lock (%s) %s recursed @ %s:%d.",
2433 			    class->lc_name, lock->lo_name,
2434 			    fixup_filename(file), line);
2435 		break;
2436 	default:
2437 		kassert_panic("Invalid lock assertion at %s:%d.",
2438 		    fixup_filename(file), line);
2439 
2440 	}
2441 #endif	/* INVARIANT_SUPPORT */
2442 }
2443 
2444 static void
2445 witness_setflag(struct lock_object *lock, int flag, int set)
2446 {
2447 	struct lock_list_entry *lock_list;
2448 	struct lock_instance *instance;
2449 	struct lock_class *class;
2450 
2451 	if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2452 		return;
2453 	class = LOCK_CLASS(lock);
2454 	if (class->lc_flags & LC_SLEEPLOCK)
2455 		lock_list = curthread->td_sleeplocks;
2456 	else {
2457 		if (witness_skipspin)
2458 			return;
2459 		lock_list = PCPU_GET(spinlocks);
2460 	}
2461 	instance = find_instance(lock_list, lock);
2462 	if (instance == NULL) {
2463 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2464 		    class->lc_name, lock->lo_name);
2465 		return;
2466 	}
2467 
2468 	if (set)
2469 		instance->li_flags |= flag;
2470 	else
2471 		instance->li_flags &= ~flag;
2472 }
2473 
2474 void
2475 witness_norelease(struct lock_object *lock)
2476 {
2477 
2478 	witness_setflag(lock, LI_NORELEASE, 1);
2479 }
2480 
2481 void
2482 witness_releaseok(struct lock_object *lock)
2483 {
2484 
2485 	witness_setflag(lock, LI_NORELEASE, 0);
2486 }
2487 
2488 #ifdef DDB
2489 static void
2490 witness_ddb_list(struct thread *td)
2491 {
2492 
2493 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2494 	KASSERT(kdb_active, ("%s: not in the debugger", __func__));
2495 
2496 	if (witness_watch < 1)
2497 		return;
2498 
2499 	witness_list_locks(&td->td_sleeplocks, db_printf);
2500 
2501 	/*
2502 	 * We only handle spinlocks if td == curthread.  This is somewhat broken
2503 	 * if td is currently executing on some other CPU and holds spin locks
2504 	 * as we won't display those locks.  If we had a MI way of getting
2505 	 * the per-cpu data for a given cpu then we could use
2506 	 * td->td_oncpu to get the list of spinlocks for this thread
2507 	 * and "fix" this.
2508 	 *
2509 	 * That still wouldn't really fix this unless we locked the scheduler
2510 	 * lock or stopped the other CPU to make sure it wasn't changing the
2511 	 * list out from under us.  It is probably best to just not try to
2512 	 * handle threads on other CPU's for now.
2513 	 */
2514 	if (td == curthread && PCPU_GET(spinlocks) != NULL)
2515 		witness_list_locks(PCPU_PTR(spinlocks), db_printf);
2516 }
2517 
2518 DB_SHOW_COMMAND(locks, db_witness_list)
2519 {
2520 	struct thread *td;
2521 
2522 	if (have_addr)
2523 		td = db_lookup_thread(addr, true);
2524 	else
2525 		td = kdb_thread;
2526 	witness_ddb_list(td);
2527 }
2528 
2529 DB_SHOW_ALL_COMMAND(locks, db_witness_list_all)
2530 {
2531 	struct thread *td;
2532 	struct proc *p;
2533 
2534 	/*
2535 	 * It would be nice to list only threads and processes that actually
2536 	 * held sleep locks, but that information is currently not exported
2537 	 * by WITNESS.
2538 	 */
2539 	FOREACH_PROC_IN_SYSTEM(p) {
2540 		if (!witness_proc_has_locks(p))
2541 			continue;
2542 		FOREACH_THREAD_IN_PROC(p, td) {
2543 			if (!witness_thread_has_locks(td))
2544 				continue;
2545 			db_printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
2546 			    p->p_comm, td, td->td_tid);
2547 			witness_ddb_list(td);
2548 			if (db_pager_quit)
2549 				return;
2550 		}
2551 	}
2552 }
2553 DB_SHOW_ALIAS(alllocks, db_witness_list_all)
2554 
2555 DB_SHOW_COMMAND(witness, db_witness_display)
2556 {
2557 
2558 	witness_ddb_display(db_printf);
2559 }
2560 #endif
2561 
2562 static void
2563 sbuf_print_witness_badstacks(struct sbuf *sb, size_t *oldidx)
2564 {
2565 	struct witness_lock_order_data *data1, *data2, *tmp_data1, *tmp_data2;
2566 	struct witness *tmp_w1, *tmp_w2, *w1, *w2;
2567 	int generation, i, j;
2568 
2569 	tmp_data1 = NULL;
2570 	tmp_data2 = NULL;
2571 	tmp_w1 = NULL;
2572 	tmp_w2 = NULL;
2573 
2574 	/* Allocate and init temporary storage space. */
2575 	tmp_w1 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2576 	tmp_w2 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2577 	tmp_data1 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2578 	    M_WAITOK | M_ZERO);
2579 	tmp_data2 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2580 	    M_WAITOK | M_ZERO);
2581 	stack_zero(&tmp_data1->wlod_stack);
2582 	stack_zero(&tmp_data2->wlod_stack);
2583 
2584 restart:
2585 	mtx_lock_spin(&w_mtx);
2586 	generation = w_generation;
2587 	mtx_unlock_spin(&w_mtx);
2588 	sbuf_printf(sb, "Number of known direct relationships is %d\n",
2589 	    w_lohash.wloh_count);
2590 	for (i = 1; i < w_max_used_index; i++) {
2591 		mtx_lock_spin(&w_mtx);
2592 		if (generation != w_generation) {
2593 			mtx_unlock_spin(&w_mtx);
2594 
2595 			/* The graph has changed, try again. */
2596 			*oldidx = 0;
2597 			sbuf_clear(sb);
2598 			goto restart;
2599 		}
2600 
2601 		w1 = &w_data[i];
2602 		if (w1->w_reversed == 0) {
2603 			mtx_unlock_spin(&w_mtx);
2604 			continue;
2605 		}
2606 
2607 		/* Copy w1 locally so we can release the spin lock. */
2608 		*tmp_w1 = *w1;
2609 		mtx_unlock_spin(&w_mtx);
2610 
2611 		if (tmp_w1->w_reversed == 0)
2612 			continue;
2613 		for (j = 1; j < w_max_used_index; j++) {
2614 			if ((w_rmatrix[i][j] & WITNESS_REVERSAL) == 0 || i > j)
2615 				continue;
2616 
2617 			mtx_lock_spin(&w_mtx);
2618 			if (generation != w_generation) {
2619 				mtx_unlock_spin(&w_mtx);
2620 
2621 				/* The graph has changed, try again. */
2622 				*oldidx = 0;
2623 				sbuf_clear(sb);
2624 				goto restart;
2625 			}
2626 
2627 			w2 = &w_data[j];
2628 			data1 = witness_lock_order_get(w1, w2);
2629 			data2 = witness_lock_order_get(w2, w1);
2630 
2631 			/*
2632 			 * Copy information locally so we can release the
2633 			 * spin lock.
2634 			 */
2635 			*tmp_w2 = *w2;
2636 
2637 			if (data1) {
2638 				stack_zero(&tmp_data1->wlod_stack);
2639 				stack_copy(&data1->wlod_stack,
2640 				    &tmp_data1->wlod_stack);
2641 			}
2642 			if (data2 && data2 != data1) {
2643 				stack_zero(&tmp_data2->wlod_stack);
2644 				stack_copy(&data2->wlod_stack,
2645 				    &tmp_data2->wlod_stack);
2646 			}
2647 			mtx_unlock_spin(&w_mtx);
2648 
2649 			sbuf_printf(sb,
2650 	    "\nLock order reversal between \"%s\"(%s) and \"%s\"(%s)!\n",
2651 			    tmp_w1->w_name, tmp_w1->w_class->lc_name,
2652 			    tmp_w2->w_name, tmp_w2->w_class->lc_name);
2653 			if (data1) {
2654 				sbuf_printf(sb,
2655 			"Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2656 				    tmp_w1->w_name, tmp_w1->w_class->lc_name,
2657 				    tmp_w2->w_name, tmp_w2->w_class->lc_name);
2658 				stack_sbuf_print(sb, &tmp_data1->wlod_stack);
2659 				sbuf_printf(sb, "\n");
2660 			}
2661 			if (data2 && data2 != data1) {
2662 				sbuf_printf(sb,
2663 			"Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2664 				    tmp_w2->w_name, tmp_w2->w_class->lc_name,
2665 				    tmp_w1->w_name, tmp_w1->w_class->lc_name);
2666 				stack_sbuf_print(sb, &tmp_data2->wlod_stack);
2667 				sbuf_printf(sb, "\n");
2668 			}
2669 		}
2670 	}
2671 	mtx_lock_spin(&w_mtx);
2672 	if (generation != w_generation) {
2673 		mtx_unlock_spin(&w_mtx);
2674 
2675 		/*
2676 		 * The graph changed while we were printing stack data,
2677 		 * try again.
2678 		 */
2679 		*oldidx = 0;
2680 		sbuf_clear(sb);
2681 		goto restart;
2682 	}
2683 	mtx_unlock_spin(&w_mtx);
2684 
2685 	/* Free temporary storage space. */
2686 	free(tmp_data1, M_TEMP);
2687 	free(tmp_data2, M_TEMP);
2688 	free(tmp_w1, M_TEMP);
2689 	free(tmp_w2, M_TEMP);
2690 }
2691 
2692 static int
2693 sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)
2694 {
2695 	struct sbuf *sb;
2696 	int error;
2697 
2698 	if (witness_watch < 1) {
2699 		error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2700 		return (error);
2701 	}
2702 	if (witness_cold) {
2703 		error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2704 		return (error);
2705 	}
2706 	error = 0;
2707 	sb = sbuf_new(NULL, NULL, badstack_sbuf_size, SBUF_AUTOEXTEND);
2708 	if (sb == NULL)
2709 		return (ENOMEM);
2710 
2711 	sbuf_print_witness_badstacks(sb, &req->oldidx);
2712 
2713 	sbuf_finish(sb);
2714 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
2715 	sbuf_delete(sb);
2716 
2717 	return (error);
2718 }
2719 
2720 #ifdef DDB
2721 static int
2722 sbuf_db_printf_drain(void *arg __unused, const char *data, int len)
2723 {
2724 
2725 	return (db_printf("%.*s", len, data));
2726 }
2727 
2728 DB_SHOW_COMMAND(badstacks, db_witness_badstacks)
2729 {
2730 	struct sbuf sb;
2731 	char buffer[128];
2732 	size_t dummy;
2733 
2734 	sbuf_new(&sb, buffer, sizeof(buffer), SBUF_FIXEDLEN);
2735 	sbuf_set_drain(&sb, sbuf_db_printf_drain, NULL);
2736 	sbuf_print_witness_badstacks(&sb, &dummy);
2737 	sbuf_finish(&sb);
2738 }
2739 #endif
2740 
2741 static int
2742 sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS)
2743 {
2744 	static const struct {
2745 		enum witness_channel channel;
2746 		const char *name;
2747 	} channels[] = {
2748 		{ WITNESS_CONSOLE, "console" },
2749 		{ WITNESS_LOG, "log" },
2750 		{ WITNESS_NONE, "none" },
2751 	};
2752 	char buf[16];
2753 	u_int i;
2754 	int error;
2755 
2756 	buf[0] = '\0';
2757 	for (i = 0; i < nitems(channels); i++)
2758 		if (witness_channel == channels[i].channel) {
2759 			snprintf(buf, sizeof(buf), "%s", channels[i].name);
2760 			break;
2761 		}
2762 
2763 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2764 	if (error != 0 || req->newptr == NULL)
2765 		return (error);
2766 
2767 	error = EINVAL;
2768 	for (i = 0; i < nitems(channels); i++)
2769 		if (strcmp(channels[i].name, buf) == 0) {
2770 			witness_channel = channels[i].channel;
2771 			error = 0;
2772 			break;
2773 		}
2774 	return (error);
2775 }
2776 
2777 static int
2778 sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
2779 {
2780 	struct witness *w;
2781 	struct sbuf *sb;
2782 	int error;
2783 
2784 #ifdef __i386__
2785 	error = SYSCTL_OUT(req, w_notallowed, sizeof(w_notallowed));
2786 	return (error);
2787 #endif
2788 
2789 	if (witness_watch < 1) {
2790 		error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2791 		return (error);
2792 	}
2793 	if (witness_cold) {
2794 		error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2795 		return (error);
2796 	}
2797 	error = 0;
2798 
2799 	error = sysctl_wire_old_buffer(req, 0);
2800 	if (error != 0)
2801 		return (error);
2802 	sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
2803 	if (sb == NULL)
2804 		return (ENOMEM);
2805 	sbuf_printf(sb, "\n");
2806 
2807 	mtx_lock_spin(&w_mtx);
2808 	STAILQ_FOREACH(w, &w_all, w_list)
2809 		w->w_displayed = 0;
2810 	STAILQ_FOREACH(w, &w_all, w_list)
2811 		witness_add_fullgraph(sb, w);
2812 	mtx_unlock_spin(&w_mtx);
2813 
2814 	/*
2815 	 * Close the sbuf and return to userland.
2816 	 */
2817 	error = sbuf_finish(sb);
2818 	sbuf_delete(sb);
2819 
2820 	return (error);
2821 }
2822 
2823 static int
2824 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
2825 {
2826 	int error, value;
2827 
2828 	value = witness_watch;
2829 	error = sysctl_handle_int(oidp, &value, 0, req);
2830 	if (error != 0 || req->newptr == NULL)
2831 		return (error);
2832 	if (value > 1 || value < -1 ||
2833 	    (witness_watch == -1 && value != witness_watch))
2834 		return (EINVAL);
2835 	witness_watch = value;
2836 	return (0);
2837 }
2838 
2839 static void
2840 witness_add_fullgraph(struct sbuf *sb, struct witness *w)
2841 {
2842 	int i;
2843 
2844 	if (w->w_displayed != 0 || (w->w_file == NULL && w->w_line == 0))
2845 		return;
2846 	w->w_displayed = 1;
2847 
2848 	WITNESS_INDEX_ASSERT(w->w_index);
2849 	for (i = 1; i <= w_max_used_index; i++) {
2850 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT) {
2851 			sbuf_printf(sb, "\"%s\",\"%s\"\n", w->w_name,
2852 			    w_data[i].w_name);
2853 			witness_add_fullgraph(sb, &w_data[i]);
2854 		}
2855 	}
2856 }
2857 
2858 /*
2859  * A simple hash function. Takes a key pointer and a key size. If size == 0,
2860  * interprets the key as a string and reads until the null
2861  * terminator. Otherwise, reads the first size bytes. Returns an unsigned 32-bit
2862  * hash value computed from the key.
2863  */
2864 static uint32_t
2865 witness_hash_djb2(const uint8_t *key, uint32_t size)
2866 {
2867 	unsigned int hash = 5381;
2868 	int i;
2869 
2870 	/* hash = hash * 33 + key[i] */
2871 	if (size)
2872 		for (i = 0; i < size; i++)
2873 			hash = ((hash << 5) + hash) + (unsigned int)key[i];
2874 	else
2875 		for (i = 0; key[i] != 0; i++)
2876 			hash = ((hash << 5) + hash) + (unsigned int)key[i];
2877 
2878 	return (hash);
2879 }
2880 
2881 
2882 /*
2883  * Initializes the two witness hash tables. Called exactly once from
2884  * witness_initialize().
2885  */
2886 static void
2887 witness_init_hash_tables(void)
2888 {
2889 	int i;
2890 
2891 	MPASS(witness_cold);
2892 
2893 	/* Initialize the hash tables. */
2894 	for (i = 0; i < WITNESS_HASH_SIZE; i++)
2895 		w_hash.wh_array[i] = NULL;
2896 
2897 	w_hash.wh_size = WITNESS_HASH_SIZE;
2898 	w_hash.wh_count = 0;
2899 
2900 	/* Initialize the lock order data hash. */
2901 	w_lofree = NULL;
2902 	for (i = 0; i < WITNESS_LO_DATA_COUNT; i++) {
2903 		memset(&w_lodata[i], 0, sizeof(w_lodata[i]));
2904 		w_lodata[i].wlod_next = w_lofree;
2905 		w_lofree = &w_lodata[i];
2906 	}
2907 	w_lohash.wloh_size = WITNESS_LO_HASH_SIZE;
2908 	w_lohash.wloh_count = 0;
2909 	for (i = 0; i < WITNESS_LO_HASH_SIZE; i++)
2910 		w_lohash.wloh_array[i] = NULL;
2911 }
2912 
2913 static struct witness *
2914 witness_hash_get(const char *key)
2915 {
2916 	struct witness *w;
2917 	uint32_t hash;
2918 
2919 	MPASS(key != NULL);
2920 	if (witness_cold == 0)
2921 		mtx_assert(&w_mtx, MA_OWNED);
2922 	hash = witness_hash_djb2(key, 0) % w_hash.wh_size;
2923 	w = w_hash.wh_array[hash];
2924 	while (w != NULL) {
2925 		if (strcmp(w->w_name, key) == 0)
2926 			goto out;
2927 		w = w->w_hash_next;
2928 	}
2929 
2930 out:
2931 	return (w);
2932 }
2933 
2934 static void
2935 witness_hash_put(struct witness *w)
2936 {
2937 	uint32_t hash;
2938 
2939 	MPASS(w != NULL);
2940 	MPASS(w->w_name != NULL);
2941 	if (witness_cold == 0)
2942 		mtx_assert(&w_mtx, MA_OWNED);
2943 	KASSERT(witness_hash_get(w->w_name) == NULL,
2944 	    ("%s: trying to add a hash entry that already exists!", __func__));
2945 	KASSERT(w->w_hash_next == NULL,
2946 	    ("%s: w->w_hash_next != NULL", __func__));
2947 
2948 	hash = witness_hash_djb2(w->w_name, 0) % w_hash.wh_size;
2949 	w->w_hash_next = w_hash.wh_array[hash];
2950 	w_hash.wh_array[hash] = w;
2951 	w_hash.wh_count++;
2952 }
2953 
2954 
2955 static struct witness_lock_order_data *
2956 witness_lock_order_get(struct witness *parent, struct witness *child)
2957 {
2958 	struct witness_lock_order_data *data = NULL;
2959 	struct witness_lock_order_key key;
2960 	unsigned int hash;
2961 
2962 	MPASS(parent != NULL && child != NULL);
2963 	key.from = parent->w_index;
2964 	key.to = child->w_index;
2965 	WITNESS_INDEX_ASSERT(key.from);
2966 	WITNESS_INDEX_ASSERT(key.to);
2967 	if ((w_rmatrix[parent->w_index][child->w_index]
2968 	    & WITNESS_LOCK_ORDER_KNOWN) == 0)
2969 		goto out;
2970 
2971 	hash = witness_hash_djb2((const char*)&key,
2972 	    sizeof(key)) % w_lohash.wloh_size;
2973 	data = w_lohash.wloh_array[hash];
2974 	while (data != NULL) {
2975 		if (witness_lock_order_key_equal(&data->wlod_key, &key))
2976 			break;
2977 		data = data->wlod_next;
2978 	}
2979 
2980 out:
2981 	return (data);
2982 }
2983 
2984 /*
2985  * Verify that parent and child have a known relationship, are not the same,
2986  * and child is actually a child of parent.  This is done without w_mtx
2987  * to avoid contention in the common case.
2988  */
2989 static int
2990 witness_lock_order_check(struct witness *parent, struct witness *child)
2991 {
2992 
2993 	if (parent != child &&
2994 	    w_rmatrix[parent->w_index][child->w_index]
2995 	    & WITNESS_LOCK_ORDER_KNOWN &&
2996 	    isitmychild(parent, child))
2997 		return (1);
2998 
2999 	return (0);
3000 }
3001 
3002 static int
3003 witness_lock_order_add(struct witness *parent, struct witness *child)
3004 {
3005 	struct witness_lock_order_data *data = NULL;
3006 	struct witness_lock_order_key key;
3007 	unsigned int hash;
3008 
3009 	MPASS(parent != NULL && child != NULL);
3010 	key.from = parent->w_index;
3011 	key.to = child->w_index;
3012 	WITNESS_INDEX_ASSERT(key.from);
3013 	WITNESS_INDEX_ASSERT(key.to);
3014 	if (w_rmatrix[parent->w_index][child->w_index]
3015 	    & WITNESS_LOCK_ORDER_KNOWN)
3016 		return (1);
3017 
3018 	hash = witness_hash_djb2((const char*)&key,
3019 	    sizeof(key)) % w_lohash.wloh_size;
3020 	w_rmatrix[parent->w_index][child->w_index] |= WITNESS_LOCK_ORDER_KNOWN;
3021 	data = w_lofree;
3022 	if (data == NULL)
3023 		return (0);
3024 	w_lofree = data->wlod_next;
3025 	data->wlod_next = w_lohash.wloh_array[hash];
3026 	data->wlod_key = key;
3027 	w_lohash.wloh_array[hash] = data;
3028 	w_lohash.wloh_count++;
3029 	stack_zero(&data->wlod_stack);
3030 	stack_save(&data->wlod_stack);
3031 	return (1);
3032 }
3033 
3034 /* Call this whenever the structure of the witness graph changes. */
3035 static void
3036 witness_increment_graph_generation(void)
3037 {
3038 
3039 	if (witness_cold == 0)
3040 		mtx_assert(&w_mtx, MA_OWNED);
3041 	w_generation++;
3042 }
3043 
3044 static int
3045 witness_output_drain(void *arg __unused, const char *data, int len)
3046 {
3047 
3048 	witness_output("%.*s", len, data);
3049 	return (len);
3050 }
3051 
3052 static void
3053 witness_debugger(int cond, const char *msg)
3054 {
3055 	char buf[32];
3056 	struct sbuf sb;
3057 	struct stack st;
3058 
3059 	if (!cond)
3060 		return;
3061 
3062 	if (witness_trace) {
3063 		sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
3064 		sbuf_set_drain(&sb, witness_output_drain, NULL);
3065 
3066 		stack_zero(&st);
3067 		stack_save(&st);
3068 		witness_output("stack backtrace:\n");
3069 		stack_sbuf_print_ddb(&sb, &st);
3070 
3071 		sbuf_finish(&sb);
3072 	}
3073 
3074 #ifdef KDB
3075 	if (witness_kdb)
3076 		kdb_enter(KDB_WHY_WITNESS, msg);
3077 #endif
3078 }
3079