subr_witness.c revision 84680
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 84680 2001-10-08 21:05:46Z 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#include "opt_ddb.h"
60#include "opt_witness.h"
61
62#include <sys/param.h>
63#include <sys/bus.h>
64#include <sys/kernel.h>
65#include <sys/ktr.h>
66#include <sys/lock.h>
67#include <sys/malloc.h>
68#include <sys/mutex.h>
69#include <sys/proc.h>
70#include <sys/sysctl.h>
71#include <sys/systm.h>
72
73#include <ddb/ddb.h>
74
75#define WITNESS_COUNT 200
76#define WITNESS_CHILDCOUNT (WITNESS_COUNT * 4)
77/*
78 * XXX: This is somewhat bogus, as we assume here that at most 1024 threads
79 * will hold LOCK_NCHILDREN * 2 locks.  We handle failure ok, and we should
80 * probably be safe for the most part, but it's still a SWAG.
81 */
82#define LOCK_CHILDCOUNT (MAXCPU + 1024) * 2
83
84#define	WITNESS_NCHILDREN 6
85
86struct witness_child_list_entry;
87
88struct witness {
89	const	char *w_name;
90	struct	lock_class *w_class;
91	STAILQ_ENTRY(witness) w_list;		/* List of all witnesses. */
92	STAILQ_ENTRY(witness) w_typelist;	/* Witnesses of a type. */
93	struct	witness_child_list_entry *w_children;	/* Great evilness... */
94	const	char *w_file;
95	int	w_line;
96	u_int	w_level;
97	u_int	w_refcount;
98	u_char	w_Giant_squawked:1;
99	u_char	w_other_squawked:1;
100	u_char	w_same_squawked:1;
101};
102
103struct witness_child_list_entry {
104	struct	witness_child_list_entry *wcl_next;
105	struct	witness *wcl_children[WITNESS_NCHILDREN];
106	u_int	wcl_count;
107};
108
109STAILQ_HEAD(witness_list, witness);
110
111struct witness_blessed {
112	const	char *b_lock1;
113	const	char *b_lock2;
114};
115
116struct witness_order_list_entry {
117	const	char *w_name;
118	struct	lock_class *w_class;
119};
120
121static struct	witness *enroll(const char *description,
122				struct lock_class *lock_class);
123static int	itismychild(struct witness *parent, struct witness *child);
124static void	removechild(struct witness *parent, struct witness *child);
125static int	isitmychild(struct witness *parent, struct witness *child);
126static int	isitmydescendant(struct witness *parent, struct witness *child);
127static int	dup_ok(struct witness *);
128static int	blessed(struct witness *, struct witness *);
129static void	witness_display_list(void(*prnt)(const char *fmt, ...),
130				     struct witness_list *list);
131static void	witness_displaydescendants(void(*)(const char *fmt, ...),
132					   struct witness *);
133static void	witness_leveldescendents(struct witness *parent, int level);
134static void	witness_levelall(void);
135static struct	witness *witness_get(void);
136static void	witness_free(struct witness *m);
137static struct	witness_child_list_entry *witness_child_get(void);
138static void	witness_child_free(struct witness_child_list_entry *wcl);
139static struct	lock_list_entry *witness_lock_list_get(void);
140static void	witness_lock_list_free(struct lock_list_entry *lle);
141static void	witness_display(void(*)(const char *fmt, ...));
142static struct	lock_instance *find_instance(struct lock_list_entry *lock_list,
143					     struct lock_object *lock);
144
145MALLOC_DEFINE(M_WITNESS, "witness", "witness structure");
146
147static int witness_watch = 1;
148TUNABLE_INT("debug.witness_watch", &witness_watch);
149SYSCTL_INT(_debug, OID_AUTO, witness_watch, CTLFLAG_RD, &witness_watch, 0, "");
150
151#ifdef DDB
152/*
153 * When DDB is enabled and witness_ddb is set to 1, it will cause the system to
154 * drop into kdebug() when:
155 *	- a lock heirarchy violation occurs
156 *	- locks are held when going to sleep.
157 */
158#ifdef WITNESS_DDB
159int	witness_ddb = 1;
160#else
161int	witness_ddb = 0;
162#endif
163TUNABLE_INT("debug.witness_ddb", &witness_ddb);
164SYSCTL_INT(_debug, OID_AUTO, witness_ddb, CTLFLAG_RW, &witness_ddb, 0, "");
165#endif /* DDB */
166
167#ifdef WITNESS_SKIPSPIN
168int	witness_skipspin = 1;
169#else
170int	witness_skipspin = 0;
171#endif
172TUNABLE_INT("debug.witness_skipspin", &witness_skipspin);
173SYSCTL_INT(_debug, OID_AUTO, witness_skipspin, CTLFLAG_RD, &witness_skipspin, 0,
174    "");
175
176static struct mtx w_mtx;
177static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
178static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
179static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
180static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
181static struct witness_child_list_entry *w_child_free = NULL;
182static struct lock_list_entry *w_lock_list_free = NULL;
183static int witness_dead;	/* fatal error, probably no memory */
184
185static struct witness w_data[WITNESS_COUNT];
186static struct witness_child_list_entry w_childdata[WITNESS_CHILDCOUNT];
187static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
188
189static struct witness_order_list_entry order_lists[] = {
190	{ "Giant", &lock_class_mtx_sleep },
191	{ "proctree", &lock_class_sx },
192	{ "allproc", &lock_class_sx },
193	{ "process lock", &lock_class_mtx_sleep },
194	{ "uidinfo hash", &lock_class_mtx_sleep },
195	{ "uidinfo struct", &lock_class_mtx_sleep },
196	{ NULL, NULL },
197	/*
198	 * spin locks
199	 */
200#ifdef SMP
201	{ "ap boot", &lock_class_mtx_spin },
202#ifdef __i386__
203	{ "com", &lock_class_mtx_spin },
204#endif
205#endif
206	{ "sio", &lock_class_mtx_spin },
207#ifdef __i386__
208	{ "cy", &lock_class_mtx_spin },
209#endif
210	{ "ng_node", &lock_class_mtx_spin },
211	{ "ng_worklist", &lock_class_mtx_spin },
212	{ "ithread table lock", &lock_class_mtx_spin },
213	{ "sched lock", &lock_class_mtx_spin },
214	{ "callout", &lock_class_mtx_spin },
215	/*
216	 * leaf locks
217	 */
218#ifdef SMP
219#ifdef __i386__
220	{ "imen", &lock_class_mtx_spin },
221#endif
222	{ "smp rendezvous", &lock_class_mtx_spin },
223#endif
224	{ "clk", &lock_class_mtx_spin },
225	{ NULL, NULL },
226	{ NULL, NULL }
227};
228
229static const char *dup_list[] = {
230	"process lock",
231	NULL
232};
233
234/*
235 * Pairs of locks which have been blessed
236 * Don't complain about order problems with blessed locks
237 */
238static struct witness_blessed blessed_list[] = {
239};
240static int blessed_count =
241	sizeof(blessed_list) / sizeof(struct witness_blessed);
242
243/*
244 * List of all locks in the system.
245 */
246STAILQ_HEAD(, lock_object) all_locks = STAILQ_HEAD_INITIALIZER(all_locks);
247
248static struct mtx all_mtx = {
249	{ &lock_class_mtx_sleep,	/* mtx_object.lo_class */
250	  "All locks list",		/* mtx_object.lo_name */
251	  LO_INITIALIZED,		/* mtx_object.lo_flags */
252	  { NULL },			/* mtx_object.lo_list */
253	  NULL },			/* mtx_object.lo_witness */
254	MTX_UNOWNED, 0,			/* mtx_lock, mtx_recurse */
255	0,				/* mtx_savecrit */
256	TAILQ_HEAD_INITIALIZER(all_mtx.mtx_blocked),
257	{ NULL, NULL }			/* mtx_contested */
258};
259
260/*
261 * This global is set to 0 once it becomes safe to use the witness code.
262 */
263static int witness_cold = 1;
264
265/*
266 * Global variables for book keeping.
267 */
268static int lock_cur_cnt;
269static int lock_max_cnt;
270
271/*
272 * The WITNESS-enabled diagnostic code.
273 */
274static void
275witness_initialize(void *dummy __unused)
276{
277	struct lock_object *lock;
278	struct witness_order_list_entry *order;
279	struct witness *w, *w1;
280	int i;
281
282	/*
283	 * We have to release Giant before initializing its witness
284	 * structure so that WITNESS doesn't get confused.
285	 */
286	mtx_unlock(&Giant);
287	mtx_assert(&Giant, MA_NOTOWNED);
288
289	CTR0(KTR_WITNESS, __func__ ": initializing witness");
290	STAILQ_INSERT_HEAD(&all_locks, &all_mtx.mtx_object, lo_list);
291	mtx_init(&w_mtx, "witness lock", MTX_SPIN | MTX_QUIET | MTX_NOWITNESS);
292	for (i = 0; i < WITNESS_COUNT; i++)
293		witness_free(&w_data[i]);
294	for (i = 0; i < WITNESS_CHILDCOUNT; i++)
295		witness_child_free(&w_childdata[i]);
296	for (i = 0; i < LOCK_CHILDCOUNT; i++)
297		witness_lock_list_free(&w_locklistdata[i]);
298
299	/* First add in all the specified order lists. */
300	for (order = order_lists; order->w_name != NULL; order++) {
301		w = enroll(order->w_name, order->w_class);
302		if (w == NULL)
303			continue;
304		w->w_file = "order list";
305		for (order++; order->w_name != NULL; order++) {
306			w1 = enroll(order->w_name, order->w_class);
307			if (w1 == NULL)
308				continue;
309			w1->w_file = "order list";
310			itismychild(w, w1);
311			w = w1;
312		}
313	}
314
315	/* Iterate through all locks and add them to witness. */
316	mtx_lock(&all_mtx);
317	STAILQ_FOREACH(lock, &all_locks, lo_list) {
318		if (lock->lo_flags & LO_WITNESS)
319			lock->lo_witness = enroll(lock->lo_name,
320			    lock->lo_class);
321		else
322			lock->lo_witness = NULL;
323	}
324	mtx_unlock(&all_mtx);
325
326	/* Mark the witness code as being ready for use. */
327	atomic_store_rel_int(&witness_cold, 0);
328
329	mtx_lock(&Giant);
330}
331SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize, NULL)
332
333void
334witness_init(struct lock_object *lock)
335{
336	struct lock_class *class;
337
338	class = lock->lo_class;
339	if (lock->lo_flags & LO_INITIALIZED)
340		panic("%s: lock (%s) %s is already initialized", __func__,
341		    class->lc_name, lock->lo_name);
342	if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
343	    (class->lc_flags & LC_RECURSABLE) == 0)
344		panic("%s: lock (%s) %s can not be recursable", __func__,
345		    class->lc_name, lock->lo_name);
346	if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
347	    (class->lc_flags & LC_SLEEPABLE) == 0)
348		panic("%s: lock (%s) %s can not be sleepable", __func__,
349		    class->lc_name, lock->lo_name);
350	if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
351	    (class->lc_flags & LC_UPGRADABLE) == 0)
352		panic("%s: lock (%s) %s can not be upgradable", __func__,
353		    class->lc_name, lock->lo_name);
354
355	mtx_lock(&all_mtx);
356	STAILQ_INSERT_TAIL(&all_locks, lock, lo_list);
357	lock->lo_flags |= LO_INITIALIZED;
358	lock_cur_cnt++;
359	if (lock_cur_cnt > lock_max_cnt)
360		lock_max_cnt = lock_cur_cnt;
361	mtx_unlock(&all_mtx);
362	if (!witness_cold && !witness_dead && panicstr == NULL &&
363	    (lock->lo_flags & LO_WITNESS) != 0)
364		lock->lo_witness = enroll(lock->lo_name, class);
365	else
366		lock->lo_witness = NULL;
367}
368
369void
370witness_destroy(struct lock_object *lock)
371{
372	struct witness *w;
373
374	if (witness_cold)
375		panic("lock (%s) %s destroyed while witness_cold",
376		    lock->lo_class->lc_name, lock->lo_name);
377	if ((lock->lo_flags & LO_INITIALIZED) == 0)
378		panic("%s: lock (%s) %s is not initialized", __func__,
379		    lock->lo_class->lc_name, lock->lo_name);
380
381	/* XXX: need to verify that no one holds the lock */
382	w = lock->lo_witness;
383	if (w != NULL) {
384		mtx_lock_spin(&w_mtx);
385		w->w_refcount--;
386		if (w->w_refcount == 0) {
387			CTR1(KTR_WITNESS,
388			    __func__ ": marking witness %s as dead", w->w_name);
389			w->w_name = "(dead)";
390			w->w_file = "(dead)";
391			w->w_line = 0;
392		}
393		mtx_unlock_spin(&w_mtx);
394	}
395
396	mtx_lock(&all_mtx);
397	lock_cur_cnt--;
398	STAILQ_REMOVE(&all_locks, lock, lock_object, lo_list);
399	lock->lo_flags &= ~LO_INITIALIZED;
400	mtx_unlock(&all_mtx);
401}
402
403static void
404witness_display_list(void(*prnt)(const char *fmt, ...),
405		     struct witness_list *list)
406{
407	struct witness *w, *w1;
408	int found;
409
410	STAILQ_FOREACH(w, list, w_typelist) {
411		if (w->w_file == NULL)
412			continue;
413		found = 0;
414		STAILQ_FOREACH(w1, list, w_typelist) {
415			if (isitmychild(w1, w)) {
416				found++;
417				break;
418			}
419		}
420		if (found)
421			continue;
422		/*
423		 * This lock has no anscestors, display its descendants.
424		 */
425		witness_displaydescendants(prnt, w);
426	}
427}
428
429static void
430witness_display(void(*prnt)(const char *fmt, ...))
431{
432	struct witness *w;
433
434	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
435	witness_levelall();
436
437	/*
438	 * First, handle sleep locks which have been acquired at least
439	 * once.
440	 */
441	prnt("Sleep locks:\n");
442	witness_display_list(prnt, &w_sleep);
443
444	/*
445	 * Now do spin locks which have been acquired at least once.
446	 */
447	prnt("\nSpin locks:\n");
448	witness_display_list(prnt, &w_spin);
449
450	/*
451	 * Finally, any locks which have not been acquired yet.
452	 */
453	prnt("\nLocks which were never acquired:\n");
454	STAILQ_FOREACH(w, &w_all, w_list) {
455		if (w->w_file != NULL)
456			continue;
457		prnt("%s\n", w->w_name);
458	}
459}
460
461void
462witness_lock(struct lock_object *lock, int flags, const char *file, int line)
463{
464	struct lock_list_entry **lock_list, *lle;
465	struct lock_instance *lock1, *lock2;
466	struct lock_class *class;
467	struct witness *w, *w1;
468	struct thread *td;
469	int i, j;
470#ifdef DDB
471	int go_into_ddb = 0;
472#endif /* DDB */
473
474	if (witness_cold || witness_dead || lock->lo_witness == NULL ||
475	    panicstr != NULL)
476		return;
477	w = lock->lo_witness;
478	class = lock->lo_class;
479	td = curthread;
480
481	/*
482	 * We have to hold a spinlock to keep lock_list valid across the check
483	 * in the LC_SLEEPLOCK case.  In the LC_SPINLOCK case, it is already
484	 * protected by the spinlock we are currently performing the witness
485	 * checks on, so it is ok to release the lock after performing this
486	 * check.  All we have to protect is the LC_SLEEPLOCK case when no
487	 * spinlocks are held as we may get preempted during this check and
488	 * lock_list could end up pointing to some other CPU's spinlock list.
489	 */
490	mtx_lock_spin(&w_mtx);
491	lock_list = PCPU_PTR(spinlocks);
492	if (class->lc_flags & LC_SLEEPLOCK) {
493		if (*lock_list != NULL && (flags & LOP_TRYLOCK) == 0) {
494			mtx_unlock_spin(&w_mtx);
495			panic("blockable sleep lock (%s) %s @ %s:%d",
496			    class->lc_name, lock->lo_name, file, line);
497		}
498		lock_list = &td->td_sleeplocks;
499	}
500	mtx_unlock_spin(&w_mtx);
501
502	/*
503	 * Try locks do not block if they fail to acquire the lock, thus
504	 * there is no danger of deadlocks or of switching while holding a
505	 * spin lock if we acquire a lock via a try operation.
506	 */
507	if (flags & LOP_TRYLOCK)
508		goto out;
509
510	/*
511	 * Is this the first lock acquired?  If so, then no order checking
512	 * is needed.
513	 */
514	if (*lock_list == NULL)
515		goto out;
516
517	/*
518	 * Check to see if we are recursing on a lock we already own.
519	 */
520	lock1 = find_instance(*lock_list, lock);
521	if (lock1 != NULL) {
522		if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
523		    (flags & LOP_EXCLUSIVE) == 0) {
524			printf("shared lock of (%s) %s @ %s:%d\n",
525			    class->lc_name, lock->lo_name, file, line);
526			printf("while exclusively locked from %s:%d\n",
527			    lock1->li_file, lock1->li_line);
528			panic("share->excl");
529		}
530		if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
531		    (flags & LOP_EXCLUSIVE) != 0) {
532			printf("exclusive lock of (%s) %s @ %s:%d\n",
533			    class->lc_name, lock->lo_name, file, line);
534			printf("while share locked from %s:%d\n",
535			    lock1->li_file, lock1->li_line);
536			panic("excl->share");
537		}
538		lock1->li_flags++;
539		if ((lock->lo_flags & LO_RECURSABLE) == 0) {
540			printf(
541			"recursed on non-recursive lock (%s) %s @ %s:%d\n",
542			    class->lc_name, lock->lo_name, file, line);
543			printf("first acquired @ %s:%d\n", lock1->li_file,
544			    lock1->li_line);
545			panic("recurse");
546		}
547		CTR3(KTR_WITNESS, __func__ ": pid %d recursed on %s r=%d",
548		    td->td_proc->p_pid, lock->lo_name,
549		    lock1->li_flags & LI_RECURSEMASK);
550		lock1->li_file = file;
551		lock1->li_line = line;
552		return;
553	}
554
555	/*
556	 * Check for duplicate locks of the same type.  Note that we only
557	 * have to check for this on the last lock we just acquired.  Any
558	 * other cases will be caught as lock order violations.
559	 */
560	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
561	w1 = lock1->li_lock->lo_witness;
562	if (w1 == w) {
563		if (w->w_same_squawked || dup_ok(w))
564			goto out;
565		w->w_same_squawked = 1;
566		printf("acquiring duplicate lock of same type: \"%s\"\n",
567			lock->lo_name);
568		printf(" 1st @ %s:%d\n", lock1->li_file, lock1->li_line);
569		printf(" 2nd @ %s:%d\n", file, line);
570#ifdef DDB
571		go_into_ddb = 1;
572#endif /* DDB */
573		goto out;
574	}
575	MPASS(!mtx_owned(&w_mtx));
576	mtx_lock_spin(&w_mtx);
577	/*
578	 * If we have a known higher number just say ok
579	 */
580	if (witness_watch > 1 && w->w_level > w1->w_level) {
581		mtx_unlock_spin(&w_mtx);
582		goto out;
583	}
584	if (isitmydescendant(w1, w)) {
585		mtx_unlock_spin(&w_mtx);
586		goto out;
587	}
588	for (j = 0, lle = *lock_list; lle != NULL; lle = lle->ll_next) {
589		for (i = lle->ll_count - 1; i >= 0; i--, j++) {
590
591			MPASS(j < WITNESS_COUNT);
592			lock1 = &lle->ll_children[i];
593			w1 = lock1->li_lock->lo_witness;
594
595			/*
596			 * If this lock doesn't undergo witness checking,
597			 * then skip it.
598			 */
599			if (w1 == NULL) {
600				KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
601				    ("lock missing witness structure"));
602				continue;
603			}
604			/*
605			 * If we are locking Giant and we slept with this
606			 * lock, then skip it.
607			 */
608			if ((lock1->li_flags & LI_SLEPT) != 0 &&
609			    lock == &Giant.mtx_object)
610				continue;
611			if (!isitmydescendant(w, w1))
612				continue;
613			/*
614			 * We have a lock order violation, check to see if it
615			 * is allowed or has already been yelled about.
616			 */
617			mtx_unlock_spin(&w_mtx);
618			if (blessed(w, w1))
619				goto out;
620			if (lock1->li_lock == &Giant.mtx_object) {
621				if (w1->w_Giant_squawked)
622					goto out;
623				else
624					w1->w_Giant_squawked = 1;
625			} else {
626				if (w1->w_other_squawked)
627					goto out;
628				else
629					w1->w_other_squawked = 1;
630			}
631			/*
632			 * Ok, yell about it.
633			 */
634			printf("lock order reversal\n");
635			/*
636			 * Try to locate an earlier lock with
637			 * witness w in our list.
638			 */
639			do {
640				lock2 = &lle->ll_children[i];
641				MPASS(lock2->li_lock != NULL);
642				if (lock2->li_lock->lo_witness == w)
643					break;
644				i--;
645				if (i == 0 && lle->ll_next != NULL) {
646					lle = lle->ll_next;
647					i = lle->ll_count - 1;
648					MPASS(i != 0);
649				}
650			} while (i >= 0);
651			if (i < 0) {
652				printf(" 1st %p %s @ %s:%d\n", lock1->li_lock,
653				    lock1->li_lock->lo_name, lock1->li_file,
654				    lock1->li_line);
655				printf(" 2nd %p %s @ %s:%d\n", lock,
656				    lock->lo_name, file, line);
657			} else {
658				printf(" 1st %p %s @ %s:%d\n", lock2->li_lock,
659				    lock2->li_lock->lo_name, lock2->li_file,
660				    lock2->li_line);
661				printf(" 2nd %p %s @ %s:%d\n", lock1->li_lock,
662				    lock1->li_lock->lo_name, lock1->li_file,
663				    lock1->li_line);
664				printf(" 3rd %p %s @ %s:%d\n", lock,
665				    lock->lo_name, file, line);
666			}
667#ifdef DDB
668			go_into_ddb = 1;
669#endif /* DDB */
670			goto out;
671		}
672	}
673	lock1 = &(*lock_list)->ll_children[(*lock_list)->ll_count - 1];
674	/*
675	 * Don't build a new relationship if we are locking Giant just
676	 * after waking up and the previous lock in the list was acquired
677	 * prior to blocking.
678	 */
679	if (lock == &Giant.mtx_object && (lock1->li_flags & LI_SLEPT) != 0)
680		mtx_unlock_spin(&w_mtx);
681	else {
682		CTR2(KTR_WITNESS, __func__ ": adding %s as a child of %s",
683		    lock->lo_name, lock1->li_lock->lo_name);
684		if (!itismychild(lock1->li_lock->lo_witness, w))
685			mtx_unlock_spin(&w_mtx);
686	}
687
688out:
689#ifdef DDB
690	if (witness_ddb && go_into_ddb)
691		Debugger(__func__);
692#endif /* DDB */
693	w->w_file = file;
694	w->w_line = line;
695
696	lle = *lock_list;
697	if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
698		lle = witness_lock_list_get();
699		if (lle == NULL)
700			return;
701		lle->ll_next = *lock_list;
702		CTR2(KTR_WITNESS, __func__ ": pid %d added lle %p",
703		    td->td_proc->p_pid, lle);
704		*lock_list = lle;
705	}
706	lock1 = &lle->ll_children[lle->ll_count++];
707	lock1->li_lock = lock;
708	lock1->li_line = line;
709	lock1->li_file = file;
710	if ((flags & LOP_EXCLUSIVE) != 0)
711		lock1->li_flags = LI_EXCLUSIVE;
712	else
713		lock1->li_flags = 0;
714	CTR3(KTR_WITNESS, __func__ ": pid %d added %s as lle[%d]",
715	    td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
716}
717
718void
719witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
720{
721	struct lock_instance *instance;
722	struct lock_class *class;
723
724	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
725	if (lock->lo_witness == NULL || witness_dead || panicstr != NULL)
726		return;
727	class = lock->lo_class;
728	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
729		panic("upgrade of non-upgradable lock (%s) %s @ %s:%d",
730		    class->lc_name, lock->lo_name, file, line);
731	if ((flags & LOP_TRYLOCK) == 0)
732		panic("non-try upgrade of lock (%s) %s @ %s:%d", class->lc_name,
733		    lock->lo_name, file, line);
734	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
735		panic("upgrade of non-sleep lock (%s) %s @ %s:%d",
736		    class->lc_name, lock->lo_name, file, line);
737	instance = find_instance(curthread->td_sleeplocks, lock);
738	if (instance == NULL)
739		panic("upgrade of unlocked lock (%s) %s @ %s:%d",
740		    class->lc_name, lock->lo_name, file, line);
741	if ((instance->li_flags & LI_EXCLUSIVE) != 0)
742		panic("upgrade of exclusive lock (%s) %s @ %s:%d",
743		    class->lc_name, lock->lo_name, file, line);
744	if ((instance->li_flags & LI_RECURSEMASK) != 0)
745		panic("upgrade of recursed lock (%s) %s r=%d @ %s:%d",
746		    class->lc_name, lock->lo_name,
747		    instance->li_flags & LI_RECURSEMASK, file, line);
748	instance->li_flags |= LI_EXCLUSIVE;
749}
750
751void
752witness_downgrade(struct lock_object *lock, int flags, const char *file,
753    int line)
754{
755	struct lock_instance *instance;
756	struct lock_class *class;
757
758	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
759	if (lock->lo_witness == NULL || witness_dead || panicstr != NULL)
760		return;
761	class = lock->lo_class;
762	if ((lock->lo_flags & LO_UPGRADABLE) == 0)
763		panic("downgrade of non-upgradable lock (%s) %s @ %s:%d",
764		    class->lc_name, lock->lo_name, file, line);
765	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
766		panic("downgrade of non-sleep lock (%s) %s @ %s:%d",
767		    class->lc_name, lock->lo_name, file, line);
768	instance = find_instance(curthread->td_sleeplocks, lock);
769	if (instance == NULL)
770		panic("downgrade of unlocked lock (%s) %s @ %s:%d",
771		    class->lc_name, lock->lo_name, file, line);
772	if ((instance->li_flags & LI_EXCLUSIVE) == 0)
773		panic("downgrade of shared lock (%s) %s @ %s:%d",
774		    class->lc_name, lock->lo_name, file, line);
775	if ((instance->li_flags & LI_RECURSEMASK) != 0)
776		panic("downgrade of recursed lock (%s) %s r=%d @ %s:%d",
777		    class->lc_name, lock->lo_name,
778		    instance->li_flags & LI_RECURSEMASK, file, line);
779	instance->li_flags &= ~LI_EXCLUSIVE;
780}
781
782void
783witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
784{
785	struct lock_list_entry **lock_list, *lle;
786	struct lock_instance *instance;
787	struct lock_class *class;
788	struct thread *td;
789	critical_t s;
790	int i, j;
791
792	if (witness_cold || witness_dead || lock->lo_witness == NULL ||
793	    panicstr != NULL)
794		return;
795	td = curthread;
796	class = lock->lo_class;
797	if (class->lc_flags & LC_SLEEPLOCK)
798		lock_list = &td->td_sleeplocks;
799	else
800		lock_list = PCPU_PTR(spinlocks);
801	for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
802		for (i = 0; i < (*lock_list)->ll_count; i++) {
803			instance = &(*lock_list)->ll_children[i];
804			if (instance->li_lock == lock) {
805				if ((instance->li_flags & LI_EXCLUSIVE) != 0 &&
806				    (flags & LOP_EXCLUSIVE) == 0) {
807					printf(
808					"shared unlock of (%s) %s @ %s:%d\n",
809					    class->lc_name, lock->lo_name,
810					    file, line);
811					printf(
812					"while exclusively locked from %s:%d\n",
813					    instance->li_file,
814					    instance->li_line);
815					panic("excl->ushare");
816				}
817				if ((instance->li_flags & LI_EXCLUSIVE) == 0 &&
818				    (flags & LOP_EXCLUSIVE) != 0) {
819					printf(
820					"exclusive unlock of (%s) %s @ %s:%d\n",
821					    class->lc_name, lock->lo_name,
822					    file, line);
823					printf(
824					"while share locked from %s:%d\n",
825					    instance->li_file,
826					    instance->li_line);
827					panic("share->uexcl");
828				}
829				/* If we are recursed, unrecurse. */
830				if ((instance->li_flags & LI_RECURSEMASK) > 0) {
831					CTR3(KTR_WITNESS,
832				    __func__ ": pid %d unrecursed on %s r=%d",
833					    td->td_proc->p_pid,
834					    instance->li_lock->lo_name,
835					    instance->li_flags);
836					instance->li_flags--;
837					goto out;
838				}
839				s = critical_enter();
840				CTR3(KTR_WITNESS,
841				    __func__ ": pid %d removed %s from lle[%d]",
842				    td->td_proc->p_pid,
843				    instance->li_lock->lo_name,
844				    (*lock_list)->ll_count - 1);
845				(*lock_list)->ll_count--;
846				for (j = i; j < (*lock_list)->ll_count; j++)
847					(*lock_list)->ll_children[j] =
848					    (*lock_list)->ll_children[j + 1];
849				critical_exit(s);
850				if ((*lock_list)->ll_count == 0) {
851					lle = *lock_list;
852					*lock_list = lle->ll_next;
853					CTR2(KTR_WITNESS,
854					    __func__ ": pid %d removed lle %p",
855					    td->td_proc->p_pid, lle);
856					witness_lock_list_free(lle);
857				}
858				goto out;
859			}
860		}
861	panic("lock (%s) %s not locked @ %s:%d", class->lc_name, lock->lo_name,
862	    file, line);
863out:
864	/*
865	 * We don't need to protect this PCPU_GET() here against preemption
866	 * because if we hold any spinlocks then we are already protected,
867	 * and if we don't we will get NULL if we hold no spinlocks even if
868	 * we switch CPU's while reading it.
869	 */
870	if (class->lc_flags & LC_SLEEPLOCK) {
871		if ((flags & LOP_NOSWITCH) == 0 && PCPU_GET(spinlocks) != NULL)
872			panic("switchable sleep unlock (%s) %s @ %s:%d",
873			    class->lc_name, lock->lo_name, file, line);
874	}
875}
876
877/*
878 * Warn if any held locks are not sleepable.  Note that Giant and the lock
879 * passed in are both special cases since they are both released during the
880 * sleep process and aren't actually held while the thread is asleep.
881 */
882int
883witness_sleep(int check_only, struct lock_object *lock, const char *file,
884	      int line)
885{
886	struct lock_list_entry **lock_list, *lle;
887	struct lock_instance *lock1;
888	struct thread *td;
889	critical_t savecrit;
890	int i, n;
891
892	if (witness_dead || panicstr != NULL)
893		return (0);
894	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
895	n = 0;
896	/*
897	 * Preemption bad because we need PCPU_PTR(spinlocks) to not change.
898	 */
899	savecrit = critical_enter();
900	td = curthread;
901	lock_list = &td->td_sleeplocks;
902again:
903	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
904		for (i = lle->ll_count - 1; i >= 0; i--) {
905			lock1 = &lle->ll_children[i];
906			if (lock1->li_lock == lock ||
907			    lock1->li_lock == &Giant.mtx_object)
908				continue;
909			if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0) {
910				if (check_only == 0) {
911					CTR3(KTR_WITNESS,
912				    "pid %d: sleeping with lock (%s) %s held",
913					    td->td_proc->p_pid,
914					    lock1->li_lock->lo_class->lc_name,
915					    lock1->li_lock->lo_name);
916					lock1->li_flags |= LI_SLEPT;
917				}
918				continue;
919			}
920			n++;
921			printf("%s:%d: %s with \"%s\" locked from %s:%d\n",
922			    file, line, check_only ? "could sleep" : "sleeping",
923			    lock1->li_lock->lo_name, lock1->li_file,
924			    lock1->li_line);
925		}
926	if (lock_list == &td->td_sleeplocks) {
927		lock_list = PCPU_PTR(spinlocks);
928		goto again;
929	}
930#ifdef DDB
931	if (witness_ddb && n)
932		Debugger(__func__);
933#endif /* DDB */
934	critical_exit(savecrit);
935	return (n);
936}
937
938static struct witness *
939enroll(const char *description, struct lock_class *lock_class)
940{
941	struct witness *w;
942
943	if (!witness_watch || witness_dead || panicstr != NULL)
944		return (NULL);
945	if ((lock_class->lc_flags & LC_SPINLOCK) && witness_skipspin)
946		return (NULL);
947	mtx_lock_spin(&w_mtx);
948	STAILQ_FOREACH(w, &w_all, w_list) {
949		if (strcmp(description, w->w_name) == 0) {
950			w->w_refcount++;
951			mtx_unlock_spin(&w_mtx);
952			if (lock_class != w->w_class)
953				panic(
954				"lock (%s) %s does not match earlier (%s) lock",
955				    description, lock_class->lc_name,
956				    w->w_class->lc_name);
957			return (w);
958		}
959	}
960	/*
961	 * This isn't quite right, as witness_cold is still 0 while we
962	 * enroll all the locks initialized before witness_initialize().
963	 */
964	if ((lock_class->lc_flags & LC_SPINLOCK) && !witness_cold) {
965		mtx_unlock_spin(&w_mtx);
966		panic("spin lock %s not in order list", description);
967	}
968	if ((w = witness_get()) == NULL)
969		return (NULL);
970	w->w_name = description;
971	w->w_class = lock_class;
972	w->w_refcount = 1;
973	STAILQ_INSERT_HEAD(&w_all, w, w_list);
974	if (lock_class->lc_flags & LC_SPINLOCK)
975		STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
976	else if (lock_class->lc_flags & LC_SLEEPLOCK)
977		STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
978	else {
979		mtx_unlock_spin(&w_mtx);
980		panic("lock class %s is not sleep or spin",
981		    lock_class->lc_name);
982	}
983	mtx_unlock_spin(&w_mtx);
984	return (w);
985}
986
987static int
988itismychild(struct witness *parent, struct witness *child)
989{
990	static int recursed;
991	struct witness_child_list_entry **wcl;
992	struct witness_list *list;
993
994	MPASS(child != NULL && parent != NULL);
995	if ((parent->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) !=
996	    (child->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)))
997		panic(
998		"%s: parent (%s) and child (%s) are not the same lock type",
999		    __func__, parent->w_class->lc_name,
1000		    child->w_class->lc_name);
1001
1002	/*
1003	 * Insert "child" after "parent"
1004	 */
1005	wcl = &parent->w_children;
1006	while (*wcl != NULL && (*wcl)->wcl_count == WITNESS_NCHILDREN)
1007		wcl = &(*wcl)->wcl_next;
1008	if (*wcl == NULL) {
1009		*wcl = witness_child_get();
1010		if (*wcl == NULL)
1011			return (1);
1012	}
1013	(*wcl)->wcl_children[(*wcl)->wcl_count++] = child;
1014
1015	/*
1016	 * Now prune whole tree.  We look for cases where a lock is now
1017	 * both a descendant and a direct child of a given lock.  In that
1018	 * case, we want to remove the direct child link from the tree.
1019	 */
1020	if (recursed)
1021		return (0);
1022	recursed = 1;
1023	if (parent->w_class->lc_flags & LC_SLEEPLOCK)
1024		list = &w_sleep;
1025	else
1026		list = &w_spin;
1027	STAILQ_FOREACH(child, list, w_typelist) {
1028		STAILQ_FOREACH(parent, list, w_typelist) {
1029			if (!isitmychild(parent, child))
1030				continue;
1031			removechild(parent, child);
1032			if (isitmydescendant(parent, child))
1033				continue;
1034			itismychild(parent, child);
1035		}
1036	}
1037	recursed = 0;
1038	witness_levelall();
1039	return (0);
1040}
1041
1042static void
1043removechild(struct witness *parent, struct witness *child)
1044{
1045	struct witness_child_list_entry **wcl, *wcl1;
1046	int i;
1047
1048	for (wcl = &parent->w_children; *wcl != NULL; wcl = &(*wcl)->wcl_next)
1049		for (i = 0; i < (*wcl)->wcl_count; i++)
1050			if ((*wcl)->wcl_children[i] == child)
1051				goto found;
1052	return;
1053found:
1054	(*wcl)->wcl_count--;
1055	if ((*wcl)->wcl_count > i)
1056		(*wcl)->wcl_children[i] =
1057		    (*wcl)->wcl_children[(*wcl)->wcl_count];
1058	MPASS((*wcl)->wcl_children[i] != NULL);
1059	if ((*wcl)->wcl_count != 0)
1060		return;
1061	wcl1 = *wcl;
1062	*wcl = wcl1->wcl_next;
1063	witness_child_free(wcl1);
1064}
1065
1066static int
1067isitmychild(struct witness *parent, struct witness *child)
1068{
1069	struct witness_child_list_entry *wcl;
1070	int i;
1071
1072	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1073		for (i = 0; i < wcl->wcl_count; i++) {
1074			if (wcl->wcl_children[i] == child)
1075				return (1);
1076		}
1077	}
1078	return (0);
1079}
1080
1081static int
1082isitmydescendant(struct witness *parent, struct witness *child)
1083{
1084	struct witness_child_list_entry *wcl;
1085	int i, j;
1086
1087	if (isitmychild(parent, child))
1088		return (1);
1089	j = 0;
1090	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next) {
1091		MPASS(j < 1000);
1092		for (i = 0; i < wcl->wcl_count; i++) {
1093			if (isitmydescendant(wcl->wcl_children[i], child))
1094				return (1);
1095		}
1096		j++;
1097	}
1098	return (0);
1099}
1100
1101void
1102witness_levelall (void)
1103{
1104	struct witness_list *list;
1105	struct witness *w, *w1;
1106
1107	/*
1108	 * First clear all levels.
1109	 */
1110	STAILQ_FOREACH(w, &w_all, w_list) {
1111		w->w_level = 0;
1112	}
1113
1114	/*
1115	 * Look for locks with no parent and level all their descendants.
1116	 */
1117	STAILQ_FOREACH(w, &w_all, w_list) {
1118		/*
1119		 * This is just an optimization, technically we could get
1120		 * away just walking the all list each time.
1121		 */
1122		if (w->w_class->lc_flags & LC_SLEEPLOCK)
1123			list = &w_sleep;
1124		else
1125			list = &w_spin;
1126		STAILQ_FOREACH(w1, list, w_typelist) {
1127			if (isitmychild(w1, w))
1128				goto skip;
1129		}
1130		witness_leveldescendents(w, 0);
1131	skip:
1132	}
1133}
1134
1135static void
1136witness_leveldescendents(struct witness *parent, int level)
1137{
1138	struct witness_child_list_entry *wcl;
1139	int i;
1140
1141	if (parent->w_level < level)
1142		parent->w_level = level;
1143	level++;
1144	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1145		for (i = 0; i < wcl->wcl_count; i++)
1146			witness_leveldescendents(wcl->wcl_children[i], level);
1147}
1148
1149static void
1150witness_displaydescendants(void(*prnt)(const char *fmt, ...),
1151			   struct witness *parent)
1152{
1153	struct witness_child_list_entry *wcl;
1154	int i, level;
1155
1156	level =  parent->w_level;
1157	prnt("%-2d", level);
1158	for (i = 0; i < level; i++)
1159		prnt(" ");
1160	prnt("%s", parent->w_name);
1161	if (parent->w_file != NULL)
1162		prnt(" -- last acquired @ %s:%d\n", parent->w_file,
1163		    parent->w_line);
1164	for (wcl = parent->w_children; wcl != NULL; wcl = wcl->wcl_next)
1165		for (i = 0; i < wcl->wcl_count; i++)
1166			    witness_displaydescendants(prnt,
1167				wcl->wcl_children[i]);
1168}
1169
1170static int
1171dup_ok(struct witness *w)
1172{
1173	const char **dup;
1174
1175	for (dup = dup_list; *dup != NULL; dup++)
1176		if (strcmp(w->w_name, *dup) == 0)
1177			return (1);
1178	return (0);
1179}
1180
1181static int
1182blessed(struct witness *w1, struct witness *w2)
1183{
1184	int i;
1185	struct witness_blessed *b;
1186
1187	for (i = 0; i < blessed_count; i++) {
1188		b = &blessed_list[i];
1189		if (strcmp(w1->w_name, b->b_lock1) == 0) {
1190			if (strcmp(w2->w_name, b->b_lock2) == 0)
1191				return (1);
1192			continue;
1193		}
1194		if (strcmp(w1->w_name, b->b_lock2) == 0)
1195			if (strcmp(w2->w_name, b->b_lock1) == 0)
1196				return (1);
1197	}
1198	return (0);
1199}
1200
1201static struct witness *
1202witness_get(void)
1203{
1204	struct witness *w;
1205
1206	if (witness_dead) {
1207		mtx_unlock_spin(&w_mtx);
1208		return (NULL);
1209	}
1210	if (STAILQ_EMPTY(&w_free)) {
1211		witness_dead = 1;
1212		mtx_unlock_spin(&w_mtx);
1213		printf("%s: witness exhausted\n", __func__);
1214		return (NULL);
1215	}
1216	w = STAILQ_FIRST(&w_free);
1217	STAILQ_REMOVE_HEAD(&w_free, w_list);
1218	bzero(w, sizeof(*w));
1219	return (w);
1220}
1221
1222static void
1223witness_free(struct witness *w)
1224{
1225
1226	STAILQ_INSERT_HEAD(&w_free, w, w_list);
1227}
1228
1229static struct witness_child_list_entry *
1230witness_child_get(void)
1231{
1232	struct witness_child_list_entry *wcl;
1233
1234	if (witness_dead) {
1235		mtx_unlock_spin(&w_mtx);
1236		return (NULL);
1237	}
1238	wcl = w_child_free;
1239	if (wcl == NULL) {
1240		witness_dead = 1;
1241		mtx_unlock_spin(&w_mtx);
1242		printf("%s: witness exhausted\n", __func__);
1243		return (NULL);
1244	}
1245	w_child_free = wcl->wcl_next;
1246	bzero(wcl, sizeof(*wcl));
1247	return (wcl);
1248}
1249
1250static void
1251witness_child_free(struct witness_child_list_entry *wcl)
1252{
1253
1254	wcl->wcl_next = w_child_free;
1255	w_child_free = wcl;
1256}
1257
1258static struct lock_list_entry *
1259witness_lock_list_get(void)
1260{
1261	struct lock_list_entry *lle;
1262
1263	if (witness_dead)
1264		return (NULL);
1265	mtx_lock_spin(&w_mtx);
1266	lle = w_lock_list_free;
1267	if (lle == NULL) {
1268		witness_dead = 1;
1269		mtx_unlock_spin(&w_mtx);
1270		printf("%s: witness exhausted\n", __func__);
1271		return (NULL);
1272	}
1273	w_lock_list_free = lle->ll_next;
1274	mtx_unlock_spin(&w_mtx);
1275	bzero(lle, sizeof(*lle));
1276	return (lle);
1277}
1278
1279static void
1280witness_lock_list_free(struct lock_list_entry *lle)
1281{
1282
1283	mtx_lock_spin(&w_mtx);
1284	lle->ll_next = w_lock_list_free;
1285	w_lock_list_free = lle;
1286	mtx_unlock_spin(&w_mtx);
1287}
1288
1289static struct lock_instance *
1290find_instance(struct lock_list_entry *lock_list, struct lock_object *lock)
1291{
1292	struct lock_list_entry *lle;
1293	struct lock_instance *instance;
1294	int i;
1295
1296	for (lle = lock_list; lle != NULL; lle = lle->ll_next)
1297		for (i = lle->ll_count - 1; i >= 0; i--) {
1298			instance = &lle->ll_children[i];
1299			if (instance->li_lock == lock)
1300				return (instance);
1301		}
1302	return (NULL);
1303}
1304
1305int
1306witness_list_locks(struct lock_list_entry **lock_list)
1307{
1308	struct lock_list_entry *lle;
1309	struct lock_instance *instance;
1310	struct lock_object *lock;
1311	int i, nheld;
1312
1313	nheld = 0;
1314	for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
1315		for (i = lle->ll_count - 1; i >= 0; i--) {
1316			instance = &lle->ll_children[i];
1317			lock = instance->li_lock;
1318			printf("%s (%s) %s (%p) locked @ %s:%d\n",
1319			    (instance->li_flags & LI_EXCLUSIVE) != 0 ?
1320			    "exclusive" : "shared",
1321			    lock->lo_class->lc_name, lock->lo_name, lock,
1322			    instance->li_file, instance->li_line);
1323			nheld++;
1324		}
1325	return (nheld);
1326}
1327
1328/*
1329 * Calling this on td != curthread is bad unless we are in ddb.
1330 */
1331int
1332witness_list(struct thread *td)
1333{
1334	critical_t savecrit;
1335	int nheld;
1336
1337	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1338#ifdef DDB
1339	KASSERT(td == curthread || db_active,
1340	    ("%s: td != curthread and we aren't in the debugger", __func__));
1341	if (!db_active && witness_dead)
1342		return (0);
1343#else
1344	KASSERT(td == curthread, ("%s: p != curthread", __func__));
1345	if (witness_dead)
1346		return (0);
1347#endif
1348	nheld = witness_list_locks(&td->td_sleeplocks);
1349
1350	/*
1351	 * We only handle spinlocks if td == curthread.  This is somewhat broken
1352	 * if td is currently executing on some other CPU and holds spin locks
1353	 * as we won't display those locks.  If we had a MI way of getting
1354	 * the per-cpu data for a given cpu then we could use
1355	 * td->td_kse->ke_oncpu to get the list of spinlocks for this thread
1356	 * and "fix" this.
1357	 */
1358	if (td == curthread) {
1359		/*
1360		 * Preemption bad because we need PCPU_PTR(spinlocks) to not
1361		 * change.
1362		 */
1363		savecrit = critical_enter();
1364		nheld += witness_list_locks(PCPU_PTR(spinlocks));
1365		critical_exit(savecrit);
1366	}
1367	return (nheld);
1368}
1369
1370void
1371witness_save(struct lock_object *lock, const char **filep, int *linep)
1372{
1373	struct lock_instance *instance;
1374
1375	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1376	if (lock->lo_witness == NULL || witness_dead || panicstr != NULL)
1377		return;
1378	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1379		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1380		    lock->lo_class->lc_name, lock->lo_name);
1381	instance = find_instance(curthread->td_sleeplocks, lock);
1382	if (instance == NULL)
1383		panic("%s: lock (%s) %s not locked", __func__,
1384		    lock->lo_class->lc_name, lock->lo_name);
1385	*filep = instance->li_file;
1386	*linep = instance->li_line;
1387}
1388
1389void
1390witness_restore(struct lock_object *lock, const char *file, int line)
1391{
1392	struct lock_instance *instance;
1393
1394	KASSERT(!witness_cold, ("%s: witness_cold", __func__));
1395	if (lock->lo_witness == NULL || witness_dead || panicstr != NULL)
1396		return;
1397	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) == 0)
1398		panic("%s: lock (%s) %s is not a sleep lock", __func__,
1399		    lock->lo_class->lc_name, lock->lo_name);
1400	instance = find_instance(curthread->td_sleeplocks, lock);
1401	if (instance == NULL)
1402		panic("%s: lock (%s) %s not locked", __func__,
1403		    lock->lo_class->lc_name, lock->lo_name);
1404	lock->lo_witness->w_file = file;
1405	lock->lo_witness->w_line = line;
1406	instance->li_file = file;
1407	instance->li_line = line;
1408}
1409
1410void
1411witness_assert(struct lock_object *lock, int flags, const char *file, int line)
1412{
1413#ifdef INVARIANT_SUPPORT
1414	struct lock_instance *instance;
1415
1416	if (lock->lo_witness == NULL || witness_dead || panicstr != NULL)
1417		return;
1418	if ((lock->lo_class->lc_flags & LC_SLEEPLOCK) != 0)
1419		instance = find_instance(curthread->td_sleeplocks, lock);
1420	else if ((lock->lo_class->lc_flags & LC_SPINLOCK) != 0)
1421		instance = find_instance(PCPU_GET(spinlocks), lock);
1422	else
1423		panic("Lock (%s) %s is not sleep or spin!",
1424		    lock->lo_class->lc_name, lock->lo_name);
1425	switch (flags) {
1426	case LA_UNLOCKED:
1427		if (instance != NULL)
1428			panic("Lock (%s) %s locked @ %s:%d.",
1429			    lock->lo_class->lc_name, lock->lo_name, file, line);
1430		break;
1431	case LA_LOCKED:
1432	case LA_LOCKED | LA_RECURSED:
1433	case LA_LOCKED | LA_NOTRECURSED:
1434	case LA_SLOCKED:
1435	case LA_SLOCKED | LA_RECURSED:
1436	case LA_SLOCKED | LA_NOTRECURSED:
1437	case LA_XLOCKED:
1438	case LA_XLOCKED | LA_RECURSED:
1439	case LA_XLOCKED | LA_NOTRECURSED:
1440		if (instance == NULL)
1441			panic("Lock (%s) %s not locked @ %s:%d.",
1442			    lock->lo_class->lc_name, lock->lo_name, file, line);
1443		if ((flags & LA_XLOCKED) != 0 &&
1444		    (instance->li_flags & LI_EXCLUSIVE) == 0)
1445			panic("Lock (%s) %s not exclusively locked @ %s:%d.",
1446			    lock->lo_class->lc_name, lock->lo_name, file, line);
1447		if ((flags & LA_SLOCKED) != 0 &&
1448		    (instance->li_flags & LI_EXCLUSIVE) != 0)
1449			panic("Lock (%s) %s exclusively locked @ %s:%d.",
1450			    lock->lo_class->lc_name, lock->lo_name, file, line);
1451		if ((flags & LA_RECURSED) != 0 &&
1452		    (instance->li_flags & LI_RECURSEMASK) == 0)
1453			panic("Lock (%s) %s not recursed @ %s:%d.",
1454			    lock->lo_class->lc_name, lock->lo_name, file, line);
1455		if ((flags & LA_NOTRECURSED) != 0 &&
1456		    (instance->li_flags & LI_RECURSEMASK) != 0)
1457			panic("Lock (%s) %s recursed @ %s:%d.",
1458			    lock->lo_class->lc_name, lock->lo_name, file, line);
1459		break;
1460	default:
1461		panic("Invalid lock assertion at %s:%d.", file, line);
1462
1463	}
1464#endif	/* INVARIANT_SUPPORT */
1465}
1466
1467#ifdef DDB
1468
1469DB_SHOW_COMMAND(locks, db_witness_list)
1470{
1471	struct thread *td;
1472	pid_t pid;
1473	struct proc *p;
1474
1475	if (have_addr) {
1476		pid = (addr % 16) + ((addr >> 4) % 16) * 10 +
1477		    ((addr >> 8) % 16) * 100 + ((addr >> 12) % 16) * 1000 +
1478		    ((addr >> 16) % 16) * 10000;
1479		/* sx_slock(&allproc_lock); */
1480		FOREACH_PROC_IN_SYSTEM(p) {
1481			if (p->p_pid == pid)
1482				break;
1483		}
1484		/* sx_sunlock(&allproc_lock); */
1485		if (p == NULL) {
1486			db_printf("pid %d not found\n", pid);
1487			return;
1488		}
1489		td = &p->p_thread; /* XXXKSE */
1490	} else {
1491		td = curthread;
1492	}
1493	witness_list(td);
1494}
1495
1496DB_SHOW_COMMAND(witness, db_witness_display)
1497{
1498
1499	witness_display(db_printf);
1500}
1501#endif
1502