xref: /freebsd/sys/kern/subr_witness.c (revision 2407abc9fb3b45d6d734d564706c76aa793b102a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2008 Isilon Systems, Inc.
5  * Copyright (c) 2008 Ilya Maykov <ivmaykov@gmail.com>
6  * Copyright (c) 1998 Berkeley Software Design, Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Berkeley Software Design Inc's name may not be used to endorse or
18  *    promote products derived from this software without specific prior
19  *    written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
34  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
35  */
36 
37 /*
38  * Implementation of the `witness' lock verifier.  Originally implemented for
39  * mutexes in BSD/OS.  Extended to handle generic lock objects and lock
40  * classes in FreeBSD.
41  */
42 
43 /*
44  *	Main Entry: witness
45  *	Pronunciation: 'wit-n&s
46  *	Function: noun
47  *	Etymology: Middle English witnesse, from Old English witnes knowledge,
48  *	    testimony, witness, from 2wit
49  *	Date: before 12th century
50  *	1 : attestation of a fact or event : TESTIMONY
51  *	2 : one that gives evidence; specifically : one who testifies in
52  *	    a cause or before a judicial tribunal
53  *	3 : one asked to be present at a transaction so as to be able to
54  *	    testify to its having taken place
55  *	4 : one who has personal knowledge of something
56  *	5 a : something serving as evidence or proof : SIGN
57  *	  b : public affirmation by word or example of usually
58  *	      religious faith or conviction <the heroic witness to divine
59  *	      life -- Pilot>
60  *	6 capitalized : a member of the Jehovah's Witnesses
61  */
62 
63 /*
64  * Special rules concerning Giant and lock orders:
65  *
66  * 1) Giant must be acquired before any other mutexes.  Stated another way,
67  *    no other mutex may be held when Giant is acquired.
68  *
69  * 2) Giant must be released when blocking on a sleepable lock.
70  *
71  * This rule is less obvious, but is a result of Giant providing the same
72  * semantics as spl().  Basically, when a thread sleeps, it must release
73  * Giant.  When a thread blocks on a sleepable lock, it sleeps.  Hence rule
74  * 2).
75  *
76  * 3) Giant may be acquired before or after sleepable locks.
77  *
78  * This rule is also not quite as obvious.  Giant may be acquired after
79  * a sleepable lock because it is a non-sleepable lock and non-sleepable
80  * locks may always be acquired while holding a sleepable lock.  The second
81  * case, Giant before a sleepable lock, follows from rule 2) above.  Suppose
82  * you have two threads T1 and T2 and a sleepable lock X.  Suppose that T1
83  * acquires X and blocks on Giant.  Then suppose that T2 acquires Giant and
84  * blocks on X.  When T2 blocks on X, T2 will release Giant allowing T1 to
85  * execute.  Thus, acquiring Giant both before and after a sleepable lock
86  * will not result in a lock order reversal.
87  */
88 
89 #include <sys/cdefs.h>
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/stdarg.h>
109 #include <sys/sysctl.h>
110 #include <sys/syslog.h>
111 #include <sys/systm.h>
112 
113 #ifdef DDB
114 #include <ddb/ddb.h>
115 #endif
116 
117 #if !defined(DDB) && !defined(STACK)
118 #error "DDB or STACK options are required for WITNESS"
119 #endif
120 
121 /* Note that these traces do not work with KTR_ALQ. */
122 #if 0
123 #define	KTR_WITNESS	KTR_SUBSYS
124 #else
125 #define	KTR_WITNESS	0
126 #endif
127 
128 #define	LI_RECURSEMASK	0x0000ffff	/* Recursion depth of lock instance. */
129 #define	LI_EXCLUSIVE	0x00010000	/* Exclusive lock instance. */
130 #define	LI_NORELEASE	0x00020000	/* Lock not allowed to be released. */
131 #define	LI_SLEEPABLE	0x00040000	/* Lock may be held while sleeping. */
132 
133 #ifndef WITNESS_COUNT
134 #define	WITNESS_COUNT		1536
135 #endif
136 #define	WITNESS_HASH_SIZE	251	/* Prime, gives load factor < 2 */
137 #define	WITNESS_PENDLIST	(512 + (MAXCPU * 4))
138 
139 /* Allocate 256 KB of stack data space */
140 #define	WITNESS_LO_DATA_COUNT	2048
141 
142 /* Prime, gives load factor of ~2 at full load */
143 #define	WITNESS_LO_HASH_SIZE	1021
144 
145 /*
146  * XXX: This is somewhat bogus, as we assume here that at most 2048 threads
147  * will hold LOCK_NCHILDREN locks.  We handle failure ok, and we should
148  * probably be safe for the most part, but it's still a SWAG.
149  */
150 #define	LOCK_NCHILDREN	5
151 #define	LOCK_CHILDCOUNT	2048
152 
153 #define	MAX_W_NAME	64
154 
155 #define	FULLGRAPH_SBUF_SIZE	512
156 
157 /*
158  * These flags go in the witness relationship matrix and describe the
159  * relationship between any two struct witness objects.
160  */
161 #define	WITNESS_UNRELATED	0x00	/* No lock order relation. */
162 #define	WITNESS_PARENT		0x01	/* Parent, aka direct ancestor. */
163 #define	WITNESS_ANCESTOR	0x02	/* Direct or indirect ancestor. */
164 #define	WITNESS_CHILD		0x04	/* Child, aka direct descendant. */
165 #define	WITNESS_DESCENDANT	0x08	/* Direct or indirect descendant. */
166 #define	WITNESS_ANCESTOR_MASK	(WITNESS_PARENT | WITNESS_ANCESTOR)
167 #define	WITNESS_DESCENDANT_MASK	(WITNESS_CHILD | WITNESS_DESCENDANT)
168 #define	WITNESS_RELATED_MASK	(WITNESS_ANCESTOR_MASK | WITNESS_DESCENDANT_MASK)
169 #define	WITNESS_REVERSAL	0x10	/* A lock order reversal has been observed. */
170 #define	WITNESS_RESERVED1	0x20	/* Unused flag, reserved. */
171 #define	WITNESS_ORDER_LISTS	0x40	/* Relationship set in order_lists[]. */
172 #define	WITNESS_LOCK_ORDER_KNOWN 0x80	/* This lock order is known. */
173 
174 /* Descendant to ancestor flags */
175 #define	WITNESS_DTOA(x)	(((x) & WITNESS_RELATED_MASK) >> 2)
176 
177 /* Ancestor to descendant flags */
178 #define	WITNESS_ATOD(x)	(((x) & WITNESS_RELATED_MASK) << 2)
179 
180 #define	WITNESS_INDEX_ASSERT(i)						\
181 	MPASS((i) > 0 && (i) <= w_max_used_index && (i) < witness_count)
182 
183 static MALLOC_DEFINE(M_WITNESS, "Witness", "Witness");
184 
185 /*
186  * Lock instances.  A lock instance is the data associated with a lock while
187  * it is held by witness.  For example, a lock instance will hold the
188  * recursion count of a lock.  Lock instances are held in lists.  Spin locks
189  * are held in a per-cpu list while sleep locks are held in per-thread list.
190  */
191 struct lock_instance {
192 	struct lock_object	*li_lock;
193 	const char		*li_file;
194 	int			li_line;
195 	u_int			li_flags;
196 };
197 
198 /*
199  * A simple list type used to build the list of locks held by a thread
200  * or CPU.  We can't simply embed the list in struct lock_object since a
201  * lock may be held by more than one thread if it is a shared lock.  Locks
202  * are added to the head of the list, so we fill up each list entry from
203  * "the back" logically.  To ease some of the arithmetic, we actually fill
204  * in each list entry the normal way (children[0] then children[1], etc.) but
205  * when we traverse the list we read children[count-1] as the first entry
206  * down to children[0] as the final entry.
207  */
208 struct lock_list_entry {
209 	struct lock_list_entry	*ll_next;
210 	struct lock_instance	ll_children[LOCK_NCHILDREN];
211 	u_int			ll_count;
212 };
213 
214 /*
215  * The main witness structure. One of these per named lock type in the system
216  * (for example, "vnode interlock").
217  */
218 struct witness {
219 	char			w_name[MAX_W_NAME];
220 	uint32_t		w_index;	/* Index in the relationship matrix */
221 	struct lock_class	*w_class;
222 	STAILQ_ENTRY(witness)	w_list;		/* List of all witnesses. */
223 	STAILQ_ENTRY(witness)	w_typelist;	/* Witnesses of a type. */
224 	struct witness		*w_hash_next;	/* Linked list in hash buckets. */
225 	const char		*w_file;	/* File where last acquired */
226 	uint32_t		w_line;		/* Line where last acquired */
227 	uint32_t		w_refcount;
228 	uint16_t		w_num_ancestors;   /* direct/indirect ancestor count */
229 	uint16_t		w_num_descendants; /* direct/indirect descendant count */
230 	int16_t			w_ddb_level;
231 	unsigned		w_displayed:1;
232 	unsigned		w_reversed:1;
233 };
234 
235 STAILQ_HEAD(witness_list, witness);
236 
237 /*
238  * The witness hash table. Keys are witness names (const char *), elements are
239  * witness objects (struct witness *).
240  */
241 struct witness_hash {
242 	struct witness	*wh_array[WITNESS_HASH_SIZE];
243 	uint32_t	wh_size;
244 	uint32_t	wh_count;
245 };
246 
247 /*
248  * Key type for the lock order data hash table.
249  */
250 struct witness_lock_order_key {
251 	uint16_t	from;
252 	uint16_t	to;
253 };
254 
255 struct witness_lock_order_data {
256 	struct stack			wlod_stack;
257 	struct witness_lock_order_key	wlod_key;
258 	struct witness_lock_order_data	*wlod_next;
259 };
260 
261 /*
262  * The witness lock order data hash table. Keys are witness index tuples
263  * (struct witness_lock_order_key), elements are lock order data objects
264  * (struct witness_lock_order_data).
265  */
266 struct witness_lock_order_hash {
267 	struct witness_lock_order_data	**wloh_array;
268 	u_int	wloh_size;
269 	u_int	wloh_count;
270 };
271 
272 struct witness_blessed {
273 	const char	*b_lock1;
274 	const char	*b_lock2;
275 };
276 
277 struct witness_pendhelp {
278 	const char		*wh_type;
279 	struct lock_object	*wh_lock;
280 };
281 
282 struct witness_order_list_entry {
283 	const char		*w_name;
284 	struct lock_class	*w_class;
285 };
286 
287 /*
288  * Returns 0 if one of the locks is a spin lock and the other is not.
289  * Returns 1 otherwise.
290  */
291 static __inline int
witness_lock_type_equal(struct witness * w1,struct witness * w2)292 witness_lock_type_equal(struct witness *w1, struct witness *w2)
293 {
294 	return ((w1->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) ==
295 		(w2->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)));
296 }
297 
298 static __inline int
witness_lock_order_key_equal(const struct witness_lock_order_key * a,const struct witness_lock_order_key * b)299 witness_lock_order_key_equal(const struct witness_lock_order_key *a,
300     const struct witness_lock_order_key *b)
301 {
302 	return (a->from == b->from && a->to == b->to);
303 }
304 
305 static int	_isitmyx(struct witness *w1, struct witness *w2, int rmask,
306 		    const char *fname);
307 static void	adopt(struct witness *parent, struct witness *child);
308 static int	blessed(struct witness *, struct witness *);
309 static void	depart(struct witness *w);
310 static struct witness	*enroll(const char *description,
311 			    struct lock_class *lock_class);
312 static struct lock_instance	*find_instance(struct lock_list_entry *list,
313 				    const struct lock_object *lock);
314 static int	isitmychild(struct witness *parent, struct witness *child);
315 static int	isitmydescendant(struct witness *parent, struct witness *child);
316 static void	itismychild(struct witness *parent, struct witness *child);
317 static int	sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS);
318 static int	sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
319 static int	sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS);
320 static int	sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS);
321 static void	witness_add_fullgraph(struct sbuf *sb, struct witness *parent);
322 #ifdef DDB
323 static void	witness_ddb_compute_levels(void);
324 static void	witness_ddb_display(int(*)(const char *fmt, ...));
325 static void	witness_ddb_display_descendants(int(*)(const char *fmt, ...),
326 		    struct witness *, int indent);
327 static void	witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
328 		    struct witness_list *list);
329 static void	witness_ddb_level_descendants(struct witness *parent, int l);
330 static void	witness_ddb_list(struct thread *td);
331 #endif
332 static void	witness_enter_debugger(const char *msg);
333 static void	witness_debugger(int cond, const char *msg);
334 static void	witness_free(struct witness *m);
335 static struct witness	*witness_get(void);
336 static uint32_t	witness_hash_djb2(const uint8_t *key, uint32_t size);
337 static struct witness	*witness_hash_get(const char *key);
338 static void	witness_hash_put(struct witness *w);
339 static void	witness_init_hash_tables(void);
340 static void	witness_increment_graph_generation(void);
341 static void	witness_lock_list_free(struct lock_list_entry *lle);
342 static struct lock_list_entry	*witness_lock_list_get(void);
343 static int	witness_lock_order_add(struct witness *parent,
344 		    struct witness *child);
345 static int	witness_lock_order_check(struct witness *parent,
346 		    struct witness *child);
347 static struct witness_lock_order_data	*witness_lock_order_get(
348 					    struct witness *parent,
349 					    struct witness *child);
350 static void	witness_list_lock(struct lock_instance *instance,
351 		    int (*prnt)(const char *fmt, ...));
352 static int	witness_output(const char *fmt, ...) __printflike(1, 2);
353 static int	witness_output_drain(void *arg __unused, const char *data,
354 		    int len);
355 static int	witness_voutput(const char *fmt, va_list ap) __printflike(1, 0);
356 static void	witness_setflag(struct lock_object *lock, int flag, int set);
357 
358 FEATURE(witness, "kernel has witness(9) support");
359 
360 static SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
361     "Witness Locking");
362 
363 /*
364  * If set to 0, lock order checking is disabled.  If set to -1,
365  * witness is completely disabled.  Otherwise witness performs full
366  * lock order checking for all locks.  At runtime, lock order checking
367  * may be toggled.  However, witness cannot be reenabled once it is
368  * completely disabled.
369  */
370 static int witness_watch = 1;
371 SYSCTL_PROC(_debug_witness, OID_AUTO, watch,
372     CTLFLAG_RWTUN | CTLTYPE_INT | CTLFLAG_MPSAFE, NULL, 0,
373     sysctl_debug_witness_watch, "I",
374     "witness is watching lock operations");
375 
376 #ifdef KDB
377 /*
378  * When KDB is enabled and witness_kdb is 1, it will cause the system
379  * to drop into kdebug() when:
380  *	- a lock hierarchy violation occurs
381  *	- locks are held when going to sleep.
382  */
383 #ifdef WITNESS_KDB
384 int	witness_kdb = 1;
385 #else
386 int	witness_kdb = 0;
387 #endif
388 SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RWTUN, &witness_kdb, 0, "");
389 #endif /* KDB */
390 
391 #if defined(DDB) || defined(KDB)
392 /*
393  * When DDB or KDB is enabled and witness_trace is > 0, it will cause the system
394  * to print a stack trace when:
395  *	- a lock hierarchy violation occurs
396  *	- locks are held when going to sleep.
397  *
398  * Additionally, if witness_trace is 2, it will cause the system to search
399  * for all locks which established the known lock ordering and print
400  * stack traces of where the lock ordering was first established.
401  */
402 int	witness_trace = 2;
403 SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RWTUN, &witness_trace, 0, "");
404 #endif /* DDB || KDB */
405 
406 #ifdef WITNESS_SKIPSPIN
407 static bool witness_skipspin = true;
408 #else
409 static bool witness_skipspin = false;
410 #endif
411 SYSCTL_BOOL(_debug_witness, OID_AUTO, skipspin,
412     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &witness_skipspin, 0,
413     "Skip all witness checks on spin locks");
414 TUNABLE_BOOL("debug.witness.skipspin", &witness_skipspin);
415 
416 int badstack_sbuf_size;
417 
418 static u_long witness_count = WITNESS_COUNT;
419 SYSCTL_ULONG(_debug_witness, OID_AUTO, witness_count,
420     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &witness_count, 0,
421     "Maximum count of lock type entries");
422 
423 static u_long witness_lo_data_count = WITNESS_LO_DATA_COUNT;
424 SYSCTL_ULONG(_debug_witness, OID_AUTO, lock_order_data_count,
425     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &witness_lo_data_count, 0,
426     "Maximum count of lock order data (stacks) to track");
427 
428 static u_long witness_lo_hash_size = WITNESS_LO_HASH_SIZE;
429 SYSCTL_ULONG(_debug_witness, OID_AUTO, lock_order_hash_size,
430     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &witness_lo_hash_size, 0,
431     "Hash table size for lock order data");
432 
433 /*
434  * Output channel for witness messages.  By default we print to the console.
435  */
436 enum witness_channel {
437 	WITNESS_CONSOLE,
438 	WITNESS_LOG,
439 	WITNESS_NONE,
440 };
441 
442 static enum witness_channel witness_channel = WITNESS_CONSOLE;
443 SYSCTL_PROC(_debug_witness, OID_AUTO, output_channel,
444     CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, NULL, 0,
445     sysctl_debug_witness_channel, "A",
446     "Output channel for warnings");
447 
448 /*
449  * Call this to print out the relations between locks.
450  */
451 SYSCTL_PROC(_debug_witness, OID_AUTO, fullgraph,
452     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
453     sysctl_debug_witness_fullgraph, "A",
454     "Show locks relation graphs");
455 
456 /*
457  * Call this to print out the witness faulty stacks.
458  */
459 SYSCTL_PROC(_debug_witness, OID_AUTO, badstacks,
460     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
461     sysctl_debug_witness_badstacks, "A",
462     "Show bad witness stacks");
463 
464 static struct mtx w_mtx;
465 
466 /* w_list */
467 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
468 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
469 
470 /* w_typelist */
471 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
472 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
473 
474 /* lock list */
475 static struct lock_list_entry *w_lock_list_free = NULL;
476 static struct witness_pendhelp pending_locks[WITNESS_PENDLIST];
477 static u_int pending_cnt;
478 
479 static int w_free_cnt, w_spin_cnt, w_sleep_cnt;
480 SYSCTL_INT(_debug_witness, OID_AUTO, free_cnt, CTLFLAG_RD, &w_free_cnt, 0, "");
481 SYSCTL_INT(_debug_witness, OID_AUTO, spin_cnt, CTLFLAG_RD, &w_spin_cnt, 0, "");
482 SYSCTL_INT(_debug_witness, OID_AUTO, sleep_cnt, CTLFLAG_RD, &w_sleep_cnt, 0,
483     "");
484 
485 static struct witness *w_data;
486 static uint8_t **w_rmatrix;
487 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
488 static struct witness_hash w_hash;	/* The witness hash table. */
489 static u_long w_sz;	/* Witness startup memory allocation size */
490 
491 /* The lock order data hash */
492 static struct witness_lock_order_data *w_lodata;
493 static struct witness_lock_order_data *w_lofree = NULL;
494 static struct witness_lock_order_hash w_lohash;
495 static int w_max_used_index = 0;
496 static unsigned int w_generation = 0;
497 static const char w_notrunning[] = "Witness not running\n";
498 static const char w_stillcold[] = "Witness is still cold\n";
499 #ifdef __i386__
500 static const char w_notallowed[] = "The sysctl is disabled on the arch\n";
501 #endif
502 
503 static struct witness_order_list_entry order_lists[] = {
504 	/*
505 	 * sx locks
506 	 */
507 	{ "proctree", &lock_class_sx },
508 	{ "allproc", &lock_class_sx },
509 	{ "allprison", &lock_class_sx },
510 	{ NULL, NULL },
511 	/*
512 	 * Various mutexes
513 	 */
514 	{ "Giant", &lock_class_mtx_sleep },
515 	{ "pipe mutex", &lock_class_mtx_sleep },
516 	{ "sigio lock", &lock_class_mtx_sleep },
517 	{ "process group", &lock_class_mtx_sleep },
518 #ifdef	HWPMC_HOOKS
519 	{ "pmc-sleep", &lock_class_mtx_sleep },
520 #endif
521 	{ "process lock", &lock_class_mtx_sleep },
522 	{ "session", &lock_class_mtx_sleep },
523 	{ "uidinfo hash", &lock_class_rw },
524 	{ "time lock", &lock_class_mtx_sleep },
525 	{ NULL, NULL },
526 	/*
527 	 * umtx
528 	 */
529 	{ "umtx lock", &lock_class_mtx_sleep },
530 	{ NULL, NULL },
531 	/*
532 	 * Sockets
533 	 */
534 	{ "accept", &lock_class_mtx_sleep },
535 	{ "so_snd", &lock_class_mtx_sleep },
536 	{ "so_rcv", &lock_class_mtx_sleep },
537 	{ "sellck", &lock_class_mtx_sleep },
538 	{ NULL, NULL },
539 	/*
540 	 * Routing
541 	 */
542 	{ "so_rcv", &lock_class_mtx_sleep },
543 	{ "radix node head", &lock_class_rm },
544 	{ "ifaddr", &lock_class_mtx_sleep },
545 	{ NULL, NULL },
546 	/*
547 	 * IPv4 multicast:
548 	 * protocol locks before interface locks, after UDP locks.
549 	 */
550 	{ "in_multi_sx", &lock_class_sx },
551 	{ "udpinp", &lock_class_rw },
552 	{ "in_multi_list_mtx", &lock_class_mtx_sleep },
553 	{ "igmp_mtx", &lock_class_mtx_sleep },
554 	{ "if_addr_lock", &lock_class_mtx_sleep },
555 	{ NULL, NULL },
556 	/*
557 	 * IPv6 multicast:
558 	 * protocol locks before interface locks, after UDP locks.
559 	 */
560 	{ "in6_multi_sx", &lock_class_sx },
561 	{ "udpinp", &lock_class_rw },
562 	{ "in6_multi_list_mtx", &lock_class_mtx_sleep },
563 	{ "mld_mtx", &lock_class_mtx_sleep },
564 	{ "if_addr_lock", &lock_class_mtx_sleep },
565 	{ NULL, NULL },
566 	/*
567 	 * UNIX Domain Sockets
568 	 */
569 	{ "unp_link_rwlock", &lock_class_rw },
570 	{ "unp_list_lock", &lock_class_mtx_sleep },
571 	{ "unp", &lock_class_mtx_sleep },
572 	{ "so_snd", &lock_class_mtx_sleep },
573 	{ NULL, NULL },
574 	/*
575 	 * UDP/IP
576 	 */
577 	{ "udpinp", &lock_class_rw },
578 	{ "udp", &lock_class_mtx_sleep },
579 	{ "so_snd", &lock_class_mtx_sleep },
580 	{ NULL, NULL },
581 	/*
582 	 * TCP/IP
583 	 */
584 	{ "tcpinp", &lock_class_rw },
585 	{ "tcp", &lock_class_mtx_sleep },
586 	{ "so_snd", &lock_class_mtx_sleep },
587 	{ NULL, NULL },
588 	/*
589 	 * IPv6 Addr
590 	 */
591 	{ "tcphash", &lock_class_mtx_sleep },
592 	{ "in6_ifaddr_lock", &lock_class_rm },
593 	{ NULL, NULL },
594 	/*
595 	 * BPF
596 	 */
597 	{ "bpf global lock", &lock_class_sx },
598 	{ "bpf cdev lock", &lock_class_mtx_sleep },
599 	{ NULL, NULL },
600 	/*
601 	 * NFS server
602 	 */
603 	{ "nfsd_mtx", &lock_class_mtx_sleep },
604 	{ "so_snd", &lock_class_mtx_sleep },
605 	{ NULL, NULL },
606 
607 	/*
608 	 * IEEE 802.11
609 	 */
610 	{ "802.11 com lock", &lock_class_mtx_sleep},
611 	{ NULL, NULL },
612 	/*
613 	 * Network drivers
614 	 */
615 	{ "network driver", &lock_class_mtx_sleep},
616 	{ NULL, NULL },
617 
618 	/*
619 	 * Netgraph
620 	 */
621 	{ "ng_node", &lock_class_mtx_sleep },
622 	{ "ng_worklist", &lock_class_mtx_sleep },
623 	{ NULL, NULL },
624 	/*
625 	 * CDEV
626 	 */
627 	{ "vm map (system)", &lock_class_mtx_sleep },
628 	{ "vnode interlock", &lock_class_mtx_sleep },
629 	{ "cdev", &lock_class_mtx_sleep },
630 	{ "devthrd", &lock_class_mtx_sleep },
631 	{ NULL, NULL },
632 	/*
633 	 * VM
634 	 */
635 	{ "vm map (user)", &lock_class_sx },
636 	{ "vm object", &lock_class_rw },
637 	{ "vm page", &lock_class_mtx_sleep },
638 	{ "pmap pv global", &lock_class_rw },
639 	{ "pmap", &lock_class_mtx_sleep },
640 	{ "pmap pv list", &lock_class_rw },
641 	{ "vm page free queue", &lock_class_mtx_sleep },
642 	{ "vm pagequeue", &lock_class_mtx_sleep },
643 	{ NULL, NULL },
644 	/*
645 	 * kqueue/VFS interaction
646 	 */
647 	{ "kqueue", &lock_class_mtx_sleep },
648 	{ "struct mount mtx", &lock_class_mtx_sleep },
649 	{ "vnode interlock", &lock_class_mtx_sleep },
650 	{ NULL, NULL },
651 	/*
652 	 * VFS namecache
653 	 */
654 	{ "ncvn", &lock_class_mtx_sleep },
655 	{ "ncbuc", &lock_class_mtx_sleep },
656 	{ "vnode interlock", &lock_class_mtx_sleep },
657 	{ "ncneg", &lock_class_mtx_sleep },
658 	{ NULL, NULL },
659 	/*
660 	 * ZFS locking
661 	 */
662 	{ "dn->dn_mtx", &lock_class_sx },
663 	{ "dr->dt.di.dr_mtx", &lock_class_sx },
664 	{ "db->db_mtx", &lock_class_sx },
665 	{ NULL, NULL },
666 	/*
667 	 * TCP log locks
668 	 */
669 	{ "TCP ID tree", &lock_class_rw },
670 	{ "tcp log id bucket", &lock_class_mtx_sleep },
671 	{ "tcpinp", &lock_class_rw },
672 	{ "TCP log expireq", &lock_class_mtx_sleep },
673 	{ NULL, NULL },
674 	/*
675 	 * spin locks
676 	 */
677 #ifdef SMP
678 	{ "ap boot", &lock_class_mtx_spin },
679 #endif
680 	{ "rm.mutex_mtx", &lock_class_mtx_spin },
681 #ifdef __i386__
682 	{ "cy", &lock_class_mtx_spin },
683 #endif
684 	{ "scc_hwmtx", &lock_class_mtx_spin },
685 	{ "uart_hwmtx", &lock_class_mtx_spin },
686 	{ "fast_taskqueue", &lock_class_mtx_spin },
687 	{ "intr table", &lock_class_mtx_spin },
688 	{ "process slock", &lock_class_mtx_spin },
689 	{ "syscons video lock", &lock_class_mtx_spin },
690 	{ "sleepq chain", &lock_class_mtx_spin },
691 	{ "rm_spinlock", &lock_class_mtx_spin },
692 	{ "turnstile chain", &lock_class_mtx_spin },
693 	{ "turnstile lock", &lock_class_mtx_spin },
694 	{ "sched lock", &lock_class_mtx_spin },
695 	{ "td_contested", &lock_class_mtx_spin },
696 	{ "callout", &lock_class_mtx_spin },
697 	{ "entropy harvest mutex", &lock_class_mtx_spin },
698 #ifdef SMP
699 	{ "smp rendezvous", &lock_class_mtx_spin },
700 #endif
701 #ifdef __powerpc__
702 	{ "tlb0", &lock_class_mtx_spin },
703 #endif
704 	{ NULL, NULL },
705 	{ "sched lock", &lock_class_mtx_spin },
706 #ifdef	HWPMC_HOOKS
707 	{ "pmc-per-proc", &lock_class_mtx_spin },
708 #endif
709 	{ NULL, NULL },
710 	/*
711 	 * leaf locks
712 	 */
713 	{ "intrcnt", &lock_class_mtx_spin },
714 	{ "icu", &lock_class_mtx_spin },
715 #ifdef __i386__
716 	{ "allpmaps", &lock_class_mtx_spin },
717 	{ "descriptor tables", &lock_class_mtx_spin },
718 #endif
719 	{ "clk", &lock_class_mtx_spin },
720 	{ "cpuset", &lock_class_mtx_spin },
721 	{ "mprof lock", &lock_class_mtx_spin },
722 	{ "zombie lock", &lock_class_mtx_spin },
723 	{ "ALD Queue", &lock_class_mtx_spin },
724 #if defined(__i386__) || defined(__amd64__)
725 	{ "pcicfg", &lock_class_mtx_spin },
726 	{ "NDIS thread lock", &lock_class_mtx_spin },
727 #endif
728 	{ "tw_osl_io_lock", &lock_class_mtx_spin },
729 	{ "tw_osl_q_lock", &lock_class_mtx_spin },
730 	{ "tw_cl_io_lock", &lock_class_mtx_spin },
731 	{ "tw_cl_intr_lock", &lock_class_mtx_spin },
732 	{ "tw_cl_gen_lock", &lock_class_mtx_spin },
733 #ifdef	HWPMC_HOOKS
734 	{ "pmc-leaf", &lock_class_mtx_spin },
735 #endif
736 	{ "blocked lock", &lock_class_mtx_spin },
737 	{ NULL, NULL },
738 	{ NULL, NULL }
739 };
740 
741 /*
742  * Pairs of locks which have been blessed.  Witness does not complain about
743  * order problems with blessed lock pairs.  Please do not add an entry to the
744  * table without an explanatory comment.
745  */
746 static struct witness_blessed blessed_list[] = {
747 	/*
748 	 * See the comment in ufs_dirhash.c.  Basically, a vnode lock serializes
749 	 * both lock orders, so a deadlock cannot happen as a result of this
750 	 * LOR.
751 	 */
752 	{ "dirhash",	"bufwait" },
753 
754 	/*
755 	 * A UFS vnode may be locked in vget() while a buffer belonging to the
756 	 * parent directory vnode is locked.
757 	 */
758 	{ "ufs",	"bufwait" },
759 
760 	/*
761 	 * The tarfs decompression stream vnode may be locked while a
762 	 * buffer belonging to a tarfs data vnode is locked.
763 	 */
764 	{ "tarfs",	"bufwait" },
765 };
766 
767 /*
768  * This global is set to 0 once it becomes safe to use the witness code.
769  */
770 static int witness_cold = 1;
771 
772 /*
773  * This global is set to 1 once the static lock orders have been enrolled
774  * so that a warning can be issued for any spin locks enrolled later.
775  */
776 static int witness_spin_warn = 0;
777 
778 /* Trim useless garbage from filenames. */
779 static const char *
fixup_filename(const char * file)780 fixup_filename(const char *file)
781 {
782 	if (file == NULL)
783 		return (NULL);
784 	while (strncmp(file, "../", 3) == 0)
785 		file += 3;
786 	return (file);
787 }
788 
789 /*
790  * Calculate the size of early witness structures.
791  */
792 static u_long
witness_startup_calc(void)793 witness_startup_calc(void)
794 {
795 	u_long sz;
796 
797 	sz = sizeof(struct witness) * witness_count;
798 	sz += sizeof(*w_rmatrix) * (witness_count + 1);
799 	sz += sizeof(*w_rmatrix[0]) * (witness_count + 1) *
800 	    (witness_count + 1);
801 	sz += sizeof(void *);
802 	sz += sizeof(w_lodata[0]) * witness_lo_data_count;
803 	sz += sizeof(w_lohash.wloh_array[0]) * witness_lo_hash_size;
804 	sz = round_page(sz);
805 
806 	return (sz);
807 }
808 
809 u_long
witness_startup_count(u_long avail)810 witness_startup_count(u_long avail)
811 {
812 
813 	/*
814 	 * Tune witness.  We make an effort to protect against misconfiguration
815 	 * consuming more memory than available, but we do not robustly protect
816 	 * against integer overflow for all possible user-supplied values.
817 	 */
818 	TUNABLE_ULONG_FETCH("debug.witness.witness_count", &witness_count);
819 	witness_count = ulmax(witness_count, 1);
820 	TUNABLE_ULONG_FETCH("debug.witness.lock_order_data_count",
821 	    &witness_lo_data_count);
822 	TUNABLE_ULONG_FETCH("debug.witness.lock_order_hash_size",
823 	    &witness_lo_hash_size);
824 	w_sz = witness_startup_calc();
825 	if (bootverbose)
826 		printf("WITNESS configuration requests %lu KiB "
827 		    "of startup allocations with witness_count=%lu, "
828 		    "lock_order_data_count=%lu, lock_order_hash_size=%lu\n",
829 		    w_sz / 1024, witness_count, witness_lo_data_count,
830 		    witness_lo_hash_size);
831 	if (w_sz <= avail)
832 		return (w_sz);
833 
834 	/* Memory allocation would be too large, try fallbacks. */
835 	printf("WARNING: WITNESS configuration requests %lu KiB, "
836 	    "with %lu KiB available\n", w_sz / 1024, avail / 1024);
837 	witness_count = ulmin(witness_count, WITNESS_COUNT);
838 	witness_lo_data_count = ulmin(witness_lo_data_count,
839 	    WITNESS_LO_DATA_COUNT);
840 	witness_lo_hash_size = ulmin(witness_lo_hash_size,
841 	    WITNESS_LO_HASH_SIZE);
842 	w_sz = witness_startup_calc();
843 	if (w_sz <= avail) {
844 		printf("WARNING: WITNESS configuration reduced to defaults\n");
845 		return (w_sz);
846 	}
847 
848 	/* Minimize startup allocations, functionally disabling witness. */
849 	witness_count = 1;
850 	witness_lo_data_count = 0;
851 	witness_lo_hash_size = 1;
852 	w_sz = witness_startup_calc();
853 	if (w_sz <= avail) {
854 		printf("WARNING: WITNESS configuration defaults too large, "
855 		    "lock order checks disabled\n");
856 		return (w_sz);
857 	}
858 
859 	panic("WITNESS unable to initialize with %lu KiB available",
860 	    avail / 1024);
861 }
862 
863 /*
864  * The WITNESS-enabled diagnostic code.  Note that the witness code does
865  * assume that the early boot is single-threaded at least until after this
866  * routine is completed.  This routine runs during SI_SUB_VM.  Any read-only
867  * tunables need to have been initialized by now.
868  */
869 void
witness_startup(void * mem)870 witness_startup(void *mem)
871 {
872 	struct lock_object *lock;
873 	struct witness_order_list_entry *order;
874 	struct witness *w, *w1;
875 	uintptr_t p;
876 	int i;
877 
878 	p = (uintptr_t)mem;
879 	w_data = (void *)p;
880 	p += sizeof(struct witness) * witness_count;
881 
882 	w_rmatrix = (void *)p;
883 	p += sizeof(*w_rmatrix) * (witness_count + 1);
884 
885 	for (i = 0; i < witness_count + 1; i++) {
886 		w_rmatrix[i] = (void *)p;
887 		p += sizeof(*w_rmatrix[i]) * (witness_count + 1);
888 	}
889 
890 	/* Fix up alignment */
891 	p = roundup2(p, sizeof(void *));
892 
893 	w_lodata = (void *)p;
894 	p += sizeof(w_lodata[0]) * witness_lo_data_count;
895 
896 	w_lohash.wloh_array = (void *)p;
897 	p += sizeof(w_lohash.wloh_array[0]) * witness_lo_hash_size;
898 
899 	MPASS(p <= (uintptr_t)mem + w_sz);
900 
901 	badstack_sbuf_size = witness_count * 256;
902 
903 	/*
904 	 * We have to release Giant before initializing its witness
905 	 * structure so that WITNESS doesn't get confused.
906 	 */
907 	mtx_unlock(&Giant);
908 	mtx_assert(&Giant, MA_NOTOWNED);
909 
910 	CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
911 	mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
912 	    MTX_NOWITNESS | MTX_NOPROFILE);
913 	for (i = witness_count - 1; i >= 0; i--) {
914 		w = &w_data[i];
915 		memset(w, 0, sizeof(*w));
916 		w_data[i].w_index = i;	/* Witness index never changes. */
917 		witness_free(w);
918 	}
919 	KASSERT(STAILQ_FIRST(&w_free)->w_index == 0,
920 	    ("%s: Invalid list of free witness objects", __func__));
921 
922 	/* Witness with index 0 is not used to aid in debugging. */
923 	STAILQ_REMOVE_HEAD(&w_free, w_list);
924 	w_free_cnt--;
925 
926 	for (i = 0; i < witness_count; i++) {
927 		memset(w_rmatrix[i], 0, sizeof(*w_rmatrix[i]) *
928 		    (witness_count + 1));
929 	}
930 
931 	for (i = 0; i < LOCK_CHILDCOUNT; i++)
932 		witness_lock_list_free(&w_locklistdata[i]);
933 	witness_init_hash_tables();
934 
935 	/* First add in all the specified order lists. */
936 	for (order = order_lists; order->w_name != NULL; order++) {
937 		w = enroll(order->w_name, order->w_class);
938 		if (w == NULL)
939 			continue;
940 		w->w_file = "order list";
941 		for (order++; order->w_name != NULL; order++) {
942 			w1 = enroll(order->w_name, order->w_class);
943 			if (w1 == NULL)
944 				continue;
945 			w1->w_file = "order list";
946 			itismychild(w, w1);
947 			w_rmatrix[w->w_index][w1->w_index] |=
948 			    WITNESS_ORDER_LISTS;
949 			w_rmatrix[w1->w_index][w->w_index] |=
950 			    WITNESS_ORDER_LISTS;
951 			w = w1;
952 		}
953 	}
954 	witness_spin_warn = 1;
955 
956 	/* Iterate through all locks and add them to witness. */
957 	for (i = 0; pending_locks[i].wh_lock != NULL; i++) {
958 		lock = pending_locks[i].wh_lock;
959 		KASSERT(lock->lo_flags & LO_WITNESS,
960 		    ("%s: lock %s is on pending list but not LO_WITNESS",
961 		    __func__, lock->lo_name));
962 		lock->lo_witness = enroll(pending_locks[i].wh_type,
963 		    LOCK_CLASS(lock));
964 	}
965 
966 	/* Mark the witness code as being ready for use. */
967 	witness_cold = 0;
968 
969 	mtx_lock(&Giant);
970 }
971 
972 void
witness_init(struct lock_object * lock,const char * type)973 witness_init(struct lock_object *lock, const char *type)
974 {
975 	struct lock_class *class;
976 
977 	/* Various sanity checks. */
978 	class = LOCK_CLASS(lock);
979 	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
980 	    (class->lc_flags & LC_RECURSABLE) == 0)
981 		kassert_panic("%s: lock (%s) %s can not be recursable",
982 		    __func__, class->lc_name, lock->lo_name);
983 	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
984 	    (class->lc_flags & LC_SLEEPABLE) == 0)
985 		kassert_panic("%s: lock (%s) %s can not be sleepable",
986 		    __func__, class->lc_name, lock->lo_name);
987 	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
988 	    (class->lc_flags & LC_UPGRADABLE) == 0)
989 		kassert_panic("%s: lock (%s) %s can not be upgradable",
990 		    __func__, class->lc_name, lock->lo_name);
991 
992 	/*
993 	 * If we shouldn't watch this lock, then just clear lo_witness.
994 	 * Otherwise, if witness_cold is set, then it is too early to
995 	 * enroll this lock, so defer it to witness_initialize() by adding
996 	 * it to the pending_locks list.  If it is not too early, then enroll
997 	 * the lock now.
998 	 */
999 	if (witness_watch < 1 || KERNEL_PANICKED() ||
1000 	    (lock->lo_flags & LO_WITNESS) == 0)
1001 		lock->lo_witness = NULL;
1002 	else if (witness_cold) {
1003 		pending_locks[pending_cnt].wh_lock = lock;
1004 		pending_locks[pending_cnt++].wh_type = type;
1005 		if (pending_cnt > WITNESS_PENDLIST)
1006 			panic("%s: pending locks list is too small, "
1007 			    "increase WITNESS_PENDLIST\n",
1008 			    __func__);
1009 	} else
1010 		lock->lo_witness = enroll(type, class);
1011 }
1012 
1013 void
witness_destroy(struct lock_object * lock)1014 witness_destroy(struct lock_object *lock)
1015 {
1016 	struct lock_class *class;
1017 	struct witness *w;
1018 
1019 	class = LOCK_CLASS(lock);
1020 
1021 	if (witness_cold)
1022 		panic("lock (%s) %s destroyed while witness_cold",
1023 		    class->lc_name, lock->lo_name);
1024 
1025 	/* XXX: need to verify that no one holds the lock */
1026 	if ((lock->lo_flags & LO_WITNESS) == 0 || lock->lo_witness == NULL)
1027 		return;
1028 	w = lock->lo_witness;
1029 
1030 	mtx_lock_spin(&w_mtx);
1031 	MPASS(w->w_refcount > 0);
1032 	w->w_refcount--;
1033 
1034 	if (w->w_refcount == 0)
1035 		depart(w);
1036 	mtx_unlock_spin(&w_mtx);
1037 }
1038 
1039 #ifdef DDB
1040 static void
witness_ddb_compute_levels(void)1041 witness_ddb_compute_levels(void)
1042 {
1043 	struct witness *w;
1044 
1045 	/*
1046 	 * First clear all levels.
1047 	 */
1048 	STAILQ_FOREACH(w, &w_all, w_list)
1049 		w->w_ddb_level = -1;
1050 
1051 	/*
1052 	 * Look for locks with no parents and level all their descendants.
1053 	 */
1054 	STAILQ_FOREACH(w, &w_all, w_list) {
1055 		/* If the witness has ancestors (is not a root), skip it. */
1056 		if (w->w_num_ancestors > 0)
1057 			continue;
1058 		witness_ddb_level_descendants(w, 0);
1059 	}
1060 }
1061 
1062 static void
witness_ddb_level_descendants(struct witness * w,int l)1063 witness_ddb_level_descendants(struct witness *w, int l)
1064 {
1065 	int i;
1066 
1067 	if (w->w_ddb_level >= l)
1068 		return;
1069 
1070 	w->w_ddb_level = l;
1071 	l++;
1072 
1073 	for (i = 1; i <= w_max_used_index; i++) {
1074 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
1075 			witness_ddb_level_descendants(&w_data[i], l);
1076 	}
1077 }
1078 
1079 static void
witness_ddb_display_descendants(int (* prnt)(const char * fmt,...),struct witness * w,int indent)1080 witness_ddb_display_descendants(int(*prnt)(const char *fmt, ...),
1081     struct witness *w, int indent)
1082 {
1083 	int i;
1084 
1085 	for (i = 0; i < indent; i++)
1086 		prnt(" ");
1087 	prnt("%s (type: %s, depth: %d, active refs: %d)",
1088 	     w->w_name, w->w_class->lc_name,
1089 	     w->w_ddb_level, w->w_refcount);
1090 	if (w->w_displayed) {
1091 		prnt(" -- (already displayed)\n");
1092 		return;
1093 	}
1094 	w->w_displayed = 1;
1095 	if (w->w_file != NULL && w->w_line != 0)
1096 		prnt(" -- last acquired @ %s:%d\n", fixup_filename(w->w_file),
1097 		    w->w_line);
1098 	else
1099 		prnt(" -- never acquired\n");
1100 	indent++;
1101 	WITNESS_INDEX_ASSERT(w->w_index);
1102 	for (i = 1; i <= w_max_used_index; i++) {
1103 		if (db_pager_quit)
1104 			return;
1105 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
1106 			witness_ddb_display_descendants(prnt, &w_data[i],
1107 			    indent);
1108 	}
1109 }
1110 
1111 static void
witness_ddb_display_list(int (* prnt)(const char * fmt,...),struct witness_list * list)1112 witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
1113     struct witness_list *list)
1114 {
1115 	struct witness *w;
1116 
1117 	STAILQ_FOREACH(w, list, w_typelist) {
1118 		if (w->w_file == NULL || w->w_ddb_level > 0)
1119 			continue;
1120 
1121 		/* This lock has no anscestors - display its descendants. */
1122 		witness_ddb_display_descendants(prnt, w, 0);
1123 		if (db_pager_quit)
1124 			return;
1125 	}
1126 }
1127 
1128 static void
witness_ddb_display(int (* prnt)(const char * fmt,...))1129 witness_ddb_display(int(*prnt)(const char *fmt, ...))
1130 {
1131 	struct witness *w;
1132 
1133 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1134 	witness_ddb_compute_levels();
1135 
1136 	/* Clear all the displayed flags. */
1137 	STAILQ_FOREACH(w, &w_all, w_list)
1138 		w->w_displayed = 0;
1139 
1140 	/*
1141 	 * First, handle sleep locks which have been acquired at least
1142 	 * once.
1143 	 */
1144 	prnt("Sleep locks:\n");
1145 	witness_ddb_display_list(prnt, &w_sleep);
1146 	if (db_pager_quit)
1147 		return;
1148 
1149 	/*
1150 	 * Now do spin locks which have been acquired at least once.
1151 	 */
1152 	prnt("\nSpin locks:\n");
1153 	witness_ddb_display_list(prnt, &w_spin);
1154 	if (db_pager_quit)
1155 		return;
1156 
1157 	/*
1158 	 * Finally, any locks which have not been acquired yet.
1159 	 */
1160 	prnt("\nLocks which were never acquired:\n");
1161 	STAILQ_FOREACH(w, &w_all, w_list) {
1162 		if (w->w_file != NULL || w->w_refcount == 0)
1163 			continue;
1164 		prnt("%s (type: %s, depth: %d)\n", w->w_name,
1165 		    w->w_class->lc_name, w->w_ddb_level);
1166 		if (db_pager_quit)
1167 			return;
1168 	}
1169 }
1170 #endif /* DDB */
1171 
1172 #define	NUM_VERBOSE_STACKS	256
1173 #define	MAX_LOCKCHAIN_RECURSION	32
1174 
1175 /*
1176  * Struct used by the verbose witness functionality. Only sb, generation,
1177  * pairs, pair_count, check_generation, and alloc_flags communicate data
1178  * between multiple functions. The rest are used to pre-allocate space for
1179  * data which would otherwise end up on the stack.
1180  */
1181 struct verbose_tracker {
1182 	struct witness	t_w1, t_w2;
1183 	struct stack	t_stack;
1184 	struct sbuf 	*sb;
1185 	int 		generation;
1186 	int		alloc_flags;
1187 	int		pairs[2 * NUM_VERBOSE_STACKS];
1188 	int		pair_count;
1189 	int		recursion_list[MAX_LOCKCHAIN_RECURSION];
1190 	int		found[MAX_LOCKCHAIN_RECURSION + 1];
1191 	int		iter[MAX_LOCKCHAIN_RECURSION];
1192 	bool		check_generation;
1193 };
1194 
1195 static void
init_verbose_tracker(struct verbose_tracker * t,struct sbuf * sb,int alloc_flags,bool check_generation)1196 init_verbose_tracker(struct verbose_tracker *t, struct sbuf *sb,
1197     int alloc_flags, bool check_generation)
1198 {
1199 
1200 	KASSERT(t != NULL,
1201 	    ("%s: NULL t argument", __func__));
1202 	KASSERT(alloc_flags == M_WAITOK || alloc_flags == M_NOWAIT,
1203 	    ("%s: Unexpected alloc_flags %d", __func__, alloc_flags));
1204 	t->sb = sb;
1205 	t->check_generation = check_generation;
1206 	t->alloc_flags = alloc_flags;
1207 }
1208 
1209 static void
reset_verbose_tracker(struct verbose_tracker * t,int generation)1210 reset_verbose_tracker(struct verbose_tracker *t, int generation)
1211 {
1212 
1213 	KASSERT(t != NULL,
1214 	    ("%s: NULL t argument", __func__));
1215 	t->pair_count = 0;
1216 	t->generation = generation;
1217 }
1218 
1219 static bool
has_verbose_lockpair(const struct verbose_tracker * t,int from,int to)1220 has_verbose_lockpair(const struct verbose_tracker *t, int from, int to)
1221 {
1222 	int i;
1223 
1224 	/* Look for value. */
1225 	for (i = 0; i < (2 * t->pair_count); i += 2)
1226 		if (t->pairs[i] == from && t->pairs[i + 1] == to)
1227 			return (true);
1228 	return (false);
1229 }
1230 
1231 static void
add_verbose_lockpair(struct verbose_tracker * t,int from,int to)1232 add_verbose_lockpair(struct verbose_tracker *t, int from, int to)
1233 {
1234 
1235 	/* Check for duplicates. */
1236 	if (has_verbose_lockpair(t, from, to))
1237 		return;
1238 
1239 	/* Add a new value. */
1240 	if (t->pair_count < NUM_VERBOSE_STACKS) {
1241 		t->pairs[t->pair_count * 2] = from;
1242 		t->pairs[(t->pair_count * 2) + 1] = to;
1243 		t->pair_count++;
1244 	}
1245 }
1246 
1247 static void
sbuf_print_verbose_witness_chains(struct verbose_tracker * t,int from,int to)1248 sbuf_print_verbose_witness_chains(struct verbose_tracker *t, int from, int to)
1249 {
1250 	struct witness *w1, *w2;
1251 	int i, recursion_count;
1252 
1253 	recursion_count = 0;
1254 
1255 	mtx_lock_spin(&w_mtx);
1256 	if (t->check_generation && t->generation != w_generation) {
1257 		mtx_unlock_spin(&w_mtx);
1258 
1259 		/*
1260 		 * The graph has changed. Break the recursion loop.
1261 		 * The calling function should figure out what happened and
1262 		 * restart.
1263 		 */
1264 		return;
1265 	}
1266 
1267 top:
1268 	t->found[recursion_count] = 0;
1269 
1270 	/*
1271 	 * Check for a direct dependence. If so, print that here.
1272 	 * However, we keep scanning just in case there are other
1273 	 * locking paths between these two locks.
1274 	 */
1275 	w1 = &w_data[from];
1276 	w2 = &w_data[to];
1277 	if (isitmychild(w1, w2)) {
1278 		t->t_w1 = *w1;
1279 		t->t_w2 = *w2;
1280 		mtx_unlock_spin(&w_mtx);
1281 
1282 		sbuf_printf(t->sb, "\"%s\" -> \"%s\"",
1283 		    t->t_w1.w_name, t->t_w2.w_name);
1284 
1285 		/* Add the lockchain which got us here. */
1286 		KASSERT(recursion_count >= 0 &&
1287 		    recursion_count <= MAX_LOCKCHAIN_RECURSION,
1288 		    ("Invalid recursion_count: %d", recursion_count));
1289 		for (i = recursion_count - 1; i >= 0; i--) {
1290 			mtx_lock_spin(&w_mtx);
1291 			if (t->check_generation &&
1292 			    t->generation != w_generation) {
1293 				mtx_unlock_spin(&w_mtx);
1294 				/* The graph has changed. */
1295 				return;
1296 			}
1297 			/*
1298 			 * Make a local copy, drop the lock, and add the lock
1299 			 * to the sbuf.
1300 			 */
1301 			t->t_w1 = w_data[t->recursion_list[i]];
1302 			mtx_unlock_spin(&w_mtx);
1303 			sbuf_printf(t->sb, " -> \"%s\"", t->t_w1.w_name);
1304 		}
1305 
1306 		sbuf_putc(t->sb, '\n');
1307 		add_verbose_lockpair(t, from, to);
1308 		t->found[recursion_count]++;
1309 
1310 		mtx_lock_spin(&w_mtx);
1311 		if (t->check_generation && t->generation != w_generation) {
1312 			mtx_unlock_spin(&w_mtx);
1313 			return;
1314 		}
1315 	}
1316 
1317 	/*
1318 	 * Ensure we aren't recursing too many times. We do this check
1319 	 * after looking for direct dependencies so we don't fail to
1320 	 * catch at least those at the limits of our recursion.
1321 	 */
1322 	if (recursion_count >= MAX_LOCKCHAIN_RECURSION)
1323 		goto end;
1324 
1325 	/*
1326 	 * Record our 'to' lock on the recursion list. We will use this
1327 	 * to build successful lock chains later.
1328 	 */
1329 	t->recursion_list[recursion_count] = to;
1330 	t->iter[recursion_count] = 1;
1331 
1332 loop:
1333 	/* Walk all parents of 'to' to see if any have a path to 'from'. */
1334 	for (; t->iter[recursion_count] < w_max_used_index;
1335 	    t->iter[recursion_count]++) {
1336 		if (t->iter[recursion_count] == to ||
1337 		    t->iter[recursion_count] == from)
1338 			continue;
1339 		if (isitmychild(&w_data[t->iter[recursion_count]],
1340 		    &w_data[to])) {
1341 			/* Recurse to the parent. */
1342 			to = t->iter[recursion_count];
1343 			recursion_count++;
1344 			goto top;
1345 		}
1346 	}
1347 end:
1348 	if (recursion_count != 0) {
1349 		recursion_count--;
1350 		to = t->recursion_list[recursion_count];
1351 		if (t->found[recursion_count + 1] > 0) {
1352 			add_verbose_lockpair(t, t->iter[recursion_count], to);
1353 			t->found[recursion_count]++;
1354 		}
1355 		t->iter[recursion_count]++;
1356 		goto loop;
1357 	}
1358 	mtx_unlock_spin(&w_mtx);
1359 }
1360 
1361 static void
sbuf_print_verbose_witness_stacks(struct verbose_tracker * t)1362 sbuf_print_verbose_witness_stacks(struct verbose_tracker *t)
1363 {
1364 	struct witness_lock_order_data *data;
1365 	int i;
1366 	bool hardcoded;
1367 
1368 	for (i = 0; i < (2 * t->pair_count); i += 2) {
1369 		mtx_lock_spin(&w_mtx);
1370 		if (t->check_generation && t->generation != w_generation) {
1371 			/*
1372 			 * The graph has changed. Return to the calling
1373 			 * function so it can restart.
1374 			 */
1375 			mtx_unlock_spin(&w_mtx);
1376 			break;
1377 		}
1378 
1379 		/*
1380 		 * Make a local copy of the data we need so we can drop
1381 		 * the lock.
1382 		 */
1383 		t->t_w1 = w_data[t->pairs[i]];
1384 		t->t_w2 = w_data[t->pairs[i + 1]];
1385 		data = witness_lock_order_get(&t->t_w1, &t->t_w2);
1386 		if (data != NULL)
1387 			stack_copy(&data->wlod_stack, &t->t_stack);
1388 		hardcoded = (w_rmatrix[t->pairs[i]][t->pairs[i + 1]] &
1389 		    WITNESS_ORDER_LISTS) == WITNESS_ORDER_LISTS;
1390 		mtx_unlock_spin(&w_mtx);
1391 
1392 		sbuf_printf(t->sb,
1393 		    "%slock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
1394 		    hardcoded ? "hardcoded " : "",
1395 		    t->t_w1.w_name, t->t_w1.w_class->lc_name,
1396 		    t->t_w2.w_name, t->t_w2.w_class->lc_name);
1397 		if (data != NULL)
1398 			stack_sbuf_print_flags(t->sb, &t->t_stack,
1399 			    t->alloc_flags, STACK_SBUF_FMT_LONG);
1400 		else
1401 			sbuf_printf(t->sb, "(No stack trace)\n");
1402 		sbuf_putc(t->sb, '\n');
1403 	}
1404 }
1405 
1406 int
witness_defineorder(struct lock_object * lock1,struct lock_object * lock2)1407 witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
1408 {
1409 	if (witness_watch == -1 || KERNEL_PANICKED())
1410 		return (0);
1411 
1412 	/* Require locks that witness knows about. */
1413 	if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
1414 	    lock2->lo_witness == NULL)
1415 		return (EINVAL);
1416 
1417 	mtx_assert(&w_mtx, MA_NOTOWNED);
1418 	mtx_lock_spin(&w_mtx);
1419 
1420 	/*
1421 	 * If we already have either an explicit or implied lock order that
1422 	 * is the other way around, then return an error.
1423 	 */
1424 	if (witness_watch &&
1425 	    isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
1426 		mtx_unlock_spin(&w_mtx);
1427 		return (EDOOFUS);
1428 	}
1429 
1430 	/* Try to add the new order. */
1431 	CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1432 	    lock2->lo_witness->w_name, lock1->lo_witness->w_name);
1433 	itismychild(lock1->lo_witness, lock2->lo_witness);
1434 	mtx_unlock_spin(&w_mtx);
1435 	return (0);
1436 }
1437 
1438 void
witness_checkorder(struct lock_object * lock,int flags,const char * file,int line,struct lock_object * interlock)1439 witness_checkorder(struct lock_object *lock, int flags, const char *file,
1440     int line, struct lock_object *interlock)
1441 {
1442 	struct lock_list_entry *lock_list, *lle;
1443 	struct lock_instance *lock1, *lock2, *plock;
1444 	struct lock_class *class, *iclass;
1445 	struct witness *w, *w1;
1446 	struct thread *td;
1447 	int i, j;
1448 	bool print_lock_order;
1449 
1450 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL ||
1451 	    KERNEL_PANICKED())
1452 		return;
1453 
1454 	w = lock->lo_witness;
1455 	class = LOCK_CLASS(lock);
1456 	td = curthread;
1457 
1458 	if (class->lc_flags & LC_SLEEPLOCK) {
1459 		/*
1460 		 * Since spin locks include a critical section, this check
1461 		 * implicitly enforces a lock order of all sleep locks before
1462 		 * all spin locks.
1463 		 */
1464 		if (td->td_critnest != 0 && !kdb_active)
1465 			kassert_panic("acquiring blockable sleep lock with "
1466 			    "spinlock or critical section held (%s) %s @ %s:%d",
1467 			    class->lc_name, lock->lo_name,
1468 			    fixup_filename(file), line);
1469 
1470 		/*
1471 		 * If this is the first lock acquired then just return as
1472 		 * no order checking is needed.
1473 		 */
1474 		lock_list = td->td_sleeplocks;
1475 		if (lock_list == NULL || lock_list->ll_count == 0)
1476 			return;
1477 	} else {
1478 		/*
1479 		 * If this is the first lock, just return as no order
1480 		 * checking is needed.  Avoid problems with thread
1481 		 * migration pinning the thread while checking if
1482 		 * spinlocks are held.  If at least one spinlock is held
1483 		 * the thread is in a safe path and it is allowed to
1484 		 * unpin it.
1485 		 */
1486 		sched_pin();
1487 		lock_list = PCPU_GET(spinlocks);
1488 		if (lock_list == NULL || lock_list->ll_count == 0) {
1489 			sched_unpin();
1490 			return;
1491 		}
1492 		sched_unpin();
1493 	}
1494 
1495 	/*
1496 	 * Check to see if we are recursing on a lock we already own.  If
1497 	 * so, make sure that we don't mismatch exclusive and shared lock
1498 	 * acquires.
1499 	 */
1500 	lock1 = find_instance(lock_list, lock);
1501 	if (lock1 != NULL) {
1502 		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
1503 		    (flags & LOP_EXCLUSIVE) == 0) {
1504 			witness_output("shared lock of (%s) %s @ %s:%d\n",
1505 			    class->lc_name, lock->lo_name,
1506 			    fixup_filename(file), line);
1507 			witness_output("while exclusively locked from %s:%d\n",
1508 			    fixup_filename(lock1->li_file), lock1->li_line);
1509 			kassert_panic("excl->share");
1510 		}
1511 		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
1512 		    (flags & LOP_EXCLUSIVE) != 0) {
1513 			witness_output("exclusive lock of (%s) %s @ %s:%d\n",
1514 			    class->lc_name, lock->lo_name,
1515 			    fixup_filename(file), line);
1516 			witness_output("while share locked from %s:%d\n",
1517 			    fixup_filename(lock1->li_file), lock1->li_line);
1518 			kassert_panic("share->excl");
1519 		}
1520 		return;
1521 	}
1522 
1523 	/* Warn if the interlock is not locked exactly once. */
1524 	if (interlock != NULL) {
1525 		iclass = LOCK_CLASS(interlock);
1526 		lock1 = find_instance(lock_list, interlock);
1527 		if (lock1 == NULL)
1528 			kassert_panic("interlock (%s) %s not locked @ %s:%d",
1529 			    iclass->lc_name, interlock->lo_name,
1530 			    fixup_filename(file), line);
1531 		else if ((lock1->li_flags & LI_RECURSEMASK) != 0)
1532 			kassert_panic("interlock (%s) %s recursed @ %s:%d",
1533 			    iclass->lc_name, interlock->lo_name,
1534 			    fixup_filename(file), line);
1535 	}
1536 
1537 	/*
1538 	 * Find the previously acquired lock, but ignore interlocks.
1539 	 */
1540 	plock = &lock_list->ll_children[lock_list->ll_count - 1];
1541 	if (interlock != NULL && plock->li_lock == interlock) {
1542 		if (lock_list->ll_count > 1)
1543 			plock =
1544 			    &lock_list->ll_children[lock_list->ll_count - 2];
1545 		else {
1546 			lle = lock_list->ll_next;
1547 
1548 			/*
1549 			 * The interlock is the only lock we hold, so
1550 			 * simply return.
1551 			 */
1552 			if (lle == NULL)
1553 				return;
1554 			plock = &lle->ll_children[lle->ll_count - 1];
1555 		}
1556 	}
1557 
1558 	/*
1559 	 * Try to perform most checks without a lock.  If this succeeds we
1560 	 * can skip acquiring the lock and return success.  Otherwise we redo
1561 	 * the check with the lock held to handle races with concurrent updates.
1562 	 */
1563 	w1 = plock->li_lock->lo_witness;
1564 	if (witness_lock_order_check(w1, w))
1565 		return;
1566 
1567 	mtx_lock_spin(&w_mtx);
1568 	if (witness_lock_order_check(w1, w)) {
1569 		mtx_unlock_spin(&w_mtx);
1570 		return;
1571 	}
1572 	witness_lock_order_add(w1, w);
1573 
1574 	/*
1575 	 * Check for duplicate locks of the same type.  Note that we only
1576 	 * have to check for this on the last lock we just acquired.  Any
1577 	 * other cases will be caught as lock order violations.
1578 	 */
1579 	if (w1 == w) {
1580 		i = w->w_index;
1581 		if (!(lock->lo_flags & LO_DUPOK) && !(flags & LOP_DUPOK) &&
1582 		    !(w_rmatrix[i][i] & WITNESS_REVERSAL)) {
1583 		    w_rmatrix[i][i] |= WITNESS_REVERSAL;
1584 			w->w_reversed = 1;
1585 			mtx_unlock_spin(&w_mtx);
1586 			witness_output(
1587 			    "acquiring duplicate lock of same type: \"%s\"\n",
1588 			    w->w_name);
1589 			witness_output(" 1st %s @ %s:%d\n", plock->li_lock->lo_name,
1590 			    fixup_filename(plock->li_file), plock->li_line);
1591 			witness_output(" 2nd %s @ %s:%d\n", lock->lo_name,
1592 			    fixup_filename(file), line);
1593 			witness_debugger(1, __func__);
1594 		} else
1595 			mtx_unlock_spin(&w_mtx);
1596 		return;
1597 	}
1598 	mtx_assert(&w_mtx, MA_OWNED);
1599 
1600 	/*
1601 	 * If we know that the lock we are acquiring comes after
1602 	 * the lock we most recently acquired in the lock order tree,
1603 	 * then there is no need for any further checks.
1604 	 */
1605 	if (isitmychild(w1, w))
1606 		goto out;
1607 
1608 	for (j = 0, lle = lock_list; lle != NULL; lle = lle->ll_next) {
1609 		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
1610 			struct stack pstack;
1611 			int trace;
1612 			bool pstackv;
1613 
1614 			MPASS(j < LOCK_CHILDCOUNT * LOCK_NCHILDREN);
1615 			lock1 = &lle->ll_children[i];
1616 
1617 			/*
1618 			 * Ignore the interlock.
1619 			 */
1620 			if (interlock == lock1->li_lock)
1621 				continue;
1622 
1623 			/*
1624 			 * If this lock doesn't undergo witness checking,
1625 			 * then skip it.
1626 			 */
1627 			w1 = lock1->li_lock->lo_witness;
1628 			if (w1 == NULL) {
1629 				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
1630 				    ("lock missing witness structure"));
1631 				continue;
1632 			}
1633 
1634 			/*
1635 			 * If we are locking Giant and this is a sleepable
1636 			 * lock, then skip it.
1637 			 */
1638 			if ((lock1->li_flags & LI_SLEEPABLE) != 0 &&
1639 			    lock == &Giant.lock_object)
1640 				continue;
1641 
1642 			/*
1643 			 * If we are locking a sleepable lock and this lock
1644 			 * is Giant, then skip it.
1645 			 */
1646 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1647 			    (flags & LOP_NOSLEEP) == 0 &&
1648 			    lock1->li_lock == &Giant.lock_object)
1649 				continue;
1650 
1651 			/*
1652 			 * If we are locking a sleepable lock and this lock
1653 			 * isn't sleepable, we want to treat it as a lock
1654 			 * order violation to enfore a general lock order of
1655 			 * sleepable locks before non-sleepable locks.
1656 			 */
1657 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1658 			    (flags & LOP_NOSLEEP) == 0 &&
1659 			    (lock1->li_flags & LI_SLEEPABLE) == 0)
1660 				goto reversal;
1661 
1662 			/*
1663 			 * If we are locking Giant and this is a non-sleepable
1664 			 * lock, then treat it as a reversal.
1665 			 */
1666 			if ((lock1->li_flags & LI_SLEEPABLE) == 0 &&
1667 			    lock == &Giant.lock_object)
1668 				goto reversal;
1669 
1670 			/*
1671 			 * Check the lock order hierarchy for a reveresal.
1672 			 */
1673 			if (!isitmydescendant(w, w1))
1674 				continue;
1675 		reversal:
1676 
1677 			/*
1678 			 * We have a lock order violation, check to see if it
1679 			 * is allowed or has already been yelled about.
1680 			 */
1681 
1682 			/* Bail if this violation is known */
1683 			if (w_rmatrix[w1->w_index][w->w_index] & WITNESS_REVERSAL)
1684 				goto out;
1685 
1686 			/* Record this as a violation */
1687 			w_rmatrix[w1->w_index][w->w_index] |= WITNESS_REVERSAL;
1688 			w_rmatrix[w->w_index][w1->w_index] |= WITNESS_REVERSAL;
1689 			w->w_reversed = w1->w_reversed = 1;
1690 			witness_increment_graph_generation();
1691 
1692 			/*
1693 			 * If the lock order is blessed, bail before logging
1694 			 * anything.  We don't look for other lock order
1695 			 * violations though, which may be a bug.
1696 			 */
1697 			if (blessed(w, w1))
1698 				goto out;
1699 
1700 			trace = atomic_load_int(&witness_trace);
1701 			if (trace) {
1702 				struct witness_lock_order_data *data;
1703 
1704 				pstackv = false;
1705 				data = witness_lock_order_get(w, w1);
1706 				if (data != NULL) {
1707 					stack_copy(&data->wlod_stack,
1708 					    &pstack);
1709 					pstackv = true;
1710 				}
1711 			}
1712 			mtx_unlock_spin(&w_mtx);
1713 
1714 #ifdef WITNESS_NO_VNODE
1715 			/*
1716 			 * There are known LORs between VNODE locks. They are
1717 			 * not an indication of a bug. VNODE locks are flagged
1718 			 * as such (LO_IS_VNODE) and we don't yell if the LOR
1719 			 * is between 2 VNODE locks.
1720 			 */
1721 			if ((lock->lo_flags & LO_IS_VNODE) != 0 &&
1722 			    (lock1->li_lock->lo_flags & LO_IS_VNODE) != 0)
1723 				return;
1724 #endif
1725 
1726 			/*
1727 			 * Ok, yell about it.
1728 			 */
1729 			print_lock_order = false;
1730 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1731 			    (flags & LOP_NOSLEEP) == 0 &&
1732 			    (lock1->li_flags & LI_SLEEPABLE) == 0)
1733 				witness_output(
1734 		"lock order reversal: (sleepable after non-sleepable)\n");
1735 			else if ((lock1->li_flags & LI_SLEEPABLE) == 0
1736 			    && lock == &Giant.lock_object)
1737 				witness_output(
1738 		"lock order reversal: (Giant after non-sleepable)\n");
1739 			else {
1740 				witness_output("lock order reversal:\n");
1741 				print_lock_order = true;
1742 			}
1743 
1744 			/*
1745 			 * Try to locate an earlier lock with
1746 			 * witness w in our list.
1747 			 */
1748 			do {
1749 				lock2 = &lle->ll_children[i];
1750 				MPASS(lock2->li_lock != NULL);
1751 				if (lock2->li_lock->lo_witness == w)
1752 					break;
1753 				if (i == 0 && lle->ll_next != NULL) {
1754 					lle = lle->ll_next;
1755 					i = lle->ll_count - 1;
1756 					MPASS(i >= 0 && i < LOCK_NCHILDREN);
1757 				} else
1758 					i--;
1759 			} while (i >= 0);
1760 			if (i < 0) {
1761 				witness_output(" 1st %p %s (%s, %s) @ %s:%d\n",
1762 				    lock1->li_lock, lock1->li_lock->lo_name,
1763 				    w1->w_name, w1->w_class->lc_name,
1764 				    fixup_filename(lock1->li_file),
1765 				    lock1->li_line);
1766 				witness_output(" 2nd %p %s (%s, %s) @ %s:%d\n",
1767 				    lock, lock->lo_name, w->w_name,
1768 				    w->w_class->lc_name, fixup_filename(file),
1769 				    line);
1770 			} else {
1771 				struct witness *w2 = lock2->li_lock->lo_witness;
1772 
1773 				witness_output(" 1st %p %s (%s, %s) @ %s:%d\n",
1774 				    lock2->li_lock, lock2->li_lock->lo_name,
1775 				    w2->w_name, w2->w_class->lc_name,
1776 				    fixup_filename(lock2->li_file),
1777 				    lock2->li_line);
1778 				witness_output(" 2nd %p %s (%s, %s) @ %s:%d\n",
1779 				    lock1->li_lock, lock1->li_lock->lo_name,
1780 				    w1->w_name, w1->w_class->lc_name,
1781 				    fixup_filename(lock1->li_file),
1782 				    lock1->li_line);
1783 				witness_output(" 3rd %p %s (%s, %s) @ %s:%d\n", lock,
1784 				    lock->lo_name, w->w_name,
1785 				    w->w_class->lc_name, fixup_filename(file),
1786 				    line);
1787 			}
1788 			if (trace) {
1789 				char buf[64];
1790 				struct sbuf sb;
1791 				struct verbose_tracker *t;
1792 
1793 				sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1794 				sbuf_set_drain(&sb, witness_output_drain,
1795 				    NULL);
1796 
1797 				if (pstackv) {
1798 					sbuf_printf(&sb,
1799 				    "lock order %s -> %s established at:\n",
1800 					    w->w_name, w1->w_name);
1801 					stack_sbuf_print_flags(&sb, &pstack,
1802 					    M_NOWAIT, STACK_SBUF_FMT_LONG);
1803 				} else if (trace > 1 && print_lock_order &&
1804 				    (t = malloc(sizeof(struct verbose_tracker),
1805 				    M_TEMP, M_NOWAIT | M_ZERO)) != NULL) {
1806 					/*
1807 					 * We make a purposeful decision to
1808 					 * ignore generation changes while
1809 					 * printing. The two locks in
1810 					 * question are in use, so won't be
1811 					 * going away. There is a small
1812 					 * chance that intermediate locks
1813 					 * in a lock chain get destroyed
1814 					 * while we are traversing the
1815 					 * chain or printing them, but even
1816 					 * then nothing "bad" should happen
1817 					 * with the current code since the
1818 					 * WITNESS objects are not actually
1819 					 * freed and re-used. If that changes,
1820 					 * we might need to reassess the
1821 					 * decision to ignore generation.
1822 					 */
1823 					init_verbose_tracker(t, &sb, M_NOWAIT,
1824 					    false);
1825 					reset_verbose_tracker(t, 0);
1826 					sbuf_printf(&sb,
1827 					    "All lock orders from %s -> %s:\n",
1828 					    w->w_name, w1->w_name);
1829 					sbuf_print_verbose_witness_chains(t,
1830 					    w->w_index, w1->w_index);
1831 					sbuf_putc(&sb, '\n');
1832 					sbuf_print_verbose_witness_stacks(t);
1833 					free(t, M_TEMP);
1834 				}
1835 
1836 				sbuf_printf(&sb,
1837 				    "lock order %s -> %s attempted at:\n",
1838 				    w1->w_name, w->w_name);
1839 				stack_save(&pstack);
1840 				stack_sbuf_print_flags(&sb, &pstack, M_NOWAIT,
1841 				    STACK_SBUF_FMT_LONG);
1842 
1843 				sbuf_finish(&sb);
1844 				sbuf_delete(&sb);
1845 			}
1846 			witness_enter_debugger(__func__);
1847 			return;
1848 		}
1849 	}
1850 
1851 	/*
1852 	 * If requested, build a new lock order.  However, don't build a new
1853 	 * relationship between a sleepable lock and Giant if it is in the
1854 	 * wrong direction.  The correct lock order is that sleepable locks
1855 	 * always come before Giant.
1856 	 */
1857 	if (flags & LOP_NEWORDER &&
1858 	    !(plock->li_lock == &Giant.lock_object &&
1859 	    (lock->lo_flags & LO_SLEEPABLE) != 0 &&
1860 	    (flags & LOP_NOSLEEP) == 0)) {
1861 		CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1862 		    w->w_name, plock->li_lock->lo_witness->w_name);
1863 		itismychild(plock->li_lock->lo_witness, w);
1864 	}
1865 out:
1866 	mtx_unlock_spin(&w_mtx);
1867 }
1868 
1869 void
witness_lock(struct lock_object * lock,int flags,const char * file,int line)1870 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
1871 {
1872 	struct lock_list_entry **lock_list, *lle;
1873 	struct lock_instance *instance;
1874 	struct witness *w;
1875 	struct thread *td;
1876 
1877 	if (witness_cold || witness_watch == -1 || lock->lo_witness == NULL ||
1878 	    KERNEL_PANICKED())
1879 		return;
1880 	w = lock->lo_witness;
1881 	td = curthread;
1882 
1883 	/* Determine lock list for this lock. */
1884 	if (LOCK_CLASS(lock)->lc_flags & LC_SLEEPLOCK)
1885 		lock_list = &td->td_sleeplocks;
1886 	else
1887 		lock_list = PCPU_PTR(spinlocks);
1888 
1889 	/* Update per-witness last file and line acquire. */
1890 	w->w_file = file;
1891 	w->w_line = line;
1892 
1893 	/* Check to see if we are recursing on a lock we already own. */
1894 	instance = find_instance(*lock_list, lock);
1895 	if (instance != NULL) {
1896 		instance->li_flags++;
1897 		CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1898 		    td->td_proc->p_pid, lock->lo_name,
1899 		    instance->li_flags & LI_RECURSEMASK);
1900 		return;
1901 	}
1902 
1903 	/* Find the next open lock instance in the list and fill it. */
1904 	lle = *lock_list;
1905 	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1906 		lle = witness_lock_list_get();
1907 		if (lle == NULL)
1908 			return;
1909 		lle->ll_next = *lock_list;
1910 		CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1911 		    td->td_proc->p_pid, lle);
1912 		*lock_list = lle;
1913 	}
1914 	instance = &lle->ll_children[lle->ll_count++];
1915 	instance->li_lock = lock;
1916 	instance->li_line = line;
1917 	instance->li_file = file;
1918 	instance->li_flags = 0;
1919 	if ((flags & LOP_EXCLUSIVE) != 0)
1920 		instance->li_flags |= LI_EXCLUSIVE;
1921 	if ((lock->lo_flags & LO_SLEEPABLE) != 0 && (flags & LOP_NOSLEEP) == 0)
1922 		instance->li_flags |= LI_SLEEPABLE;
1923 	CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1924 	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1925 }
1926 
1927 void
witness_upgrade(struct lock_object * lock,int flags,const char * file,int line)1928 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1929 {
1930 	struct lock_instance *instance;
1931 	struct lock_class *class;
1932 
1933 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1934 	if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
1935 		return;
1936 	class = LOCK_CLASS(lock);
1937 	if (witness_watch) {
1938 		if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1939 			kassert_panic(
1940 			    "upgrade of non-upgradable lock (%s) %s @ %s:%d",
1941 			    class->lc_name, lock->lo_name,
1942 			    fixup_filename(file), line);
1943 		if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1944 			kassert_panic(
1945 			    "upgrade of non-sleep lock (%s) %s @ %s:%d",
1946 			    class->lc_name, lock->lo_name,
1947 			    fixup_filename(file), line);
1948 	}
1949 	instance = find_instance(curthread->td_sleeplocks, lock);
1950 	if (instance == NULL) {
1951 		kassert_panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1952 		    class->lc_name, lock->lo_name,
1953 		    fixup_filename(file), line);
1954 		return;
1955 	}
1956 	if (witness_watch) {
1957 		if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1958 			kassert_panic(
1959 			    "upgrade of exclusive lock (%s) %s @ %s:%d",
1960 			    class->lc_name, lock->lo_name,
1961 			    fixup_filename(file), line);
1962 		if ((instance->li_flags & LI_RECURSEMASK) != 0)
1963 			kassert_panic(
1964 			    "upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1965 			    class->lc_name, lock->lo_name,
1966 			    instance->li_flags & LI_RECURSEMASK,
1967 			    fixup_filename(file), line);
1968 	}
1969 	instance->li_flags |= LI_EXCLUSIVE;
1970 }
1971 
1972 void
witness_downgrade(struct lock_object * lock,int flags,const char * file,int line)1973 witness_downgrade(struct lock_object *lock, int flags, const char *file,
1974     int line)
1975 {
1976 	struct lock_instance *instance;
1977 	struct lock_class *class;
1978 
1979 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1980 	if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
1981 		return;
1982 	class = LOCK_CLASS(lock);
1983 	if (witness_watch) {
1984 		if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1985 			kassert_panic(
1986 			    "downgrade of non-upgradable lock (%s) %s @ %s:%d",
1987 			    class->lc_name, lock->lo_name,
1988 			    fixup_filename(file), line);
1989 		if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1990 			kassert_panic(
1991 			    "downgrade of non-sleep lock (%s) %s @ %s:%d",
1992 			    class->lc_name, lock->lo_name,
1993 			    fixup_filename(file), line);
1994 	}
1995 	instance = find_instance(curthread->td_sleeplocks, lock);
1996 	if (instance == NULL) {
1997 		kassert_panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1998 		    class->lc_name, lock->lo_name,
1999 		    fixup_filename(file), line);
2000 		return;
2001 	}
2002 	if (witness_watch) {
2003 		if ((instance->li_flags & LI_EXCLUSIVE) == 0)
2004 			kassert_panic(
2005 			    "downgrade of shared lock (%s) %s @ %s:%d",
2006 			    class->lc_name, lock->lo_name,
2007 			    fixup_filename(file), line);
2008 		if ((instance->li_flags & LI_RECURSEMASK) != 0)
2009 			kassert_panic(
2010 			    "downgrade of recursed lock (%s) %s r=%d @ %s:%d",
2011 			    class->lc_name, lock->lo_name,
2012 			    instance->li_flags & LI_RECURSEMASK,
2013 			    fixup_filename(file), line);
2014 	}
2015 	instance->li_flags &= ~LI_EXCLUSIVE;
2016 }
2017 
2018 void
witness_unlock(struct lock_object * lock,int flags,const char * file,int line)2019 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
2020 {
2021 	struct lock_list_entry **lock_list, *lle;
2022 	struct lock_instance *instance;
2023 	struct lock_class *class;
2024 	struct thread *td;
2025 	register_t s;
2026 	int i, j;
2027 
2028 	if (witness_cold || lock->lo_witness == NULL || KERNEL_PANICKED())
2029 		return;
2030 	td = curthread;
2031 	class = LOCK_CLASS(lock);
2032 
2033 	/* Find lock instance associated with this lock. */
2034 	if (class->lc_flags & LC_SLEEPLOCK)
2035 		lock_list = &td->td_sleeplocks;
2036 	else
2037 		lock_list = PCPU_PTR(spinlocks);
2038 	lle = *lock_list;
2039 	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
2040 		for (i = 0; i < (*lock_list)->ll_count; i++) {
2041 			instance = &(*lock_list)->ll_children[i];
2042 			if (instance->li_lock == lock)
2043 				goto found;
2044 		}
2045 
2046 	/*
2047 	 * When disabling WITNESS through witness_watch we could end up in
2048 	 * having registered locks in the td_sleeplocks queue.
2049 	 * We have to make sure we flush these queues, so just search for
2050 	 * eventual register locks and remove them.
2051 	 */
2052 	if (witness_watch > 0) {
2053 		kassert_panic("lock (%s) %s not locked @ %s:%d", class->lc_name,
2054 		    lock->lo_name, fixup_filename(file), line);
2055 		return;
2056 	} else {
2057 		return;
2058 	}
2059 found:
2060 
2061 	/* First, check for shared/exclusive mismatches. */
2062 	if ((instance->li_flags & LI_EXCLUSIVE) != 0 && witness_watch > 0 &&
2063 	    (flags & LOP_EXCLUSIVE) == 0) {
2064 		witness_output("shared unlock of (%s) %s @ %s:%d\n",
2065 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
2066 		witness_output("while exclusively locked from %s:%d\n",
2067 		    fixup_filename(instance->li_file), instance->li_line);
2068 		kassert_panic("excl->ushare");
2069 	}
2070 	if ((instance->li_flags & LI_EXCLUSIVE) == 0 && witness_watch > 0 &&
2071 	    (flags & LOP_EXCLUSIVE) != 0) {
2072 		witness_output("exclusive unlock of (%s) %s @ %s:%d\n",
2073 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
2074 		witness_output("while share locked from %s:%d\n",
2075 		    fixup_filename(instance->li_file),
2076 		    instance->li_line);
2077 		kassert_panic("share->uexcl");
2078 	}
2079 	/* If we are recursed, unrecurse. */
2080 	if ((instance->li_flags & LI_RECURSEMASK) > 0) {
2081 		CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
2082 		    td->td_proc->p_pid, instance->li_lock->lo_name,
2083 		    instance->li_flags);
2084 		instance->li_flags--;
2085 		return;
2086 	}
2087 	/* The lock is now being dropped, check for NORELEASE flag */
2088 	if ((instance->li_flags & LI_NORELEASE) != 0 && witness_watch > 0) {
2089 		witness_output("forbidden unlock of (%s) %s @ %s:%d\n",
2090 		    class->lc_name, lock->lo_name, fixup_filename(file), line);
2091 		kassert_panic("lock marked norelease");
2092 	}
2093 
2094 	/* Otherwise, remove this item from the list. */
2095 	s = intr_disable();
2096 	CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
2097 	    td->td_proc->p_pid, instance->li_lock->lo_name,
2098 	    (*lock_list)->ll_count - 1);
2099 	for (j = i; j < (*lock_list)->ll_count - 1; j++)
2100 		(*lock_list)->ll_children[j] =
2101 		    (*lock_list)->ll_children[j + 1];
2102 	(*lock_list)->ll_count--;
2103 	intr_restore(s);
2104 
2105 	/*
2106 	 * In order to reduce contention on w_mtx, we want to keep always an
2107 	 * head object into lists so that frequent allocation from the
2108 	 * free witness pool (and subsequent locking) is avoided.
2109 	 * In order to maintain the current code simple, when the head
2110 	 * object is totally unloaded it means also that we do not have
2111 	 * further objects in the list, so the list ownership needs to be
2112 	 * hand over to another object if the current head needs to be freed.
2113 	 */
2114 	if ((*lock_list)->ll_count == 0) {
2115 		if (*lock_list == lle) {
2116 			if (lle->ll_next == NULL)
2117 				return;
2118 		} else
2119 			lle = *lock_list;
2120 		*lock_list = lle->ll_next;
2121 		CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
2122 		    td->td_proc->p_pid, lle);
2123 		witness_lock_list_free(lle);
2124 	}
2125 }
2126 
2127 void
witness_thread_exit(struct thread * td)2128 witness_thread_exit(struct thread *td)
2129 {
2130 	struct lock_list_entry *lle;
2131 	int i, n;
2132 
2133 	lle = td->td_sleeplocks;
2134 	if (lle == NULL || KERNEL_PANICKED())
2135 		return;
2136 	if (lle->ll_count != 0) {
2137 		for (n = 0; lle != NULL; lle = lle->ll_next)
2138 			for (i = lle->ll_count - 1; i >= 0; i--) {
2139 				if (n == 0)
2140 					witness_output(
2141 		    "Thread %p exiting with the following locks held:\n", td);
2142 				n++;
2143 				witness_list_lock(&lle->ll_children[i],
2144 				    witness_output);
2145 
2146 			}
2147 		kassert_panic(
2148 		    "Thread %p cannot exit while holding sleeplocks\n", td);
2149 	}
2150 	witness_lock_list_free(lle);
2151 }
2152 
2153 /*
2154  * Warn if any locks other than 'lock' are held.  Flags can be passed in to
2155  * exempt Giant and sleepable locks from the checks as well.  If any
2156  * non-exempt locks are held, then a supplied message is printed to the
2157  * output channel along with a list of the offending locks.  If indicated in the
2158  * flags then a failure results in a panic as well.
2159  */
2160 int
witness_warn(int flags,struct lock_object * lock,const char * fmt,...)2161 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
2162 {
2163 	struct lock_list_entry *lock_list, *lle;
2164 	struct lock_instance *lock1;
2165 	struct thread *td;
2166 	va_list ap;
2167 	int i, n;
2168 
2169 	if (witness_cold || witness_watch < 1 || KERNEL_PANICKED())
2170 		return (0);
2171 	n = 0;
2172 	td = curthread;
2173 	for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
2174 		for (i = lle->ll_count - 1; i >= 0; i--) {
2175 			lock1 = &lle->ll_children[i];
2176 			if (lock1->li_lock == lock)
2177 				continue;
2178 			if (flags & WARN_GIANTOK &&
2179 			    lock1->li_lock == &Giant.lock_object)
2180 				continue;
2181 			if (flags & WARN_SLEEPOK &&
2182 			    (lock1->li_flags & LI_SLEEPABLE) != 0)
2183 				continue;
2184 			if (n == 0) {
2185 				va_start(ap, fmt);
2186 				vprintf(fmt, ap);
2187 				va_end(ap);
2188 				printf(" with the following %slocks held:\n",
2189 				    (flags & WARN_SLEEPOK) != 0 ?
2190 				    "non-sleepable " : "");
2191 			}
2192 			n++;
2193 			witness_list_lock(lock1, printf);
2194 		}
2195 
2196 	/*
2197 	 * Pin the thread in order to avoid problems with thread migration.
2198 	 * Once that all verifies are passed about spinlocks ownership,
2199 	 * the thread is in a safe path and it can be unpinned.
2200 	 */
2201 	sched_pin();
2202 	lock_list = PCPU_GET(spinlocks);
2203 	if (lock_list != NULL && lock_list->ll_count != 0) {
2204 		sched_unpin();
2205 
2206 		/*
2207 		 * We should only have one spinlock and as long as
2208 		 * the flags cannot match for this locks class,
2209 		 * check if the first spinlock is the one curthread
2210 		 * should hold.
2211 		 */
2212 		lock1 = &lock_list->ll_children[lock_list->ll_count - 1];
2213 		if (lock_list->ll_count == 1 && lock_list->ll_next == NULL &&
2214 		    lock1->li_lock == lock && n == 0)
2215 			return (0);
2216 
2217 		va_start(ap, fmt);
2218 		vprintf(fmt, ap);
2219 		va_end(ap);
2220 		printf(" with the following %slocks held:\n",
2221 		    (flags & WARN_SLEEPOK) != 0 ?  "non-sleepable " : "");
2222 		n += witness_list_locks(&lock_list, printf);
2223 	} else
2224 		sched_unpin();
2225 
2226 	if (td->td_no_sleeping != 0 && (flags & WARN_SLEEPOK) != 0) {
2227 		va_start(ap, fmt);
2228 		vprintf(fmt, ap);
2229 		va_end(ap);
2230 		printf(" with %d sleep inhibitors\n", td->td_no_sleeping);
2231 		n += td->td_no_sleeping;
2232 	}
2233 
2234 	if (flags & WARN_PANIC && n)
2235 		kassert_panic("%s", __func__);
2236 	else
2237 		witness_debugger(n, __func__);
2238 	return (n);
2239 }
2240 
2241 const char *
witness_file(struct lock_object * lock)2242 witness_file(struct lock_object *lock)
2243 {
2244 	struct witness *w;
2245 
2246 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
2247 		return ("?");
2248 	w = lock->lo_witness;
2249 	return (w->w_file);
2250 }
2251 
2252 int
witness_line(struct lock_object * lock)2253 witness_line(struct lock_object *lock)
2254 {
2255 	struct witness *w;
2256 
2257 	if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
2258 		return (0);
2259 	w = lock->lo_witness;
2260 	return (w->w_line);
2261 }
2262 
2263 static struct witness *
enroll(const char * description,struct lock_class * lock_class)2264 enroll(const char *description, struct lock_class *lock_class)
2265 {
2266 	struct witness *w;
2267 
2268 	MPASS(description != NULL);
2269 
2270 	if (witness_watch == -1 || KERNEL_PANICKED())
2271 		return (NULL);
2272 	if ((lock_class->lc_flags & LC_SPINLOCK)) {
2273 		if (witness_skipspin)
2274 			return (NULL);
2275 	} else if ((lock_class->lc_flags & LC_SLEEPLOCK) == 0) {
2276 		kassert_panic("lock class %s is not sleep or spin",
2277 		    lock_class->lc_name);
2278 		return (NULL);
2279 	}
2280 
2281 	mtx_lock_spin(&w_mtx);
2282 	w = witness_hash_get(description);
2283 	if (w)
2284 		goto found;
2285 	if ((w = witness_get()) == NULL)
2286 		return (NULL);
2287 	MPASS(strlen(description) < MAX_W_NAME);
2288 	strcpy(w->w_name, description);
2289 	w->w_class = lock_class;
2290 	w->w_refcount = 1;
2291 	STAILQ_INSERT_HEAD(&w_all, w, w_list);
2292 	if (lock_class->lc_flags & LC_SPINLOCK) {
2293 		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
2294 		w_spin_cnt++;
2295 	} else if (lock_class->lc_flags & LC_SLEEPLOCK) {
2296 		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
2297 		w_sleep_cnt++;
2298 	}
2299 
2300 	/* Insert new witness into the hash */
2301 	witness_hash_put(w);
2302 	witness_increment_graph_generation();
2303 	mtx_unlock_spin(&w_mtx);
2304 	return (w);
2305 found:
2306 	w->w_refcount++;
2307 	if (w->w_refcount == 1)
2308 		w->w_class = lock_class;
2309 	mtx_unlock_spin(&w_mtx);
2310 	if (lock_class != w->w_class)
2311 		kassert_panic(
2312 		    "lock (%s) %s does not match earlier (%s) lock",
2313 		    description, lock_class->lc_name,
2314 		    w->w_class->lc_name);
2315 	return (w);
2316 }
2317 
2318 static void
depart(struct witness * w)2319 depart(struct witness *w)
2320 {
2321 	MPASS(w->w_refcount == 0);
2322 	if (w->w_class->lc_flags & LC_SLEEPLOCK) {
2323 		w_sleep_cnt--;
2324 	} else {
2325 		w_spin_cnt--;
2326 	}
2327 	/*
2328 	 * Set file to NULL as it may point into a loadable module.
2329 	 */
2330 	w->w_file = NULL;
2331 	w->w_line = 0;
2332 	witness_increment_graph_generation();
2333 }
2334 
2335 static void
adopt(struct witness * parent,struct witness * child)2336 adopt(struct witness *parent, struct witness *child)
2337 {
2338 	int pi, ci, i, j;
2339 
2340 	if (witness_cold == 0)
2341 		mtx_assert(&w_mtx, MA_OWNED);
2342 
2343 	/* If the relationship is already known, there's no work to be done. */
2344 	if (isitmychild(parent, child))
2345 		return;
2346 
2347 	/* When the structure of the graph changes, bump up the generation. */
2348 	witness_increment_graph_generation();
2349 
2350 	/*
2351 	 * The hard part ... create the direct relationship, then propagate all
2352 	 * indirect relationships.
2353 	 */
2354 	pi = parent->w_index;
2355 	ci = child->w_index;
2356 	WITNESS_INDEX_ASSERT(pi);
2357 	WITNESS_INDEX_ASSERT(ci);
2358 	MPASS(pi != ci);
2359 	w_rmatrix[pi][ci] |= WITNESS_PARENT;
2360 	w_rmatrix[ci][pi] |= WITNESS_CHILD;
2361 
2362 	/*
2363 	 * If parent was not already an ancestor of child,
2364 	 * then we increment the descendant and ancestor counters.
2365 	 */
2366 	if ((w_rmatrix[pi][ci] & WITNESS_ANCESTOR) == 0) {
2367 		parent->w_num_descendants++;
2368 		child->w_num_ancestors++;
2369 	}
2370 
2371 	/*
2372 	 * Find each ancestor of 'pi'. Note that 'pi' itself is counted as
2373 	 * an ancestor of 'pi' during this loop.
2374 	 */
2375 	for (i = 1; i <= w_max_used_index; i++) {
2376 		if ((w_rmatrix[i][pi] & WITNESS_ANCESTOR_MASK) == 0 &&
2377 		    (i != pi))
2378 			continue;
2379 
2380 		/* Find each descendant of 'i' and mark it as a descendant. */
2381 		for (j = 1; j <= w_max_used_index; j++) {
2382 			/*
2383 			 * Skip children that are already marked as
2384 			 * descendants of 'i'.
2385 			 */
2386 			if (w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK)
2387 				continue;
2388 
2389 			/*
2390 			 * We are only interested in descendants of 'ci'. Note
2391 			 * that 'ci' itself is counted as a descendant of 'ci'.
2392 			 */
2393 			if ((w_rmatrix[ci][j] & WITNESS_ANCESTOR_MASK) == 0 &&
2394 			    (j != ci))
2395 				continue;
2396 			w_rmatrix[i][j] |= WITNESS_ANCESTOR;
2397 			w_rmatrix[j][i] |= WITNESS_DESCENDANT;
2398 			w_data[i].w_num_descendants++;
2399 			w_data[j].w_num_ancestors++;
2400 
2401 			/*
2402 			 * Make sure we aren't marking a node as both an
2403 			 * ancestor and descendant. We should have caught
2404 			 * this as a lock order reversal earlier.
2405 			 */
2406 			if ((w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK) &&
2407 			    (w_rmatrix[i][j] & WITNESS_DESCENDANT_MASK)) {
2408 				printf("witness rmatrix paradox! [%d][%d]=%d "
2409 				    "both ancestor and descendant\n",
2410 				    i, j, w_rmatrix[i][j]);
2411 				kdb_backtrace();
2412 				printf("Witness disabled.\n");
2413 				witness_watch = -1;
2414 			}
2415 			if ((w_rmatrix[j][i] & WITNESS_ANCESTOR_MASK) &&
2416 			    (w_rmatrix[j][i] & WITNESS_DESCENDANT_MASK)) {
2417 				printf("witness rmatrix paradox! [%d][%d]=%d "
2418 				    "both ancestor and descendant\n",
2419 				    j, i, w_rmatrix[j][i]);
2420 				kdb_backtrace();
2421 				printf("Witness disabled.\n");
2422 				witness_watch = -1;
2423 			}
2424 		}
2425 	}
2426 }
2427 
2428 static void
itismychild(struct witness * parent,struct witness * child)2429 itismychild(struct witness *parent, struct witness *child)
2430 {
2431 	int unlocked;
2432 
2433 	MPASS(child != NULL && parent != NULL);
2434 	if (witness_cold == 0)
2435 		mtx_assert(&w_mtx, MA_OWNED);
2436 
2437 	if (!witness_lock_type_equal(parent, child)) {
2438 		if (witness_cold == 0) {
2439 			unlocked = 1;
2440 			mtx_unlock_spin(&w_mtx);
2441 		} else {
2442 			unlocked = 0;
2443 		}
2444 		kassert_panic(
2445 		    "%s: parent \"%s\" (%s) and child \"%s\" (%s) are not "
2446 		    "the same lock type", __func__, parent->w_name,
2447 		    parent->w_class->lc_name, child->w_name,
2448 		    child->w_class->lc_name);
2449 		if (unlocked)
2450 			mtx_lock_spin(&w_mtx);
2451 	}
2452 	adopt(parent, child);
2453 }
2454 
2455 /*
2456  * Generic code for the isitmy*() functions. The rmask parameter is the
2457  * expected relationship of w1 to w2.
2458  */
2459 static int
_isitmyx(struct witness * w1,struct witness * w2,int rmask,const char * fname)2460 _isitmyx(struct witness *w1, struct witness *w2, int rmask, const char *fname)
2461 {
2462 	unsigned char r1, r2;
2463 	int i1, i2;
2464 
2465 	i1 = w1->w_index;
2466 	i2 = w2->w_index;
2467 	WITNESS_INDEX_ASSERT(i1);
2468 	WITNESS_INDEX_ASSERT(i2);
2469 	r1 = w_rmatrix[i1][i2] & WITNESS_RELATED_MASK;
2470 	r2 = w_rmatrix[i2][i1] & WITNESS_RELATED_MASK;
2471 
2472 	/* The flags on one better be the inverse of the flags on the other */
2473 	if (!((WITNESS_ATOD(r1) == r2 && WITNESS_DTOA(r2) == r1) ||
2474 	    (WITNESS_DTOA(r1) == r2 && WITNESS_ATOD(r2) == r1))) {
2475 		/* Don't squawk if we're potentially racing with an update. */
2476 		if (!mtx_owned(&w_mtx))
2477 			return (0);
2478 		printf("%s: rmatrix mismatch between %s (index %d) and %s "
2479 		    "(index %d): w_rmatrix[%d][%d] == %hhx but "
2480 		    "w_rmatrix[%d][%d] == %hhx\n",
2481 		    fname, w1->w_name, i1, w2->w_name, i2, i1, i2, r1,
2482 		    i2, i1, r2);
2483 		kdb_backtrace();
2484 		printf("Witness disabled.\n");
2485 		witness_watch = -1;
2486 	}
2487 	return (r1 & rmask);
2488 }
2489 
2490 /*
2491  * Checks if @child is a direct child of @parent.
2492  */
2493 static int
isitmychild(struct witness * parent,struct witness * child)2494 isitmychild(struct witness *parent, struct witness *child)
2495 {
2496 	return (_isitmyx(parent, child, WITNESS_PARENT, __func__));
2497 }
2498 
2499 /*
2500  * Checks if @descendant is a direct or inderect descendant of @ancestor.
2501  */
2502 static int
isitmydescendant(struct witness * ancestor,struct witness * descendant)2503 isitmydescendant(struct witness *ancestor, struct witness *descendant)
2504 {
2505 	return (_isitmyx(ancestor, descendant, WITNESS_ANCESTOR_MASK,
2506 	    __func__));
2507 }
2508 
2509 static int
blessed(struct witness * w1,struct witness * w2)2510 blessed(struct witness *w1, struct witness *w2)
2511 {
2512 	int i;
2513 	struct witness_blessed *b;
2514 
2515 	for (i = 0; i < nitems(blessed_list); i++) {
2516 		b = &blessed_list[i];
2517 		if (strcmp(w1->w_name, b->b_lock1) == 0) {
2518 			if (strcmp(w2->w_name, b->b_lock2) == 0)
2519 				return (1);
2520 			continue;
2521 		}
2522 		if (strcmp(w1->w_name, b->b_lock2) == 0)
2523 			if (strcmp(w2->w_name, b->b_lock1) == 0)
2524 				return (1);
2525 	}
2526 	return (0);
2527 }
2528 
2529 static struct witness *
witness_get(void)2530 witness_get(void)
2531 {
2532 	struct witness *w;
2533 	int index;
2534 
2535 	if (witness_cold == 0)
2536 		mtx_assert(&w_mtx, MA_OWNED);
2537 
2538 	if (witness_watch == -1) {
2539 		mtx_unlock_spin(&w_mtx);
2540 		return (NULL);
2541 	}
2542 	if (STAILQ_EMPTY(&w_free)) {
2543 		witness_watch = -1;
2544 		mtx_unlock_spin(&w_mtx);
2545 		printf("WITNESS: unable to allocate a new witness object\n");
2546 		return (NULL);
2547 	}
2548 	w = STAILQ_FIRST(&w_free);
2549 	STAILQ_REMOVE_HEAD(&w_free, w_list);
2550 	w_free_cnt--;
2551 	index = w->w_index;
2552 	MPASS(index > 0 && index == w_max_used_index + 1 &&
2553 	    index < witness_count);
2554 	bzero(w, sizeof(*w));
2555 	w->w_index = index;
2556 	if (index > w_max_used_index)
2557 		w_max_used_index = index;
2558 	return (w);
2559 }
2560 
2561 static void
witness_free(struct witness * w)2562 witness_free(struct witness *w)
2563 {
2564 	STAILQ_INSERT_HEAD(&w_free, w, w_list);
2565 	w_free_cnt++;
2566 }
2567 
2568 static struct lock_list_entry *
witness_lock_list_get(void)2569 witness_lock_list_get(void)
2570 {
2571 	struct lock_list_entry *lle;
2572 
2573 	if (witness_watch == -1)
2574 		return (NULL);
2575 	mtx_lock_spin(&w_mtx);
2576 	lle = w_lock_list_free;
2577 	if (lle == NULL) {
2578 		witness_watch = -1;
2579 		mtx_unlock_spin(&w_mtx);
2580 		printf("%s: witness exhausted\n", __func__);
2581 		return (NULL);
2582 	}
2583 	w_lock_list_free = lle->ll_next;
2584 	mtx_unlock_spin(&w_mtx);
2585 	bzero(lle, sizeof(*lle));
2586 	return (lle);
2587 }
2588 
2589 static void
witness_lock_list_free(struct lock_list_entry * lle)2590 witness_lock_list_free(struct lock_list_entry *lle)
2591 {
2592 	mtx_lock_spin(&w_mtx);
2593 	lle->ll_next = w_lock_list_free;
2594 	w_lock_list_free = lle;
2595 	mtx_unlock_spin(&w_mtx);
2596 }
2597 
2598 static struct lock_instance *
find_instance(struct lock_list_entry * list,const struct lock_object * lock)2599 find_instance(struct lock_list_entry *list, const struct lock_object *lock)
2600 {
2601 	struct lock_list_entry *lle;
2602 	struct lock_instance *instance;
2603 	int i;
2604 
2605 	for (lle = list; lle != NULL; lle = lle->ll_next)
2606 		for (i = lle->ll_count - 1; i >= 0; i--) {
2607 			instance = &lle->ll_children[i];
2608 			if (instance->li_lock == lock)
2609 				return (instance);
2610 		}
2611 	return (NULL);
2612 }
2613 
2614 static void
witness_list_lock(struct lock_instance * instance,int (* prnt)(const char * fmt,...))2615 witness_list_lock(struct lock_instance *instance,
2616     int (*prnt)(const char *fmt, ...))
2617 {
2618 	struct lock_object *lock;
2619 
2620 	lock = instance->li_lock;
2621 	prnt("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
2622 	    "exclusive" : "shared", LOCK_CLASS(lock)->lc_name, lock->lo_name);
2623 	if (lock->lo_witness->w_name != lock->lo_name)
2624 		prnt(" (%s)", lock->lo_witness->w_name);
2625 	prnt(" r = %d (%p) locked @ %s:%d\n",
2626 	    instance->li_flags & LI_RECURSEMASK, lock,
2627 	    fixup_filename(instance->li_file), instance->li_line);
2628 }
2629 
2630 static int
witness_output(const char * fmt,...)2631 witness_output(const char *fmt, ...)
2632 {
2633 	va_list ap;
2634 	int ret;
2635 
2636 	va_start(ap, fmt);
2637 	ret = witness_voutput(fmt, ap);
2638 	va_end(ap);
2639 	return (ret);
2640 }
2641 
2642 static int
witness_voutput(const char * fmt,va_list ap)2643 witness_voutput(const char *fmt, va_list ap)
2644 {
2645 	int ret;
2646 
2647 	ret = 0;
2648 	switch (witness_channel) {
2649 	case WITNESS_CONSOLE:
2650 		ret = vprintf(fmt, ap);
2651 		break;
2652 	case WITNESS_LOG:
2653 		vlog(LOG_NOTICE, fmt, ap);
2654 		break;
2655 	case WITNESS_NONE:
2656 		break;
2657 	}
2658 	return (ret);
2659 }
2660 
2661 #ifdef DDB
2662 static int
witness_thread_has_locks(struct thread * td)2663 witness_thread_has_locks(struct thread *td)
2664 {
2665 	if (td->td_sleeplocks == NULL)
2666 		return (0);
2667 	return (td->td_sleeplocks->ll_count != 0);
2668 }
2669 
2670 static int
witness_proc_has_locks(struct proc * p)2671 witness_proc_has_locks(struct proc *p)
2672 {
2673 	struct thread *td;
2674 
2675 	FOREACH_THREAD_IN_PROC(p, td) {
2676 		if (witness_thread_has_locks(td))
2677 			return (1);
2678 	}
2679 	return (0);
2680 }
2681 #endif
2682 
2683 int
witness_list_locks(struct lock_list_entry ** lock_list,int (* prnt)(const char * fmt,...))2684 witness_list_locks(struct lock_list_entry **lock_list,
2685     int (*prnt)(const char *fmt, ...))
2686 {
2687 	struct lock_list_entry *lle;
2688 	int i, nheld;
2689 
2690 	nheld = 0;
2691 	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
2692 		for (i = lle->ll_count - 1; i >= 0; i--) {
2693 			witness_list_lock(&lle->ll_children[i], prnt);
2694 			nheld++;
2695 		}
2696 	return (nheld);
2697 }
2698 
2699 /*
2700  * This is a bit risky at best.  We call this function when we have timed
2701  * out acquiring a spin lock, and we assume that the other CPU is stuck
2702  * with this lock held.  So, we go groveling around in the other CPU's
2703  * per-cpu data to try to find the lock instance for this spin lock to
2704  * see when it was last acquired.
2705  */
2706 void
witness_display_spinlock(struct lock_object * lock,struct thread * owner,int (* prnt)(const char * fmt,...))2707 witness_display_spinlock(struct lock_object *lock, struct thread *owner,
2708     int (*prnt)(const char *fmt, ...))
2709 {
2710 	struct lock_instance *instance;
2711 	struct pcpu *pc;
2712 
2713 	if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
2714 		return;
2715 	pc = pcpu_find(owner->td_oncpu);
2716 	instance = find_instance(pc->pc_spinlocks, lock);
2717 	if (instance != NULL)
2718 		witness_list_lock(instance, prnt);
2719 }
2720 
2721 void
witness_save(struct lock_object * lock,const char ** filep,int * linep)2722 witness_save(struct lock_object *lock, const char **filep, int *linep)
2723 {
2724 	struct lock_list_entry *lock_list;
2725 	struct lock_instance *instance;
2726 	struct lock_class *class;
2727 
2728 	/* Initialize for KMSAN's benefit. */
2729 	*filep = NULL;
2730 	*linep = 0;
2731 
2732 	/*
2733 	 * This function is used independently in locking code to deal with
2734 	 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2735 	 * is gone.
2736 	 */
2737 	if (SCHEDULER_STOPPED())
2738 		return;
2739 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2740 	if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2741 		return;
2742 	class = LOCK_CLASS(lock);
2743 	if (class->lc_flags & LC_SLEEPLOCK)
2744 		lock_list = curthread->td_sleeplocks;
2745 	else {
2746 		if (witness_skipspin)
2747 			return;
2748 		lock_list = PCPU_GET(spinlocks);
2749 	}
2750 	instance = find_instance(lock_list, lock);
2751 	if (instance == NULL) {
2752 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2753 		    class->lc_name, lock->lo_name);
2754 		return;
2755 	}
2756 	*filep = instance->li_file;
2757 	*linep = instance->li_line;
2758 }
2759 
2760 void
witness_restore(struct lock_object * lock,const char * file,int line)2761 witness_restore(struct lock_object *lock, const char *file, int line)
2762 {
2763 	struct lock_list_entry *lock_list;
2764 	struct lock_instance *instance;
2765 	struct lock_class *class;
2766 
2767 	/*
2768 	 * This function is used independently in locking code to deal with
2769 	 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2770 	 * is gone.
2771 	 */
2772 	if (SCHEDULER_STOPPED())
2773 		return;
2774 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2775 	if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2776 		return;
2777 	class = LOCK_CLASS(lock);
2778 	if (class->lc_flags & LC_SLEEPLOCK)
2779 		lock_list = curthread->td_sleeplocks;
2780 	else {
2781 		if (witness_skipspin)
2782 			return;
2783 		lock_list = PCPU_GET(spinlocks);
2784 	}
2785 	instance = find_instance(lock_list, lock);
2786 	if (instance == NULL)
2787 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2788 		    class->lc_name, lock->lo_name);
2789 	lock->lo_witness->w_file = file;
2790 	lock->lo_witness->w_line = line;
2791 	if (instance == NULL)
2792 		return;
2793 	instance->li_file = file;
2794 	instance->li_line = line;
2795 }
2796 
2797 static bool
witness_find_instance(const struct lock_object * lock,struct lock_instance ** instance)2798 witness_find_instance(const struct lock_object *lock,
2799     struct lock_instance **instance)
2800 {
2801 #ifdef INVARIANT_SUPPORT
2802 	struct lock_class *class;
2803 
2804 	if (lock->lo_witness == NULL || witness_watch < 1 || KERNEL_PANICKED())
2805 		return (false);
2806 	class = LOCK_CLASS(lock);
2807 	if ((class->lc_flags & LC_SLEEPLOCK) != 0) {
2808 		*instance = find_instance(curthread->td_sleeplocks, lock);
2809 		return (true);
2810 	} else if ((class->lc_flags & LC_SPINLOCK) != 0) {
2811 		*instance = find_instance(PCPU_GET(spinlocks), lock);
2812 		return (true);
2813 	} else {
2814 		kassert_panic("Lock (%s) %s is not sleep or spin!",
2815 		    class->lc_name, lock->lo_name);
2816 		return (false);
2817 	}
2818 #else
2819 	return (false);
2820 #endif
2821 }
2822 
2823 void
witness_assert(const struct lock_object * lock,int flags,const char * file,int line)2824 witness_assert(const struct lock_object *lock, int flags, const char *file,
2825     int line)
2826 {
2827 #ifdef INVARIANT_SUPPORT
2828 	struct lock_instance *instance;
2829 	struct lock_class *class;
2830 
2831 	if (!witness_find_instance(lock, &instance))
2832 		return;
2833 	class = LOCK_CLASS(lock);
2834 	switch (flags) {
2835 	case LA_UNLOCKED:
2836 		if (instance != NULL)
2837 			kassert_panic("Lock (%s) %s locked @ %s:%d.",
2838 			    class->lc_name, lock->lo_name,
2839 			    fixup_filename(file), line);
2840 		break;
2841 	case LA_LOCKED:
2842 	case LA_LOCKED | LA_RECURSED:
2843 	case LA_LOCKED | LA_NOTRECURSED:
2844 	case LA_SLOCKED:
2845 	case LA_SLOCKED | LA_RECURSED:
2846 	case LA_SLOCKED | LA_NOTRECURSED:
2847 	case LA_XLOCKED:
2848 	case LA_XLOCKED | LA_RECURSED:
2849 	case LA_XLOCKED | LA_NOTRECURSED:
2850 		if (instance == NULL) {
2851 			kassert_panic("Lock (%s) %s not locked @ %s:%d.",
2852 			    class->lc_name, lock->lo_name,
2853 			    fixup_filename(file), line);
2854 			break;
2855 		}
2856 		if ((flags & LA_XLOCKED) != 0 &&
2857 		    (instance->li_flags & LI_EXCLUSIVE) == 0)
2858 			kassert_panic(
2859 			    "Lock (%s) %s not exclusively locked @ %s:%d.",
2860 			    class->lc_name, lock->lo_name,
2861 			    fixup_filename(file), line);
2862 		if ((flags & LA_SLOCKED) != 0 &&
2863 		    (instance->li_flags & LI_EXCLUSIVE) != 0)
2864 			kassert_panic(
2865 			    "Lock (%s) %s exclusively locked @ %s:%d.",
2866 			    class->lc_name, lock->lo_name,
2867 			    fixup_filename(file), line);
2868 		if ((flags & LA_RECURSED) != 0 &&
2869 		    (instance->li_flags & LI_RECURSEMASK) == 0)
2870 			kassert_panic("Lock (%s) %s not recursed @ %s:%d.",
2871 			    class->lc_name, lock->lo_name,
2872 			    fixup_filename(file), line);
2873 		if ((flags & LA_NOTRECURSED) != 0 &&
2874 		    (instance->li_flags & LI_RECURSEMASK) != 0)
2875 			kassert_panic("Lock (%s) %s recursed @ %s:%d.",
2876 			    class->lc_name, lock->lo_name,
2877 			    fixup_filename(file), line);
2878 		break;
2879 	default:
2880 		kassert_panic("Invalid lock assertion at %s:%d.",
2881 		    fixup_filename(file), line);
2882 	}
2883 #endif	/* INVARIANT_SUPPORT */
2884 }
2885 
2886 /*
2887  * Checks the ownership of the lock by curthread, consulting the witness list.
2888  * Returns:
2889  *   0  if witness is disabled or did not work
2890  *   -1 if not owned
2891  *   1  if owned
2892  */
2893 int
witness_is_owned(const struct lock_object * lock)2894 witness_is_owned(const struct lock_object *lock)
2895 {
2896 #ifdef INVARIANT_SUPPORT
2897 	struct lock_instance *instance;
2898 
2899 	if (!witness_find_instance(lock, &instance))
2900 		return (0);
2901 	return (instance == NULL ? -1 : 1);
2902 #else
2903 	return (0);
2904 #endif
2905 }
2906 
2907 static void
witness_setflag(struct lock_object * lock,int flag,int set)2908 witness_setflag(struct lock_object *lock, int flag, int set)
2909 {
2910 	struct lock_list_entry *lock_list;
2911 	struct lock_instance *instance;
2912 	struct lock_class *class;
2913 
2914 	if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2915 		return;
2916 	class = LOCK_CLASS(lock);
2917 	if (class->lc_flags & LC_SLEEPLOCK)
2918 		lock_list = curthread->td_sleeplocks;
2919 	else {
2920 		if (witness_skipspin)
2921 			return;
2922 		lock_list = PCPU_GET(spinlocks);
2923 	}
2924 	instance = find_instance(lock_list, lock);
2925 	if (instance == NULL) {
2926 		kassert_panic("%s: lock (%s) %s not locked", __func__,
2927 		    class->lc_name, lock->lo_name);
2928 		return;
2929 	}
2930 
2931 	if (set)
2932 		instance->li_flags |= flag;
2933 	else
2934 		instance->li_flags &= ~flag;
2935 }
2936 
2937 void
witness_norelease(struct lock_object * lock)2938 witness_norelease(struct lock_object *lock)
2939 {
2940 	witness_setflag(lock, LI_NORELEASE, 1);
2941 }
2942 
2943 void
witness_releaseok(struct lock_object * lock)2944 witness_releaseok(struct lock_object *lock)
2945 {
2946 	witness_setflag(lock, LI_NORELEASE, 0);
2947 }
2948 
2949 #ifdef DDB
2950 static void
witness_ddb_list(struct thread * td)2951 witness_ddb_list(struct thread *td)
2952 {
2953 	KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2954 	KASSERT(kdb_active, ("%s: not in the debugger", __func__));
2955 
2956 	if (witness_watch < 1)
2957 		return;
2958 
2959 	witness_list_locks(&td->td_sleeplocks, db_printf);
2960 
2961 	/*
2962 	 * We only handle spinlocks if td == curthread.  This is somewhat broken
2963 	 * if td is currently executing on some other CPU and holds spin locks
2964 	 * as we won't display those locks.  If we had a MI way of getting
2965 	 * the per-cpu data for a given cpu then we could use
2966 	 * td->td_oncpu to get the list of spinlocks for this thread
2967 	 * and "fix" this.
2968 	 *
2969 	 * That still wouldn't really fix this unless we locked the scheduler
2970 	 * lock or stopped the other CPU to make sure it wasn't changing the
2971 	 * list out from under us.  It is probably best to just not try to
2972 	 * handle threads on other CPU's for now.
2973 	 */
2974 	if (td == curthread && PCPU_GET(spinlocks) != NULL)
2975 		witness_list_locks(PCPU_PTR(spinlocks), db_printf);
2976 }
2977 
DB_SHOW_COMMAND(locks,db_witness_list)2978 DB_SHOW_COMMAND(locks, db_witness_list)
2979 {
2980 	struct thread *td;
2981 
2982 	if (have_addr)
2983 		td = db_lookup_thread(addr, true);
2984 	else
2985 		td = kdb_thread;
2986 	witness_ddb_list(td);
2987 }
2988 
DB_SHOW_ALL_COMMAND(locks,db_witness_list_all)2989 DB_SHOW_ALL_COMMAND(locks, db_witness_list_all)
2990 {
2991 	struct thread *td;
2992 	struct proc *p;
2993 
2994 	/*
2995 	 * It would be nice to list only threads and processes that actually
2996 	 * held sleep locks, but that information is currently not exported
2997 	 * by WITNESS.
2998 	 */
2999 	FOREACH_PROC_IN_SYSTEM(p) {
3000 		if (!witness_proc_has_locks(p))
3001 			continue;
3002 		FOREACH_THREAD_IN_PROC(p, td) {
3003 			if (!witness_thread_has_locks(td))
3004 				continue;
3005 			db_printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
3006 			    p->p_comm, td, td->td_tid);
3007 			witness_ddb_list(td);
3008 			if (db_pager_quit)
3009 				return;
3010 		}
3011 	}
3012 }
3013 DB_SHOW_ALIAS_FLAGS(alllocks, db_witness_list_all, DB_CMD_MEMSAFE);
3014 
DB_SHOW_COMMAND_FLAGS(witness,db_witness_display,DB_CMD_MEMSAFE)3015 DB_SHOW_COMMAND_FLAGS(witness, db_witness_display, DB_CMD_MEMSAFE)
3016 {
3017 	witness_ddb_display(db_printf);
3018 }
3019 #endif
3020 
3021 static void
sbuf_print_witness_badstacks(struct sbuf * sb,size_t * oldidx,bool check_generation)3022 sbuf_print_witness_badstacks(struct sbuf *sb, size_t *oldidx,
3023     bool check_generation)
3024 {
3025 	struct witness_lock_order_data *data1, *data2, *tmp_data1, *tmp_data2;
3026 	struct witness *tmp_w1, *tmp_w2, *w1, *w2;
3027 	struct verbose_tracker *t;
3028 	int generation, i, j;
3029 	bool w1_is_parent, w2_is_parent;
3030 
3031 	/* Allocate and init temporary storage space. */
3032 	tmp_w1 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
3033 	tmp_w2 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
3034 	tmp_data1 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
3035 	    M_WAITOK | M_ZERO);
3036 	tmp_data2 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
3037 	    M_WAITOK | M_ZERO);
3038 	stack_zero(&tmp_data1->wlod_stack);
3039 	stack_zero(&tmp_data2->wlod_stack);
3040 	t = malloc(sizeof(struct verbose_tracker), M_TEMP, M_WAITOK | M_ZERO);
3041 	init_verbose_tracker(t, sb, M_WAITOK, check_generation);
3042 
3043 restart:
3044 	mtx_lock_spin(&w_mtx);
3045 	generation = w_generation;
3046 	mtx_unlock_spin(&w_mtx);
3047 	reset_verbose_tracker(t, generation);
3048 	sbuf_printf(sb, "Number of known direct relationships is %d\n",
3049 	    w_lohash.wloh_count);
3050 	for (i = 1; i < w_max_used_index; i++) {
3051 		mtx_lock_spin(&w_mtx);
3052 		if (check_generation && generation != w_generation) {
3053 			mtx_unlock_spin(&w_mtx);
3054 
3055 			/* The graph has changed, try again. */
3056 			*oldidx = 0;
3057 			sbuf_clear(sb);
3058 			goto restart;
3059 		}
3060 
3061 		w1 = &w_data[i];
3062 		if (w1->w_reversed == 0) {
3063 			mtx_unlock_spin(&w_mtx);
3064 			continue;
3065 		}
3066 
3067 		/* Copy w1 locally so we can release the spin lock. */
3068 		*tmp_w1 = *w1;
3069 		mtx_unlock_spin(&w_mtx);
3070 
3071 		if (tmp_w1->w_reversed == 0)
3072 			continue;
3073 		for (j = 1; j < w_max_used_index; j++) {
3074 			if ((w_rmatrix[i][j] & WITNESS_REVERSAL) == 0 || i > j)
3075 				continue;
3076 
3077 			mtx_lock_spin(&w_mtx);
3078 			if (check_generation && generation != w_generation) {
3079 				mtx_unlock_spin(&w_mtx);
3080 
3081 				/* The graph has changed, try again. */
3082 				*oldidx = 0;
3083 				sbuf_clear(sb);
3084 				goto restart;
3085 			}
3086 
3087 			w2 = &w_data[j];
3088 			data1 = witness_lock_order_get(w1, w2);
3089 			data2 = witness_lock_order_get(w2, w1);
3090 
3091 			/*
3092 			 * Copy information locally so we can release the
3093 			 * spin lock.
3094 			 */
3095 			*tmp_w2 = *w2;
3096 
3097 			if (data1) {
3098 				stack_zero(&tmp_data1->wlod_stack);
3099 				stack_copy(&data1->wlod_stack,
3100 				    &tmp_data1->wlod_stack);
3101 			}
3102 			if (data2 && data2 != data1) {
3103 				stack_zero(&tmp_data2->wlod_stack);
3104 				stack_copy(&data2->wlod_stack,
3105 				    &tmp_data2->wlod_stack);
3106 			}
3107 			w1_is_parent = isitmydescendant(w1, w2);
3108 			w2_is_parent = isitmydescendant(w2, w1);
3109 			mtx_unlock_spin(&w_mtx);
3110 
3111 			if (blessed(tmp_w1, tmp_w2))
3112 				continue;
3113 
3114 			sbuf_printf(sb,
3115 	    "\nLock order reversal between \"%s\"(%s) and \"%s\"(%s)!\n",
3116 			    tmp_w1->w_name, tmp_w1->w_class->lc_name,
3117 			    tmp_w2->w_name, tmp_w2->w_class->lc_name);
3118 			if (w1_is_parent || data1 != NULL) {
3119 				sbuf_printf(sb,
3120 			    "All lock orders from \"%s\"(%s) -> \"%s\"(%s):\n",
3121 				    tmp_w1->w_name, tmp_w1->w_class->lc_name,
3122 				    tmp_w2->w_name, tmp_w2->w_class->lc_name);
3123 				if (w1_is_parent)
3124 					sbuf_print_verbose_witness_chains(t, i,
3125 					    j);
3126 				if (data1 && !has_verbose_lockpair(t, i, j)) {
3127 					sbuf_printf(t->sb,
3128 					    "** \"%s\" -> \"%s\"\n",
3129 					    tmp_w1->w_name, tmp_w2->w_name);
3130 					add_verbose_lockpair(t, i, j);
3131 				}
3132 				sbuf_putc(sb, '\n');
3133 				sbuf_print_verbose_witness_stacks(t);
3134 				sbuf_putc(sb, '\n');
3135 				reset_verbose_tracker(t, generation);
3136 			}
3137 			if (w2_is_parent || (data2 != NULL && data2 != data1)) {
3138 				sbuf_printf(sb,
3139 			    "All lock orders from \"%s\"(%s) -> \"%s\"(%s):\n",
3140 				    tmp_w2->w_name, tmp_w2->w_class->lc_name,
3141 				    tmp_w1->w_name, tmp_w1->w_class->lc_name);
3142 				if (w2_is_parent)
3143 					sbuf_print_verbose_witness_chains(t, j,
3144 					    i);
3145 				if (data2 && data2 != data1 &&
3146 				    !has_verbose_lockpair(t, j, i)) {
3147 					sbuf_printf(t->sb,
3148 					    "** \"%s\" -> \"%s\"\n",
3149 					    tmp_w2->w_name, tmp_w1->w_name);
3150 					add_verbose_lockpair(t, j, i);
3151 				}
3152 				sbuf_putc(sb, '\n');
3153 				sbuf_print_verbose_witness_stacks(t);
3154 				sbuf_putc(sb, '\n');
3155 				reset_verbose_tracker(t, generation);
3156 			}
3157 		}
3158 	}
3159 	mtx_lock_spin(&w_mtx);
3160 	if (check_generation && generation != w_generation) {
3161 		mtx_unlock_spin(&w_mtx);
3162 
3163 		/*
3164 		 * The graph changed while we were printing stack data,
3165 		 * try again.
3166 		 */
3167 		*oldidx = 0;
3168 		sbuf_clear(sb);
3169 		goto restart;
3170 	}
3171 	mtx_unlock_spin(&w_mtx);
3172 
3173 	/* Free temporary storage space. */
3174 	free(tmp_data1, M_TEMP);
3175 	free(tmp_data2, M_TEMP);
3176 	free(tmp_w1, M_TEMP);
3177 	free(tmp_w2, M_TEMP);
3178 	free(t, M_TEMP);
3179 }
3180 
3181 static int
sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)3182 sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)
3183 {
3184 	struct sbuf *sb;
3185 	int error;
3186 
3187 	if (witness_watch < 1) {
3188 		error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
3189 		return (error);
3190 	}
3191 	if (witness_cold) {
3192 		error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
3193 		return (error);
3194 	}
3195 	error = 0;
3196 	sb = sbuf_new(NULL, NULL, badstack_sbuf_size, SBUF_AUTOEXTEND);
3197 	if (sb == NULL)
3198 		return (ENOMEM);
3199 
3200 	sbuf_print_witness_badstacks(sb, &req->oldidx, true);
3201 
3202 	sbuf_finish(sb);
3203 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
3204 	sbuf_delete(sb);
3205 
3206 	return (error);
3207 }
3208 
3209 #ifdef DDB
DB_SHOW_COMMAND_FLAGS(badstacks,db_witness_badstacks,DB_CMD_MEMSAFE)3210 DB_SHOW_COMMAND_FLAGS(badstacks, db_witness_badstacks, DB_CMD_MEMSAFE)
3211 {
3212 	struct sbuf sb;
3213 	char buffer[128];
3214 	size_t dummy;
3215 
3216 	sbuf_new(&sb, buffer, sizeof(buffer), SBUF_FIXEDLEN);
3217 	sbuf_set_drain(&sb, sbuf_db_printf_drain, NULL);
3218 	sbuf_print_witness_badstacks(&sb, &dummy, false);
3219 	sbuf_finish(&sb);
3220 }
3221 #endif
3222 
3223 static int
sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS)3224 sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS)
3225 {
3226 	static const struct {
3227 		enum witness_channel channel;
3228 		const char *name;
3229 	} channels[] = {
3230 		{ WITNESS_CONSOLE, "console" },
3231 		{ WITNESS_LOG, "log" },
3232 		{ WITNESS_NONE, "none" },
3233 	};
3234 	char buf[16];
3235 	u_int i;
3236 	int error;
3237 
3238 	buf[0] = '\0';
3239 	for (i = 0; i < nitems(channels); i++)
3240 		if (witness_channel == channels[i].channel) {
3241 			snprintf(buf, sizeof(buf), "%s", channels[i].name);
3242 			break;
3243 		}
3244 
3245 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
3246 	if (error != 0 || req->newptr == NULL)
3247 		return (error);
3248 
3249 	error = EINVAL;
3250 	for (i = 0; i < nitems(channels); i++)
3251 		if (strcmp(channels[i].name, buf) == 0) {
3252 			witness_channel = channels[i].channel;
3253 			error = 0;
3254 			break;
3255 		}
3256 	return (error);
3257 }
3258 
3259 static int
sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)3260 sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
3261 {
3262 	struct witness *w;
3263 	struct sbuf *sb;
3264 	int error;
3265 
3266 #ifdef __i386__
3267 	error = SYSCTL_OUT(req, w_notallowed, sizeof(w_notallowed));
3268 	return (error);
3269 #endif
3270 
3271 	if (witness_watch < 1) {
3272 		error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
3273 		return (error);
3274 	}
3275 	if (witness_cold) {
3276 		error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
3277 		return (error);
3278 	}
3279 	error = 0;
3280 
3281 	error = sysctl_wire_old_buffer(req, 0);
3282 	if (error != 0)
3283 		return (error);
3284 	sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
3285 	if (sb == NULL)
3286 		return (ENOMEM);
3287 	sbuf_putc(sb, '\n');
3288 
3289 	mtx_lock_spin(&w_mtx);
3290 	STAILQ_FOREACH(w, &w_all, w_list)
3291 		w->w_displayed = 0;
3292 	STAILQ_FOREACH(w, &w_all, w_list)
3293 		witness_add_fullgraph(sb, w);
3294 	mtx_unlock_spin(&w_mtx);
3295 
3296 	/*
3297 	 * Close the sbuf and return to userland.
3298 	 */
3299 	error = sbuf_finish(sb);
3300 	sbuf_delete(sb);
3301 
3302 	return (error);
3303 }
3304 
3305 static int
sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)3306 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
3307 {
3308 	int error, value;
3309 
3310 	value = witness_watch;
3311 	error = sysctl_handle_int(oidp, &value, 0, req);
3312 	if (error != 0 || req->newptr == NULL)
3313 		return (error);
3314 	if (value > 1 || value < -1 ||
3315 	    (witness_watch == -1 && value != witness_watch))
3316 		return (EINVAL);
3317 	witness_watch = value;
3318 	return (0);
3319 }
3320 
3321 static void
witness_add_fullgraph(struct sbuf * sb,struct witness * w)3322 witness_add_fullgraph(struct sbuf *sb, struct witness *w)
3323 {
3324 	int i;
3325 
3326 	if (w->w_displayed != 0 || (w->w_file == NULL && w->w_line == 0))
3327 		return;
3328 	w->w_displayed = 1;
3329 
3330 	WITNESS_INDEX_ASSERT(w->w_index);
3331 	for (i = 1; i <= w_max_used_index; i++) {
3332 		if (w_rmatrix[w->w_index][i] & WITNESS_PARENT) {
3333 			sbuf_printf(sb, "\"%s\",\"%s\"\n", w->w_name,
3334 			    w_data[i].w_name);
3335 			witness_add_fullgraph(sb, &w_data[i]);
3336 		}
3337 	}
3338 }
3339 
3340 /*
3341  * A simple hash function. Takes a key pointer and a key size. If size == 0,
3342  * interprets the key as a string and reads until the null
3343  * terminator. Otherwise, reads the first size bytes. Returns an unsigned 32-bit
3344  * hash value computed from the key.
3345  */
3346 static uint32_t
witness_hash_djb2(const uint8_t * key,uint32_t size)3347 witness_hash_djb2(const uint8_t *key, uint32_t size)
3348 {
3349 	unsigned int hash = 5381;
3350 	int i;
3351 
3352 	/* hash = hash * 33 + key[i] */
3353 	if (size)
3354 		for (i = 0; i < size; i++)
3355 			hash = ((hash << 5) + hash) + (unsigned int)key[i];
3356 	else
3357 		for (i = 0; key[i] != 0; i++)
3358 			hash = ((hash << 5) + hash) + (unsigned int)key[i];
3359 
3360 	return (hash);
3361 }
3362 
3363 /*
3364  * Initializes the two witness hash tables. Called exactly once from
3365  * witness_initialize().
3366  */
3367 static void
witness_init_hash_tables(void)3368 witness_init_hash_tables(void)
3369 {
3370 	int i;
3371 
3372 	MPASS(witness_cold);
3373 
3374 	/* Initialize the hash tables. */
3375 	for (i = 0; i < WITNESS_HASH_SIZE; i++)
3376 		w_hash.wh_array[i] = NULL;
3377 
3378 	w_hash.wh_size = WITNESS_HASH_SIZE;
3379 	w_hash.wh_count = 0;
3380 
3381 	/* Initialize the lock order data hash. */
3382 	w_lofree = NULL;
3383 	for (i = 0; i < witness_lo_data_count; i++) {
3384 		memset(&w_lodata[i], 0, sizeof(w_lodata[i]));
3385 		w_lodata[i].wlod_next = w_lofree;
3386 		w_lofree = &w_lodata[i];
3387 	}
3388 	w_lohash.wloh_size = witness_lo_hash_size;
3389 	w_lohash.wloh_count = 0;
3390 	for (i = 0; i < w_lohash.wloh_size; i++)
3391 		w_lohash.wloh_array[i] = NULL;
3392 }
3393 
3394 static struct witness *
witness_hash_get(const char * key)3395 witness_hash_get(const char *key)
3396 {
3397 	struct witness *w;
3398 	uint32_t hash;
3399 
3400 	MPASS(key != NULL);
3401 	if (witness_cold == 0)
3402 		mtx_assert(&w_mtx, MA_OWNED);
3403 	hash = witness_hash_djb2(key, 0) % w_hash.wh_size;
3404 	w = w_hash.wh_array[hash];
3405 	while (w != NULL) {
3406 		if (strcmp(w->w_name, key) == 0)
3407 			goto out;
3408 		w = w->w_hash_next;
3409 	}
3410 
3411 out:
3412 	return (w);
3413 }
3414 
3415 static void
witness_hash_put(struct witness * w)3416 witness_hash_put(struct witness *w)
3417 {
3418 	uint32_t hash;
3419 
3420 	MPASS(w != NULL);
3421 	MPASS(w->w_name != NULL);
3422 	if (witness_cold == 0)
3423 		mtx_assert(&w_mtx, MA_OWNED);
3424 	KASSERT(witness_hash_get(w->w_name) == NULL,
3425 	    ("%s: trying to add a hash entry that already exists!", __func__));
3426 	KASSERT(w->w_hash_next == NULL,
3427 	    ("%s: w->w_hash_next != NULL", __func__));
3428 
3429 	hash = witness_hash_djb2(w->w_name, 0) % w_hash.wh_size;
3430 	w->w_hash_next = w_hash.wh_array[hash];
3431 	w_hash.wh_array[hash] = w;
3432 	w_hash.wh_count++;
3433 }
3434 
3435 static struct witness_lock_order_data *
witness_lock_order_get(struct witness * parent,struct witness * child)3436 witness_lock_order_get(struct witness *parent, struct witness *child)
3437 {
3438 	struct witness_lock_order_data *data = NULL;
3439 	struct witness_lock_order_key key;
3440 	unsigned int hash;
3441 
3442 	MPASS(parent != NULL && child != NULL);
3443 	key.from = parent->w_index;
3444 	key.to = child->w_index;
3445 	WITNESS_INDEX_ASSERT(key.from);
3446 	WITNESS_INDEX_ASSERT(key.to);
3447 	if ((w_rmatrix[parent->w_index][child->w_index]
3448 	    & WITNESS_LOCK_ORDER_KNOWN) == 0)
3449 		goto out;
3450 
3451 	hash = witness_hash_djb2((const char *)&key,
3452 	    sizeof(key)) % w_lohash.wloh_size;
3453 	data = w_lohash.wloh_array[hash];
3454 	while (data != NULL) {
3455 		if (witness_lock_order_key_equal(&data->wlod_key, &key))
3456 			break;
3457 		data = data->wlod_next;
3458 	}
3459 
3460 out:
3461 	return (data);
3462 }
3463 
3464 /*
3465  * Verify that parent and child have a known relationship, are not the same,
3466  * and child is actually a child of parent.  This is done without w_mtx
3467  * to avoid contention in the common case.
3468  */
3469 static int
witness_lock_order_check(struct witness * parent,struct witness * child)3470 witness_lock_order_check(struct witness *parent, struct witness *child)
3471 {
3472 	if (parent != child &&
3473 	    w_rmatrix[parent->w_index][child->w_index]
3474 	    & WITNESS_LOCK_ORDER_KNOWN &&
3475 	    isitmychild(parent, child))
3476 		return (1);
3477 
3478 	return (0);
3479 }
3480 
3481 static int
witness_lock_order_add(struct witness * parent,struct witness * child)3482 witness_lock_order_add(struct witness *parent, struct witness *child)
3483 {
3484 	struct witness_lock_order_data *data = NULL;
3485 	struct witness_lock_order_key key;
3486 	unsigned int hash;
3487 
3488 	MPASS(parent != NULL && child != NULL);
3489 	key.from = parent->w_index;
3490 	key.to = child->w_index;
3491 	WITNESS_INDEX_ASSERT(key.from);
3492 	WITNESS_INDEX_ASSERT(key.to);
3493 	if (w_rmatrix[parent->w_index][child->w_index]
3494 	    & WITNESS_LOCK_ORDER_KNOWN)
3495 		return (1);
3496 
3497 	w_rmatrix[parent->w_index][child->w_index] |= WITNESS_LOCK_ORDER_KNOWN;
3498 	data = w_lofree;
3499 	if (data == NULL)
3500 		return (0);
3501 	w_lofree = data->wlod_next;
3502 	hash = witness_hash_djb2((const char *)&key,
3503 	    sizeof(key)) % w_lohash.wloh_size;
3504 	data->wlod_next = w_lohash.wloh_array[hash];
3505 	data->wlod_key = key;
3506 	w_lohash.wloh_array[hash] = data;
3507 	w_lohash.wloh_count++;
3508 	stack_save(&data->wlod_stack);
3509 	return (1);
3510 }
3511 
3512 /* Call this whenever the structure of the witness graph changes. */
3513 static void
witness_increment_graph_generation(void)3514 witness_increment_graph_generation(void)
3515 {
3516 	if (witness_cold == 0)
3517 		mtx_assert(&w_mtx, MA_OWNED);
3518 	w_generation++;
3519 }
3520 
3521 static int
witness_output_drain(void * arg __unused,const char * data,int len)3522 witness_output_drain(void *arg __unused, const char *data, int len)
3523 {
3524 	witness_output("%.*s", len, data);
3525 	return (len);
3526 }
3527 
3528 static void
witness_debugger(int cond,const char * msg)3529 witness_debugger(int cond, const char *msg)
3530 {
3531 	char buf[32];
3532 	struct sbuf sb;
3533 	struct stack st;
3534 
3535 	if (!cond)
3536 		return;
3537 
3538 	if (witness_trace) {
3539 		sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
3540 		sbuf_set_drain(&sb, witness_output_drain, NULL);
3541 
3542 		stack_save(&st);
3543 		witness_output("stack backtrace:\n");
3544 		stack_sbuf_print_ddb(&sb, &st);
3545 
3546 		sbuf_finish(&sb);
3547 	}
3548 
3549 	witness_enter_debugger(msg);
3550 }
3551 
3552 static void
witness_enter_debugger(const char * msg)3553 witness_enter_debugger(const char *msg)
3554 {
3555 #ifdef KDB
3556 	if (witness_kdb)
3557 		kdb_enter(KDB_WHY_WITNESS, msg);
3558 #endif
3559 }
3560