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