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