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