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