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