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