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