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