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