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