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