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