xref: /freebsd/sys/kern/subr_witness.c (revision 3193579b66fd7067f898dbc54bdea81a0e6f9bd0)
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_RDTUN, &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 #endif
276 	{ "sio", &lock_class_mtx_spin },
277 #ifdef __i386__
278 	{ "cy", &lock_class_mtx_spin },
279 #endif
280 	{ "sabtty", &lock_class_mtx_spin },
281 	{ "zstty", &lock_class_mtx_spin },
282 	{ "ng_node", &lock_class_mtx_spin },
283 	{ "ng_worklist", &lock_class_mtx_spin },
284 	{ "taskqueue_fast", &lock_class_mtx_spin },
285 	{ "intr table", &lock_class_mtx_spin },
286 	{ "ithread table lock", &lock_class_mtx_spin },
287 	{ "sched lock", &lock_class_mtx_spin },
288 	{ "turnstile chain", &lock_class_mtx_spin },
289 	{ "td_contested", &lock_class_mtx_spin },
290 	{ "callout", &lock_class_mtx_spin },
291 	/*
292 	 * leaf locks
293 	 */
294 	{ "allpmaps", &lock_class_mtx_spin },
295 	{ "vm page queue free mutex", &lock_class_mtx_spin },
296 	{ "icu", &lock_class_mtx_spin },
297 #ifdef SMP
298 	{ "smp rendezvous", &lock_class_mtx_spin },
299 #if defined(__i386__) || defined(__amd64__)
300 	{ "tlb", &lock_class_mtx_spin },
301 	{ "lazypmap", &lock_class_mtx_spin },
302 #endif
303 #ifdef __sparc64__
304 	{ "ipi", &lock_class_mtx_spin },
305 #endif
306 #endif
307 	{ "clk", &lock_class_mtx_spin },
308 	{ "mutex profiling lock", &lock_class_mtx_spin },
309 	{ "kse zombie lock", &lock_class_mtx_spin },
310 	{ "ALD Queue", &lock_class_mtx_spin },
311 #ifdef __ia64__
312 	{ "MCA spin lock", &lock_class_mtx_spin },
313 #endif
314 #if defined(__i386__) || defined(__amd64__)
315 	{ "pcicfg", &lock_class_mtx_spin },
316 #endif
317 	{ NULL, NULL },
318 	{ NULL, NULL }
319 };
320 
321 #ifdef BLESSING
322 /*
323  * Pairs of locks which have been blessed
324  * Don't complain about order problems with blessed locks
325  */
326 static struct witness_blessed blessed_list[] = {
327 };
328 static int blessed_count =
329 	sizeof(blessed_list) / sizeof(struct witness_blessed);
330 #endif
331 
332 /*
333  * List of all locks in the system.
334  */
335 TAILQ_HEAD(, lock_object) all_locks = TAILQ_HEAD_INITIALIZER(all_locks);
336 
337 static struct mtx all_mtx = {
338 	{ &lock_class_mtx_sleep,	/* mtx_object.lo_class */
339 	  "All locks list",		/* mtx_object.lo_name */
340 	  "All locks list",		/* mtx_object.lo_type */
341 	  LO_INITIALIZED,		/* mtx_object.lo_flags */
342 	  { NULL, NULL },		/* mtx_object.lo_list */
343 	  NULL },			/* mtx_object.lo_witness */
344 	MTX_UNOWNED, 0			/* mtx_lock, mtx_recurse */
345 };
346 
347 /*
348  * This global is set to 0 once it becomes safe to use the witness code.
349  */
350 static int witness_cold = 1;
351 
352 /*
353  * Global variables for book keeping.
354  */
355 static int lock_cur_cnt;
356 static int lock_max_cnt;
357 
358 /*
359  * The WITNESS-enabled diagnostic code.
360  */
361 static void
362 witness_initialize(void *dummy __unused)
363 {
364 	struct lock_object *lock;
365 	struct witness_order_list_entry *order;
366 	struct witness *w, *w1;
367 	int i;
368 
369 	/*
370 	 * We have to release Giant before initializing its witness
371 	 * structure so that WITNESS doesn't get confused.
372 	 */
373 	mtx_unlock(&Giant);
374 	mtx_assert(&Giant, MA_NOTOWNED);
375 
376 	CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
377 	TAILQ_INSERT_HEAD(&all_locks, &all_mtx.mtx_object, lo_list);
378 	mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
379 	    MTX_NOWITNESS);
380 	for (i = 0; i < WITNESS_COUNT; i++)
381 		witness_free(&w_data[i]);
382 	for (i = 0; i < WITNESS_CHILDCOUNT; i++)
383 		witness_child_free(&w_childdata[i]);
384 	for (i = 0; i < LOCK_CHILDCOUNT; i++)
385 		witness_lock_list_free(&w_locklistdata[i]);
386 
387 	/* First add in all the specified order lists. */
388 	for (order = order_lists; order->w_name != NULL; order++) {
389 		w = enroll(order->w_name, order->w_class);
390 		if (w == NULL)
391 			continue;
392 		w->w_file = "order list";
393 		for (order++; order->w_name != NULL; order++) {
394 			w1 = enroll(order->w_name, order->w_class);
395 			if (w1 == NULL)
396 				continue;
397 			w1->w_file = "order list";
398 			if (!itismychild(w, w1))
399 				panic("Not enough memory for static orders!");
400 			w = w1;
401 		}
402 	}
403 
404 	/* Iterate through all locks and add them to witness. */
405 	mtx_lock(&all_mtx);
406 	TAILQ_FOREACH(lock, &all_locks, lo_list) {
407 		if (lock->lo_flags & LO_WITNESS)
408 			lock->lo_witness = enroll(lock->lo_type,
409 			    lock->lo_class);
410 		else
411 			lock->lo_witness = NULL;
412 	}
413 	mtx_unlock(&all_mtx);
414 
415 	/* Mark the witness code as being ready for use. */
416 	atomic_store_rel_int(&witness_cold, 0);
417 
418 	mtx_lock(&Giant);
419 }
420 SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize, NULL)
421 
422 static int
423 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
424 {
425 	int error, value;
426 
427 	value = witness_watch;
428 	error = sysctl_handle_int(oidp, &value, 0, req);
429 	if (error != 0 || req->newptr == NULL)
430 		return (error);
431 	error = suser(req->td);
432 	if (error != 0)
433 		return (error);
434 	if (value == witness_watch)
435 		return (0);
436 	if (value != 0)
437 		return (EINVAL);
438 	witness_watch = 0;
439 	return (0);
440 }
441 
442 void
443 witness_init(struct lock_object *lock)
444 {
445 	struct lock_class *class;
446 
447 	class = lock->lo_class;
448 	if (lock->lo_flags & LO_INITIALIZED)
449 		panic("%s: lock (%s) %s is already initialized", __func__,
450 		    class->lc_name, lock->lo_name);
451 	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
452 	    (class->lc_flags & LC_RECURSABLE) == 0)
453 		panic("%s: lock (%s) %s can not be recursable", __func__,
454 		    class->lc_name, lock->lo_name);
455 	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
456 	    (class->lc_flags & LC_SLEEPABLE) == 0)
457 		panic("%s: lock (%s) %s can not be sleepable", __func__,
458 		    class->lc_name, lock->lo_name);
459 	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
460 	    (class->lc_flags & LC_UPGRADABLE) == 0)
461 		panic("%s: lock (%s) %s can not be upgradable", __func__,
462 		    class->lc_name, lock->lo_name);
463 
464 	mtx_lock(&all_mtx);
465 	TAILQ_INSERT_TAIL(&all_locks, lock, lo_list);
466 	lock->lo_flags |= LO_INITIALIZED;
467 	lock_cur_cnt++;
468 	if (lock_cur_cnt > lock_max_cnt)
469 		lock_max_cnt = lock_cur_cnt;
470 	mtx_unlock(&all_mtx);
471 	if (!witness_cold && witness_watch != 0 && panicstr == NULL &&
472 	    (lock->lo_flags & LO_WITNESS) != 0)
473 		lock->lo_witness = enroll(lock->lo_type, class);
474 	else
475 		lock->lo_witness = NULL;
476 }
477 
478 void
479 witness_destroy(struct lock_object *lock)
480 {
481 	struct witness *w;
482 
483 	if (witness_cold)
484 		panic("lock (%s) %s destroyed while witness_cold",
485 		    lock->lo_class->lc_name, lock->lo_name);
486 	if ((lock->lo_flags & LO_INITIALIZED) == 0)
487 		panic("%s: lock (%s) %s is not initialized", __func__,
488 		    lock->lo_class->lc_name, lock->lo_name);
489 
490 	/* XXX: need to verify that no one holds the lock */
491 	w = lock->lo_witness;
492 	if (w != NULL) {
493 		mtx_lock_spin(&w_mtx);
494 		MPASS(w->w_refcount > 0);
495 		w->w_refcount--;
496 
497 		/*
498 		 * Lock is already released if we have an allocation failure
499 		 * and depart() fails.
500 		 */
501 		if (w->w_refcount != 0 || depart(w))
502 			mtx_unlock_spin(&w_mtx);
503 	}
504 
505 	mtx_lock(&all_mtx);
506 	lock_cur_cnt--;
507 	TAILQ_REMOVE(&all_locks, lock, lo_list);
508 	lock->lo_flags &= ~LO_INITIALIZED;
509 	mtx_unlock(&all_mtx);
510 }
511 
512 #ifdef DDB
513 static void
514 witness_display_list(void(*prnt)(const char *fmt, ...),
515 		     struct witness_list *list)
516 {
517 	struct witness *w;
518 
519 	STAILQ_FOREACH(w, list, w_typelist) {
520 		if (w->w_file == NULL || w->w_level > 0)
521 			continue;
522 		/*
523 		 * This lock has no anscestors, display its descendants.
524 		 */
525 		witness_displaydescendants(prnt, w, 0);
526 	}
527 }
528 
529 static void
530 witness_display(void(*prnt)(const char *fmt, ...))
531 {
532 	struct witness *w;
533 
534 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
535 	witness_levelall();
536 
537 	/* Clear all the displayed flags. */
538 	STAILQ_FOREACH(w, &w_all, w_list) {
539 		w->w_displayed = 0;
540 	}
541 
542 	/*
543 	 * First, handle sleep locks which have been acquired at least
544 	 * once.
545 	 */
546 	prnt("Sleep locks:\n");
547 	witness_display_list(prnt, &w_sleep);
548 
549 	/*
550 	 * Now do spin locks which have been acquired at least once.
551 	 */
552 	prnt("\nSpin locks:\n");
553 	witness_display_list(prnt, &w_spin);
554 
555 	/*
556 	 * Finally, any locks which have not been acquired yet.
557 	 */
558 	prnt("\nLocks which were never acquired:\n");
559 	STAILQ_FOREACH(w, &w_all, w_list) {
560 		if (w->w_file != NULL || w->w_refcount == 0)
561 			continue;
562 		prnt("%s\n", w->w_name);
563 	}
564 }
565 #endif /* DDB */
566 
567 /* Trim useless garbage from filenames. */
568 static const char *
569 fixup_filename(const char *file)
570 {
571 
572 	if (file == NULL)
573 		return (NULL);
574 	while (strncmp(file, "../", 3) == 0)
575 		file += 3;
576 	return (file);
577 }
578 
579 void
580 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
581 {
582 	struct lock_list_entry **lock_list, *lle;
583 	struct lock_instance *lock1, *lock2;
584 	struct lock_class *class;
585 	struct witness *w, *w1;
586 	struct thread *td;
587 	int i, j;
588 #ifdef DDB
589 	int go_into_ddb = 0;
590 #endif
591 
592 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
593 	    panicstr != NULL)
594 		return;
595 	w = lock->lo_witness;
596 	class = lock->lo_class;
597 	td = curthread;
598 	file = fixup_filename(file);
599 
600 	if (class->lc_flags & LC_SLEEPLOCK) {
601 		/*
602 		 * Since spin locks include a critical section, this check
603 		 * impliclty enforces a lock order of all sleep locks before
604 		 * all spin locks.
605 		 */
606 		if (td->td_critnest != 0 && (flags & LOP_TRYLOCK) == 0)
607 			panic("blockable sleep lock (%s) %s @ %s:%d",
608 			    class->lc_name, lock->lo_name, file, line);
609 		lock_list = &td->td_sleeplocks;
610 	} else
611 		lock_list = PCPU_PTR(spinlocks);
612 
613 	/*
614 	 * Is this the first lock acquired?  If so, then no order checking
615 	 * is needed.
616 	 */
617 	if (*lock_list == NULL)
618 		goto out;
619 
620 	/*
621 	 * Check to see if we are recursing on a lock we already own.
622 	 */
623 	lock1 = find_instance(*lock_list, lock);
624 	if (lock1 != NULL) {
625 		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
626 		    (flags & LOP_EXCLUSIVE) == 0) {
627 			printf("shared lock of (%s) %s @ %s:%d\n",
628 			    class->lc_name, lock->lo_name, file, line);
629 			printf("while exclusively locked from %s:%d\n",
630 			    lock1->li_file, lock1->li_line);
631 			panic("share->excl");
632 		}
633 		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
634 		    (flags & LOP_EXCLUSIVE) != 0) {
635 			printf("exclusive lock of (%s) %s @ %s:%d\n",
636 			    class->lc_name, lock->lo_name, file, line);
637 			printf("while share locked from %s:%d\n",
638 			    lock1->li_file, lock1->li_line);
639 			panic("excl->share");
640 		}
641 		lock1->li_flags++;
642 		if ((lock->lo_flags & LO_RECURSABLE) == 0) {
643 			printf(
644 			"recursed on non-recursive lock (%s) %s @ %s:%d\n",
645 			    class->lc_name, lock->lo_name, file, line);
646 			printf("first acquired @ %s:%d\n", lock1->li_file,
647 			    lock1->li_line);
648 			panic("recurse");
649 		}
650 		CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
651 		    td->td_proc->p_pid, lock->lo_name,
652 		    lock1->li_flags & LI_RECURSEMASK);
653 		lock1->li_file = file;
654 		lock1->li_line = line;
655 		return;
656 	}
657 
658 	/*
659 	 * Try locks do not block if they fail to acquire the lock, thus
660 	 * there is no danger of deadlocks or of switching while holding a
661 	 * spin lock if we acquire a lock via a try operation.
662 	 */
663 	if (flags & LOP_TRYLOCK)
664 		goto out;
665 
666 	/*
667 	 * Check for duplicate locks of the same type.  Note that we only
668 	 * have to check for this on the last lock we just acquired.  Any
669 	 * other cases will be caught as lock order violations.
670 	 */
671 	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
672 	w1 = lock1->li_lock->lo_witness;
673 	if (w1 == w) {
674 		if (w->w_same_squawked || (lock->lo_flags & LO_DUPOK))
675 			goto out;
676 		w->w_same_squawked = 1;
677 		printf("acquiring duplicate lock of same type: \"%s\"\n",
678 			lock->lo_type);
679 		printf(" 1st %s @ %s:%d\n", lock1->li_lock->lo_name,
680 		    lock1->li_file, lock1->li_line);
681 		printf(" 2nd %s @ %s:%d\n", lock->lo_name, file, line);
682 #ifdef DDB
683 		go_into_ddb = 1;
684 #endif
685 		goto out;
686 	}
687 	MPASS(!mtx_owned(&w_mtx));
688 	mtx_lock_spin(&w_mtx);
689 	/*
690 	 * If we have a known higher number just say ok
691 	 */
692 	if (witness_watch > 1 && w->w_level > w1->w_level) {
693 		mtx_unlock_spin(&w_mtx);
694 		goto out;
695 	}
696 	/*
697 	 * If we know that the the lock we are acquiring comes after
698 	 * the lock we most recently acquired in the lock order tree,
699 	 * then there is no need for any further checks.
700 	 */
701 	if (isitmydescendant(w1, w)) {
702 		mtx_unlock_spin(&w_mtx);
703 		goto out;
704 	}
705 	for (j = 0, lle = *lock_list; lle != NULL; lle = lle->ll_next) {
706 		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
707 
708 			MPASS(j < WITNESS_COUNT);
709 			lock1 = &lle->ll_children[i];
710 			w1 = lock1->li_lock->lo_witness;
711 
712 			/*
713 			 * If this lock doesn't undergo witness checking,
714 			 * then skip it.
715 			 */
716 			if (w1 == NULL) {
717 				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
718 				    ("lock missing witness structure"));
719 				continue;
720 			}
721 			/*
722 			 * If we are locking Giant and this is a sleepable
723 			 * lock, then skip it.
724 			 */
725 			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
726 			    lock == &Giant.mtx_object)
727 				continue;
728 			/*
729 			 * If we are locking a sleepable lock and this lock
730 			 * is Giant, then skip it.
731 			 */
732 			if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
733 			    lock1->li_lock == &Giant.mtx_object)
734 				continue;
735 			/*
736 			 * If we are locking a sleepable lock and this lock
737 			 * isn't sleepable, we want to treat it as a lock
738 			 * order violation to enfore a general lock order of
739 			 * sleepable locks before non-sleepable locks.
740 			 */
741 			if (!((lock->lo_flags & LO_SLEEPABLE) != 0 &&
742 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
743 			    /*
744 			     * Check the lock order hierarchy for a reveresal.
745 			     */
746 			    if (!isitmydescendant(w, w1))
747 				continue;
748 			/*
749 			 * We have a lock order violation, check to see if it
750 			 * is allowed or has already been yelled about.
751 			 */
752 			mtx_unlock_spin(&w_mtx);
753 #ifdef BLESSING
754 			if (blessed(w, w1))
755 				goto out;
756 #endif
757 			if (lock1->li_lock == &Giant.mtx_object) {
758 				if (w1->w_Giant_squawked)
759 					goto out;
760 				else
761 					w1->w_Giant_squawked = 1;
762 			} else {
763 				if (w1->w_other_squawked)
764 					goto out;
765 				else
766 					w1->w_other_squawked = 1;
767 			}
768 			/*
769 			 * Ok, yell about it.
770 			 */
771 			printf("lock order reversal\n");
772 			/*
773 			 * Try to locate an earlier lock with
774 			 * witness w in our list.
775 			 */
776 			do {
777 				lock2 = &lle->ll_children[i];
778 				MPASS(lock2->li_lock != NULL);
779 				if (lock2->li_lock->lo_witness == w)
780 					break;
781 				i--;
782 				if (i == 0 && lle->ll_next != NULL) {
783 					lle = lle->ll_next;
784 					i = lle->ll_count - 1;
785 					MPASS(i >= 0 && i < LOCK_NCHILDREN);
786 				}
787 			} while (i >= 0);
788 			if (i < 0) {
789 				printf(" 1st %p %s (%s) @ %s:%d\n",
790 				    lock1->li_lock, lock1->li_lock->lo_name,
791 				    lock1->li_lock->lo_type, lock1->li_file,
792 				    lock1->li_line);
793 				printf(" 2nd %p %s (%s) @ %s:%d\n", lock,
794 				    lock->lo_name, lock->lo_type, file, line);
795 			} else {
796 				printf(" 1st %p %s (%s) @ %s:%d\n",
797 				    lock2->li_lock, lock2->li_lock->lo_name,
798 				    lock2->li_lock->lo_type, lock2->li_file,
799 				    lock2->li_line);
800 				printf(" 2nd %p %s (%s) @ %s:%d\n",
801 				    lock1->li_lock, lock1->li_lock->lo_name,
802 				    lock1->li_lock->lo_type, lock1->li_file,
803 				    lock1->li_line);
804 				printf(" 3rd %p %s (%s) @ %s:%d\n", lock,
805 				    lock->lo_name, lock->lo_type, file, line);
806 			}
807 #ifdef DDB
808 			go_into_ddb = 1;
809 #endif
810 			goto out;
811 		}
812 	}
813 	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
814 	/*
815 	 * Don't build a new relationship between a sleepable lock and
816 	 * Giant if it is the wrong direction.  The real lock order is that
817 	 * sleepable locks come before Giant.
818 	 */
819 	if (!(lock1->li_lock == &Giant.mtx_object &&
820 	    (lock->lo_flags & LO_SLEEPABLE) != 0)) {
821 		CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
822 		    lock->lo_type, lock1->li_lock->lo_type);
823 		if (!itismychild(lock1->li_lock->lo_witness, w))
824 			/* Witness is dead. */
825 			return;
826 	}
827 	mtx_unlock_spin(&w_mtx);
828 
829 out:
830 #ifdef DDB
831 	if (go_into_ddb) {
832 		if (witness_trace)
833 			backtrace();
834 		if (witness_ddb)
835 			Debugger(__func__);
836 	}
837 #endif
838 	w->w_file = file;
839 	w->w_line = line;
840 
841 	lle = *lock_list;
842 	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
843 		lle = witness_lock_list_get();
844 		if (lle == NULL)
845 			return;
846 		lle->ll_next = *lock_list;
847 		CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
848 		    td->td_proc->p_pid, lle);
849 		*lock_list = lle;
850 	}
851 	lock1 = &lle->ll_children[lle->ll_count++];
852 	lock1->li_lock = lock;
853 	lock1->li_line = line;
854 	lock1->li_file = file;
855 	if ((flags & LOP_EXCLUSIVE) != 0)
856 		lock1->li_flags = LI_EXCLUSIVE;
857 	else
858 		lock1->li_flags = 0;
859 	CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
860 	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
861 }
862 
863 void
864 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
865 {
866 	struct lock_instance *instance;
867 	struct lock_class *class;
868 
869 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
870 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
871 		return;
872 	class = lock->lo_class;
873 	file = fixup_filename(file);
874 	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
875 		panic("upgrade of non-upgradable lock (%s) %s @ %s:%d",
876 		    class->lc_name, lock->lo_name, file, line);
877 	if ((flags & LOP_TRYLOCK) == 0)
878 		panic("non-try upgrade of lock (%s) %s @ %s:%d", class->lc_name,
879 		    lock->lo_name, file, line);
880 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
881 		panic("upgrade of non-sleep lock (%s) %s @ %s:%d",
882 		    class->lc_name, lock->lo_name, file, line);
883 	instance = find_instance(curthread->td_sleeplocks, lock);
884 	if (instance == NULL)
885 		panic("upgrade of unlocked lock (%s) %s @ %s:%d",
886 		    class->lc_name, lock->lo_name, file, line);
887 	if ((instance->li_flags & LI_EXCLUSIVE) != 0)
888 		panic("upgrade of exclusive lock (%s) %s @ %s:%d",
889 		    class->lc_name, lock->lo_name, file, line);
890 	if ((instance->li_flags & LI_RECURSEMASK) != 0)
891 		panic("upgrade of recursed lock (%s) %s r=%d @ %s:%d",
892 		    class->lc_name, lock->lo_name,
893 		    instance->li_flags & LI_RECURSEMASK, file, line);
894 	instance->li_flags |= LI_EXCLUSIVE;
895 }
896 
897 void
898 witness_downgrade(struct lock_object *lock, int flags, const char *file,
899     int line)
900 {
901 	struct lock_instance *instance;
902 	struct lock_class *class;
903 
904 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
905 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
906 		return;
907 	class = lock->lo_class;
908 	file = fixup_filename(file);
909 	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
910 		panic("downgrade of non-upgradable lock (%s) %s @ %s:%d",
911 		    class->lc_name, lock->lo_name, file, line);
912 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
913 		panic("downgrade of non-sleep lock (%s) %s @ %s:%d",
914 		    class->lc_name, lock->lo_name, file, line);
915 	instance = find_instance(curthread->td_sleeplocks, lock);
916 	if (instance == NULL)
917 		panic("downgrade of unlocked lock (%s) %s @ %s:%d",
918 		    class->lc_name, lock->lo_name, file, line);
919 	if ((instance->li_flags & LI_EXCLUSIVE) == 0)
920 		panic("downgrade of shared lock (%s) %s @ %s:%d",
921 		    class->lc_name, lock->lo_name, file, line);
922 	if ((instance->li_flags & LI_RECURSEMASK) != 0)
923 		panic("downgrade of recursed lock (%s) %s r=%d @ %s:%d",
924 		    class->lc_name, lock->lo_name,
925 		    instance->li_flags & LI_RECURSEMASK, file, line);
926 	instance->li_flags &= ~LI_EXCLUSIVE;
927 }
928 
929 void
930 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
931 {
932 	struct lock_list_entry **lock_list, *lle;
933 	struct lock_instance *instance;
934 	struct lock_class *class;
935 	struct thread *td;
936 	register_t s;
937 	int i, j;
938 
939 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL ||
940 	    panicstr != NULL)
941 		return;
942 	td = curthread;
943 	class = lock->lo_class;
944 	file = fixup_filename(file);
945 	if (class->lc_flags & LC_SLEEPLOCK)
946 		lock_list = &td->td_sleeplocks;
947 	else
948 		lock_list = PCPU_PTR(spinlocks);
949 	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
950 		for (i = 0; i < (*lock_list)->ll_count; i++) {
951 			instance = &(*lock_list)->ll_children[i];
952 			if (instance->li_lock == lock) {
953 				if ((instance->li_flags & LI_EXCLUSIVE) != 0 &&
954 				    (flags & LOP_EXCLUSIVE) == 0) {
955 					printf(
956 					"shared unlock of (%s) %s @ %s:%d\n",
957 					    class->lc_name, lock->lo_name,
958 					    file, line);
959 					printf(
960 					"while exclusively locked from %s:%d\n",
961 					    instance->li_file,
962 					    instance->li_line);
963 					panic("excl->ushare");
964 				}
965 				if ((instance->li_flags & LI_EXCLUSIVE) == 0 &&
966 				    (flags & LOP_EXCLUSIVE) != 0) {
967 					printf(
968 					"exclusive unlock of (%s) %s @ %s:%d\n",
969 					    class->lc_name, lock->lo_name,
970 					    file, line);
971 					printf(
972 					"while share locked from %s:%d\n",
973 					    instance->li_file,
974 					    instance->li_line);
975 					panic("share->uexcl");
976 				}
977 				/* If we are recursed, unrecurse. */
978 				if ((instance->li_flags & LI_RECURSEMASK) > 0) {
979 					CTR4(KTR_WITNESS,
980 				    "%s: pid %d unrecursed on %s r=%d", __func__,
981 					    td->td_proc->p_pid,
982 					    instance->li_lock->lo_name,
983 					    instance->li_flags);
984 					instance->li_flags--;
985 					return;
986 				}
987 				s = intr_disable();
988 				CTR4(KTR_WITNESS,
989 				    "%s: pid %d removed %s from lle[%d]", __func__,
990 				    td->td_proc->p_pid,
991 				    instance->li_lock->lo_name,
992 				    (*lock_list)->ll_count - 1);
993 				for (j = i; j < (*lock_list)->ll_count - 1; j++)
994 					(*lock_list)->ll_children[j] =
995 					    (*lock_list)->ll_children[j + 1];
996 				(*lock_list)->ll_count--;
997 				intr_restore(s);
998 				if ((*lock_list)->ll_count == 0) {
999 					lle = *lock_list;
1000 					*lock_list = lle->ll_next;
1001 					CTR3(KTR_WITNESS,
1002 					    "%s: pid %d removed lle %p", __func__,
1003 					    td->td_proc->p_pid, lle);
1004 					witness_lock_list_free(lle);
1005 				}
1006 				return;
1007 			}
1008 		}
1009 	panic("lock (%s) %s not locked @ %s:%d", class->lc_name, lock->lo_name,
1010 	    file, line);
1011 }
1012 
1013 /*
1014  * Warn if any locks other than 'lock' are held.  Flags can be passed in to
1015  * exempt Giant and sleepable locks from the checks as well.  If any
1016  * non-exempt locks are held, then a supplied message is printed to the
1017  * console along with a list of the offending locks.  If indicated in the
1018  * flags then a failure results in a panic as well.
1019  */
1020 int
1021 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1022 {
1023 	struct lock_list_entry *lle;
1024 	struct lock_instance *lock1;
1025 	struct thread *td;
1026 	va_list ap;
1027 	int i, n;
1028 
1029 	if (witness_cold || witness_watch == 0 || panicstr != NULL)
1030 		return (0);
1031 	n = 0;
1032 	td = curthread;
1033 	for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1034 		for (i = lle->ll_count - 1; i >= 0; i--) {
1035 			lock1 = &lle->ll_children[i];
1036 			if (lock1->li_lock == lock)
1037 				continue;
1038 			if (flags & WARN_GIANTOK &&
1039 			    lock1->li_lock == &Giant.mtx_object)
1040 				continue;
1041 			if (flags & WARN_SLEEPOK &&
1042 			    (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1043 				continue;
1044 			if (n == 0) {
1045 				va_start(ap, fmt);
1046 				vprintf(fmt, ap);
1047 				va_end(ap);
1048 				printf(" with the following");
1049 				if (flags & WARN_SLEEPOK)
1050 					printf(" non-sleepable");
1051 				printf(" locks held:\n");
1052 			}
1053 			n++;
1054 			witness_list_lock(lock1);
1055 		}
1056 	if (PCPU_GET(spinlocks) != NULL) {
1057 		/*
1058 		 * Since we already hold a spinlock preemption is
1059 		 * already blocked.
1060 		 */
1061 		if (n == 0) {
1062 			va_start(ap, fmt);
1063 			vprintf(fmt, ap);
1064 			va_end(ap);
1065 			printf(" with the following");
1066 			if (flags & WARN_SLEEPOK)
1067 				printf(" non-sleepable");
1068 			printf(" locks held:\n");
1069 		}
1070 		n += witness_list_locks(PCPU_PTR(spinlocks));
1071 	}
1072 	if (flags & WARN_PANIC && n)
1073 		panic("witness_warn");
1074 #ifdef DDB
1075 	else if (witness_ddb && n)
1076 		Debugger(__func__);
1077 #endif
1078 	return (n);
1079 }
1080 
1081 const char *
1082 witness_file(struct lock_object *lock)
1083 {
1084 	struct witness *w;
1085 
1086 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1087 		return ("?");
1088 	w = lock->lo_witness;
1089 	return (w->w_file);
1090 }
1091 
1092 int
1093 witness_line(struct lock_object *lock)
1094 {
1095 	struct witness *w;
1096 
1097 	if (witness_cold || witness_watch == 0 || lock->lo_witness == NULL)
1098 		return (0);
1099 	w = lock->lo_witness;
1100 	return (w->w_line);
1101 }
1102 
1103 static struct witness *
1104 enroll(const char *description, struct lock_class *lock_class)
1105 {
1106 	struct witness *w;
1107 
1108 	if (!witness_watch || witness_watch == 0 || panicstr != NULL)
1109 		return (NULL);
1110 	if ((lock_class->lc_flags & LC_SPINLOCK) && witness_skipspin)
1111 		return (NULL);
1112 	mtx_lock_spin(&w_mtx);
1113 	STAILQ_FOREACH(w, &w_all, w_list) {
1114 		if (w->w_name == description || (w->w_refcount > 0 &&
1115 		    strcmp(description, w->w_name) == 0)) {
1116 			w->w_refcount++;
1117 			mtx_unlock_spin(&w_mtx);
1118 			if (lock_class != w->w_class)
1119 				panic(
1120 				"lock (%s) %s does not match earlier (%s) lock",
1121 				    description, lock_class->lc_name,
1122 				    w->w_class->lc_name);
1123 			return (w);
1124 		}
1125 	}
1126 	/*
1127 	 * This isn't quite right, as witness_cold is still 0 while we
1128 	 * enroll all the locks initialized before witness_initialize().
1129 	 */
1130 	if ((lock_class->lc_flags & LC_SPINLOCK) && !witness_cold) {
1131 		mtx_unlock_spin(&w_mtx);
1132 		panic("spin lock %s not in order list", description);
1133 	}
1134 	if ((w = witness_get()) == NULL)
1135 		return (NULL);
1136 	w->w_name = description;
1137 	w->w_class = lock_class;
1138 	w->w_refcount = 1;
1139 	STAILQ_INSERT_HEAD(&w_all, w, w_list);
1140 	if (lock_class->lc_flags & LC_SPINLOCK)
1141 		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1142 	else if (lock_class->lc_flags & LC_SLEEPLOCK)
1143 		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1144 	else {
1145 		mtx_unlock_spin(&w_mtx);
1146 		panic("lock class %s is not sleep or spin",
1147 		    lock_class->lc_name);
1148 	}
1149 	mtx_unlock_spin(&w_mtx);
1150 	return (w);
1151 }
1152 
1153 /* Don't let the door bang you on the way out... */
1154 static int
1155 depart(struct witness *w)
1156 {
1157 	struct witness_child_list_entry *wcl, *nwcl;
1158 	struct witness_list *list;
1159 	struct witness *parent;
1160 
1161 	MPASS(w->w_refcount == 0);
1162 	if (w->w_class->lc_flags & LC_SLEEPLOCK)
1163 		list = &w_sleep;
1164 	else
1165 		list = &w_spin;
1166 	/*
1167 	 * First, we run through the entire tree looking for any
1168 	 * witnesses that the outgoing witness is a child of.  For
1169 	 * each parent that we find, we reparent all the direct
1170 	 * children of the outgoing witness to its parent.
1171 	 */
1172 	STAILQ_FOREACH(parent, list, w_typelist) {
1173 		if (!isitmychild(parent, w))
1174 			continue;
1175 		removechild(parent, w);
1176 		if (!reparentchildren(parent, w))
1177 			return (0);
1178 	}
1179 
1180 	/*
1181 	 * Now we go through and free up the child list of the
1182 	 * outgoing witness.
1183 	 */
1184 	for (wcl = w->w_children; wcl != NULL; wcl = nwcl) {
1185 		nwcl = wcl->wcl_next;
1186 		witness_child_free(wcl);
1187 	}
1188 
1189 	/*
1190 	 * Detach from various lists and free.
1191 	 */
1192 	STAILQ_REMOVE(list, w, witness, w_typelist);
1193 	STAILQ_REMOVE(&w_all, w, witness, w_list);
1194 	witness_free(w);
1195 
1196 	/* Finally, fixup the tree. */
1197 	return (rebalancetree(list));
1198 }
1199 
1200 /*
1201  * Prune an entire lock order tree.  We look for cases where a lock
1202  * is now both a descendant and a direct child of a given lock.  In
1203  * that case, we want to remove the direct child link from the tree.
1204  *
1205  * Returns false if insertchild() fails.
1206  */
1207 static int
1208 rebalancetree(struct witness_list *list)
1209 {
1210 	struct witness *child, *parent;
1211 
1212 	STAILQ_FOREACH(child, list, w_typelist) {
1213 		STAILQ_FOREACH(parent, list, w_typelist) {
1214 			if (!isitmychild(parent, child))
1215 				continue;
1216 			removechild(parent, child);
1217 			if (isitmydescendant(parent, child))
1218 				continue;
1219 			if (!insertchild(parent, child))
1220 				return (0);
1221 		}
1222 	}
1223 	witness_levelall();
1224 	return (1);
1225 }
1226 
1227 /*
1228  * Add "child" as a direct child of "parent".  Returns false if
1229  * we fail due to out of memory.
1230  */
1231 static int
1232 insertchild(struct witness *parent, struct witness *child)
1233 {
1234 	struct witness_child_list_entry **wcl;
1235 
1236 	MPASS(child != NULL && parent != NULL);
1237 
1238 	/*
1239 	 * Insert "child" after "parent"
1240 	 */
1241 	wcl = &parent->w_children;
1242 	while (*wcl != NULL && (*wcl)->wcl_count == WITNESS_NCHILDREN)
1243 		wcl = &(*wcl)->wcl_next;
1244 	if (*wcl == NULL) {
1245 		*wcl = witness_child_get();
1246 		if (*wcl == NULL)
1247 			return (0);
1248 	}
1249 	(*wcl)->wcl_children[(*wcl)->wcl_count++] = child;
1250 
1251 	return (1);
1252 }
1253 
1254 /*
1255  * Make all the direct descendants of oldparent be direct descendants
1256  * of newparent.
1257  */
1258 static int
1259 reparentchildren(struct witness *newparent, struct witness *oldparent)
1260 {
1261 	struct witness_child_list_entry *wcl;
1262 	int i;
1263 
1264 	/* Avoid making a witness a child of itself. */
1265 	MPASS(!isitmychild(oldparent, newparent));
1266 
1267 	for (wcl = oldparent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1268 		for (i = 0; i < wcl->wcl_count; i++)
1269 			if (!insertchild(newparent, wcl->wcl_children[i]))
1270 				return (0);
1271 	return (1);
1272 }
1273 
1274 static int
1275 itismychild(struct witness *parent, struct witness *child)
1276 {
1277 	struct witness_list *list;
1278 
1279 	MPASS(child != NULL && parent != NULL);
1280 	if ((parent->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) !=
1281 	    (child->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)))
1282 		panic(
1283 		"%s: parent (%s) and child (%s) are not the same lock type",
1284 		    __func__, parent->w_class->lc_name,
1285 		    child->w_class->lc_name);
1286 
1287 	if (!insertchild(parent, child))
1288 		return (0);
1289 
1290 	if (parent->w_class->lc_flags & LC_SLEEPLOCK)
1291 		list = &w_sleep;
1292 	else
1293 		list = &w_spin;
1294 	return (rebalancetree(list));
1295 }
1296 
1297 static void
1298 removechild(struct witness *parent, struct witness *child)
1299 {
1300 	struct witness_child_list_entry **wcl, *wcl1;
1301 	int i;
1302 
1303 	for (wcl = &parent->w_children; *wcl != NULL; wcl = &(*wcl)->wcl_next)
1304 		for (i = 0; i < (*wcl)->wcl_count; i++)
1305 			if ((*wcl)->wcl_children[i] == child)
1306 				goto found;
1307 	return;
1308 found:
1309 	(*wcl)->wcl_count--;
1310 	if ((*wcl)->wcl_count > i)
1311 		(*wcl)->wcl_children[i] =
1312 		    (*wcl)->wcl_children[(*wcl)->wcl_count];
1313 	MPASS((*wcl)->wcl_children[i] != NULL);
1314 	if ((*wcl)->wcl_count != 0)
1315 		return;
1316 	wcl1 = *wcl;
1317 	*wcl = wcl1->wcl_next;
1318 	witness_child_free(wcl1);
1319 }
1320 
1321 static int
1322 isitmychild(struct witness *parent, struct witness *child)
1323 {
1324 	struct witness_child_list_entry *wcl;
1325 	int i;
1326 
1327 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1328 		for (i = 0; i < wcl->wcl_count; i++) {
1329 			if (wcl->wcl_children[i] == child)
1330 				return (1);
1331 		}
1332 	}
1333 	return (0);
1334 }
1335 
1336 static int
1337 isitmydescendant(struct witness *parent, struct witness *child)
1338 {
1339 	struct witness_child_list_entry *wcl;
1340 	int i, j;
1341 
1342 	if (isitmychild(parent, child))
1343 		return (1);
1344 	j = 0;
1345 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1346 		MPASS(j < 1000);
1347 		for (i = 0; i < wcl->wcl_count; i++) {
1348 			if (isitmydescendant(wcl->wcl_children[i], child))
1349 				return (1);
1350 		}
1351 		j++;
1352 	}
1353 	return (0);
1354 }
1355 
1356 static void
1357 witness_levelall (void)
1358 {
1359 	struct witness_list *list;
1360 	struct witness *w, *w1;
1361 
1362 	/*
1363 	 * First clear all levels.
1364 	 */
1365 	STAILQ_FOREACH(w, &w_all, w_list) {
1366 		w->w_level = 0;
1367 	}
1368 
1369 	/*
1370 	 * Look for locks with no parent and level all their descendants.
1371 	 */
1372 	STAILQ_FOREACH(w, &w_all, w_list) {
1373 		/*
1374 		 * This is just an optimization, technically we could get
1375 		 * away just walking the all list each time.
1376 		 */
1377 		if (w->w_class->lc_flags & LC_SLEEPLOCK)
1378 			list = &w_sleep;
1379 		else
1380 			list = &w_spin;
1381 		STAILQ_FOREACH(w1, list, w_typelist) {
1382 			if (isitmychild(w1, w))
1383 				goto skip;
1384 		}
1385 		witness_leveldescendents(w, 0);
1386 	skip:
1387 		;	/* silence GCC 3.x */
1388 	}
1389 }
1390 
1391 static void
1392 witness_leveldescendents(struct witness *parent, int level)
1393 {
1394 	struct witness_child_list_entry *wcl;
1395 	int i;
1396 
1397 	if (parent->w_level < level)
1398 		parent->w_level = level;
1399 	level++;
1400 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1401 		for (i = 0; i < wcl->wcl_count; i++)
1402 			witness_leveldescendents(wcl->wcl_children[i], level);
1403 }
1404 
1405 static void
1406 witness_displaydescendants(void(*prnt)(const char *fmt, ...),
1407 			   struct witness *parent, int indent)
1408 {
1409 	struct witness_child_list_entry *wcl;
1410 	int i, level;
1411 
1412 	level = parent->w_level;
1413 	prnt("%-2d", level);
1414 	for (i = 0; i < indent; i++)
1415 		prnt(" ");
1416 	if (parent->w_refcount > 0)
1417 		prnt("%s", parent->w_name);
1418 	else
1419 		prnt("(dead)");
1420 	if (parent->w_displayed) {
1421 		prnt(" -- (already displayed)\n");
1422 		return;
1423 	}
1424 	parent->w_displayed = 1;
1425 	if (parent->w_refcount > 0) {
1426 		if (parent->w_file != NULL)
1427 			prnt(" -- last acquired @ %s:%d", parent->w_file,
1428 			    parent->w_line);
1429 	}
1430 	prnt("\n");
1431 	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1432 		for (i = 0; i < wcl->wcl_count; i++)
1433 			    witness_displaydescendants(prnt,
1434 				wcl->wcl_children[i], indent + 1);
1435 }
1436 
1437 #ifdef BLESSING
1438 static int
1439 blessed(struct witness *w1, struct witness *w2)
1440 {
1441 	int i;
1442 	struct witness_blessed *b;
1443 
1444 	for (i = 0; i < blessed_count; i++) {
1445 		b = &blessed_list[i];
1446 		if (strcmp(w1->w_name, b->b_lock1) == 0) {
1447 			if (strcmp(w2->w_name, b->b_lock2) == 0)
1448 				return (1);
1449 			continue;
1450 		}
1451 		if (strcmp(w1->w_name, b->b_lock2) == 0)
1452 			if (strcmp(w2->w_name, b->b_lock1) == 0)
1453 				return (1);
1454 	}
1455 	return (0);
1456 }
1457 #endif
1458 
1459 static struct witness *
1460 witness_get(void)
1461 {
1462 	struct witness *w;
1463 
1464 	if (witness_watch == 0) {
1465 		mtx_unlock_spin(&w_mtx);
1466 		return (NULL);
1467 	}
1468 	if (STAILQ_EMPTY(&w_free)) {
1469 		witness_watch = 0;
1470 		mtx_unlock_spin(&w_mtx);
1471 		printf("%s: witness exhausted\n", __func__);
1472 		return (NULL);
1473 	}
1474 	w = STAILQ_FIRST(&w_free);
1475 	STAILQ_REMOVE_HEAD(&w_free, w_list);
1476 	bzero(w, sizeof(*w));
1477 	return (w);
1478 }
1479 
1480 static void
1481 witness_free(struct witness *w)
1482 {
1483 
1484 	STAILQ_INSERT_HEAD(&w_free, w, w_list);
1485 }
1486 
1487 static struct witness_child_list_entry *
1488 witness_child_get(void)
1489 {
1490 	struct witness_child_list_entry *wcl;
1491 
1492 	if (witness_watch == 0) {
1493 		mtx_unlock_spin(&w_mtx);
1494 		return (NULL);
1495 	}
1496 	wcl = w_child_free;
1497 	if (wcl == NULL) {
1498 		witness_watch = 0;
1499 		mtx_unlock_spin(&w_mtx);
1500 		printf("%s: witness exhausted\n", __func__);
1501 		return (NULL);
1502 	}
1503 	w_child_free = wcl->wcl_next;
1504 	bzero(wcl, sizeof(*wcl));
1505 	return (wcl);
1506 }
1507 
1508 static void
1509 witness_child_free(struct witness_child_list_entry *wcl)
1510 {
1511 
1512 	wcl->wcl_next = w_child_free;
1513 	w_child_free = wcl;
1514 }
1515 
1516 static struct lock_list_entry *
1517 witness_lock_list_get(void)
1518 {
1519 	struct lock_list_entry *lle;
1520 
1521 	if (witness_watch == 0)
1522 		return (NULL);
1523 	mtx_lock_spin(&w_mtx);
1524 	lle = w_lock_list_free;
1525 	if (lle == NULL) {
1526 		witness_watch = 0;
1527 		mtx_unlock_spin(&w_mtx);
1528 		printf("%s: witness exhausted\n", __func__);
1529 		return (NULL);
1530 	}
1531 	w_lock_list_free = lle->ll_next;
1532 	mtx_unlock_spin(&w_mtx);
1533 	bzero(lle, sizeof(*lle));
1534 	return (lle);
1535 }
1536 
1537 static void
1538 witness_lock_list_free(struct lock_list_entry *lle)
1539 {
1540 
1541 	mtx_lock_spin(&w_mtx);
1542 	lle->ll_next = w_lock_list_free;
1543 	w_lock_list_free = lle;
1544 	mtx_unlock_spin(&w_mtx);
1545 }
1546 
1547 static struct lock_instance *
1548 find_instance(struct lock_list_entry *lock_list, struct lock_object *lock)
1549 {
1550 	struct lock_list_entry *lle;
1551 	struct lock_instance *instance;
1552 	int i;
1553 
1554 	for (lle = lock_list; lle != NULL; lle = lle->ll_next)
1555 		for (i = lle->ll_count - 1; i >= 0; i--) {
1556 			instance = &lle->ll_children[i];
1557 			if (instance->li_lock == lock)
1558 				return (instance);
1559 		}
1560 	return (NULL);
1561 }
1562 
1563 static void
1564 witness_list_lock(struct lock_instance *instance)
1565 {
1566 	struct lock_object *lock;
1567 
1568 	lock = instance->li_lock;
1569 	printf("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
1570 	    "exclusive" : "shared", lock->lo_class->lc_name, lock->lo_name);
1571 	if (lock->lo_type != lock->lo_name)
1572 		printf(" (%s)", lock->lo_type);
1573 	printf(" r = %d (%p) locked @ %s:%d\n",
1574 	    instance->li_flags & LI_RECURSEMASK, lock, instance->li_file,
1575 	    instance->li_line);
1576 }
1577 
1578 int
1579 witness_list_locks(struct lock_list_entry **lock_list)
1580 {
1581 	struct lock_list_entry *lle;
1582 	int i, nheld;
1583 
1584 	nheld = 0;
1585 	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
1586 		for (i = lle->ll_count - 1; i >= 0; i--) {
1587 			witness_list_lock(&lle->ll_children[i]);
1588 			nheld++;
1589 		}
1590 	return (nheld);
1591 }
1592 
1593 /*
1594  * This is a bit risky at best.  We call this function when we have timed
1595  * out acquiring a spin lock, and we assume that the other CPU is stuck
1596  * with this lock held.  So, we go groveling around in the other CPU's
1597  * per-cpu data to try to find the lock instance for this spin lock to
1598  * see when it was last acquired.
1599  */
1600 void
1601 witness_display_spinlock(struct lock_object *lock, struct thread *owner)
1602 {
1603 	struct lock_instance *instance;
1604 	struct pcpu *pc;
1605 
1606 	if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
1607 		return;
1608 	pc = pcpu_find(owner->td_oncpu);
1609 	instance = find_instance(pc->pc_spinlocks, lock);
1610 	if (instance != NULL)
1611 		witness_list_lock(instance);
1612 }
1613 
1614 void
1615 witness_save(struct lock_object *lock, const char **filep, int *linep)
1616 {
1617 	struct lock_instance *instance;
1618 
1619 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1620 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1621 		return;
1622 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1623 		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1624 		    lock->lo_class->lc_name, lock->lo_name);
1625 	instance = find_instance(curthread->td_sleeplocks, lock);
1626 	if (instance == NULL)
1627 		panic("%s: lock (%s) %s not locked", __func__,
1628 		    lock->lo_class->lc_name, lock->lo_name);
1629 	*filep = instance->li_file;
1630 	*linep = instance->li_line;
1631 }
1632 
1633 void
1634 witness_restore(struct lock_object *lock, const char *file, int line)
1635 {
1636 	struct lock_instance *instance;
1637 
1638 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1639 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1640 		return;
1641 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1642 		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1643 		    lock->lo_class->lc_name, lock->lo_name);
1644 	instance = find_instance(curthread->td_sleeplocks, lock);
1645 	if (instance == NULL)
1646 		panic("%s: lock (%s) %s not locked", __func__,
1647 		    lock->lo_class->lc_name, lock->lo_name);
1648 	lock->lo_witness->w_file = file;
1649 	lock->lo_witness->w_line = line;
1650 	instance->li_file = file;
1651 	instance->li_line = line;
1652 }
1653 
1654 void
1655 witness_assert(struct lock_object *lock, int flags, const char *file, int line)
1656 {
1657 #ifdef INVARIANT_SUPPORT
1658 	struct lock_instance *instance;
1659 
1660 	if (lock->lo_witness == NULL || witness_watch == 0 || panicstr != NULL)
1661 		return;
1662 	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) != 0)
1663 		instance = find_instance(curthread->td_sleeplocks, lock);
1664 	else if ((lock->lo_class->lc_flags & LC_SPINLOCK) != 0)
1665 		instance = find_instance(PCPU_GET(spinlocks), lock);
1666 	else {
1667 		panic("Lock (%s) %s is not sleep or spin!",
1668 		    lock->lo_class->lc_name, lock->lo_name);
1669 	}
1670 	file = fixup_filename(file);
1671 	switch (flags) {
1672 	case LA_UNLOCKED:
1673 		if (instance != NULL)
1674 			panic("Lock (%s) %s locked @ %s:%d.",
1675 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1676 		break;
1677 	case LA_LOCKED:
1678 	case LA_LOCKED | LA_RECURSED:
1679 	case LA_LOCKED | LA_NOTRECURSED:
1680 	case LA_SLOCKED:
1681 	case LA_SLOCKED | LA_RECURSED:
1682 	case LA_SLOCKED | LA_NOTRECURSED:
1683 	case LA_XLOCKED:
1684 	case LA_XLOCKED | LA_RECURSED:
1685 	case LA_XLOCKED | LA_NOTRECURSED:
1686 		if (instance == NULL) {
1687 			panic("Lock (%s) %s not locked @ %s:%d.",
1688 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1689 			break;
1690 		}
1691 		if ((flags & LA_XLOCKED) != 0 &&
1692 		    (instance->li_flags & LI_EXCLUSIVE) == 0)
1693 			panic("Lock (%s) %s not exclusively locked @ %s:%d.",
1694 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1695 		if ((flags & LA_SLOCKED) != 0 &&
1696 		    (instance->li_flags & LI_EXCLUSIVE) != 0)
1697 			panic("Lock (%s) %s exclusively locked @ %s:%d.",
1698 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1699 		if ((flags & LA_RECURSED) != 0 &&
1700 		    (instance->li_flags & LI_RECURSEMASK) == 0)
1701 			panic("Lock (%s) %s not recursed @ %s:%d.",
1702 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1703 		if ((flags & LA_NOTRECURSED) != 0 &&
1704 		    (instance->li_flags & LI_RECURSEMASK) != 0)
1705 			panic("Lock (%s) %s recursed @ %s:%d.",
1706 			    lock->lo_class->lc_name, lock->lo_name, file, line);
1707 		break;
1708 	default:
1709 		panic("Invalid lock assertion at %s:%d.", file, line);
1710 
1711 	}
1712 #endif	/* INVARIANT_SUPPORT */
1713 }
1714 
1715 #ifdef DDB
1716 static void
1717 witness_list(struct thread *td)
1718 {
1719 
1720 	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1721 	KASSERT(db_active, ("%s: not in the debugger", __func__));
1722 
1723 	if (witness_watch == 0)
1724 		return;
1725 
1726 	witness_list_locks(&td->td_sleeplocks);
1727 
1728 	/*
1729 	 * We only handle spinlocks if td == curthread.  This is somewhat broken
1730 	 * if td is currently executing on some other CPU and holds spin locks
1731 	 * as we won't display those locks.  If we had a MI way of getting
1732 	 * the per-cpu data for a given cpu then we could use
1733 	 * td->td_oncpu to get the list of spinlocks for this thread
1734 	 * and "fix" this.
1735 	 *
1736 	 * That still wouldn't really fix this unless we locked sched_lock
1737 	 * or stopped the other CPU to make sure it wasn't changing the list
1738 	 * out from under us.  It is probably best to just not try to handle
1739 	 * threads on other CPU's for now.
1740 	 */
1741 	if (td == curthread && PCPU_GET(spinlocks) != NULL)
1742 		witness_list_locks(PCPU_PTR(spinlocks));
1743 }
1744 
1745 DB_SHOW_COMMAND(locks, db_witness_list)
1746 {
1747 	struct thread *td;
1748 	pid_t pid;
1749 	struct proc *p;
1750 
1751 	if (have_addr) {
1752 		pid = (addr % 16) + ((addr >> 4) % 16) * 10 +
1753 		    ((addr >> 8) % 16) * 100 + ((addr >> 12) % 16) * 1000 +
1754 		    ((addr >> 16) % 16) * 10000;
1755 		/* sx_slock(&allproc_lock); */
1756 		FOREACH_PROC_IN_SYSTEM(p) {
1757 			if (p->p_pid == pid)
1758 				break;
1759 		}
1760 		/* sx_sunlock(&allproc_lock); */
1761 		if (p == NULL) {
1762 			db_printf("pid %d not found\n", pid);
1763 			return;
1764 		}
1765 		FOREACH_THREAD_IN_PROC(p, td) {
1766 			witness_list(td);
1767 		}
1768 	} else {
1769 		td = curthread;
1770 		witness_list(td);
1771 	}
1772 }
1773 
1774 DB_SHOW_COMMAND(witness, db_witness_display)
1775 {
1776 
1777 	witness_display(db_printf);
1778 }
1779 #endif
1780