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