2 * Copyright (c) 2008 Isilon Systems, Inc.
3 * Copyright (c) 2008 Ilya Maykov <ivmaykov@gmail.com>
4 * Copyright (c) 1998 Berkeley Software Design, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Berkeley Software Design Inc's name may not be used to endorse or
16 * promote products derived from this software without specific prior
19 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
32 * and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
36 * Implementation of the `witness' lock verifier. Originally implemented for
37 * mutexes in BSD/OS. Extended to handle generic lock objects and lock
43 * Pronunciation: 'wit-n&s
45 * Etymology: Middle English witnesse, from Old English witnes knowledge,
46 * testimony, witness, from 2wit
47 * Date: before 12th century
48 * 1 : attestation of a fact or event : TESTIMONY
49 * 2 : one that gives evidence; specifically : one who testifies in
50 * a cause or before a judicial tribunal
51 * 3 : one asked to be present at a transaction so as to be able to
52 * testify to its having taken place
53 * 4 : one who has personal knowledge of something
54 * 5 a : something serving as evidence or proof : SIGN
55 * b : public affirmation by word or example of usually
56 * religious faith or conviction <the heroic witness to divine
58 * 6 capitalized : a member of the Jehovah's Witnesses
62 * Special rules concerning Giant and lock orders:
64 * 1) Giant must be acquired before any other mutexes. Stated another way,
65 * no other mutex may be held when Giant is acquired.
67 * 2) Giant must be released when blocking on a sleepable lock.
69 * This rule is less obvious, but is a result of Giant providing the same
70 * semantics as spl(). Basically, when a thread sleeps, it must release
71 * Giant. When a thread blocks on a sleepable lock, it sleeps. Hence rule
74 * 3) Giant may be acquired before or after sleepable locks.
76 * This rule is also not quite as obvious. Giant may be acquired after
77 * a sleepable lock because it is a non-sleepable lock and non-sleepable
78 * locks may always be acquired while holding a sleepable lock. The second
79 * case, Giant before a sleepable lock, follows from rule 2) above. Suppose
80 * you have two threads T1 and T2 and a sleepable lock X. Suppose that T1
81 * acquires X and blocks on Giant. Then suppose that T2 acquires Giant and
82 * blocks on X. When T2 blocks on X, T2 will release Giant allowing T1 to
83 * execute. Thus, acquiring Giant both before and after a sleepable lock
84 * will not result in a lock order reversal.
87 #include <sys/cdefs.h>
88 __FBSDID("$FreeBSD$");
91 #include "opt_hwpmc_hooks.h"
92 #include "opt_stack.h"
93 #include "opt_witness.h"
95 #include <sys/param.h>
98 #include <sys/kernel.h>
100 #include <sys/lock.h>
101 #include <sys/malloc.h>
102 #include <sys/mutex.h>
103 #include <sys/priv.h>
104 #include <sys/proc.h>
105 #include <sys/sbuf.h>
106 #include <sys/sched.h>
107 #include <sys/stack.h>
108 #include <sys/sysctl.h>
109 #include <sys/systm.h>
115 #include <machine/stdarg.h>
117 #if !defined(DDB) && !defined(STACK)
118 #error "DDB or STACK options are required for WITNESS"
121 /* Note that these traces do not work with KTR_ALQ. */
123 #define KTR_WITNESS KTR_SUBSYS
125 #define KTR_WITNESS 0
128 #define LI_RECURSEMASK 0x0000ffff /* Recursion depth of lock instance. */
129 #define LI_EXCLUSIVE 0x00010000 /* Exclusive lock instance. */
130 #define LI_NORELEASE 0x00020000 /* Lock not allowed to be released. */
132 /* Define this to check for blessed mutexes */
135 #define WITNESS_COUNT 1536
136 #define WITNESS_CHILDCOUNT (WITNESS_COUNT * 4)
137 #define WITNESS_HASH_SIZE 251 /* Prime, gives load factor < 2 */
138 #define WITNESS_PENDLIST 1024
140 /* Allocate 256 KB of stack data space */
141 #define WITNESS_LO_DATA_COUNT 2048
143 /* Prime, gives load factor of ~2 at full load */
144 #define WITNESS_LO_HASH_SIZE 1021
147 * XXX: This is somewhat bogus, as we assume here that at most 2048 threads
148 * will hold LOCK_NCHILDREN locks. We handle failure ok, and we should
149 * probably be safe for the most part, but it's still a SWAG.
151 #define LOCK_NCHILDREN 5
152 #define LOCK_CHILDCOUNT 2048
154 #define MAX_W_NAME 64
156 #define BADSTACK_SBUF_SIZE (256 * WITNESS_COUNT)
157 #define FULLGRAPH_SBUF_SIZE 512
160 * These flags go in the witness relationship matrix and describe the
161 * relationship between any two struct witness objects.
163 #define WITNESS_UNRELATED 0x00 /* No lock order relation. */
164 #define WITNESS_PARENT 0x01 /* Parent, aka direct ancestor. */
165 #define WITNESS_ANCESTOR 0x02 /* Direct or indirect ancestor. */
166 #define WITNESS_CHILD 0x04 /* Child, aka direct descendant. */
167 #define WITNESS_DESCENDANT 0x08 /* Direct or indirect descendant. */
168 #define WITNESS_ANCESTOR_MASK (WITNESS_PARENT | WITNESS_ANCESTOR)
169 #define WITNESS_DESCENDANT_MASK (WITNESS_CHILD | WITNESS_DESCENDANT)
170 #define WITNESS_RELATED_MASK \
171 (WITNESS_ANCESTOR_MASK | WITNESS_DESCENDANT_MASK)
172 #define WITNESS_REVERSAL 0x10 /* A lock order reversal has been
174 #define WITNESS_RESERVED1 0x20 /* Unused flag, reserved. */
175 #define WITNESS_RESERVED2 0x40 /* Unused flag, reserved. */
176 #define WITNESS_LOCK_ORDER_KNOWN 0x80 /* This lock order is known. */
178 /* Descendant to ancestor flags */
179 #define WITNESS_DTOA(x) (((x) & WITNESS_RELATED_MASK) >> 2)
181 /* Ancestor to descendant flags */
182 #define WITNESS_ATOD(x) (((x) & WITNESS_RELATED_MASK) << 2)
184 #define WITNESS_INDEX_ASSERT(i) \
185 MPASS((i) > 0 && (i) <= w_max_used_index && (i) < WITNESS_COUNT)
187 static MALLOC_DEFINE(M_WITNESS, "Witness", "Witness");
190 * Lock instances. A lock instance is the data associated with a lock while
191 * it is held by witness. For example, a lock instance will hold the
192 * recursion count of a lock. Lock instances are held in lists. Spin locks
193 * are held in a per-cpu list while sleep locks are held in per-thread list.
195 struct lock_instance {
196 struct lock_object *li_lock;
203 * A simple list type used to build the list of locks held by a thread
204 * or CPU. We can't simply embed the list in struct lock_object since a
205 * lock may be held by more than one thread if it is a shared lock. Locks
206 * are added to the head of the list, so we fill up each list entry from
207 * "the back" logically. To ease some of the arithmetic, we actually fill
208 * in each list entry the normal way (children[0] then children[1], etc.) but
209 * when we traverse the list we read children[count-1] as the first entry
210 * down to children[0] as the final entry.
212 struct lock_list_entry {
213 struct lock_list_entry *ll_next;
214 struct lock_instance ll_children[LOCK_NCHILDREN];
219 * The main witness structure. One of these per named lock type in the system
220 * (for example, "vnode interlock").
223 char w_name[MAX_W_NAME];
224 uint32_t w_index; /* Index in the relationship matrix */
225 struct lock_class *w_class;
226 STAILQ_ENTRY(witness) w_list; /* List of all witnesses. */
227 STAILQ_ENTRY(witness) w_typelist; /* Witnesses of a type. */
228 struct witness *w_hash_next; /* Linked list in hash buckets. */
229 const char *w_file; /* File where last acquired */
230 uint32_t w_line; /* Line where last acquired */
232 uint16_t w_num_ancestors; /* direct/indirect
234 uint16_t w_num_descendants; /* direct/indirect
235 * descendant count */
237 unsigned w_displayed:1;
238 unsigned w_reversed:1;
241 STAILQ_HEAD(witness_list, witness);
244 * The witness hash table. Keys are witness names (const char *), elements are
245 * witness objects (struct witness *).
247 struct witness_hash {
248 struct witness *wh_array[WITNESS_HASH_SIZE];
254 * Key type for the lock order data hash table.
256 struct witness_lock_order_key {
261 struct witness_lock_order_data {
262 struct stack wlod_stack;
263 struct witness_lock_order_key wlod_key;
264 struct witness_lock_order_data *wlod_next;
268 * The witness lock order data hash table. Keys are witness index tuples
269 * (struct witness_lock_order_key), elements are lock order data objects
270 * (struct witness_lock_order_data).
272 struct witness_lock_order_hash {
273 struct witness_lock_order_data *wloh_array[WITNESS_LO_HASH_SIZE];
279 struct witness_blessed {
285 struct witness_pendhelp {
287 struct lock_object *wh_lock;
290 struct witness_order_list_entry {
292 struct lock_class *w_class;
296 * Returns 0 if one of the locks is a spin lock and the other is not.
297 * Returns 1 otherwise.
300 witness_lock_type_equal(struct witness *w1, struct witness *w2)
303 return ((w1->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) ==
304 (w2->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)));
308 witness_lock_order_key_equal(const struct witness_lock_order_key *a,
309 const struct witness_lock_order_key *b)
312 return (a->from == b->from && a->to == b->to);
315 static int _isitmyx(struct witness *w1, struct witness *w2, int rmask,
318 static void _witness_debugger(int cond, const char *msg);
320 static void adopt(struct witness *parent, struct witness *child);
322 static int blessed(struct witness *, struct witness *);
324 static void depart(struct witness *w);
325 static struct witness *enroll(const char *description,
326 struct lock_class *lock_class);
327 static struct lock_instance *find_instance(struct lock_list_entry *list,
328 const struct lock_object *lock);
329 static int isitmychild(struct witness *parent, struct witness *child);
330 static int isitmydescendant(struct witness *parent, struct witness *child);
331 static void itismychild(struct witness *parent, struct witness *child);
332 static int sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS);
333 static int sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
334 static int sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS);
335 static void witness_add_fullgraph(struct sbuf *sb, struct witness *parent);
337 static void witness_ddb_compute_levels(void);
338 static void witness_ddb_display(int(*)(const char *fmt, ...));
339 static void witness_ddb_display_descendants(int(*)(const char *fmt, ...),
340 struct witness *, int indent);
341 static void witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
342 struct witness_list *list);
343 static void witness_ddb_level_descendants(struct witness *parent, int l);
344 static void witness_ddb_list(struct thread *td);
346 static void witness_free(struct witness *m);
347 static struct witness *witness_get(void);
348 static uint32_t witness_hash_djb2(const uint8_t *key, uint32_t size);
349 static struct witness *witness_hash_get(const char *key);
350 static void witness_hash_put(struct witness *w);
351 static void witness_init_hash_tables(void);
352 static void witness_increment_graph_generation(void);
353 static void witness_lock_list_free(struct lock_list_entry *lle);
354 static struct lock_list_entry *witness_lock_list_get(void);
355 static int witness_lock_order_add(struct witness *parent,
356 struct witness *child);
357 static int witness_lock_order_check(struct witness *parent,
358 struct witness *child);
359 static struct witness_lock_order_data *witness_lock_order_get(
360 struct witness *parent,
361 struct witness *child);
362 static void witness_list_lock(struct lock_instance *instance,
363 int (*prnt)(const char *fmt, ...));
364 static void witness_setflag(struct lock_object *lock, int flag, int set);
367 #define witness_debugger(c) _witness_debugger(c, __func__)
369 #define witness_debugger(c)
372 static SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW, NULL,
376 * If set to 0, lock order checking is disabled. If set to -1,
377 * witness is completely disabled. Otherwise witness performs full
378 * lock order checking for all locks. At runtime, lock order checking
379 * may be toggled. However, witness cannot be reenabled once it is
380 * completely disabled.
382 static int witness_watch = 1;
383 TUNABLE_INT("debug.witness.watch", &witness_watch);
384 SYSCTL_PROC(_debug_witness, OID_AUTO, watch, CTLFLAG_RW | CTLTYPE_INT, NULL, 0,
385 sysctl_debug_witness_watch, "I", "witness is watching lock operations");
389 * When KDB is enabled and witness_kdb is 1, it will cause the system
390 * to drop into kdebug() when:
391 * - a lock hierarchy violation occurs
392 * - locks are held when going to sleep.
399 TUNABLE_INT("debug.witness.kdb", &witness_kdb);
400 SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RW, &witness_kdb, 0, "");
403 * When KDB is enabled and witness_trace is 1, it will cause the system
404 * to print a stack trace:
405 * - a lock hierarchy violation occurs
406 * - locks are held when going to sleep.
408 int witness_trace = 1;
409 TUNABLE_INT("debug.witness.trace", &witness_trace);
410 SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RW, &witness_trace, 0, "");
413 #ifdef WITNESS_SKIPSPIN
414 int witness_skipspin = 1;
416 int witness_skipspin = 0;
418 TUNABLE_INT("debug.witness.skipspin", &witness_skipspin);
419 SYSCTL_INT(_debug_witness, OID_AUTO, skipspin, CTLFLAG_RDTUN, &witness_skipspin,
423 * Call this to print out the relations between locks.
425 SYSCTL_PROC(_debug_witness, OID_AUTO, fullgraph, CTLTYPE_STRING | CTLFLAG_RD,
426 NULL, 0, sysctl_debug_witness_fullgraph, "A", "Show locks relation graphs");
429 * Call this to print out the witness faulty stacks.
431 SYSCTL_PROC(_debug_witness, OID_AUTO, badstacks, CTLTYPE_STRING | CTLFLAG_RD,
432 NULL, 0, sysctl_debug_witness_badstacks, "A", "Show bad witness stacks");
434 static struct mtx w_mtx;
437 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
438 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
441 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
442 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
445 static struct lock_list_entry *w_lock_list_free = NULL;
446 static struct witness_pendhelp pending_locks[WITNESS_PENDLIST];
447 static u_int pending_cnt;
449 static int w_free_cnt, w_spin_cnt, w_sleep_cnt;
450 SYSCTL_INT(_debug_witness, OID_AUTO, free_cnt, CTLFLAG_RD, &w_free_cnt, 0, "");
451 SYSCTL_INT(_debug_witness, OID_AUTO, spin_cnt, CTLFLAG_RD, &w_spin_cnt, 0, "");
452 SYSCTL_INT(_debug_witness, OID_AUTO, sleep_cnt, CTLFLAG_RD, &w_sleep_cnt, 0,
455 static struct witness *w_data;
456 static uint8_t w_rmatrix[WITNESS_COUNT+1][WITNESS_COUNT+1];
457 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
458 static struct witness_hash w_hash; /* The witness hash table. */
460 /* The lock order data hash */
461 static struct witness_lock_order_data w_lodata[WITNESS_LO_DATA_COUNT];
462 static struct witness_lock_order_data *w_lofree = NULL;
463 static struct witness_lock_order_hash w_lohash;
464 static int w_max_used_index = 0;
465 static unsigned int w_generation = 0;
466 static const char w_notrunning[] = "Witness not running\n";
467 static const char w_stillcold[] = "Witness is still cold\n";
470 static struct witness_order_list_entry order_lists[] = {
474 { "proctree", &lock_class_sx },
475 { "allproc", &lock_class_sx },
476 { "allprison", &lock_class_sx },
481 { "Giant", &lock_class_mtx_sleep },
482 { "pipe mutex", &lock_class_mtx_sleep },
483 { "sigio lock", &lock_class_mtx_sleep },
484 { "process group", &lock_class_mtx_sleep },
485 { "process lock", &lock_class_mtx_sleep },
486 { "session", &lock_class_mtx_sleep },
487 { "uidinfo hash", &lock_class_rw },
489 { "pmc-sleep", &lock_class_mtx_sleep },
491 { "time lock", &lock_class_mtx_sleep },
496 { "accept", &lock_class_mtx_sleep },
497 { "so_snd", &lock_class_mtx_sleep },
498 { "so_rcv", &lock_class_mtx_sleep },
499 { "sellck", &lock_class_mtx_sleep },
504 { "so_rcv", &lock_class_mtx_sleep },
505 { "radix node head", &lock_class_rw },
506 { "rtentry", &lock_class_mtx_sleep },
507 { "ifaddr", &lock_class_mtx_sleep },
511 * protocol locks before interface locks, after UDP locks.
513 { "udpinp", &lock_class_rw },
514 { "in_multi_mtx", &lock_class_mtx_sleep },
515 { "igmp_mtx", &lock_class_mtx_sleep },
516 { "if_addr_lock", &lock_class_rw },
520 * protocol locks before interface locks, after UDP locks.
522 { "udpinp", &lock_class_rw },
523 { "in6_multi_mtx", &lock_class_mtx_sleep },
524 { "mld_mtx", &lock_class_mtx_sleep },
525 { "if_addr_lock", &lock_class_rw },
528 * UNIX Domain Sockets
530 { "unp_global_rwlock", &lock_class_rw },
531 { "unp_list_lock", &lock_class_mtx_sleep },
532 { "unp", &lock_class_mtx_sleep },
533 { "so_snd", &lock_class_mtx_sleep },
538 { "udp", &lock_class_rw },
539 { "udpinp", &lock_class_rw },
540 { "so_snd", &lock_class_mtx_sleep },
545 { "tcp", &lock_class_rw },
546 { "tcpinp", &lock_class_rw },
547 { "so_snd", &lock_class_mtx_sleep },
552 { "bpf global lock", &lock_class_mtx_sleep },
553 { "bpf interface lock", &lock_class_rw },
554 { "bpf cdev lock", &lock_class_mtx_sleep },
559 { "nfsd_mtx", &lock_class_mtx_sleep },
560 { "so_snd", &lock_class_mtx_sleep },
566 { "802.11 com lock", &lock_class_mtx_sleep},
571 { "network driver", &lock_class_mtx_sleep},
577 { "ng_node", &lock_class_mtx_sleep },
578 { "ng_worklist", &lock_class_mtx_sleep },
583 { "vm map (system)", &lock_class_mtx_sleep },
584 { "vm page queue", &lock_class_mtx_sleep },
585 { "vnode interlock", &lock_class_mtx_sleep },
586 { "cdev", &lock_class_mtx_sleep },
591 { "vm map (user)", &lock_class_sx },
592 { "vm object", &lock_class_rw },
593 { "vm page", &lock_class_mtx_sleep },
594 { "vm page queue", &lock_class_mtx_sleep },
595 { "pmap pv global", &lock_class_rw },
596 { "pmap", &lock_class_mtx_sleep },
597 { "pmap pv list", &lock_class_rw },
598 { "vm page free queue", &lock_class_mtx_sleep },
601 * kqueue/VFS interaction
603 { "kqueue", &lock_class_mtx_sleep },
604 { "struct mount mtx", &lock_class_mtx_sleep },
605 { "vnode interlock", &lock_class_mtx_sleep },
610 { "dn->dn_mtx", &lock_class_sx },
611 { "dr->dt.di.dr_mtx", &lock_class_sx },
612 { "db->db_mtx", &lock_class_sx },
618 { "ap boot", &lock_class_mtx_spin },
620 { "rm.mutex_mtx", &lock_class_mtx_spin },
621 { "sio", &lock_class_mtx_spin },
622 { "scrlock", &lock_class_mtx_spin },
624 { "cy", &lock_class_mtx_spin },
627 { "pcib_mtx", &lock_class_mtx_spin },
628 { "rtc_mtx", &lock_class_mtx_spin },
630 { "scc_hwmtx", &lock_class_mtx_spin },
631 { "uart_hwmtx", &lock_class_mtx_spin },
632 { "fast_taskqueue", &lock_class_mtx_spin },
633 { "intr table", &lock_class_mtx_spin },
635 { "pmc-per-proc", &lock_class_mtx_spin },
637 { "process slock", &lock_class_mtx_spin },
638 { "sleepq chain", &lock_class_mtx_spin },
639 { "umtx lock", &lock_class_mtx_spin },
640 { "rm_spinlock", &lock_class_mtx_spin },
641 { "turnstile chain", &lock_class_mtx_spin },
642 { "turnstile lock", &lock_class_mtx_spin },
643 { "sched lock", &lock_class_mtx_spin },
644 { "td_contested", &lock_class_mtx_spin },
645 { "callout", &lock_class_mtx_spin },
646 { "entropy harvest mutex", &lock_class_mtx_spin },
647 { "syscons video lock", &lock_class_mtx_spin },
649 { "smp rendezvous", &lock_class_mtx_spin },
652 { "tlb0", &lock_class_mtx_spin },
657 { "intrcnt", &lock_class_mtx_spin },
658 { "icu", &lock_class_mtx_spin },
660 { "allpmaps", &lock_class_mtx_spin },
661 { "descriptor tables", &lock_class_mtx_spin },
663 { "clk", &lock_class_mtx_spin },
664 { "cpuset", &lock_class_mtx_spin },
665 { "mprof lock", &lock_class_mtx_spin },
666 { "zombie lock", &lock_class_mtx_spin },
667 { "ALD Queue", &lock_class_mtx_spin },
669 { "MCA spin lock", &lock_class_mtx_spin },
671 #if defined(__i386__) || defined(__amd64__)
672 { "pcicfg", &lock_class_mtx_spin },
673 { "NDIS thread lock", &lock_class_mtx_spin },
675 { "tw_osl_io_lock", &lock_class_mtx_spin },
676 { "tw_osl_q_lock", &lock_class_mtx_spin },
677 { "tw_cl_io_lock", &lock_class_mtx_spin },
678 { "tw_cl_intr_lock", &lock_class_mtx_spin },
679 { "tw_cl_gen_lock", &lock_class_mtx_spin },
681 { "pmc-leaf", &lock_class_mtx_spin },
683 { "blocked lock", &lock_class_mtx_spin },
690 * Pairs of locks which have been blessed
691 * Don't complain about order problems with blessed locks
693 static struct witness_blessed blessed_list[] = {
695 static int blessed_count =
696 sizeof(blessed_list) / sizeof(struct witness_blessed);
700 * This global is set to 0 once it becomes safe to use the witness code.
702 static int witness_cold = 1;
705 * This global is set to 1 once the static lock orders have been enrolled
706 * so that a warning can be issued for any spin locks enrolled later.
708 static int witness_spin_warn = 0;
710 /* Trim useless garbage from filenames. */
712 fixup_filename(const char *file)
717 while (strncmp(file, "../", 3) == 0)
723 * The WITNESS-enabled diagnostic code. Note that the witness code does
724 * assume that the early boot is single-threaded at least until after this
725 * routine is completed.
728 witness_initialize(void *dummy __unused)
730 struct lock_object *lock;
731 struct witness_order_list_entry *order;
732 struct witness *w, *w1;
735 w_data = malloc(sizeof (struct witness) * WITNESS_COUNT, M_WITNESS,
739 * We have to release Giant before initializing its witness
740 * structure so that WITNESS doesn't get confused.
743 mtx_assert(&Giant, MA_NOTOWNED);
745 CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
746 mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
747 MTX_NOWITNESS | MTX_NOPROFILE);
748 for (i = WITNESS_COUNT - 1; i >= 0; i--) {
750 memset(w, 0, sizeof(*w));
751 w_data[i].w_index = i; /* Witness index never changes. */
754 KASSERT(STAILQ_FIRST(&w_free)->w_index == 0,
755 ("%s: Invalid list of free witness objects", __func__));
757 /* Witness with index 0 is not used to aid in debugging. */
758 STAILQ_REMOVE_HEAD(&w_free, w_list);
762 (sizeof(**w_rmatrix) * (WITNESS_COUNT+1) * (WITNESS_COUNT+1)));
764 for (i = 0; i < LOCK_CHILDCOUNT; i++)
765 witness_lock_list_free(&w_locklistdata[i]);
766 witness_init_hash_tables();
768 /* First add in all the specified order lists. */
769 for (order = order_lists; order->w_name != NULL; order++) {
770 w = enroll(order->w_name, order->w_class);
773 w->w_file = "order list";
774 for (order++; order->w_name != NULL; order++) {
775 w1 = enroll(order->w_name, order->w_class);
778 w1->w_file = "order list";
783 witness_spin_warn = 1;
785 /* Iterate through all locks and add them to witness. */
786 for (i = 0; pending_locks[i].wh_lock != NULL; i++) {
787 lock = pending_locks[i].wh_lock;
788 KASSERT(lock->lo_flags & LO_WITNESS,
789 ("%s: lock %s is on pending list but not LO_WITNESS",
790 __func__, lock->lo_name));
791 lock->lo_witness = enroll(pending_locks[i].wh_type,
795 /* Mark the witness code as being ready for use. */
800 SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize,
804 witness_init(struct lock_object *lock, const char *type)
806 struct lock_class *class;
808 /* Various sanity checks. */
809 class = LOCK_CLASS(lock);
810 if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
811 (class->lc_flags & LC_RECURSABLE) == 0)
812 kassert_panic("%s: lock (%s) %s can not be recursable",
813 __func__, class->lc_name, lock->lo_name);
814 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
815 (class->lc_flags & LC_SLEEPABLE) == 0)
816 kassert_panic("%s: lock (%s) %s can not be sleepable",
817 __func__, class->lc_name, lock->lo_name);
818 if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
819 (class->lc_flags & LC_UPGRADABLE) == 0)
820 kassert_panic("%s: lock (%s) %s can not be upgradable",
821 __func__, class->lc_name, lock->lo_name);
824 * If we shouldn't watch this lock, then just clear lo_witness.
825 * Otherwise, if witness_cold is set, then it is too early to
826 * enroll this lock, so defer it to witness_initialize() by adding
827 * it to the pending_locks list. If it is not too early, then enroll
830 if (witness_watch < 1 || panicstr != NULL ||
831 (lock->lo_flags & LO_WITNESS) == 0)
832 lock->lo_witness = NULL;
833 else if (witness_cold) {
834 pending_locks[pending_cnt].wh_lock = lock;
835 pending_locks[pending_cnt++].wh_type = type;
836 if (pending_cnt > WITNESS_PENDLIST)
837 panic("%s: pending locks list is too small, "
838 "increase WITNESS_PENDLIST\n",
841 lock->lo_witness = enroll(type, class);
845 witness_destroy(struct lock_object *lock)
847 struct lock_class *class;
850 class = LOCK_CLASS(lock);
853 panic("lock (%s) %s destroyed while witness_cold",
854 class->lc_name, lock->lo_name);
856 /* XXX: need to verify that no one holds the lock */
857 if ((lock->lo_flags & LO_WITNESS) == 0 || lock->lo_witness == NULL)
859 w = lock->lo_witness;
861 mtx_lock_spin(&w_mtx);
862 MPASS(w->w_refcount > 0);
865 if (w->w_refcount == 0)
867 mtx_unlock_spin(&w_mtx);
872 witness_ddb_compute_levels(void)
877 * First clear all levels.
879 STAILQ_FOREACH(w, &w_all, w_list)
883 * Look for locks with no parents and level all their descendants.
885 STAILQ_FOREACH(w, &w_all, w_list) {
887 /* If the witness has ancestors (is not a root), skip it. */
888 if (w->w_num_ancestors > 0)
890 witness_ddb_level_descendants(w, 0);
895 witness_ddb_level_descendants(struct witness *w, int l)
899 if (w->w_ddb_level >= l)
905 for (i = 1; i <= w_max_used_index; i++) {
906 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
907 witness_ddb_level_descendants(&w_data[i], l);
912 witness_ddb_display_descendants(int(*prnt)(const char *fmt, ...),
913 struct witness *w, int indent)
917 for (i = 0; i < indent; i++)
919 prnt("%s (type: %s, depth: %d, active refs: %d)",
920 w->w_name, w->w_class->lc_name,
921 w->w_ddb_level, w->w_refcount);
922 if (w->w_displayed) {
923 prnt(" -- (already displayed)\n");
927 if (w->w_file != NULL && w->w_line != 0)
928 prnt(" -- last acquired @ %s:%d\n", fixup_filename(w->w_file),
931 prnt(" -- never acquired\n");
933 WITNESS_INDEX_ASSERT(w->w_index);
934 for (i = 1; i <= w_max_used_index; i++) {
937 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
938 witness_ddb_display_descendants(prnt, &w_data[i],
944 witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
945 struct witness_list *list)
949 STAILQ_FOREACH(w, list, w_typelist) {
950 if (w->w_file == NULL || w->w_ddb_level > 0)
953 /* This lock has no anscestors - display its descendants. */
954 witness_ddb_display_descendants(prnt, w, 0);
961 witness_ddb_display(int(*prnt)(const char *fmt, ...))
965 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
966 witness_ddb_compute_levels();
968 /* Clear all the displayed flags. */
969 STAILQ_FOREACH(w, &w_all, w_list)
973 * First, handle sleep locks which have been acquired at least
976 prnt("Sleep locks:\n");
977 witness_ddb_display_list(prnt, &w_sleep);
982 * Now do spin locks which have been acquired at least once.
984 prnt("\nSpin locks:\n");
985 witness_ddb_display_list(prnt, &w_spin);
990 * Finally, any locks which have not been acquired yet.
992 prnt("\nLocks which were never acquired:\n");
993 STAILQ_FOREACH(w, &w_all, w_list) {
994 if (w->w_file != NULL || w->w_refcount == 0)
996 prnt("%s (type: %s, depth: %d)\n", w->w_name,
997 w->w_class->lc_name, w->w_ddb_level);
1005 witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
1008 if (witness_watch == -1 || panicstr != NULL)
1011 /* Require locks that witness knows about. */
1012 if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
1013 lock2->lo_witness == NULL)
1016 mtx_assert(&w_mtx, MA_NOTOWNED);
1017 mtx_lock_spin(&w_mtx);
1020 * If we already have either an explicit or implied lock order that
1021 * is the other way around, then return an error.
1023 if (witness_watch &&
1024 isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
1025 mtx_unlock_spin(&w_mtx);
1029 /* Try to add the new order. */
1030 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1031 lock2->lo_witness->w_name, lock1->lo_witness->w_name);
1032 itismychild(lock1->lo_witness, lock2->lo_witness);
1033 mtx_unlock_spin(&w_mtx);
1038 witness_checkorder(struct lock_object *lock, int flags, const char *file,
1039 int line, struct lock_object *interlock)
1041 struct lock_list_entry *lock_list, *lle;
1042 struct lock_instance *lock1, *lock2, *plock;
1043 struct lock_class *class, *iclass;
1044 struct witness *w, *w1;
1048 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL ||
1052 w = lock->lo_witness;
1053 class = LOCK_CLASS(lock);
1056 if (class->lc_flags & LC_SLEEPLOCK) {
1059 * Since spin locks include a critical section, this check
1060 * implicitly enforces a lock order of all sleep locks before
1063 if (td->td_critnest != 0 && !kdb_active)
1064 kassert_panic("acquiring blockable sleep lock with "
1065 "spinlock or critical section held (%s) %s @ %s:%d",
1066 class->lc_name, lock->lo_name,
1067 fixup_filename(file), line);
1070 * If this is the first lock acquired then just return as
1071 * no order checking is needed.
1073 lock_list = td->td_sleeplocks;
1074 if (lock_list == NULL || lock_list->ll_count == 0)
1079 * If this is the first lock, just return as no order
1080 * checking is needed. Avoid problems with thread
1081 * migration pinning the thread while checking if
1082 * spinlocks are held. If at least one spinlock is held
1083 * the thread is in a safe path and it is allowed to
1087 lock_list = PCPU_GET(spinlocks);
1088 if (lock_list == NULL || lock_list->ll_count == 0) {
1096 * Check to see if we are recursing on a lock we already own. If
1097 * so, make sure that we don't mismatch exclusive and shared lock
1100 lock1 = find_instance(lock_list, lock);
1101 if (lock1 != NULL) {
1102 if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
1103 (flags & LOP_EXCLUSIVE) == 0) {
1104 printf("shared lock of (%s) %s @ %s:%d\n",
1105 class->lc_name, lock->lo_name,
1106 fixup_filename(file), line);
1107 printf("while exclusively locked from %s:%d\n",
1108 fixup_filename(lock1->li_file), lock1->li_line);
1109 kassert_panic("excl->share");
1111 if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
1112 (flags & LOP_EXCLUSIVE) != 0) {
1113 printf("exclusive lock of (%s) %s @ %s:%d\n",
1114 class->lc_name, lock->lo_name,
1115 fixup_filename(file), line);
1116 printf("while share locked from %s:%d\n",
1117 fixup_filename(lock1->li_file), lock1->li_line);
1118 kassert_panic("share->excl");
1123 /* Warn if the interlock is not locked exactly once. */
1124 if (interlock != NULL) {
1125 iclass = LOCK_CLASS(interlock);
1126 lock1 = find_instance(lock_list, interlock);
1128 kassert_panic("interlock (%s) %s not locked @ %s:%d",
1129 iclass->lc_name, interlock->lo_name,
1130 fixup_filename(file), line);
1131 else if ((lock1->li_flags & LI_RECURSEMASK) != 0)
1132 kassert_panic("interlock (%s) %s recursed @ %s:%d",
1133 iclass->lc_name, interlock->lo_name,
1134 fixup_filename(file), line);
1138 * Find the previously acquired lock, but ignore interlocks.
1140 plock = &lock_list->ll_children[lock_list->ll_count - 1];
1141 if (interlock != NULL && plock->li_lock == interlock) {
1142 if (lock_list->ll_count > 1)
1144 &lock_list->ll_children[lock_list->ll_count - 2];
1146 lle = lock_list->ll_next;
1149 * The interlock is the only lock we hold, so
1154 plock = &lle->ll_children[lle->ll_count - 1];
1159 * Try to perform most checks without a lock. If this succeeds we
1160 * can skip acquiring the lock and return success.
1162 w1 = plock->li_lock->lo_witness;
1163 if (witness_lock_order_check(w1, w))
1167 * Check for duplicate locks of the same type. Note that we only
1168 * have to check for this on the last lock we just acquired. Any
1169 * other cases will be caught as lock order violations.
1171 mtx_lock_spin(&w_mtx);
1172 witness_lock_order_add(w1, w);
1175 if (!(lock->lo_flags & LO_DUPOK) && !(flags & LOP_DUPOK) &&
1176 !(w_rmatrix[i][i] & WITNESS_REVERSAL)) {
1177 w_rmatrix[i][i] |= WITNESS_REVERSAL;
1179 mtx_unlock_spin(&w_mtx);
1181 "acquiring duplicate lock of same type: \"%s\"\n",
1183 printf(" 1st %s @ %s:%d\n", plock->li_lock->lo_name,
1184 fixup_filename(plock->li_file), plock->li_line);
1185 printf(" 2nd %s @ %s:%d\n", lock->lo_name,
1186 fixup_filename(file), line);
1187 witness_debugger(1);
1189 mtx_unlock_spin(&w_mtx);
1192 mtx_assert(&w_mtx, MA_OWNED);
1195 * If we know that the lock we are acquiring comes after
1196 * the lock we most recently acquired in the lock order tree,
1197 * then there is no need for any further checks.
1199 if (isitmychild(w1, w))
1202 for (j = 0, lle = lock_list; lle != NULL; lle = lle->ll_next) {
1203 for (i = lle->ll_count - 1; i >= 0; i--, j++) {
1205 MPASS(j < WITNESS_COUNT);
1206 lock1 = &lle->ll_children[i];
1209 * Ignore the interlock.
1211 if (interlock == lock1->li_lock)
1215 * If this lock doesn't undergo witness checking,
1218 w1 = lock1->li_lock->lo_witness;
1220 KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
1221 ("lock missing witness structure"));
1226 * If we are locking Giant and this is a sleepable
1227 * lock, then skip it.
1229 if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
1230 lock == &Giant.lock_object)
1234 * If we are locking a sleepable lock and this lock
1235 * is Giant, then skip it.
1237 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1238 lock1->li_lock == &Giant.lock_object)
1242 * If we are locking a sleepable lock and this lock
1243 * isn't sleepable, we want to treat it as a lock
1244 * order violation to enfore a general lock order of
1245 * sleepable locks before non-sleepable locks.
1247 if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1248 (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1252 * If we are locking Giant and this is a non-sleepable
1253 * lock, then treat it as a reversal.
1255 if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0 &&
1256 lock == &Giant.lock_object)
1260 * Check the lock order hierarchy for a reveresal.
1262 if (!isitmydescendant(w, w1))
1267 * We have a lock order violation, check to see if it
1268 * is allowed or has already been yelled about.
1273 * If the lock order is blessed, just bail. We don't
1274 * look for other lock order violations though, which
1281 /* Bail if this violation is known */
1282 if (w_rmatrix[w1->w_index][w->w_index] & WITNESS_REVERSAL)
1285 /* Record this as a violation */
1286 w_rmatrix[w1->w_index][w->w_index] |= WITNESS_REVERSAL;
1287 w_rmatrix[w->w_index][w1->w_index] |= WITNESS_REVERSAL;
1288 w->w_reversed = w1->w_reversed = 1;
1289 witness_increment_graph_generation();
1290 mtx_unlock_spin(&w_mtx);
1292 #ifdef WITNESS_NO_VNODE
1294 * There are known LORs between VNODE locks. They are
1295 * not an indication of a bug. VNODE locks are flagged
1296 * as such (LO_IS_VNODE) and we don't yell if the LOR
1297 * is between 2 VNODE locks.
1299 if ((lock->lo_flags & LO_IS_VNODE) != 0 &&
1300 (lock1->li_lock->lo_flags & LO_IS_VNODE) != 0)
1305 * Ok, yell about it.
1307 if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1308 (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1310 "lock order reversal: (sleepable after non-sleepable)\n");
1311 else if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0
1312 && lock == &Giant.lock_object)
1314 "lock order reversal: (Giant after non-sleepable)\n");
1316 printf("lock order reversal:\n");
1319 * Try to locate an earlier lock with
1320 * witness w in our list.
1323 lock2 = &lle->ll_children[i];
1324 MPASS(lock2->li_lock != NULL);
1325 if (lock2->li_lock->lo_witness == w)
1327 if (i == 0 && lle->ll_next != NULL) {
1329 i = lle->ll_count - 1;
1330 MPASS(i >= 0 && i < LOCK_NCHILDREN);
1335 printf(" 1st %p %s (%s) @ %s:%d\n",
1336 lock1->li_lock, lock1->li_lock->lo_name,
1337 w1->w_name, fixup_filename(lock1->li_file),
1339 printf(" 2nd %p %s (%s) @ %s:%d\n", lock,
1340 lock->lo_name, w->w_name,
1341 fixup_filename(file), line);
1343 printf(" 1st %p %s (%s) @ %s:%d\n",
1344 lock2->li_lock, lock2->li_lock->lo_name,
1345 lock2->li_lock->lo_witness->w_name,
1346 fixup_filename(lock2->li_file),
1348 printf(" 2nd %p %s (%s) @ %s:%d\n",
1349 lock1->li_lock, lock1->li_lock->lo_name,
1350 w1->w_name, fixup_filename(lock1->li_file),
1352 printf(" 3rd %p %s (%s) @ %s:%d\n", lock,
1353 lock->lo_name, w->w_name,
1354 fixup_filename(file), line);
1356 witness_debugger(1);
1362 * If requested, build a new lock order. However, don't build a new
1363 * relationship between a sleepable lock and Giant if it is in the
1364 * wrong direction. The correct lock order is that sleepable locks
1365 * always come before Giant.
1367 if (flags & LOP_NEWORDER &&
1368 !(plock->li_lock == &Giant.lock_object &&
1369 (lock->lo_flags & LO_SLEEPABLE) != 0)) {
1370 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1371 w->w_name, plock->li_lock->lo_witness->w_name);
1372 itismychild(plock->li_lock->lo_witness, w);
1375 mtx_unlock_spin(&w_mtx);
1379 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
1381 struct lock_list_entry **lock_list, *lle;
1382 struct lock_instance *instance;
1386 if (witness_cold || witness_watch == -1 || lock->lo_witness == NULL ||
1389 w = lock->lo_witness;
1392 /* Determine lock list for this lock. */
1393 if (LOCK_CLASS(lock)->lc_flags & LC_SLEEPLOCK)
1394 lock_list = &td->td_sleeplocks;
1396 lock_list = PCPU_PTR(spinlocks);
1398 /* Check to see if we are recursing on a lock we already own. */
1399 instance = find_instance(*lock_list, lock);
1400 if (instance != NULL) {
1401 instance->li_flags++;
1402 CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1403 td->td_proc->p_pid, lock->lo_name,
1404 instance->li_flags & LI_RECURSEMASK);
1405 instance->li_file = file;
1406 instance->li_line = line;
1410 /* Update per-witness last file and line acquire. */
1414 /* Find the next open lock instance in the list and fill it. */
1416 if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1417 lle = witness_lock_list_get();
1420 lle->ll_next = *lock_list;
1421 CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1422 td->td_proc->p_pid, lle);
1425 instance = &lle->ll_children[lle->ll_count++];
1426 instance->li_lock = lock;
1427 instance->li_line = line;
1428 instance->li_file = file;
1429 if ((flags & LOP_EXCLUSIVE) != 0)
1430 instance->li_flags = LI_EXCLUSIVE;
1432 instance->li_flags = 0;
1433 CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1434 td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1438 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1440 struct lock_instance *instance;
1441 struct lock_class *class;
1443 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1444 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1446 class = LOCK_CLASS(lock);
1447 if (witness_watch) {
1448 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1450 "upgrade of non-upgradable lock (%s) %s @ %s:%d",
1451 class->lc_name, lock->lo_name,
1452 fixup_filename(file), line);
1453 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1455 "upgrade of non-sleep lock (%s) %s @ %s:%d",
1456 class->lc_name, lock->lo_name,
1457 fixup_filename(file), line);
1459 instance = find_instance(curthread->td_sleeplocks, lock);
1460 if (instance == NULL) {
1461 kassert_panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1462 class->lc_name, lock->lo_name,
1463 fixup_filename(file), line);
1466 if (witness_watch) {
1467 if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1469 "upgrade of exclusive lock (%s) %s @ %s:%d",
1470 class->lc_name, lock->lo_name,
1471 fixup_filename(file), line);
1472 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1474 "upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1475 class->lc_name, lock->lo_name,
1476 instance->li_flags & LI_RECURSEMASK,
1477 fixup_filename(file), line);
1479 instance->li_flags |= LI_EXCLUSIVE;
1483 witness_downgrade(struct lock_object *lock, int flags, const char *file,
1486 struct lock_instance *instance;
1487 struct lock_class *class;
1489 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1490 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1492 class = LOCK_CLASS(lock);
1493 if (witness_watch) {
1494 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1496 "downgrade of non-upgradable lock (%s) %s @ %s:%d",
1497 class->lc_name, lock->lo_name,
1498 fixup_filename(file), line);
1499 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1501 "downgrade of non-sleep lock (%s) %s @ %s:%d",
1502 class->lc_name, lock->lo_name,
1503 fixup_filename(file), line);
1505 instance = find_instance(curthread->td_sleeplocks, lock);
1506 if (instance == NULL) {
1507 kassert_panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1508 class->lc_name, lock->lo_name,
1509 fixup_filename(file), line);
1512 if (witness_watch) {
1513 if ((instance->li_flags & LI_EXCLUSIVE) == 0)
1515 "downgrade of shared lock (%s) %s @ %s:%d",
1516 class->lc_name, lock->lo_name,
1517 fixup_filename(file), line);
1518 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1520 "downgrade of recursed lock (%s) %s r=%d @ %s:%d",
1521 class->lc_name, lock->lo_name,
1522 instance->li_flags & LI_RECURSEMASK,
1523 fixup_filename(file), line);
1525 instance->li_flags &= ~LI_EXCLUSIVE;
1529 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
1531 struct lock_list_entry **lock_list, *lle;
1532 struct lock_instance *instance;
1533 struct lock_class *class;
1538 if (witness_cold || lock->lo_witness == NULL || panicstr != NULL)
1541 class = LOCK_CLASS(lock);
1543 /* Find lock instance associated with this lock. */
1544 if (class->lc_flags & LC_SLEEPLOCK)
1545 lock_list = &td->td_sleeplocks;
1547 lock_list = PCPU_PTR(spinlocks);
1549 for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
1550 for (i = 0; i < (*lock_list)->ll_count; i++) {
1551 instance = &(*lock_list)->ll_children[i];
1552 if (instance->li_lock == lock)
1557 * When disabling WITNESS through witness_watch we could end up in
1558 * having registered locks in the td_sleeplocks queue.
1559 * We have to make sure we flush these queues, so just search for
1560 * eventual register locks and remove them.
1562 if (witness_watch > 0) {
1563 kassert_panic("lock (%s) %s not locked @ %s:%d", class->lc_name,
1564 lock->lo_name, fixup_filename(file), line);
1571 /* First, check for shared/exclusive mismatches. */
1572 if ((instance->li_flags & LI_EXCLUSIVE) != 0 && witness_watch > 0 &&
1573 (flags & LOP_EXCLUSIVE) == 0) {
1574 printf("shared unlock of (%s) %s @ %s:%d\n", class->lc_name,
1575 lock->lo_name, fixup_filename(file), line);
1576 printf("while exclusively locked from %s:%d\n",
1577 fixup_filename(instance->li_file), instance->li_line);
1578 kassert_panic("excl->ushare");
1580 if ((instance->li_flags & LI_EXCLUSIVE) == 0 && witness_watch > 0 &&
1581 (flags & LOP_EXCLUSIVE) != 0) {
1582 printf("exclusive unlock of (%s) %s @ %s:%d\n", class->lc_name,
1583 lock->lo_name, fixup_filename(file), line);
1584 printf("while share locked from %s:%d\n",
1585 fixup_filename(instance->li_file),
1587 kassert_panic("share->uexcl");
1589 /* If we are recursed, unrecurse. */
1590 if ((instance->li_flags & LI_RECURSEMASK) > 0) {
1591 CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
1592 td->td_proc->p_pid, instance->li_lock->lo_name,
1593 instance->li_flags);
1594 instance->li_flags--;
1597 /* The lock is now being dropped, check for NORELEASE flag */
1598 if ((instance->li_flags & LI_NORELEASE) != 0 && witness_watch > 0) {
1599 printf("forbidden unlock of (%s) %s @ %s:%d\n", class->lc_name,
1600 lock->lo_name, fixup_filename(file), line);
1601 kassert_panic("lock marked norelease");
1604 /* Otherwise, remove this item from the list. */
1606 CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
1607 td->td_proc->p_pid, instance->li_lock->lo_name,
1608 (*lock_list)->ll_count - 1);
1609 for (j = i; j < (*lock_list)->ll_count - 1; j++)
1610 (*lock_list)->ll_children[j] =
1611 (*lock_list)->ll_children[j + 1];
1612 (*lock_list)->ll_count--;
1616 * In order to reduce contention on w_mtx, we want to keep always an
1617 * head object into lists so that frequent allocation from the
1618 * free witness pool (and subsequent locking) is avoided.
1619 * In order to maintain the current code simple, when the head
1620 * object is totally unloaded it means also that we do not have
1621 * further objects in the list, so the list ownership needs to be
1622 * hand over to another object if the current head needs to be freed.
1624 if ((*lock_list)->ll_count == 0) {
1625 if (*lock_list == lle) {
1626 if (lle->ll_next == NULL)
1630 *lock_list = lle->ll_next;
1631 CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
1632 td->td_proc->p_pid, lle);
1633 witness_lock_list_free(lle);
1638 witness_thread_exit(struct thread *td)
1640 struct lock_list_entry *lle;
1643 lle = td->td_sleeplocks;
1644 if (lle == NULL || panicstr != NULL)
1646 if (lle->ll_count != 0) {
1647 for (n = 0; lle != NULL; lle = lle->ll_next)
1648 for (i = lle->ll_count - 1; i >= 0; i--) {
1650 printf("Thread %p exiting with the following locks held:\n",
1653 witness_list_lock(&lle->ll_children[i], printf);
1657 "Thread %p cannot exit while holding sleeplocks\n", td);
1659 witness_lock_list_free(lle);
1663 * Warn if any locks other than 'lock' are held. Flags can be passed in to
1664 * exempt Giant and sleepable locks from the checks as well. If any
1665 * non-exempt locks are held, then a supplied message is printed to the
1666 * console along with a list of the offending locks. If indicated in the
1667 * flags then a failure results in a panic as well.
1670 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1672 struct lock_list_entry *lock_list, *lle;
1673 struct lock_instance *lock1;
1678 if (witness_cold || witness_watch < 1 || panicstr != NULL)
1682 for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1683 for (i = lle->ll_count - 1; i >= 0; i--) {
1684 lock1 = &lle->ll_children[i];
1685 if (lock1->li_lock == lock)
1687 if (flags & WARN_GIANTOK &&
1688 lock1->li_lock == &Giant.lock_object)
1690 if (flags & WARN_SLEEPOK &&
1691 (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1697 printf(" with the following");
1698 if (flags & WARN_SLEEPOK)
1699 printf(" non-sleepable");
1700 printf(" locks held:\n");
1703 witness_list_lock(lock1, printf);
1707 * Pin the thread in order to avoid problems with thread migration.
1708 * Once that all verifies are passed about spinlocks ownership,
1709 * the thread is in a safe path and it can be unpinned.
1712 lock_list = PCPU_GET(spinlocks);
1713 if (lock_list != NULL && lock_list->ll_count != 0) {
1717 * We should only have one spinlock and as long as
1718 * the flags cannot match for this locks class,
1719 * check if the first spinlock is the one curthread
1722 lock1 = &lock_list->ll_children[lock_list->ll_count - 1];
1723 if (lock_list->ll_count == 1 && lock_list->ll_next == NULL &&
1724 lock1->li_lock == lock && n == 0)
1730 printf(" with the following");
1731 if (flags & WARN_SLEEPOK)
1732 printf(" non-sleepable");
1733 printf(" locks held:\n");
1734 n += witness_list_locks(&lock_list, printf);
1737 if (flags & WARN_PANIC && n)
1738 kassert_panic("%s", __func__);
1740 witness_debugger(n);
1745 witness_file(struct lock_object *lock)
1749 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1751 w = lock->lo_witness;
1756 witness_line(struct lock_object *lock)
1760 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1762 w = lock->lo_witness;
1766 static struct witness *
1767 enroll(const char *description, struct lock_class *lock_class)
1770 struct witness_list *typelist;
1772 MPASS(description != NULL);
1774 if (witness_watch == -1 || panicstr != NULL)
1776 if ((lock_class->lc_flags & LC_SPINLOCK)) {
1777 if (witness_skipspin)
1781 } else if ((lock_class->lc_flags & LC_SLEEPLOCK)) {
1782 typelist = &w_sleep;
1784 kassert_panic("lock class %s is not sleep or spin",
1785 lock_class->lc_name);
1789 mtx_lock_spin(&w_mtx);
1790 w = witness_hash_get(description);
1793 if ((w = witness_get()) == NULL)
1795 MPASS(strlen(description) < MAX_W_NAME);
1796 strcpy(w->w_name, description);
1797 w->w_class = lock_class;
1799 STAILQ_INSERT_HEAD(&w_all, w, w_list);
1800 if (lock_class->lc_flags & LC_SPINLOCK) {
1801 STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1803 } else if (lock_class->lc_flags & LC_SLEEPLOCK) {
1804 STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1808 /* Insert new witness into the hash */
1809 witness_hash_put(w);
1810 witness_increment_graph_generation();
1811 mtx_unlock_spin(&w_mtx);
1815 mtx_unlock_spin(&w_mtx);
1816 if (lock_class != w->w_class)
1818 "lock (%s) %s does not match earlier (%s) lock",
1819 description, lock_class->lc_name,
1820 w->w_class->lc_name);
1825 depart(struct witness *w)
1827 struct witness_list *list;
1829 MPASS(w->w_refcount == 0);
1830 if (w->w_class->lc_flags & LC_SLEEPLOCK) {
1838 * Set file to NULL as it may point into a loadable module.
1842 witness_increment_graph_generation();
1847 adopt(struct witness *parent, struct witness *child)
1851 if (witness_cold == 0)
1852 mtx_assert(&w_mtx, MA_OWNED);
1854 /* If the relationship is already known, there's no work to be done. */
1855 if (isitmychild(parent, child))
1858 /* When the structure of the graph changes, bump up the generation. */
1859 witness_increment_graph_generation();
1862 * The hard part ... create the direct relationship, then propagate all
1863 * indirect relationships.
1865 pi = parent->w_index;
1866 ci = child->w_index;
1867 WITNESS_INDEX_ASSERT(pi);
1868 WITNESS_INDEX_ASSERT(ci);
1870 w_rmatrix[pi][ci] |= WITNESS_PARENT;
1871 w_rmatrix[ci][pi] |= WITNESS_CHILD;
1874 * If parent was not already an ancestor of child,
1875 * then we increment the descendant and ancestor counters.
1877 if ((w_rmatrix[pi][ci] & WITNESS_ANCESTOR) == 0) {
1878 parent->w_num_descendants++;
1879 child->w_num_ancestors++;
1883 * Find each ancestor of 'pi'. Note that 'pi' itself is counted as
1884 * an ancestor of 'pi' during this loop.
1886 for (i = 1; i <= w_max_used_index; i++) {
1887 if ((w_rmatrix[i][pi] & WITNESS_ANCESTOR_MASK) == 0 &&
1891 /* Find each descendant of 'i' and mark it as a descendant. */
1892 for (j = 1; j <= w_max_used_index; j++) {
1895 * Skip children that are already marked as
1896 * descendants of 'i'.
1898 if (w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK)
1902 * We are only interested in descendants of 'ci'. Note
1903 * that 'ci' itself is counted as a descendant of 'ci'.
1905 if ((w_rmatrix[ci][j] & WITNESS_ANCESTOR_MASK) == 0 &&
1908 w_rmatrix[i][j] |= WITNESS_ANCESTOR;
1909 w_rmatrix[j][i] |= WITNESS_DESCENDANT;
1910 w_data[i].w_num_descendants++;
1911 w_data[j].w_num_ancestors++;
1914 * Make sure we aren't marking a node as both an
1915 * ancestor and descendant. We should have caught
1916 * this as a lock order reversal earlier.
1918 if ((w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK) &&
1919 (w_rmatrix[i][j] & WITNESS_DESCENDANT_MASK)) {
1920 printf("witness rmatrix paradox! [%d][%d]=%d "
1921 "both ancestor and descendant\n",
1922 i, j, w_rmatrix[i][j]);
1924 printf("Witness disabled.\n");
1927 if ((w_rmatrix[j][i] & WITNESS_ANCESTOR_MASK) &&
1928 (w_rmatrix[j][i] & WITNESS_DESCENDANT_MASK)) {
1929 printf("witness rmatrix paradox! [%d][%d]=%d "
1930 "both ancestor and descendant\n",
1931 j, i, w_rmatrix[j][i]);
1933 printf("Witness disabled.\n");
1941 itismychild(struct witness *parent, struct witness *child)
1945 MPASS(child != NULL && parent != NULL);
1946 if (witness_cold == 0)
1947 mtx_assert(&w_mtx, MA_OWNED);
1949 if (!witness_lock_type_equal(parent, child)) {
1950 if (witness_cold == 0) {
1952 mtx_unlock_spin(&w_mtx);
1957 "%s: parent \"%s\" (%s) and child \"%s\" (%s) are not "
1958 "the same lock type", __func__, parent->w_name,
1959 parent->w_class->lc_name, child->w_name,
1960 child->w_class->lc_name);
1962 mtx_lock_spin(&w_mtx);
1964 adopt(parent, child);
1968 * Generic code for the isitmy*() functions. The rmask parameter is the
1969 * expected relationship of w1 to w2.
1972 _isitmyx(struct witness *w1, struct witness *w2, int rmask, const char *fname)
1974 unsigned char r1, r2;
1979 WITNESS_INDEX_ASSERT(i1);
1980 WITNESS_INDEX_ASSERT(i2);
1981 r1 = w_rmatrix[i1][i2] & WITNESS_RELATED_MASK;
1982 r2 = w_rmatrix[i2][i1] & WITNESS_RELATED_MASK;
1984 /* The flags on one better be the inverse of the flags on the other */
1985 if (!((WITNESS_ATOD(r1) == r2 && WITNESS_DTOA(r2) == r1) ||
1986 (WITNESS_DTOA(r1) == r2 && WITNESS_ATOD(r2) == r1))) {
1987 printf("%s: rmatrix mismatch between %s (index %d) and %s "
1988 "(index %d): w_rmatrix[%d][%d] == %hhx but "
1989 "w_rmatrix[%d][%d] == %hhx\n",
1990 fname, w1->w_name, i1, w2->w_name, i2, i1, i2, r1,
1993 printf("Witness disabled.\n");
1996 return (r1 & rmask);
2000 * Checks if @child is a direct child of @parent.
2003 isitmychild(struct witness *parent, struct witness *child)
2006 return (_isitmyx(parent, child, WITNESS_PARENT, __func__));
2010 * Checks if @descendant is a direct or inderect descendant of @ancestor.
2013 isitmydescendant(struct witness *ancestor, struct witness *descendant)
2016 return (_isitmyx(ancestor, descendant, WITNESS_ANCESTOR_MASK,
2022 blessed(struct witness *w1, struct witness *w2)
2025 struct witness_blessed *b;
2027 for (i = 0; i < blessed_count; i++) {
2028 b = &blessed_list[i];
2029 if (strcmp(w1->w_name, b->b_lock1) == 0) {
2030 if (strcmp(w2->w_name, b->b_lock2) == 0)
2034 if (strcmp(w1->w_name, b->b_lock2) == 0)
2035 if (strcmp(w2->w_name, b->b_lock1) == 0)
2042 static struct witness *
2048 if (witness_cold == 0)
2049 mtx_assert(&w_mtx, MA_OWNED);
2051 if (witness_watch == -1) {
2052 mtx_unlock_spin(&w_mtx);
2055 if (STAILQ_EMPTY(&w_free)) {
2057 mtx_unlock_spin(&w_mtx);
2058 printf("WITNESS: unable to allocate a new witness object\n");
2061 w = STAILQ_FIRST(&w_free);
2062 STAILQ_REMOVE_HEAD(&w_free, w_list);
2065 MPASS(index > 0 && index == w_max_used_index+1 &&
2066 index < WITNESS_COUNT);
2067 bzero(w, sizeof(*w));
2069 if (index > w_max_used_index)
2070 w_max_used_index = index;
2075 witness_free(struct witness *w)
2078 STAILQ_INSERT_HEAD(&w_free, w, w_list);
2082 static struct lock_list_entry *
2083 witness_lock_list_get(void)
2085 struct lock_list_entry *lle;
2087 if (witness_watch == -1)
2089 mtx_lock_spin(&w_mtx);
2090 lle = w_lock_list_free;
2093 mtx_unlock_spin(&w_mtx);
2094 printf("%s: witness exhausted\n", __func__);
2097 w_lock_list_free = lle->ll_next;
2098 mtx_unlock_spin(&w_mtx);
2099 bzero(lle, sizeof(*lle));
2104 witness_lock_list_free(struct lock_list_entry *lle)
2107 mtx_lock_spin(&w_mtx);
2108 lle->ll_next = w_lock_list_free;
2109 w_lock_list_free = lle;
2110 mtx_unlock_spin(&w_mtx);
2113 static struct lock_instance *
2114 find_instance(struct lock_list_entry *list, const struct lock_object *lock)
2116 struct lock_list_entry *lle;
2117 struct lock_instance *instance;
2120 for (lle = list; lle != NULL; lle = lle->ll_next)
2121 for (i = lle->ll_count - 1; i >= 0; i--) {
2122 instance = &lle->ll_children[i];
2123 if (instance->li_lock == lock)
2130 witness_list_lock(struct lock_instance *instance,
2131 int (*prnt)(const char *fmt, ...))
2133 struct lock_object *lock;
2135 lock = instance->li_lock;
2136 prnt("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
2137 "exclusive" : "shared", LOCK_CLASS(lock)->lc_name, lock->lo_name);
2138 if (lock->lo_witness->w_name != lock->lo_name)
2139 prnt(" (%s)", lock->lo_witness->w_name);
2140 prnt(" r = %d (%p) locked @ %s:%d\n",
2141 instance->li_flags & LI_RECURSEMASK, lock,
2142 fixup_filename(instance->li_file), instance->li_line);
2147 witness_thread_has_locks(struct thread *td)
2150 if (td->td_sleeplocks == NULL)
2152 return (td->td_sleeplocks->ll_count != 0);
2156 witness_proc_has_locks(struct proc *p)
2160 FOREACH_THREAD_IN_PROC(p, td) {
2161 if (witness_thread_has_locks(td))
2169 witness_list_locks(struct lock_list_entry **lock_list,
2170 int (*prnt)(const char *fmt, ...))
2172 struct lock_list_entry *lle;
2176 for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
2177 for (i = lle->ll_count - 1; i >= 0; i--) {
2178 witness_list_lock(&lle->ll_children[i], prnt);
2185 * This is a bit risky at best. We call this function when we have timed
2186 * out acquiring a spin lock, and we assume that the other CPU is stuck
2187 * with this lock held. So, we go groveling around in the other CPU's
2188 * per-cpu data to try to find the lock instance for this spin lock to
2189 * see when it was last acquired.
2192 witness_display_spinlock(struct lock_object *lock, struct thread *owner,
2193 int (*prnt)(const char *fmt, ...))
2195 struct lock_instance *instance;
2198 if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
2200 pc = pcpu_find(owner->td_oncpu);
2201 instance = find_instance(pc->pc_spinlocks, lock);
2202 if (instance != NULL)
2203 witness_list_lock(instance, prnt);
2207 witness_save(struct lock_object *lock, const char **filep, int *linep)
2209 struct lock_list_entry *lock_list;
2210 struct lock_instance *instance;
2211 struct lock_class *class;
2214 * This function is used independently in locking code to deal with
2215 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2218 if (SCHEDULER_STOPPED())
2220 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2221 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2223 class = LOCK_CLASS(lock);
2224 if (class->lc_flags & LC_SLEEPLOCK)
2225 lock_list = curthread->td_sleeplocks;
2227 if (witness_skipspin)
2229 lock_list = PCPU_GET(spinlocks);
2231 instance = find_instance(lock_list, lock);
2232 if (instance == NULL) {
2233 kassert_panic("%s: lock (%s) %s not locked", __func__,
2234 class->lc_name, lock->lo_name);
2237 *filep = instance->li_file;
2238 *linep = instance->li_line;
2242 witness_restore(struct lock_object *lock, const char *file, int line)
2244 struct lock_list_entry *lock_list;
2245 struct lock_instance *instance;
2246 struct lock_class *class;
2249 * This function is used independently in locking code to deal with
2250 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2253 if (SCHEDULER_STOPPED())
2255 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2256 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2258 class = LOCK_CLASS(lock);
2259 if (class->lc_flags & LC_SLEEPLOCK)
2260 lock_list = curthread->td_sleeplocks;
2262 if (witness_skipspin)
2264 lock_list = PCPU_GET(spinlocks);
2266 instance = find_instance(lock_list, lock);
2267 if (instance == NULL)
2268 kassert_panic("%s: lock (%s) %s not locked", __func__,
2269 class->lc_name, lock->lo_name);
2270 lock->lo_witness->w_file = file;
2271 lock->lo_witness->w_line = line;
2272 if (instance == NULL)
2274 instance->li_file = file;
2275 instance->li_line = line;
2279 witness_assert(const struct lock_object *lock, int flags, const char *file,
2282 #ifdef INVARIANT_SUPPORT
2283 struct lock_instance *instance;
2284 struct lock_class *class;
2286 if (lock->lo_witness == NULL || witness_watch < 1 || panicstr != NULL)
2288 class = LOCK_CLASS(lock);
2289 if ((class->lc_flags & LC_SLEEPLOCK) != 0)
2290 instance = find_instance(curthread->td_sleeplocks, lock);
2291 else if ((class->lc_flags & LC_SPINLOCK) != 0)
2292 instance = find_instance(PCPU_GET(spinlocks), lock);
2294 kassert_panic("Lock (%s) %s is not sleep or spin!",
2295 class->lc_name, lock->lo_name);
2300 if (instance != NULL)
2301 kassert_panic("Lock (%s) %s locked @ %s:%d.",
2302 class->lc_name, lock->lo_name,
2303 fixup_filename(file), line);
2306 case LA_LOCKED | LA_RECURSED:
2307 case LA_LOCKED | LA_NOTRECURSED:
2309 case LA_SLOCKED | LA_RECURSED:
2310 case LA_SLOCKED | LA_NOTRECURSED:
2312 case LA_XLOCKED | LA_RECURSED:
2313 case LA_XLOCKED | LA_NOTRECURSED:
2314 if (instance == NULL) {
2315 kassert_panic("Lock (%s) %s not locked @ %s:%d.",
2316 class->lc_name, lock->lo_name,
2317 fixup_filename(file), line);
2320 if ((flags & LA_XLOCKED) != 0 &&
2321 (instance->li_flags & LI_EXCLUSIVE) == 0)
2323 "Lock (%s) %s not exclusively locked @ %s:%d.",
2324 class->lc_name, lock->lo_name,
2325 fixup_filename(file), line);
2326 if ((flags & LA_SLOCKED) != 0 &&
2327 (instance->li_flags & LI_EXCLUSIVE) != 0)
2329 "Lock (%s) %s exclusively locked @ %s:%d.",
2330 class->lc_name, lock->lo_name,
2331 fixup_filename(file), line);
2332 if ((flags & LA_RECURSED) != 0 &&
2333 (instance->li_flags & LI_RECURSEMASK) == 0)
2334 kassert_panic("Lock (%s) %s not recursed @ %s:%d.",
2335 class->lc_name, lock->lo_name,
2336 fixup_filename(file), line);
2337 if ((flags & LA_NOTRECURSED) != 0 &&
2338 (instance->li_flags & LI_RECURSEMASK) != 0)
2339 kassert_panic("Lock (%s) %s recursed @ %s:%d.",
2340 class->lc_name, lock->lo_name,
2341 fixup_filename(file), line);
2344 kassert_panic("Invalid lock assertion at %s:%d.",
2345 fixup_filename(file), line);
2348 #endif /* INVARIANT_SUPPORT */
2352 witness_setflag(struct lock_object *lock, int flag, int set)
2354 struct lock_list_entry *lock_list;
2355 struct lock_instance *instance;
2356 struct lock_class *class;
2358 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2360 class = LOCK_CLASS(lock);
2361 if (class->lc_flags & LC_SLEEPLOCK)
2362 lock_list = curthread->td_sleeplocks;
2364 if (witness_skipspin)
2366 lock_list = PCPU_GET(spinlocks);
2368 instance = find_instance(lock_list, lock);
2369 if (instance == NULL) {
2370 kassert_panic("%s: lock (%s) %s not locked", __func__,
2371 class->lc_name, lock->lo_name);
2376 instance->li_flags |= flag;
2378 instance->li_flags &= ~flag;
2382 witness_norelease(struct lock_object *lock)
2385 witness_setflag(lock, LI_NORELEASE, 1);
2389 witness_releaseok(struct lock_object *lock)
2392 witness_setflag(lock, LI_NORELEASE, 0);
2397 witness_ddb_list(struct thread *td)
2400 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2401 KASSERT(kdb_active, ("%s: not in the debugger", __func__));
2403 if (witness_watch < 1)
2406 witness_list_locks(&td->td_sleeplocks, db_printf);
2409 * We only handle spinlocks if td == curthread. This is somewhat broken
2410 * if td is currently executing on some other CPU and holds spin locks
2411 * as we won't display those locks. If we had a MI way of getting
2412 * the per-cpu data for a given cpu then we could use
2413 * td->td_oncpu to get the list of spinlocks for this thread
2416 * That still wouldn't really fix this unless we locked the scheduler
2417 * lock or stopped the other CPU to make sure it wasn't changing the
2418 * list out from under us. It is probably best to just not try to
2419 * handle threads on other CPU's for now.
2421 if (td == curthread && PCPU_GET(spinlocks) != NULL)
2422 witness_list_locks(PCPU_PTR(spinlocks), db_printf);
2425 DB_SHOW_COMMAND(locks, db_witness_list)
2430 td = db_lookup_thread(addr, TRUE);
2433 witness_ddb_list(td);
2436 DB_SHOW_ALL_COMMAND(locks, db_witness_list_all)
2442 * It would be nice to list only threads and processes that actually
2443 * held sleep locks, but that information is currently not exported
2446 FOREACH_PROC_IN_SYSTEM(p) {
2447 if (!witness_proc_has_locks(p))
2449 FOREACH_THREAD_IN_PROC(p, td) {
2450 if (!witness_thread_has_locks(td))
2452 db_printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
2453 p->p_comm, td, td->td_tid);
2454 witness_ddb_list(td);
2460 DB_SHOW_ALIAS(alllocks, db_witness_list_all)
2462 DB_SHOW_COMMAND(witness, db_witness_display)
2465 witness_ddb_display(db_printf);
2470 sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)
2472 struct witness_lock_order_data *data1, *data2, *tmp_data1, *tmp_data2;
2473 struct witness *tmp_w1, *tmp_w2, *w1, *w2;
2475 u_int w_rmatrix1, w_rmatrix2;
2476 int error, generation, i, j;
2482 if (witness_watch < 1) {
2483 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2487 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2491 sb = sbuf_new(NULL, NULL, BADSTACK_SBUF_SIZE, SBUF_AUTOEXTEND);
2495 /* Allocate and init temporary storage space. */
2496 tmp_w1 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2497 tmp_w2 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2498 tmp_data1 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2500 tmp_data2 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2502 stack_zero(&tmp_data1->wlod_stack);
2503 stack_zero(&tmp_data2->wlod_stack);
2506 mtx_lock_spin(&w_mtx);
2507 generation = w_generation;
2508 mtx_unlock_spin(&w_mtx);
2509 sbuf_printf(sb, "Number of known direct relationships is %d\n",
2510 w_lohash.wloh_count);
2511 for (i = 1; i < w_max_used_index; i++) {
2512 mtx_lock_spin(&w_mtx);
2513 if (generation != w_generation) {
2514 mtx_unlock_spin(&w_mtx);
2516 /* The graph has changed, try again. */
2523 if (w1->w_reversed == 0) {
2524 mtx_unlock_spin(&w_mtx);
2528 /* Copy w1 locally so we can release the spin lock. */
2530 mtx_unlock_spin(&w_mtx);
2532 if (tmp_w1->w_reversed == 0)
2534 for (j = 1; j < w_max_used_index; j++) {
2535 if ((w_rmatrix[i][j] & WITNESS_REVERSAL) == 0 || i > j)
2538 mtx_lock_spin(&w_mtx);
2539 if (generation != w_generation) {
2540 mtx_unlock_spin(&w_mtx);
2542 /* The graph has changed, try again. */
2549 data1 = witness_lock_order_get(w1, w2);
2550 data2 = witness_lock_order_get(w2, w1);
2553 * Copy information locally so we can release the
2557 w_rmatrix1 = (unsigned int)w_rmatrix[i][j];
2558 w_rmatrix2 = (unsigned int)w_rmatrix[j][i];
2561 stack_zero(&tmp_data1->wlod_stack);
2562 stack_copy(&data1->wlod_stack,
2563 &tmp_data1->wlod_stack);
2565 if (data2 && data2 != data1) {
2566 stack_zero(&tmp_data2->wlod_stack);
2567 stack_copy(&data2->wlod_stack,
2568 &tmp_data2->wlod_stack);
2570 mtx_unlock_spin(&w_mtx);
2573 "\nLock order reversal between \"%s\"(%s) and \"%s\"(%s)!\n",
2574 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2575 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2578 "w_rmatrix[%s][%s] == %x, w_rmatrix[%s][%s] == %x\n",
2579 tmp_w1->name, tmp_w2->w_name, w_rmatrix1,
2580 tmp_w2->name, tmp_w1->w_name, w_rmatrix2);
2584 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2585 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2586 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2587 stack_sbuf_print(sb, &tmp_data1->wlod_stack);
2588 sbuf_printf(sb, "\n");
2590 if (data2 && data2 != data1) {
2592 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2593 tmp_w2->w_name, tmp_w2->w_class->lc_name,
2594 tmp_w1->w_name, tmp_w1->w_class->lc_name);
2595 stack_sbuf_print(sb, &tmp_data2->wlod_stack);
2596 sbuf_printf(sb, "\n");
2600 mtx_lock_spin(&w_mtx);
2601 if (generation != w_generation) {
2602 mtx_unlock_spin(&w_mtx);
2605 * The graph changed while we were printing stack data,
2612 mtx_unlock_spin(&w_mtx);
2614 /* Free temporary storage space. */
2615 free(tmp_data1, M_TEMP);
2616 free(tmp_data2, M_TEMP);
2617 free(tmp_w1, M_TEMP);
2618 free(tmp_w2, M_TEMP);
2621 error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
2628 sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
2634 if (witness_watch < 1) {
2635 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2639 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2644 error = sysctl_wire_old_buffer(req, 0);
2647 sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
2650 sbuf_printf(sb, "\n");
2652 mtx_lock_spin(&w_mtx);
2653 STAILQ_FOREACH(w, &w_all, w_list)
2655 STAILQ_FOREACH(w, &w_all, w_list)
2656 witness_add_fullgraph(sb, w);
2657 mtx_unlock_spin(&w_mtx);
2660 * Close the sbuf and return to userland.
2662 error = sbuf_finish(sb);
2669 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
2673 value = witness_watch;
2674 error = sysctl_handle_int(oidp, &value, 0, req);
2675 if (error != 0 || req->newptr == NULL)
2677 if (value > 1 || value < -1 ||
2678 (witness_watch == -1 && value != witness_watch))
2680 witness_watch = value;
2685 witness_add_fullgraph(struct sbuf *sb, struct witness *w)
2689 if (w->w_displayed != 0 || (w->w_file == NULL && w->w_line == 0))
2693 WITNESS_INDEX_ASSERT(w->w_index);
2694 for (i = 1; i <= w_max_used_index; i++) {
2695 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT) {
2696 sbuf_printf(sb, "\"%s\",\"%s\"\n", w->w_name,
2698 witness_add_fullgraph(sb, &w_data[i]);
2704 * A simple hash function. Takes a key pointer and a key size. If size == 0,
2705 * interprets the key as a string and reads until the null
2706 * terminator. Otherwise, reads the first size bytes. Returns an unsigned 32-bit
2707 * hash value computed from the key.
2710 witness_hash_djb2(const uint8_t *key, uint32_t size)
2712 unsigned int hash = 5381;
2715 /* hash = hash * 33 + key[i] */
2717 for (i = 0; i < size; i++)
2718 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2720 for (i = 0; key[i] != 0; i++)
2721 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2728 * Initializes the two witness hash tables. Called exactly once from
2729 * witness_initialize().
2732 witness_init_hash_tables(void)
2736 MPASS(witness_cold);
2738 /* Initialize the hash tables. */
2739 for (i = 0; i < WITNESS_HASH_SIZE; i++)
2740 w_hash.wh_array[i] = NULL;
2742 w_hash.wh_size = WITNESS_HASH_SIZE;
2743 w_hash.wh_count = 0;
2745 /* Initialize the lock order data hash. */
2747 for (i = 0; i < WITNESS_LO_DATA_COUNT; i++) {
2748 memset(&w_lodata[i], 0, sizeof(w_lodata[i]));
2749 w_lodata[i].wlod_next = w_lofree;
2750 w_lofree = &w_lodata[i];
2752 w_lohash.wloh_size = WITNESS_LO_HASH_SIZE;
2753 w_lohash.wloh_count = 0;
2754 for (i = 0; i < WITNESS_LO_HASH_SIZE; i++)
2755 w_lohash.wloh_array[i] = NULL;
2758 static struct witness *
2759 witness_hash_get(const char *key)
2765 if (witness_cold == 0)
2766 mtx_assert(&w_mtx, MA_OWNED);
2767 hash = witness_hash_djb2(key, 0) % w_hash.wh_size;
2768 w = w_hash.wh_array[hash];
2770 if (strcmp(w->w_name, key) == 0)
2780 witness_hash_put(struct witness *w)
2785 MPASS(w->w_name != NULL);
2786 if (witness_cold == 0)
2787 mtx_assert(&w_mtx, MA_OWNED);
2788 KASSERT(witness_hash_get(w->w_name) == NULL,
2789 ("%s: trying to add a hash entry that already exists!", __func__));
2790 KASSERT(w->w_hash_next == NULL,
2791 ("%s: w->w_hash_next != NULL", __func__));
2793 hash = witness_hash_djb2(w->w_name, 0) % w_hash.wh_size;
2794 w->w_hash_next = w_hash.wh_array[hash];
2795 w_hash.wh_array[hash] = w;
2800 static struct witness_lock_order_data *
2801 witness_lock_order_get(struct witness *parent, struct witness *child)
2803 struct witness_lock_order_data *data = NULL;
2804 struct witness_lock_order_key key;
2807 MPASS(parent != NULL && child != NULL);
2808 key.from = parent->w_index;
2809 key.to = child->w_index;
2810 WITNESS_INDEX_ASSERT(key.from);
2811 WITNESS_INDEX_ASSERT(key.to);
2812 if ((w_rmatrix[parent->w_index][child->w_index]
2813 & WITNESS_LOCK_ORDER_KNOWN) == 0)
2816 hash = witness_hash_djb2((const char*)&key,
2817 sizeof(key)) % w_lohash.wloh_size;
2818 data = w_lohash.wloh_array[hash];
2819 while (data != NULL) {
2820 if (witness_lock_order_key_equal(&data->wlod_key, &key))
2822 data = data->wlod_next;
2830 * Verify that parent and child have a known relationship, are not the same,
2831 * and child is actually a child of parent. This is done without w_mtx
2832 * to avoid contention in the common case.
2835 witness_lock_order_check(struct witness *parent, struct witness *child)
2838 if (parent != child &&
2839 w_rmatrix[parent->w_index][child->w_index]
2840 & WITNESS_LOCK_ORDER_KNOWN &&
2841 isitmychild(parent, child))
2848 witness_lock_order_add(struct witness *parent, struct witness *child)
2850 struct witness_lock_order_data *data = NULL;
2851 struct witness_lock_order_key key;
2854 MPASS(parent != NULL && child != NULL);
2855 key.from = parent->w_index;
2856 key.to = child->w_index;
2857 WITNESS_INDEX_ASSERT(key.from);
2858 WITNESS_INDEX_ASSERT(key.to);
2859 if (w_rmatrix[parent->w_index][child->w_index]
2860 & WITNESS_LOCK_ORDER_KNOWN)
2863 hash = witness_hash_djb2((const char*)&key,
2864 sizeof(key)) % w_lohash.wloh_size;
2865 w_rmatrix[parent->w_index][child->w_index] |= WITNESS_LOCK_ORDER_KNOWN;
2869 w_lofree = data->wlod_next;
2870 data->wlod_next = w_lohash.wloh_array[hash];
2871 data->wlod_key = key;
2872 w_lohash.wloh_array[hash] = data;
2873 w_lohash.wloh_count++;
2874 stack_zero(&data->wlod_stack);
2875 stack_save(&data->wlod_stack);
2879 /* Call this whenver the structure of the witness graph changes. */
2881 witness_increment_graph_generation(void)
2884 if (witness_cold == 0)
2885 mtx_assert(&w_mtx, MA_OWNED);
2891 _witness_debugger(int cond, const char *msg)
2894 if (witness_trace && cond)
2896 if (witness_kdb && cond)
2897 kdb_enter(KDB_WHY_WITNESS, msg);