xref: /freebsd/sys/kern/subr_witness.c (revision c69db88340f9a7659ab4faa7fd328a3fb858b72e)
1 /*-
2  * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. Berkeley Software Design Inc's name may not be used to endorse or
13  *    promote products derived from this software without specific prior
14  *    written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
29  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
30  */
31 
32 /*
33  * Implementation of the `witness' lock verifier.  Originally implemented for
34  * mutexes in BSD/OS.  Extended to handle generic lock objects and lock
35  * classes in FreeBSD.
36  */
37 
38 /*
39  *	Main Entry: witness
40  *	Pronunciation: 'wit-n&s
41  *	Function: noun
42  *	Etymology: Middle English witnesse, from Old English witnes knowledge,
43  *	    testimony, witness, from 2wit
44  *	Date: before 12th century
45  *	1 : attestation of a fact or event : TESTIMONY
46  *	2 : one that gives evidence; specifically : one who testifies in
47  *	    a cause or before a judicial tribunal
48  *	3 : one asked to be present at a transaction so as to be able to
49  *	    testify to its having taken place
50  *	4 : one who has personal knowledge of something
51  *	5 a : something serving as evidence or proof : SIGN
52  *	  b : public affirmation by word or example of usually
53  *	      religious faith or conviction <the heroic witness to divine
54  *	      life -- Pilot>
55  *	6 capitalized : a member of the Jehovah's Witnesses
56  */
57 
58 /*
59  * Special rules concerning Giant and lock orders:
60  *
61  * 1) Giant must be acquired before any other mutexes.  Stated another way,
62  *    no other mutex may be held when Giant is acquired.
63  *
64  * 2) Giant must be released when blocking on a sleepable lock.
65  *
66  * This rule is less obvious, but is a result of Giant providing the same
67  * semantics as spl().  Basically, when a thread sleeps, it must release
68  * Giant.  When a thread blocks on a sleepable lock, it sleeps.  Hence rule
69  * 2).
70  *
71  * 3) Giant may be acquired before or after sleepable locks.
72  *
73  * This rule is also not quite as obvious.  Giant may be acquired after
74  * a sleepable lock because it is a non-sleepable lock and non-sleepable
75  * locks may always be acquired while holding a sleepable lock.  The second
76  * case, Giant before a sleepable lock, follows from rule 2) above.  Suppose
77  * you have two threads T1 and T2 and a sleepable lock X.  Suppose that T1
78  * acquires X and blocks on Giant.  Then suppose that T2 acquires Giant and
79  * blocks on X.  When T2 blocks on X, T2 will release Giant allowing T1 to
80  * execute.  Thus, acquiring Giant both before and after a sleepable lock
81  * will not result in a lock order reversal.
82  */
83 
84 #include <sys/cdefs.h>
85 __FBSDID("$FreeBSD$");
86 
87 #include "opt_ddb.h"
88 #include "opt_witness.h"
89 
90 #include <sys/param.h>
91 #include <sys/bus.h>
92 #include <sys/kernel.h>
93 #include <sys/ktr.h>
94 #include <sys/lock.h>
95 #include <sys/malloc.h>
96 #include <sys/mutex.h>
97 #include <sys/proc.h>
98 #include <sys/sysctl.h>
99 #include <sys/systm.h>
100 
101 #include <ddb/ddb.h>
102 
103 #include <machine/stdarg.h>
104 
105 /* Define this to check for blessed mutexes */
106 #undef BLESSING
107 
108 #define WITNESS_COUNT 200
109 #define WITNESS_CHILDCOUNT (WITNESS_COUNT * 4)
110 /*
111  * XXX: This is somewhat bogus, as we assume here that at most 1024 threads
112  * will hold LOCK_NCHILDREN * 2 locks.  We handle failure ok, and we should
113  * probably be safe for the most part, but it's still a SWAG.
114  */
115 #define LOCK_CHILDCOUNT (MAXCPU + 1024) * 2
116 
117 #define	WITNESS_NCHILDREN 6
118 
119 struct witness_child_list_entry;
120 
121 struct witness {
122 	const	char *w_name;
123 	struct	lock_class *w_class;
124 	STAILQ_ENTRY(witness) w_list;		/* List of all witnesses. */
125 	STAILQ_ENTRY(witness) w_typelist;	/* Witnesses of a type. */
126 	struct	witness_child_list_entry *w_children;	/* Great evilness... */
127 	const	char *w_file;
128 	int	w_line;
129 	u_int	w_level;
130 	u_int	w_refcount;
131 	u_char	w_Giant_squawked:1;
132 	u_char	w_other_squawked:1;
133 	u_char	w_same_squawked:1;
134 	u_char	w_displayed:1;
135 };
136 
137 struct witness_child_list_entry {
138 	struct	witness_child_list_entry *wcl_next;
139 	struct	witness *wcl_children[WITNESS_NCHILDREN];
140 	u_int	wcl_count;
141 };
142 
143 STAILQ_HEAD(witness_list, witness);
144 
145 #ifdef BLESSING
146 struct witness_blessed {
147 	const	char *b_lock1;
148 	const	char *b_lock2;
149 };
150 #endif
151 
152 struct witness_order_list_entry {
153 	const	char *w_name;
154 	struct	lock_class *w_class;
155 };
156 
157 #ifdef BLESSING
158 static int	blessed(struct witness *, struct witness *);
159 #endif
160 static int	depart(struct witness *w);
161 static struct	witness *enroll(const char *description,
162 				struct lock_class *lock_class);
163 static int	insertchild(struct witness *parent, struct witness *child);
164 static int	isitmychild(struct witness *parent, struct witness *child);
165 static int	isitmydescendant(struct witness *parent, struct witness *child);
166 static int	itismychild(struct witness *parent, struct witness *child);
167 static int	rebalancetree(struct witness_list *list);
168 static void	removechild(struct witness *parent, struct witness *child);
169 static int	reparentchildren(struct witness *newparent,
170 		    struct witness *oldparent);
171 static int	sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
172 static void	witness_displaydescendants(void(*)(const char *fmt, ...),
173 					   struct witness *, int indent);
174 static const char *fixup_filename(const char *file);
175 static void	witness_leveldescendents(struct witness *parent, int level);
176 static void	witness_levelall(void);
177 static struct	witness *witness_get(void);
178 static void	witness_free(struct witness *m);
179 static struct	witness_child_list_entry *witness_child_get(void);
180 static void	witness_child_free(struct witness_child_list_entry *wcl);
181 static struct	lock_list_entry *witness_lock_list_get(void);
182 static void	witness_lock_list_free(struct lock_list_entry *lle);
183 static struct	lock_instance *find_instance(struct lock_list_entry *lock_list,
184 					     struct lock_object *lock);
185 static void	witness_list_lock(struct lock_instance *instance);
186 #ifdef DDB
187 static void	witness_list(struct thread *td);
188 static void	witness_display_list(void(*prnt)(const char *fmt, ...),
189 				     struct witness_list *list);
190 static void	witness_display(void(*)(const char *fmt, ...));
191 #endif
192 
193 MALLOC_DEFINE(M_WITNESS, "witness", "witness structure");
194 
195 /*
196  * If set to 0, witness is disabled.  If set to 1, witness performs full lock
197  * order checking for all locks.  If set to 2 or higher, then witness skips
198  * the full lock order check if the lock being acquired is at a higher level
199  * (i.e. farther down in the tree) than the current lock.  This last mode is
200  * somewhat experimental and not considered fully safe.  At runtime, this
201  * value may be set to 0 to turn off witness.  witness is not allowed be
202  * turned on once it is turned off, however.
203  */
204 static int witness_watch = 1;
205 TUNABLE_INT("debug.witness_watch", &witness_watch);
206 SYSCTL_PROC(_debug, OID_AUTO, witness_watch, CTLFLAG_RW | CTLTYPE_INT, NULL, 0,
207     sysctl_debug_witness_watch, "I", "witness is watching lock operations");
208 
209 #ifdef DDB
210 /*
211  * When DDB is enabled and witness_ddb is set to 1, it will cause the system to
212  * drop into kdebug() when:
213  *	- a lock heirarchy violation occurs
214  *	- locks are held when going to sleep.
215  */
216 #ifdef WITNESS_DDB
217 int	witness_ddb = 1;
218 #else
219 int	witness_ddb = 0;
220 #endif
221 TUNABLE_INT("debug.witness_ddb", &witness_ddb);
222 SYSCTL_INT(_debug, OID_AUTO, witness_ddb, CTLFLAG_RW, &witness_ddb, 0, "");
223 
224 /*
225  * When DDB is enabled and witness_trace is set to 1, it will cause the system
226  * to print a stack trace:
227  *	- a lock heirarchy violation occurs
228  *	- locks are held when going to sleep.
229  */
230 int	witness_trace = 1;
231 TUNABLE_INT("debug.witness_trace", &witness_trace);
232 SYSCTL_INT(_debug, OID_AUTO, witness_trace, CTLFLAG_RW, &witness_trace, 0, "");
233 #endif /* DDB */
234 
235 #ifdef WITNESS_SKIPSPIN
236 int	witness_skipspin = 1;
237 #else
238 int	witness_skipspin = 0;
239 #endif
240 TUNABLE_INT("debug.witness_skipspin", &witness_skipspin);
241 SYSCTL_INT(_debug, OID_AUTO, witness_skipspin, CTLFLAG_RD, &witness_skipspin, 0,
242     "");
243 
244 static struct mtx w_mtx;
245 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
246 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
247 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
248 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
249 static struct witness_child_list_entry *w_child_free = NULL;
250 static struct lock_list_entry *w_lock_list_free = NULL;
251 
252 static struct witness w_data[WITNESS_COUNT];
253 static struct witness_child_list_entry w_childdata[WITNESS_CHILDCOUNT];
254 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
255 
256 static struct witness_order_list_entry order_lists[] = {
257 	{ "proctree", &lock_class_sx },
258 	{ "allproc", &lock_class_sx },
259 	{ "Giant", &lock_class_mtx_sleep },
260 	{ "filedesc structure", &lock_class_mtx_sleep },
261 	{ "pipe mutex", &lock_class_mtx_sleep },
262 	{ "sigio lock", &lock_class_mtx_sleep },
263 	{ "process group", &lock_class_mtx_sleep },
264 	{ "process lock", &lock_class_mtx_sleep },
265 	{ "session", &lock_class_mtx_sleep },
266 	{ "uidinfo hash", &lock_class_mtx_sleep },
267 	{ "uidinfo struct", &lock_class_mtx_sleep },
268 	{ "allprison", &lock_class_mtx_sleep },
269 	{ NULL, NULL },
270 	/*
271 	 * spin locks
272 	 */
273 #ifdef SMP
274 	{ "ap boot", &lock_class_mtx_spin },
275 #ifdef __i386__
276 	{ "com", &lock_class_mtx_spin },
277 #endif
278 #endif
279 	{ "sio", &lock_class_mtx_spin },
280 #ifdef __i386__
281 	{ "cy", &lock_class_mtx_spin },
282 #endif
283 	{ "sabtty", &lock_class_mtx_spin },
284 	{ "zstty", &lock_class_mtx_spin },
285 	{ "ng_node", &lock_class_mtx_spin },
286 	{ "ng_worklist", &lock_class_mtx_spin },
287 	{ "ithread table lock", &lock_class_mtx_spin },
288 	{ "sched lock", &lock_class_mtx_spin },
289 	{ "callout", &lock_class_mtx_spin },
290 	/*
291 	 * leaf locks
292 	 */
293 	{ "allpmaps", &lock_class_mtx_spin },
294 	{ "vm page queue free mutex", &lock_class_mtx_spin },
295 	{ "icu", &lock_class_mtx_spin },
296 #ifdef SMP
297 	{ "smp rendezvous", &lock_class_mtx_spin },
298 #if defined(__i386__) && defined(APIC_IO)
299 	{ "tlb", &lock_class_mtx_spin },
300 #endif
301 #ifdef __i386__
302 	{ "lazypmap", &lock_class_mtx_spin },
303 #endif
304 #ifdef __sparc64__
305 	{ "ipi", &lock_class_mtx_spin },
306 #endif
307 #endif
308 	{ "clk", &lock_class_mtx_spin },
309 	{ "mutex profiling lock", &lock_class_mtx_spin },
310 	{ "kse zombie lock", &lock_class_mtx_spin },
311 	{ "ALD Queue", &lock_class_mtx_spin },
312 #ifdef __ia64__
313 	{ "MCA spin lock", &lock_class_mtx_spin },
314 #endif
315 #if defined(__i386__) || defined(__amd64__)
316 	{ "pcicfg", &lock_class_mtx_spin },
317 #endif
318 	{ NULL, NULL },
319 	{ NULL, NULL }
320 };
321 
322 #ifdef BLESSING
323 /*
324  * Pairs of locks which have been blessed
325  * Don't complain about order problems with blessed locks
326  */
327 static struct witness_blessed blessed_list[] = {
328 };
329 static int blessed_count =
330 	sizeof(blessed_list) / sizeof(struct witness_blessed);
331 #endif
332 
333 /*
334  * List of all locks in the system.
335  */
336 TAILQ_HEAD(, lock_object) all_locks = TAILQ_HEAD_INITIALIZER(all_locks);
337 
338 static struct mtx all_mtx = {
339 	{ &lock_class_mtx_sleep,	/* mtx_object.lo_class */
340 	  "All locks list",		/* mtx_object.lo_name */
341 	  "All locks list",		/* mtx_object.lo_type */
342 	  LO_INITIALIZED,		/* mtx_object.lo_flags */
343 	  { NULL, NULL },		/* mtx_object.lo_list */
344 	  NULL },			/* mtx_object.lo_witness */
345 	MTX_UNOWNED, 0,			/* mtx_lock, mtx_recurse */
346 	TAILQ_HEAD_INITIALIZER(all_mtx.mtx_blocked),
347 	{ NULL, NULL }			/* mtx_contested */
348 };
349 
350 /*
351  * This global is set to 0 once it becomes safe to use the witness code.
352  */
353 static int witness_cold = 1;
354 
355 /*
356  * Global variables for book keeping.
357  */
358 static int lock_cur_cnt;
359 static int lock_max_cnt;
360 
361 /*
362  * The WITNESS-enabled diagnostic code.
363  */
364 static void
365 witness_initialize(void *dummy __unused)
366 {
367 	struct lock_object *lock;
368 	struct witness_order_list_entry *order;
369 	struct witness *w, *w1;
370 	int i;
371 
372 	/*
373 	 * We have to release Giant before initializing its witness
374 	 * structure so that WITNESS doesn't get confused.
375 	 */
376 	mtx_unlock(&Giant);
377 	mtx_assert(&Giant, MA_NOTOWNED);
378 
379 	CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
380 	TAILQ_INSERT_HEAD(&all_locks, &all_mtx.mtx_object, lo_list);
381 	mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
382 	    MTX_NOWITNESS);
383 	for (i = 0; i < WITNESS_COUNT; i++)
384 		witness_free(&w_data[i]);
385 	for (i = 0; i < WITNESS_CHILDCOUNT; i++)
386 		witness_child_free(&w_childdata[i]);
387 	for (i = 0; i < LOCK_CHILDCOUNT; i++)
388 		witness_lock_list_free(&w_locklistdata[i]);
389 
390 	/* First add in all the specified order lists. */
391 	for (order = order_lists; order->w_name != NULL; order++) {
392 		w = enroll(order->w_name, order->w_class);
393 		if (w == NULL)
394 			continue;
395 		w->w_file = "order list";
396 		for (order++; order->w_name != NULL; order++) {
397 			w1 = enroll(order->w_name, order->w_class);
398 			if (w1 == NULL)
399 				continue;
400 			w1->w_file = "order list";
401 			if (!itismychild(w, w1))
402 				panic("Not enough memory for static orders!");
403 			w = w1;
404 		}
405 	}
406 
407 	/* Iterate through all locks and add them to witness. */
408 	mtx_lock(&all_mtx);
409 	TAILQ_FOREACH(lock, &all_locks, lo_list) {
410 		if (lock->lo_flags & LO_WITNESS)
411 			lock->lo_witness = enroll(lock->lo_type,
412 			    lock->lo_class);
413 		else
414 			lock->lo_witness = NULL;
415 	}
416 	mtx_unlock(&all_mtx);
417 
418 	/* Mark the witness code as being ready for use. */
419 	atomic_store_rel_int(&witness_cold, 0);
420 
421 	mtx_lock(&Giant);
422 }
423 SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize, NULL)
424 
425 static int
426 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
427 {
428 	int error, value;
429 
430 	value = witness_watch;
431 	error = sysctl_handle_int(oidp, &value, 0, req);
432 	if (error != 0 || req->newptr == NULL)
433 		return (error);
434 	error = suser(req->td);
435 	if (error != 0)
436 		return (error);
437 	if (value == witness_watch)
438 		return (0);
439 	if (value != 0)
440 		return (EINVAL);
441 	witness_watch = 0;
442 	return (0);
443 }
444 
445 void
446 witness_init(struct lock_object *lock)
447 {
448 	struct lock_class *class;
449 
450 	class = lock->lo_class;
451 	if (lock->lo_flags & LO_INITIALIZED)
452 		panic("%s: lock (%s) %s is already initialized", __func__,
453 		    class->lc_name, lock->lo_name);
454 	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
455 	    (class->lc_flags & LC_RECURSABLE) == 0)
456 		panic("%s: lock (%s) %s can not be recursable", __func__,
457 		    class->lc_name, lock->lo_name);
458 	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
459 	    (class->lc_flags & LC_SLEEPABLE) == 0)
460 		panic("%s: lock (%s) %s can not be sleepable", __func__,
461 		    class->lc_name, lock->lo_name);
462 	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
463 	    (class->lc_flags & LC_UPGRADABLE) == 0)
464 		panic("%s: lock (%s) %s can not be upgradable", __func__,
465 		    class->lc_name, lock->lo_name);
466 
467 	mtx_lock(&all_mtx);
468 	TAILQ_INSERT_TAIL(&all_locks, lock, lo_list);
469 	lock->lo_flags |= LO_INITIALIZED;
470 	lock_cur_cnt++;
471 	if (lock_cur_cnt > lock_max_cnt)
472 		lock_max_cnt = lock_cur_cnt;
473 	mtx_unlock(&all_mtx);
474 	if (!witness_cold && witness_watch != 0 && panicstr == NULL &&
475 	    (lock->lo_flags & LO_WITNESS) != 0)
476 		lock->lo_witness = enroll(lock->lo_type, class);
477 	else
478 		lock->lo_witness = NULL;
479 }
480 
481 void
482 witness_destroy(struct lock_object *lock)
483 {
484 	struct witness *w;
485 
486 	if (witness_cold)
487 		panic("lock (%s) %s destroyed while witness_cold",
488 		    lock->lo_class->lc_name, lock->lo_name);
489 	if ((lock->lo_flags & LO_INITIALIZED) == 0)
490 		panic("%s: lock (%s) %s is not initialized", __func__,
491 		    lock->lo_class->lc_name, lock->lo_name);
492 
493 	/* XXX: need to verify that no one holds the lock */
494 	w = lock->lo_witness;
495 	if (w != NULL) {
496 		mtx_lock_spin(&w_mtx);
497 		MPASS(w->w_refcount > 0);
498 		w->w_refcount--;
499 
500 		/*
501 		 * Lock is already released if we have an allocation failure
502 		 * and depart() fails.
503 		 */
504 		if (w->w_refcount != 0 || depart(w))
505 			mtx_unlock_spin(&w_mtx);
506 	}
507 
508 	mtx_lock(&all_mtx);
509 	lock_cur_cnt--;
510 	TAILQ_REMOVE(&all_locks, lock, lo_list);
511 	lock->lo_flags &= ~LO_INITIALIZED;
512 	mtx_unlock(&all_mtx);
513 }
514 
515 #ifdef DDB
516 static void
517 witness_display_list(void(*prnt)(const char *fmt, ...),
518 		     struct witness_list *list)
519 {
520 	struct witness *w;
521 
522 	STAILQ_FOREACH(w, list, w_typelist) {
523 		if (w->w_file == NULL || w->w_level > 0)
524 			continue;
525 		/*
526 		 * This lock has no anscestors, display its descendants.
527 		 */
528 		witness_displaydescendants(prnt, w, 0);
529 	}
530 }
531 
532 static void
533 witness_display(void(*prnt)(const char *fmt, ...))
534 {
535 	struct witness *w;
536 
537 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
538 	witness_levelall();
539 
540 	/* Clear all the displayed flags. */
541 	STAILQ_FOREACH(w, &w_all, w_list) {
542 		w->w_displayed = 0;
543 	}
544 
545 	/*
546 	 * First, handle sleep locks which have been acquired at least
547 	 * once.
548 	 */
549 	prnt("Sleep locks:\n");
550 	witness_display_list(prnt, &w_sleep);
551 
552 	/*
553 	 * Now do spin locks which have been acquired at least once.
554 	 */
555 	prnt("\nSpin locks:\n");
556 	witness_display_list(prnt, &w_spin);
557 
558 	/*
559 	 * Finally, any locks which have not been acquired yet.
560 	 */
561 	prnt("\nLocks which were never acquired:\n");
562 	STAILQ_FOREACH(w, &w_all, w_list) {
563 		if (w->w_file != NULL || w->w_refcount == 0)
564 			continue;
565 		prnt("%s\n", w->w_name);
566 	}
567 }
568 #endif /* DDB */
569 
570 /* Trim useless garbage from filenames. */
571 static const char *
572 fixup_filename(const char *file)
573 {
574 
575 	if (file == NULL)
576 		return (NULL);
577 	while (strncmp(file, "../", 3) == 0)
578 		file += 3;
579 	return (file);
580 }
581 
582 void
583 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
584 {
585 	struct lock_list_entry **lock_list, *lle;
586 	struct lock_instance *lock1, *lock2;
587 	struct lock_class *class;
588 	struct witness *w, *w1;
589 	struct thread *td;
590 	int i, j;
591 #ifdef DDB
592 	int go_into_ddb = 0;
593 #endif
594 
595 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
596 	    panicstr != NULL)
597 		return;
598 	w = lock->lo_witness;
599 	class = lock->lo_class;
600 	td = curthread;
601 	file = fixup_filename(file);
602 
603 	if (class->lc_flags & LC_SLEEPLOCK) {
604 		/*
605 		 * Since spin locks include a critical section, this check
606 		 * impliclty enforces a lock order of all sleep locks before
607 		 * all spin locks.
608 		 */
609 		if (td->td_critnest != 0 && (flags & LOP_TRYLOCK) == 0)
610 			panic("blockable sleep lock (%s) %s @ %s:%d",
611 			    class->lc_name, lock->lo_name, file, line);
612 		lock_list = &td->td_sleeplocks;
613 	} else
614 		lock_list = PCPU_PTR(spinlocks);
615 
616 	/*
617 	 * Is this the first lock acquired?  If so, then no order checking
618 	 * is needed.
619 	 */
620 	if (*lock_list == NULL)
621 		goto out;
622 
623 	/*
624 	 * Check to see if we are recursing on a lock we already own.
625 	 */
626 	lock1 = find_instance(*lock_list, lock);
627 	if (lock1 != NULL) {
628 		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
629 		    (flags & LOP_EXCLUSIVE) == 0) {
630 			printf("shared lock of (%s) %s @ %s:%d\n",
631 			    class->lc_name, lock->lo_name, file, line);
632 			printf("while exclusively locked from %s:%d\n",
633 			    lock1->li_file, lock1->li_line);
634 			panic("share->excl");
635 		}
636 		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
637 		    (flags & LOP_EXCLUSIVE) != 0) {
638 			printf("exclusive lock of (%s) %s @ %s:%d\n",
639 			    class->lc_name, lock->lo_name, file, line);
640 			printf("while share locked from %s:%d\n",
641 			    lock1->li_file, lock1->li_line);
642 			panic("excl->share");
643 		}
644 		lock1->li_flags++;
645 		if ((lock->lo_flags & LO_RECURSABLE) == 0) {
646 			printf(
647 			"recursed on non-recursive lock (%s) %s @ %s:%d\n",
648 			    class->lc_name, lock->lo_name, file, line);
649 			printf("first acquired @ %s:%d\n", lock1->li_file,
650 			    lock1->li_line);
651 			panic("recurse");
652 		}
653 		CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
654 		    td->td_proc->p_pid, lock->lo_name,
655 		    lock1->li_flags & LI_RECURSEMASK);
656 		lock1->li_file = file;
657 		lock1->li_line = line;
658 		return;
659 	}
660 
661 	/*
662 	 * Try locks do not block if they fail to acquire the lock, thus
663 	 * there is no danger of deadlocks or of switching while holding a
664 	 * spin lock if we acquire a lock via a try operation.
665 	 */
666 	if (flags & LOP_TRYLOCK)
667 		goto out;
668 
669 	/*
670 	 * Check for duplicate locks of the same type.  Note that we only
671 	 * have to check for this on the last lock we just acquired.  Any
672 	 * other cases will be caught as lock order violations.
673 	 */
674 	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
675 	w1 = lock1->li_lock->lo_witness;
676 	if (w1 == w) {
677 		if (w->w_same_squawked || (lock->lo_flags & LO_DUPOK))
678 			goto out;
679 		w->w_same_squawked = 1;
680 		printf("acquiring duplicate lock of same type: \"%s\"\n",
681 			lock->lo_type);
682 		printf(" 1st %s @ %s:%d\n", lock1->li_lock->lo_name,
683 		    lock1->li_file, lock1->li_line);
684 		printf(" 2nd %s @ %s:%d\n", lock->lo_name, file, line);
685 #ifdef DDB
686 		go_into_ddb = 1;
687 #endif
688 		goto out;
689 	}
690 	MPASS(!mtx_owned(&w_mtx));
691 	mtx_lock_spin(&w_mtx);
692 	/*
693 	 * If we have a known higher number just say ok
694 	 */
695 	if (witness_watch > 1 && w->w_level > w1->w_level) {
696 		mtx_unlock_spin(&w_mtx);
697 		goto out;
698 	}
699 	/*
700 	 * If we know that the the lock we are acquiring comes after
701 	 * the lock we most recently acquired in the lock order tree,
702 	 * then there is no need for any further checks.
703 	 */
704 	if (isitmydescendant(w1, w)) {
705 		mtx_unlock_spin(&w_mtx);
706 		goto out;
707 	}
708 	for (j = 0, lle = *lock_list; lle != NULL; lle = lle->ll_next) {
709 		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
710 
711 			MPASS(j < WITNESS_COUNT);
712 			lock1 = &lle->ll_children[i];
713 			w1 = lock1->li_lock->lo_witness;
714 
715 			/*
716 			 * If this lock doesn't undergo witness checking,
717 			 * then skip it.
718 			 */
719 			if (w1 == NULL) {
720 				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
721 				    ("lock missing witness structure"));
722 				continue;
723 			}
724 			/*
725 			 * If we are locking Giant and this is a sleepable
726 			 * lock, then skip it.
727 			 */
728 			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
729 			    lock == &Giant.mtx_object)
730 				continue;
731 			/*
732 			 * If we are locking a sleepable lock and this lock
733 			 * is Giant, then skip it.
734 			 */
735 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
736 			    lock1->li_lock == &Giant.mtx_object)
737 				continue;
738 			/*
739 			 * If we are locking a sleepable lock and this lock
740 			 * isn't sleepable, we want to treat it as a lock
741 			 * order violation to enfore a general lock order of
742 			 * sleepable locks before non-sleepable locks.
743 			 */
744 			if (!((lock->lo_flags & LO_SLEEPABLE) != 0 &&
745 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
746 			    /*
747 			     * Check the lock order hierarchy for a reveresal.
748 			     */
749 			    if (!isitmydescendant(w, w1))
750 				continue;
751 			/*
752 			 * We have a lock order violation, check to see if it
753 			 * is allowed or has already been yelled about.
754 			 */
755 			mtx_unlock_spin(&w_mtx);
756 #ifdef BLESSING
757 			if (blessed(w, w1))
758 				goto out;
759 #endif
760 			if (lock1->li_lock == &Giant.mtx_object) {
761 				if (w1->w_Giant_squawked)
762 					goto out;
763 				else
764 					w1->w_Giant_squawked = 1;
765 			} else {
766 				if (w1->w_other_squawked)
767 					goto out;
768 				else
769 					w1->w_other_squawked = 1;
770 			}
771 			/*
772 			 * Ok, yell about it.
773 			 */
774 			printf("lock order reversal\n");
775 			/*
776 			 * Try to locate an earlier lock with
777 			 * witness w in our list.
778 			 */
779 			do {
780 				lock2 = &lle->ll_children[i];
781 				MPASS(lock2->li_lock != NULL);
782 				if (lock2->li_lock->lo_witness == w)
783 					break;
784 				i--;
785 				if (i == 0 && lle->ll_next != NULL) {
786 					lle = lle->ll_next;
787 					i = lle->ll_count - 1;
788 					MPASS(i >= 0 && i < LOCK_NCHILDREN);
789 				}
790 			} while (i >= 0);
791 			if (i < 0) {
792 				printf(" 1st %p %s (%s) @ %s:%d\n",
793 				    lock1->li_lock, lock1->li_lock->lo_name,
794 				    lock1->li_lock->lo_type, lock1->li_file,
795 				    lock1->li_line);
796 				printf(" 2nd %p %s (%s) @ %s:%d\n", lock,
797 				    lock->lo_name, lock->lo_type, file, line);
798 			} else {
799 				printf(" 1st %p %s (%s) @ %s:%d\n",
800 				    lock2->li_lock, lock2->li_lock->lo_name,
801 				    lock2->li_lock->lo_type, lock2->li_file,
802 				    lock2->li_line);
803 				printf(" 2nd %p %s (%s) @ %s:%d\n",
804 				    lock1->li_lock, lock1->li_lock->lo_name,
805 				    lock1->li_lock->lo_type, lock1->li_file,
806 				    lock1->li_line);
807 				printf(" 3rd %p %s (%s) @ %s:%d\n", lock,
808 				    lock->lo_name, lock->lo_type, file, line);
809 			}
810 #ifdef DDB
811 			go_into_ddb = 1;
812 #endif
813 			goto out;
814 		}
815 	}
816 	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
817 	/*
818 	 * Don't build a new relationship between a sleepable lock and
819 	 * Giant if it is the wrong direction.  The real lock order is that
820 	 * sleepable locks come before Giant.
821 	 */
822 	if (!(lock1->li_lock == &Giant.mtx_object &&
823 	    (lock->lo_flags & LO_SLEEPABLE) != 0)) {
824 		CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
825 		    lock->lo_type, lock1->li_lock->lo_type);
826 		if (!itismychild(lock1->li_lock->lo_witness, w))
827 			/* Witness is dead. */
828 			return;
829 	}
830 	mtx_unlock_spin(&w_mtx);
831 
832 out:
833 #ifdef DDB
834 	if (go_into_ddb) {
835 		if (witness_trace)
836 			backtrace();
837 		if (witness_ddb)
838 			Debugger(__func__);
839 	}
840 #endif
841 	w->w_file = file;
842 	w->w_line = line;
843 
844 	lle = *lock_list;
845 	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
846 		lle = witness_lock_list_get();
847 		if (lle == NULL)
848 			return;
849 		lle->ll_next = *lock_list;
850 		CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
851 		    td->td_proc->p_pid, lle);
852 		*lock_list = lle;
853 	}
854 	lock1 = &lle->ll_children[lle->ll_count++];
855 	lock1->li_lock = lock;
856 	lock1->li_line = line;
857 	lock1->li_file = file;
858 	if ((flags & LOP_EXCLUSIVE) != 0)
859 		lock1->li_flags = LI_EXCLUSIVE;
860 	else
861 		lock1->li_flags = 0;
862 	CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
863 	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
864 }
865 
866 void
867 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
868 {
869 	struct lock_instance *instance;
870 	struct lock_class *class;
871 
872 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
873 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
874 		return;
875 	class = lock->lo_class;
876 	file = fixup_filename(file);
877 	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
878 		panic("upgrade of non-upgradable lock (%s) %s @ %s:%d",
879 		    class->lc_name, lock->lo_name, file, line);
880 	if ((flags & LOP_TRYLOCK) == 0)
881 		panic("non-try upgrade of lock (%s) %s @ %s:%d", class->lc_name,
882 		    lock->lo_name, file, line);
883 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
884 		panic("upgrade of non-sleep lock (%s) %s @ %s:%d",
885 		    class->lc_name, lock->lo_name, file, line);
886 	instance = find_instance(curthread->td_sleeplocks, lock);
887 	if (instance == NULL)
888 		panic("upgrade of unlocked lock (%s) %s @ %s:%d",
889 		    class->lc_name, lock->lo_name, file, line);
890 	if ((instance->li_flags & LI_EXCLUSIVE) != 0)
891 		panic("upgrade of exclusive lock (%s) %s @ %s:%d",
892 		    class->lc_name, lock->lo_name, file, line);
893 	if ((instance->li_flags & LI_RECURSEMASK) != 0)
894 		panic("upgrade of recursed lock (%s) %s r=%d @ %s:%d",
895 		    class->lc_name, lock->lo_name,
896 		    instance->li_flags & LI_RECURSEMASK, file, line);
897 	instance->li_flags |= LI_EXCLUSIVE;
898 }
899 
900 void
901 witness_downgrade(struct lock_object *lock, int flags, const char *file,
902     int line)
903 {
904 	struct lock_instance *instance;
905 	struct lock_class *class;
906 
907 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
908 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
909 		return;
910 	class = lock->lo_class;
911 	file = fixup_filename(file);
912 	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
913 		panic("downgrade of non-upgradable lock (%s) %s @ %s:%d",
914 		    class->lc_name, lock->lo_name, file, line);
915 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
916 		panic("downgrade of non-sleep lock (%s) %s @ %s:%d",
917 		    class->lc_name, lock->lo_name, file, line);
918 	instance = find_instance(curthread->td_sleeplocks, lock);
919 	if (instance == NULL)
920 		panic("downgrade of unlocked lock (%s) %s @ %s:%d",
921 		    class->lc_name, lock->lo_name, file, line);
922 	if ((instance->li_flags & LI_EXCLUSIVE) == 0)
923 		panic("downgrade of shared lock (%s) %s @ %s:%d",
924 		    class->lc_name, lock->lo_name, file, line);
925 	if ((instance->li_flags & LI_RECURSEMASK) != 0)
926 		panic("downgrade of recursed lock (%s) %s r=%d @ %s:%d",
927 		    class->lc_name, lock->lo_name,
928 		    instance->li_flags & LI_RECURSEMASK, file, line);
929 	instance->li_flags &= ~LI_EXCLUSIVE;
930 }
931 
932 void
933 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
934 {
935 	struct lock_list_entry **lock_list, *lle;
936 	struct lock_instance *instance;
937 	struct lock_class *class;
938 	struct thread *td;
939 	register_t s;
940 	int i, j;
941 
942 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
943 	    panicstr != NULL)
944 		return;
945 	td = curthread;
946 	class = lock->lo_class;
947 	file = fixup_filename(file);
948 	if (class->lc_flags & LC_SLEEPLOCK)
949 		lock_list = &td->td_sleeplocks;
950 	else
951 		lock_list = PCPU_PTR(spinlocks);
952 	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
953 		for (i = 0; i < (*lock_list)->ll_count; i++) {
954 			instance = &(*lock_list)->ll_children[i];
955 			if (instance->li_lock == lock) {
956 				if ((instance->li_flags & LI_EXCLUSIVE) != 0 &&
957 				    (flags & LOP_EXCLUSIVE) == 0) {
958 					printf(
959 					"shared unlock of (%s) %s @ %s:%d\n",
960 					    class->lc_name, lock->lo_name,
961 					    file, line);
962 					printf(
963 					"while exclusively locked from %s:%d\n",
964 					    instance->li_file,
965 					    instance->li_line);
966 					panic("excl->ushare");
967 				}
968 				if ((instance->li_flags & LI_EXCLUSIVE) == 0 &&
969 				    (flags & LOP_EXCLUSIVE) != 0) {
970 					printf(
971 					"exclusive unlock of (%s) %s @ %s:%d\n",
972 					    class->lc_name, lock->lo_name,
973 					    file, line);
974 					printf(
975 					"while share locked from %s:%d\n",
976 					    instance->li_file,
977 					    instance->li_line);
978 					panic("share->uexcl");
979 				}
980 				/* If we are recursed, unrecurse. */
981 				if ((instance->li_flags & LI_RECURSEMASK) > 0) {
982 					CTR4(KTR_WITNESS,
983 				    "%s: pid %d unrecursed on %s r=%d", __func__,
984 					    td->td_proc->p_pid,
985 					    instance->li_lock->lo_name,
986 					    instance->li_flags);
987 					instance->li_flags--;
988 					return;
989 				}
990 				s = intr_disable();
991 				CTR4(KTR_WITNESS,
992 				    "%s: pid %d removed %s from lle[%d]", __func__,
993 				    td->td_proc->p_pid,
994 				    instance->li_lock->lo_name,
995 				    (*lock_list)->ll_count - 1);
996 				for (j = i; j < (*lock_list)->ll_count - 1; j++)
997 					(*lock_list)->ll_children[j] =
998 					    (*lock_list)->ll_children[j + 1];
999 				(*lock_list)->ll_count--;
1000 				intr_restore(s);
1001 				if ((*lock_list)->ll_count == 0) {
1002 					lle = *lock_list;
1003 					*lock_list = lle->ll_next;
1004 					CTR3(KTR_WITNESS,
1005 					    "%s: pid %d removed lle %p", __func__,
1006 					    td->td_proc->p_pid, lle);
1007 					witness_lock_list_free(lle);
1008 				}
1009 				return;
1010 			}
1011 		}
1012 	panic("lock (%s) %s not locked @ %s:%d", class->lc_name, lock->lo_name,
1013 	    file, line);
1014 }
1015 
1016 /*
1017  * Warn if any locks other than 'lock' are held.  Flags can be passed in to
1018  * exempt Giant and sleepable locks from the checks as well.  If any
1019  * non-exempt locks are held, then a supplied message is printed to the
1020  * console along with a list of the offending locks.  If indicated in the
1021  * flags then a failure results in a panic as well.
1022  */
1023 int
1024 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1025 {
1026 	struct lock_list_entry *lle;
1027 	struct lock_instance *lock1;
1028 	struct thread *td;
1029 	va_list ap;
1030 	int i, n;
1031 
1032 	if (witness_cold || witness_watch == 0 || panicstr != NULL)
1033 		return (0);
1034 	n = 0;
1035 	td = curthread;
1036 	for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1037 		for (i = lle->ll_count - 1; i >= 0; i--) {
1038 			lock1 = &lle->ll_children[i];
1039 			if (lock1->li_lock == lock)
1040 				continue;
1041 			if (flags & WARN_GIANTOK &&
1042 			    lock1->li_lock == &Giant.mtx_object)
1043 				continue;
1044 			if (flags & WARN_SLEEPOK &&
1045 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1046 				continue;
1047 			if (n == 0) {
1048 				va_start(ap, fmt);
1049 				vprintf(fmt, ap);
1050 				va_end(ap);
1051 				printf(" with the following");
1052 				if (flags & WARN_SLEEPOK)
1053 					printf(" non-sleepable");
1054 				printf(" locks held:\n");
1055 			}
1056 			n++;
1057 			witness_list_lock(lock1);
1058 		}
1059 	if (PCPU_GET(spinlocks) != NULL) {
1060 		/*
1061 		 * Since we already hold a spinlock preemption is
1062 		 * already blocked.
1063 		 */
1064 		if (n == 0) {
1065 			va_start(ap, fmt);
1066 			vprintf(fmt, ap);
1067 			va_end(ap);
1068 			printf(" with the following");
1069 			if (flags & WARN_SLEEPOK)
1070 				printf(" non-sleepable");
1071 			printf(" locks held:\n");
1072 		}
1073 		n += witness_list_locks(PCPU_PTR(spinlocks));
1074 	}
1075 	if (flags & WARN_PANIC && n)
1076 		panic("witness_warn");
1077 #ifdef DDB
1078 	else if (witness_ddb && n)
1079 		Debugger(__func__);
1080 #endif
1081 	return (n);
1082 }
1083 
1084 const char *
1085 witness_file(struct lock_object *lock)
1086 {
1087 	struct witness *w;
1088 
1089 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1090 		return ("?");
1091 	w = lock->lo_witness;
1092 	return (w->w_file);
1093 }
1094 
1095 int
1096 witness_line(struct lock_object *lock)
1097 {
1098 	struct witness *w;
1099 
1100 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1101 		return (0);
1102 	w = lock->lo_witness;
1103 	return (w->w_line);
1104 }
1105 
1106 static struct witness *
1107 enroll(const char *description, struct lock_class *lock_class)
1108 {
1109 	struct witness *w;
1110 
1111 	if (!witness_watch || witness_watch == 0 || panicstr != NULL)
1112 		return (NULL);
1113 	if ((lock_class->lc_flags & LC_SPINLOCK) && witness_skipspin)
1114 		return (NULL);
1115 	mtx_lock_spin(&w_mtx);
1116 	STAILQ_FOREACH(w, &w_all, w_list) {
1117 		if (w->w_name == description || (w->w_refcount > 0 &&
1118 		    strcmp(description, w->w_name) == 0)) {
1119 			w->w_refcount++;
1120 			mtx_unlock_spin(&w_mtx);
1121 			if (lock_class != w->w_class)
1122 				panic(
1123 				"lock (%s) %s does not match earlier (%s) lock",
1124 				    description, lock_class->lc_name,
1125 				    w->w_class->lc_name);
1126 			return (w);
1127 		}
1128 	}
1129 	/*
1130 	 * This isn't quite right, as witness_cold is still 0 while we
1131 	 * enroll all the locks initialized before witness_initialize().
1132 	 */
1133 	if ((lock_class->lc_flags & LC_SPINLOCK) && !witness_cold) {
1134 		mtx_unlock_spin(&w_mtx);
1135 		panic("spin lock %s not in order list", description);
1136 	}
1137 	if ((w = witness_get()) == NULL)
1138 		return (NULL);
1139 	w->w_name = description;
1140 	w->w_class = lock_class;
1141 	w->w_refcount = 1;
1142 	STAILQ_INSERT_HEAD(&w_all, w, w_list);
1143 	if (lock_class->lc_flags & LC_SPINLOCK)
1144 		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1145 	else if (lock_class->lc_flags & LC_SLEEPLOCK)
1146 		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1147 	else {
1148 		mtx_unlock_spin(&w_mtx);
1149 		panic("lock class %s is not sleep or spin",
1150 		    lock_class->lc_name);
1151 	}
1152 	mtx_unlock_spin(&w_mtx);
1153 	return (w);
1154 }
1155 
1156 /* Don't let the door bang you on the way out... */
1157 static int
1158 depart(struct witness *w)
1159 {
1160 	struct witness_child_list_entry *wcl, *nwcl;
1161 	struct witness_list *list;
1162 	struct witness *parent;
1163 
1164 	MPASS(w->w_refcount == 0);
1165 	if (w->w_class->lc_flags & LC_SLEEPLOCK)
1166 		list = &w_sleep;
1167 	else
1168 		list = &w_spin;
1169 	/*
1170 	 * First, we run through the entire tree looking for any
1171 	 * witnesses that the outgoing witness is a child of.  For
1172 	 * each parent that we find, we reparent all the direct
1173 	 * children of the outgoing witness to its parent.
1174 	 */
1175 	STAILQ_FOREACH(parent, list, w_typelist) {
1176 		if (!isitmychild(parent, w))
1177 			continue;
1178 		removechild(parent, w);
1179 		if (!reparentchildren(parent, w))
1180 			return (0);
1181 	}
1182 
1183 	/*
1184 	 * Now we go through and free up the child list of the
1185 	 * outgoing witness.
1186 	 */
1187 	for (wcl = w->w_children; wcl != NULL; wcl = nwcl) {
1188 		nwcl = wcl->wcl_next;
1189 		witness_child_free(wcl);
1190 	}
1191 
1192 	/*
1193 	 * Detach from various lists and free.
1194 	 */
1195 	STAILQ_REMOVE(list, w, witness, w_typelist);
1196 	STAILQ_REMOVE(&w_all, w, witness, w_list);
1197 	witness_free(w);
1198 
1199 	/* Finally, fixup the tree. */
1200 	return (rebalancetree(list));
1201 }
1202 
1203 /*
1204  * Prune an entire lock order tree.  We look for cases where a lock
1205  * is now both a descendant and a direct child of a given lock.  In
1206  * that case, we want to remove the direct child link from the tree.
1207  *
1208  * Returns false if insertchild() fails.
1209  */
1210 static int
1211 rebalancetree(struct witness_list *list)
1212 {
1213 	struct witness *child, *parent;
1214 
1215 	STAILQ_FOREACH(child, list, w_typelist) {
1216 		STAILQ_FOREACH(parent, list, w_typelist) {
1217 			if (!isitmychild(parent, child))
1218 				continue;
1219 			removechild(parent, child);
1220 			if (isitmydescendant(parent, child))
1221 				continue;
1222 			if (!insertchild(parent, child))
1223 				return (0);
1224 		}
1225 	}
1226 	witness_levelall();
1227 	return (1);
1228 }
1229 
1230 /*
1231  * Add "child" as a direct child of "parent".  Returns false if
1232  * we fail due to out of memory.
1233  */
1234 static int
1235 insertchild(struct witness *parent, struct witness *child)
1236 {
1237 	struct witness_child_list_entry **wcl;
1238 
1239 	MPASS(child != NULL && parent != NULL);
1240 
1241 	/*
1242 	 * Insert "child" after "parent"
1243 	 */
1244 	wcl = &parent->w_children;
1245 	while (*wcl != NULL && (*wcl)->wcl_count == WITNESS_NCHILDREN)
1246 		wcl = &(*wcl)->wcl_next;
1247 	if (*wcl == NULL) {
1248 		*wcl = witness_child_get();
1249 		if (*wcl == NULL)
1250 			return (0);
1251 	}
1252 	(*wcl)->wcl_children[(*wcl)->wcl_count++] = child;
1253 
1254 	return (1);
1255 }
1256 
1257 /*
1258  * Make all the direct descendants of oldparent be direct descendants
1259  * of newparent.
1260  */
1261 static int
1262 reparentchildren(struct witness *newparent, struct witness *oldparent)
1263 {
1264 	struct witness_child_list_entry *wcl;
1265 	int i;
1266 
1267 	/* Avoid making a witness a child of itself. */
1268 	MPASS(!isitmychild(oldparent, newparent));
1269 
1270 	for (wcl = oldparent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1271 		for (i = 0; i < wcl->wcl_count; i++)
1272 			if (!insertchild(newparent, wcl->wcl_children[i]))
1273 				return (0);
1274 	return (1);
1275 }
1276 
1277 static int
1278 itismychild(struct witness *parent, struct witness *child)
1279 {
1280 	struct witness_list *list;
1281 
1282 	MPASS(child != NULL && parent != NULL);
1283 	if ((parent->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) !=
1284 	    (child->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)))
1285 		panic(
1286 		"%s: parent (%s) and child (%s) are not the same lock type",
1287 		    __func__, parent->w_class->lc_name,
1288 		    child->w_class->lc_name);
1289 
1290 	if (!insertchild(parent, child))
1291 		return (0);
1292 
1293 	if (parent->w_class->lc_flags & LC_SLEEPLOCK)
1294 		list = &w_sleep;
1295 	else
1296 		list = &w_spin;
1297 	return (rebalancetree(list));
1298 }
1299 
1300 static void
1301 removechild(struct witness *parent, struct witness *child)
1302 {
1303 	struct witness_child_list_entry **wcl, *wcl1;
1304 	int i;
1305 
1306 	for (wcl = &parent->w_children; *wcl != NULL; wcl = &(*wcl)->wcl_next)
1307 		for (i = 0; i < (*wcl)->wcl_count; i++)
1308 			if ((*wcl)->wcl_children[i] == child)
1309 				goto found;
1310 	return;
1311 found:
1312 	(*wcl)->wcl_count--;
1313 	if ((*wcl)->wcl_count > i)
1314 		(*wcl)->wcl_children[i] =
1315 		    (*wcl)->wcl_children[(*wcl)->wcl_count];
1316 	MPASS((*wcl)->wcl_children[i] != NULL);
1317 	if ((*wcl)->wcl_count != 0)
1318 		return;
1319 	wcl1 = *wcl;
1320 	*wcl = wcl1->wcl_next;
1321 	witness_child_free(wcl1);
1322 }
1323 
1324 static int
1325 isitmychild(struct witness *parent, struct witness *child)
1326 {
1327 	struct witness_child_list_entry *wcl;
1328 	int i;
1329 
1330 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1331 		for (i = 0; i < wcl->wcl_count; i++) {
1332 			if (wcl->wcl_children[i] == child)
1333 				return (1);
1334 		}
1335 	}
1336 	return (0);
1337 }
1338 
1339 static int
1340 isitmydescendant(struct witness *parent, struct witness *child)
1341 {
1342 	struct witness_child_list_entry *wcl;
1343 	int i, j;
1344 
1345 	if (isitmychild(parent, child))
1346 		return (1);
1347 	j = 0;
1348 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1349 		MPASS(j < 1000);
1350 		for (i = 0; i < wcl->wcl_count; i++) {
1351 			if (isitmydescendant(wcl->wcl_children[i], child))
1352 				return (1);
1353 		}
1354 		j++;
1355 	}
1356 	return (0);
1357 }
1358 
1359 static void
1360 witness_levelall (void)
1361 {
1362 	struct witness_list *list;
1363 	struct witness *w, *w1;
1364 
1365 	/*
1366 	 * First clear all levels.
1367 	 */
1368 	STAILQ_FOREACH(w, &w_all, w_list) {
1369 		w->w_level = 0;
1370 	}
1371 
1372 	/*
1373 	 * Look for locks with no parent and level all their descendants.
1374 	 */
1375 	STAILQ_FOREACH(w, &w_all, w_list) {
1376 		/*
1377 		 * This is just an optimization, technically we could get
1378 		 * away just walking the all list each time.
1379 		 */
1380 		if (w->w_class->lc_flags & LC_SLEEPLOCK)
1381 			list = &w_sleep;
1382 		else
1383 			list = &w_spin;
1384 		STAILQ_FOREACH(w1, list, w_typelist) {
1385 			if (isitmychild(w1, w))
1386 				goto skip;
1387 		}
1388 		witness_leveldescendents(w, 0);
1389 	skip:
1390 		;	/* silence GCC 3.x */
1391 	}
1392 }
1393 
1394 static void
1395 witness_leveldescendents(struct witness *parent, int level)
1396 {
1397 	struct witness_child_list_entry *wcl;
1398 	int i;
1399 
1400 	if (parent->w_level < level)
1401 		parent->w_level = level;
1402 	level++;
1403 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1404 		for (i = 0; i < wcl->wcl_count; i++)
1405 			witness_leveldescendents(wcl->wcl_children[i], level);
1406 }
1407 
1408 static void
1409 witness_displaydescendants(void(*prnt)(const char *fmt, ...),
1410 			   struct witness *parent, int indent)
1411 {
1412 	struct witness_child_list_entry *wcl;
1413 	int i, level;
1414 
1415 	level = parent->w_level;
1416 	prnt("%-2d", level);
1417 	for (i = 0; i < indent; i++)
1418 		prnt(" ");
1419 	if (parent->w_refcount > 0)
1420 		prnt("%s", parent->w_name);
1421 	else
1422 		prnt("(dead)");
1423 	if (parent->w_displayed) {
1424 		prnt(" -- (already displayed)\n");
1425 		return;
1426 	}
1427 	parent->w_displayed = 1;
1428 	if (parent->w_refcount > 0) {
1429 		if (parent->w_file != NULL)
1430 			prnt(" -- last acquired @ %s:%d", parent->w_file,
1431 			    parent->w_line);
1432 	}
1433 	prnt("\n");
1434 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1435 		for (i = 0; i < wcl->wcl_count; i++)
1436 			    witness_displaydescendants(prnt,
1437 				wcl->wcl_children[i], indent + 1);
1438 }
1439 
1440 #ifdef BLESSING
1441 static int
1442 blessed(struct witness *w1, struct witness *w2)
1443 {
1444 	int i;
1445 	struct witness_blessed *b;
1446 
1447 	for (i = 0; i < blessed_count; i++) {
1448 		b = &blessed_list[i];
1449 		if (strcmp(w1->w_name, b->b_lock1) == 0) {
1450 			if (strcmp(w2->w_name, b->b_lock2) == 0)
1451 				return (1);
1452 			continue;
1453 		}
1454 		if (strcmp(w1->w_name, b->b_lock2) == 0)
1455 			if (strcmp(w2->w_name, b->b_lock1) == 0)
1456 				return (1);
1457 	}
1458 	return (0);
1459 }
1460 #endif
1461 
1462 static struct witness *
1463 witness_get(void)
1464 {
1465 	struct witness *w;
1466 
1467 	if (witness_watch == 0) {
1468 		mtx_unlock_spin(&w_mtx);
1469 		return (NULL);
1470 	}
1471 	if (STAILQ_EMPTY(&w_free)) {
1472 		witness_watch = 0;
1473 		mtx_unlock_spin(&w_mtx);
1474 		printf("%s: witness exhausted\n", __func__);
1475 		return (NULL);
1476 	}
1477 	w = STAILQ_FIRST(&w_free);
1478 	STAILQ_REMOVE_HEAD(&w_free, w_list);
1479 	bzero(w, sizeof(*w));
1480 	return (w);
1481 }
1482 
1483 static void
1484 witness_free(struct witness *w)
1485 {
1486 
1487 	STAILQ_INSERT_HEAD(&w_free, w, w_list);
1488 }
1489 
1490 static struct witness_child_list_entry *
1491 witness_child_get(void)
1492 {
1493 	struct witness_child_list_entry *wcl;
1494 
1495 	if (witness_watch == 0) {
1496 		mtx_unlock_spin(&w_mtx);
1497 		return (NULL);
1498 	}
1499 	wcl = w_child_free;
1500 	if (wcl == NULL) {
1501 		witness_watch = 0;
1502 		mtx_unlock_spin(&w_mtx);
1503 		printf("%s: witness exhausted\n", __func__);
1504 		return (NULL);
1505 	}
1506 	w_child_free = wcl->wcl_next;
1507 	bzero(wcl, sizeof(*wcl));
1508 	return (wcl);
1509 }
1510 
1511 static void
1512 witness_child_free(struct witness_child_list_entry *wcl)
1513 {
1514 
1515 	wcl->wcl_next = w_child_free;
1516 	w_child_free = wcl;
1517 }
1518 
1519 static struct lock_list_entry *
1520 witness_lock_list_get(void)
1521 {
1522 	struct lock_list_entry *lle;
1523 
1524 	if (witness_watch == 0)
1525 		return (NULL);
1526 	mtx_lock_spin(&w_mtx);
1527 	lle = w_lock_list_free;
1528 	if (lle == NULL) {
1529 		witness_watch = 0;
1530 		mtx_unlock_spin(&w_mtx);
1531 		printf("%s: witness exhausted\n", __func__);
1532 		return (NULL);
1533 	}
1534 	w_lock_list_free = lle->ll_next;
1535 	mtx_unlock_spin(&w_mtx);
1536 	bzero(lle, sizeof(*lle));
1537 	return (lle);
1538 }
1539 
1540 static void
1541 witness_lock_list_free(struct lock_list_entry *lle)
1542 {
1543 
1544 	mtx_lock_spin(&w_mtx);
1545 	lle->ll_next = w_lock_list_free;
1546 	w_lock_list_free = lle;
1547 	mtx_unlock_spin(&w_mtx);
1548 }
1549 
1550 static struct lock_instance *
1551 find_instance(struct lock_list_entry *lock_list, struct lock_object *lock)
1552 {
1553 	struct lock_list_entry *lle;
1554 	struct lock_instance *instance;
1555 	int i;
1556 
1557 	for (lle = lock_list; lle != NULL; lle = lle->ll_next)
1558 		for (i = lle->ll_count - 1; i >= 0; i--) {
1559 			instance = &lle->ll_children[i];
1560 			if (instance->li_lock == lock)
1561 				return (instance);
1562 		}
1563 	return (NULL);
1564 }
1565 
1566 static void
1567 witness_list_lock(struct lock_instance *instance)
1568 {
1569 	struct lock_object *lock;
1570 
1571 	lock = instance->li_lock;
1572 	printf("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
1573 	    "exclusive" : "shared", lock->lo_class->lc_name, lock->lo_name);
1574 	if (lock->lo_type != lock->lo_name)
1575 		printf(" (%s)", lock->lo_type);
1576 	printf(" r = %d (%p) locked @ %s:%d\n",
1577 	    instance->li_flags & LI_RECURSEMASK, lock, instance->li_file,
1578 	    instance->li_line);
1579 }
1580 
1581 int
1582 witness_list_locks(struct lock_list_entry **lock_list)
1583 {
1584 	struct lock_list_entry *lle;
1585 	int i, nheld;
1586 
1587 	nheld = 0;
1588 	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
1589 		for (i = lle->ll_count - 1; i >= 0; i--) {
1590 			witness_list_lock(&lle->ll_children[i]);
1591 			nheld++;
1592 		}
1593 	return (nheld);
1594 }
1595 
1596 /*
1597  * This is a bit risky at best.  We call this function when we have timed
1598  * out acquiring a spin lock, and we assume that the other CPU is stuck
1599  * with this lock held.  So, we go groveling around in the other CPU's
1600  * per-cpu data to try to find the lock instance for this spin lock to
1601  * see when it was last acquired.
1602  */
1603 void
1604 witness_display_spinlock(struct lock_object *lock, struct thread *owner)
1605 {
1606 	struct lock_instance *instance;
1607 	struct pcpu *pc;
1608 
1609 	if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
1610 		return;
1611 	pc = pcpu_find(owner->td_oncpu);
1612 	instance = find_instance(pc->pc_spinlocks, lock);
1613 	if (instance != NULL)
1614 		witness_list_lock(instance);
1615 }
1616 
1617 void
1618 witness_save(struct lock_object *lock, const char **filep, int *linep)
1619 {
1620 	struct lock_instance *instance;
1621 
1622 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1623 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1624 		return;
1625 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1626 		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1627 		    lock->lo_class->lc_name, lock->lo_name);
1628 	instance = find_instance(curthread->td_sleeplocks, lock);
1629 	if (instance == NULL)
1630 		panic("%s: lock (%s) %s not locked", __func__,
1631 		    lock->lo_class->lc_name, lock->lo_name);
1632 	*filep = instance->li_file;
1633 	*linep = instance->li_line;
1634 }
1635 
1636 void
1637 witness_restore(struct lock_object *lock, const char *file, int line)
1638 {
1639 	struct lock_instance *instance;
1640 
1641 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1642 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1643 		return;
1644 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1645 		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1646 		    lock->lo_class->lc_name, lock->lo_name);
1647 	instance = find_instance(curthread->td_sleeplocks, lock);
1648 	if (instance == NULL)
1649 		panic("%s: lock (%s) %s not locked", __func__,
1650 		    lock->lo_class->lc_name, lock->lo_name);
1651 	lock->lo_witness->w_file = file;
1652 	lock->lo_witness->w_line = line;
1653 	instance->li_file = file;
1654 	instance->li_line = line;
1655 }
1656 
1657 void
1658 witness_assert(struct lock_object *lock, int flags, const char *file, int line)
1659 {
1660 #ifdef INVARIANT_SUPPORT
1661 	struct lock_instance *instance;
1662 
1663 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1664 		return;
1665 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) != 0)
1666 		instance = find_instance(curthread->td_sleeplocks, lock);
1667 	else if ((lock->lo_class->lc_flags & LC_SPINLOCK) != 0)
1668 		instance = find_instance(PCPU_GET(spinlocks), lock);
1669 	else {
1670 		panic("Lock (%s) %s is not sleep or spin!",
1671 		    lock->lo_class->lc_name, lock->lo_name);
1672 	}
1673 	file = fixup_filename(file);
1674 	switch (flags) {
1675 	case LA_UNLOCKED:
1676 		if (instance != NULL)
1677 			panic("Lock (%s) %s locked @ %s:%d.",
1678 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1679 		break;
1680 	case LA_LOCKED:
1681 	case LA_LOCKED | LA_RECURSED:
1682 	case LA_LOCKED | LA_NOTRECURSED:
1683 	case LA_SLOCKED:
1684 	case LA_SLOCKED | LA_RECURSED:
1685 	case LA_SLOCKED | LA_NOTRECURSED:
1686 	case LA_XLOCKED:
1687 	case LA_XLOCKED | LA_RECURSED:
1688 	case LA_XLOCKED | LA_NOTRECURSED:
1689 		if (instance == NULL) {
1690 			panic("Lock (%s) %s not locked @ %s:%d.",
1691 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1692 			break;
1693 		}
1694 		if ((flags & LA_XLOCKED) != 0 &&
1695 		    (instance->li_flags & LI_EXCLUSIVE) == 0)
1696 			panic("Lock (%s) %s not exclusively locked @ %s:%d.",
1697 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1698 		if ((flags & LA_SLOCKED) != 0 &&
1699 		    (instance->li_flags & LI_EXCLUSIVE) != 0)
1700 			panic("Lock (%s) %s exclusively locked @ %s:%d.",
1701 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1702 		if ((flags & LA_RECURSED) != 0 &&
1703 		    (instance->li_flags & LI_RECURSEMASK) == 0)
1704 			panic("Lock (%s) %s not recursed @ %s:%d.",
1705 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1706 		if ((flags & LA_NOTRECURSED) != 0 &&
1707 		    (instance->li_flags & LI_RECURSEMASK) != 0)
1708 			panic("Lock (%s) %s recursed @ %s:%d.",
1709 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1710 		break;
1711 	default:
1712 		panic("Invalid lock assertion at %s:%d.", file, line);
1713 
1714 	}
1715 #endif	/* INVARIANT_SUPPORT */
1716 }
1717 
1718 #ifdef DDB
1719 static void
1720 witness_list(struct thread *td)
1721 {
1722 
1723 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1724 	KASSERT(db_active, ("%s: not in the debugger", __func__));
1725 
1726 	if (witness_watch == 0)
1727 		return;
1728 
1729 	witness_list_locks(&td->td_sleeplocks);
1730 
1731 	/*
1732 	 * We only handle spinlocks if td == curthread.  This is somewhat broken
1733 	 * if td is currently executing on some other CPU and holds spin locks
1734 	 * as we won't display those locks.  If we had a MI way of getting
1735 	 * the per-cpu data for a given cpu then we could use
1736 	 * td->td_oncpu to get the list of spinlocks for this thread
1737 	 * and "fix" this.
1738 	 *
1739 	 * That still wouldn't really fix this unless we locked sched_lock
1740 	 * or stopped the other CPU to make sure it wasn't changing the list
1741 	 * out from under us.  It is probably best to just not try to handle
1742 	 * threads on other CPU's for now.
1743 	 */
1744 	if (td == curthread && PCPU_GET(spinlocks) != NULL)
1745 		witness_list_locks(PCPU_PTR(spinlocks));
1746 }
1747 
1748 DB_SHOW_COMMAND(locks, db_witness_list)
1749 {
1750 	struct thread *td;
1751 	pid_t pid;
1752 	struct proc *p;
1753 
1754 	if (have_addr) {
1755 		pid = (addr % 16) + ((addr >> 4) % 16) * 10 +
1756 		    ((addr >> 8) % 16) * 100 + ((addr >> 12) % 16) * 1000 +
1757 		    ((addr >> 16) % 16) * 10000;
1758 		/* sx_slock(&allproc_lock); */
1759 		FOREACH_PROC_IN_SYSTEM(p) {
1760 			if (p->p_pid == pid)
1761 				break;
1762 		}
1763 		/* sx_sunlock(&allproc_lock); */
1764 		if (p == NULL) {
1765 			db_printf("pid %d not found\n", pid);
1766 			return;
1767 		}
1768 		FOREACH_THREAD_IN_PROC(p, td) {
1769 			witness_list(td);
1770 		}
1771 	} else {
1772 		td = curthread;
1773 		witness_list(td);
1774 	}
1775 }
1776 
1777 DB_SHOW_COMMAND(witness, db_witness_display)
1778 {
1779 
1780 	witness_display(db_printf);
1781 }
1782 #endif
1783