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