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