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 #ifndef WITNESS_COUNT
136 #define WITNESS_COUNT 1536
138 #define WITNESS_CHILDCOUNT (WITNESS_COUNT * 4)
139 #define WITNESS_HASH_SIZE 251 /* Prime, gives load factor < 2 */
140 #define WITNESS_PENDLIST (1024 + MAXCPU)
142 /* Allocate 256 KB of stack data space */
143 #define WITNESS_LO_DATA_COUNT 2048
145 /* Prime, gives load factor of ~2 at full load */
146 #define WITNESS_LO_HASH_SIZE 1021
149 * XXX: This is somewhat bogus, as we assume here that at most 2048 threads
150 * will hold LOCK_NCHILDREN locks. We handle failure ok, and we should
151 * probably be safe for the most part, but it's still a SWAG.
153 #define LOCK_NCHILDREN 5
154 #define LOCK_CHILDCOUNT 2048
156 #define MAX_W_NAME 64
158 #define BADSTACK_SBUF_SIZE (256 * WITNESS_COUNT)
159 #define FULLGRAPH_SBUF_SIZE 512
162 * These flags go in the witness relationship matrix and describe the
163 * relationship between any two struct witness objects.
165 #define WITNESS_UNRELATED 0x00 /* No lock order relation. */
166 #define WITNESS_PARENT 0x01 /* Parent, aka direct ancestor. */
167 #define WITNESS_ANCESTOR 0x02 /* Direct or indirect ancestor. */
168 #define WITNESS_CHILD 0x04 /* Child, aka direct descendant. */
169 #define WITNESS_DESCENDANT 0x08 /* Direct or indirect descendant. */
170 #define WITNESS_ANCESTOR_MASK (WITNESS_PARENT | WITNESS_ANCESTOR)
171 #define WITNESS_DESCENDANT_MASK (WITNESS_CHILD | WITNESS_DESCENDANT)
172 #define WITNESS_RELATED_MASK \
173 (WITNESS_ANCESTOR_MASK | WITNESS_DESCENDANT_MASK)
174 #define WITNESS_REVERSAL 0x10 /* A lock order reversal has been
176 #define WITNESS_RESERVED1 0x20 /* Unused flag, reserved. */
177 #define WITNESS_RESERVED2 0x40 /* Unused flag, reserved. */
178 #define WITNESS_LOCK_ORDER_KNOWN 0x80 /* This lock order is known. */
180 /* Descendant to ancestor flags */
181 #define WITNESS_DTOA(x) (((x) & WITNESS_RELATED_MASK) >> 2)
183 /* Ancestor to descendant flags */
184 #define WITNESS_ATOD(x) (((x) & WITNESS_RELATED_MASK) << 2)
186 #define WITNESS_INDEX_ASSERT(i) \
187 MPASS((i) > 0 && (i) <= w_max_used_index && (i) < WITNESS_COUNT)
189 static MALLOC_DEFINE(M_WITNESS, "Witness", "Witness");
192 * Lock instances. A lock instance is the data associated with a lock while
193 * it is held by witness. For example, a lock instance will hold the
194 * recursion count of a lock. Lock instances are held in lists. Spin locks
195 * are held in a per-cpu list while sleep locks are held in per-thread list.
197 struct lock_instance {
198 struct lock_object *li_lock;
205 * A simple list type used to build the list of locks held by a thread
206 * or CPU. We can't simply embed the list in struct lock_object since a
207 * lock may be held by more than one thread if it is a shared lock. Locks
208 * are added to the head of the list, so we fill up each list entry from
209 * "the back" logically. To ease some of the arithmetic, we actually fill
210 * in each list entry the normal way (children[0] then children[1], etc.) but
211 * when we traverse the list we read children[count-1] as the first entry
212 * down to children[0] as the final entry.
214 struct lock_list_entry {
215 struct lock_list_entry *ll_next;
216 struct lock_instance ll_children[LOCK_NCHILDREN];
221 * The main witness structure. One of these per named lock type in the system
222 * (for example, "vnode interlock").
225 char w_name[MAX_W_NAME];
226 uint32_t w_index; /* Index in the relationship matrix */
227 struct lock_class *w_class;
228 STAILQ_ENTRY(witness) w_list; /* List of all witnesses. */
229 STAILQ_ENTRY(witness) w_typelist; /* Witnesses of a type. */
230 struct witness *w_hash_next; /* Linked list in hash buckets. */
231 const char *w_file; /* File where last acquired */
232 uint32_t w_line; /* Line where last acquired */
234 uint16_t w_num_ancestors; /* direct/indirect
236 uint16_t w_num_descendants; /* direct/indirect
237 * descendant count */
239 unsigned w_displayed:1;
240 unsigned w_reversed:1;
243 STAILQ_HEAD(witness_list, witness);
246 * The witness hash table. Keys are witness names (const char *), elements are
247 * witness objects (struct witness *).
249 struct witness_hash {
250 struct witness *wh_array[WITNESS_HASH_SIZE];
256 * Key type for the lock order data hash table.
258 struct witness_lock_order_key {
263 struct witness_lock_order_data {
264 struct stack wlod_stack;
265 struct witness_lock_order_key wlod_key;
266 struct witness_lock_order_data *wlod_next;
270 * The witness lock order data hash table. Keys are witness index tuples
271 * (struct witness_lock_order_key), elements are lock order data objects
272 * (struct witness_lock_order_data).
274 struct witness_lock_order_hash {
275 struct witness_lock_order_data *wloh_array[WITNESS_LO_HASH_SIZE];
281 struct witness_blessed {
287 struct witness_pendhelp {
289 struct lock_object *wh_lock;
292 struct witness_order_list_entry {
294 struct lock_class *w_class;
298 * Returns 0 if one of the locks is a spin lock and the other is not.
299 * Returns 1 otherwise.
302 witness_lock_type_equal(struct witness *w1, struct witness *w2)
305 return ((w1->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) ==
306 (w2->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)));
310 witness_lock_order_key_equal(const struct witness_lock_order_key *a,
311 const struct witness_lock_order_key *b)
314 return (a->from == b->from && a->to == b->to);
317 static int _isitmyx(struct witness *w1, struct witness *w2, int rmask,
320 static void _witness_debugger(int cond, const char *msg);
322 static void adopt(struct witness *parent, struct witness *child);
324 static int blessed(struct witness *, struct witness *);
326 static void depart(struct witness *w);
327 static struct witness *enroll(const char *description,
328 struct lock_class *lock_class);
329 static struct lock_instance *find_instance(struct lock_list_entry *list,
330 const struct lock_object *lock);
331 static int isitmychild(struct witness *parent, struct witness *child);
332 static int isitmydescendant(struct witness *parent, struct witness *child);
333 static void itismychild(struct witness *parent, struct witness *child);
334 static int sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS);
335 static int sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
336 static int sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS);
337 static void witness_add_fullgraph(struct sbuf *sb, struct witness *parent);
339 static void witness_ddb_compute_levels(void);
340 static void witness_ddb_display(int(*)(const char *fmt, ...));
341 static void witness_ddb_display_descendants(int(*)(const char *fmt, ...),
342 struct witness *, int indent);
343 static void witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
344 struct witness_list *list);
345 static void witness_ddb_level_descendants(struct witness *parent, int l);
346 static void witness_ddb_list(struct thread *td);
348 static void witness_free(struct witness *m);
349 static struct witness *witness_get(void);
350 static uint32_t witness_hash_djb2(const uint8_t *key, uint32_t size);
351 static struct witness *witness_hash_get(const char *key);
352 static void witness_hash_put(struct witness *w);
353 static void witness_init_hash_tables(void);
354 static void witness_increment_graph_generation(void);
355 static void witness_lock_list_free(struct lock_list_entry *lle);
356 static struct lock_list_entry *witness_lock_list_get(void);
357 static int witness_lock_order_add(struct witness *parent,
358 struct witness *child);
359 static int witness_lock_order_check(struct witness *parent,
360 struct witness *child);
361 static struct witness_lock_order_data *witness_lock_order_get(
362 struct witness *parent,
363 struct witness *child);
364 static void witness_list_lock(struct lock_instance *instance,
365 int (*prnt)(const char *fmt, ...));
366 static void witness_setflag(struct lock_object *lock, int flag, int set);
369 #define witness_debugger(c) _witness_debugger(c, __func__)
371 #define witness_debugger(c)
374 static SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW, NULL,
378 * If set to 0, lock order checking is disabled. If set to -1,
379 * witness is completely disabled. Otherwise witness performs full
380 * lock order checking for all locks. At runtime, lock order checking
381 * may be toggled. However, witness cannot be reenabled once it is
382 * completely disabled.
384 static int witness_watch = 1;
385 SYSCTL_PROC(_debug_witness, OID_AUTO, watch, CTLFLAG_RWTUN | CTLTYPE_INT, NULL, 0,
386 sysctl_debug_witness_watch, "I", "witness is watching lock operations");
390 * When KDB is enabled and witness_kdb is 1, it will cause the system
391 * to drop into kdebug() when:
392 * - a lock hierarchy violation occurs
393 * - locks are held when going to sleep.
400 SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RWTUN, &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 SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RWTUN, &witness_trace, 0, "");
412 #ifdef WITNESS_SKIPSPIN
413 int witness_skipspin = 1;
415 int witness_skipspin = 0;
417 SYSCTL_INT(_debug_witness, OID_AUTO, skipspin, CTLFLAG_RDTUN, &witness_skipspin, 0, "");
420 * Call this to print out the relations between locks.
422 SYSCTL_PROC(_debug_witness, OID_AUTO, fullgraph, CTLTYPE_STRING | CTLFLAG_RD,
423 NULL, 0, sysctl_debug_witness_fullgraph, "A", "Show locks relation graphs");
426 * Call this to print out the witness faulty stacks.
428 SYSCTL_PROC(_debug_witness, OID_AUTO, badstacks, CTLTYPE_STRING | CTLFLAG_RD,
429 NULL, 0, sysctl_debug_witness_badstacks, "A", "Show bad witness stacks");
431 static struct mtx w_mtx;
434 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
435 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
438 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
439 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
442 static struct lock_list_entry *w_lock_list_free = NULL;
443 static struct witness_pendhelp pending_locks[WITNESS_PENDLIST];
444 static u_int pending_cnt;
446 static int w_free_cnt, w_spin_cnt, w_sleep_cnt;
447 SYSCTL_INT(_debug_witness, OID_AUTO, free_cnt, CTLFLAG_RD, &w_free_cnt, 0, "");
448 SYSCTL_INT(_debug_witness, OID_AUTO, spin_cnt, CTLFLAG_RD, &w_spin_cnt, 0, "");
449 SYSCTL_INT(_debug_witness, OID_AUTO, sleep_cnt, CTLFLAG_RD, &w_sleep_cnt, 0,
452 static struct witness *w_data;
453 static uint8_t w_rmatrix[WITNESS_COUNT+1][WITNESS_COUNT+1];
454 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
455 static struct witness_hash w_hash; /* The witness hash table. */
457 /* The lock order data hash */
458 static struct witness_lock_order_data w_lodata[WITNESS_LO_DATA_COUNT];
459 static struct witness_lock_order_data *w_lofree = NULL;
460 static struct witness_lock_order_hash w_lohash;
461 static int w_max_used_index = 0;
462 static unsigned int w_generation = 0;
463 static const char w_notrunning[] = "Witness not running\n";
464 static const char w_stillcold[] = "Witness is still cold\n";
467 static struct witness_order_list_entry order_lists[] = {
471 { "proctree", &lock_class_sx },
472 { "allproc", &lock_class_sx },
473 { "allprison", &lock_class_sx },
478 { "Giant", &lock_class_mtx_sleep },
479 { "pipe mutex", &lock_class_mtx_sleep },
480 { "sigio lock", &lock_class_mtx_sleep },
481 { "process group", &lock_class_mtx_sleep },
482 { "process lock", &lock_class_mtx_sleep },
483 { "session", &lock_class_mtx_sleep },
484 { "uidinfo hash", &lock_class_rw },
486 { "pmc-sleep", &lock_class_mtx_sleep },
488 { "time lock", &lock_class_mtx_sleep },
493 { "accept", &lock_class_mtx_sleep },
494 { "so_snd", &lock_class_mtx_sleep },
495 { "so_rcv", &lock_class_mtx_sleep },
496 { "sellck", &lock_class_mtx_sleep },
501 { "so_rcv", &lock_class_mtx_sleep },
502 { "radix node head", &lock_class_rw },
503 { "rtentry", &lock_class_mtx_sleep },
504 { "ifaddr", &lock_class_mtx_sleep },
508 * protocol locks before interface locks, after UDP locks.
510 { "udpinp", &lock_class_rw },
511 { "in_multi_mtx", &lock_class_mtx_sleep },
512 { "igmp_mtx", &lock_class_mtx_sleep },
513 { "if_addr_lock", &lock_class_rw },
517 * protocol locks before interface locks, after UDP locks.
519 { "udpinp", &lock_class_rw },
520 { "in6_multi_mtx", &lock_class_mtx_sleep },
521 { "mld_mtx", &lock_class_mtx_sleep },
522 { "if_addr_lock", &lock_class_rw },
525 * UNIX Domain Sockets
527 { "unp_global_rwlock", &lock_class_rw },
528 { "unp_list_lock", &lock_class_mtx_sleep },
529 { "unp", &lock_class_mtx_sleep },
530 { "so_snd", &lock_class_mtx_sleep },
535 { "udp", &lock_class_rw },
536 { "udpinp", &lock_class_rw },
537 { "so_snd", &lock_class_mtx_sleep },
542 { "tcp", &lock_class_rw },
543 { "tcpinp", &lock_class_rw },
544 { "so_snd", &lock_class_mtx_sleep },
549 { "bpf global lock", &lock_class_mtx_sleep },
550 { "bpf interface lock", &lock_class_rw },
551 { "bpf cdev lock", &lock_class_mtx_sleep },
556 { "nfsd_mtx", &lock_class_mtx_sleep },
557 { "so_snd", &lock_class_mtx_sleep },
563 { "802.11 com lock", &lock_class_mtx_sleep},
568 { "network driver", &lock_class_mtx_sleep},
574 { "ng_node", &lock_class_mtx_sleep },
575 { "ng_worklist", &lock_class_mtx_sleep },
580 { "vm map (system)", &lock_class_mtx_sleep },
581 { "vm page queue", &lock_class_mtx_sleep },
582 { "vnode interlock", &lock_class_mtx_sleep },
583 { "cdev", &lock_class_mtx_sleep },
588 { "vm map (user)", &lock_class_sx },
589 { "vm object", &lock_class_rw },
590 { "vm page", &lock_class_mtx_sleep },
591 { "vm page queue", &lock_class_mtx_sleep },
592 { "pmap pv global", &lock_class_rw },
593 { "pmap", &lock_class_mtx_sleep },
594 { "pmap pv list", &lock_class_rw },
595 { "vm page free queue", &lock_class_mtx_sleep },
598 * kqueue/VFS interaction
600 { "kqueue", &lock_class_mtx_sleep },
601 { "struct mount mtx", &lock_class_mtx_sleep },
602 { "vnode interlock", &lock_class_mtx_sleep },
607 { "dn->dn_mtx", &lock_class_sx },
608 { "dr->dt.di.dr_mtx", &lock_class_sx },
609 { "db->db_mtx", &lock_class_sx },
615 { "ap boot", &lock_class_mtx_spin },
617 { "rm.mutex_mtx", &lock_class_mtx_spin },
618 { "sio", &lock_class_mtx_spin },
619 { "scrlock", &lock_class_mtx_spin },
621 { "cy", &lock_class_mtx_spin },
624 { "pcib_mtx", &lock_class_mtx_spin },
625 { "rtc_mtx", &lock_class_mtx_spin },
627 { "scc_hwmtx", &lock_class_mtx_spin },
628 { "uart_hwmtx", &lock_class_mtx_spin },
629 { "fast_taskqueue", &lock_class_mtx_spin },
630 { "intr table", &lock_class_mtx_spin },
632 { "pmc-per-proc", &lock_class_mtx_spin },
634 { "process slock", &lock_class_mtx_spin },
635 { "sleepq chain", &lock_class_mtx_spin },
636 { "umtx lock", &lock_class_mtx_spin },
637 { "rm_spinlock", &lock_class_mtx_spin },
638 { "turnstile chain", &lock_class_mtx_spin },
639 { "turnstile lock", &lock_class_mtx_spin },
640 { "sched lock", &lock_class_mtx_spin },
641 { "td_contested", &lock_class_mtx_spin },
642 { "callout", &lock_class_mtx_spin },
643 { "entropy harvest mutex", &lock_class_mtx_spin },
644 { "syscons video lock", &lock_class_mtx_spin },
646 { "smp rendezvous", &lock_class_mtx_spin },
649 { "tlb0", &lock_class_mtx_spin },
654 { "intrcnt", &lock_class_mtx_spin },
655 { "icu", &lock_class_mtx_spin },
657 { "allpmaps", &lock_class_mtx_spin },
658 { "descriptor tables", &lock_class_mtx_spin },
660 { "clk", &lock_class_mtx_spin },
661 { "cpuset", &lock_class_mtx_spin },
662 { "mprof lock", &lock_class_mtx_spin },
663 { "zombie lock", &lock_class_mtx_spin },
664 { "ALD Queue", &lock_class_mtx_spin },
665 #if defined(__i386__) || defined(__amd64__)
666 { "pcicfg", &lock_class_mtx_spin },
667 { "NDIS thread lock", &lock_class_mtx_spin },
669 { "tw_osl_io_lock", &lock_class_mtx_spin },
670 { "tw_osl_q_lock", &lock_class_mtx_spin },
671 { "tw_cl_io_lock", &lock_class_mtx_spin },
672 { "tw_cl_intr_lock", &lock_class_mtx_spin },
673 { "tw_cl_gen_lock", &lock_class_mtx_spin },
675 { "pmc-leaf", &lock_class_mtx_spin },
677 { "blocked lock", &lock_class_mtx_spin },
684 * Pairs of locks which have been blessed
685 * Don't complain about order problems with blessed locks
687 static struct witness_blessed blessed_list[] = {
689 static int blessed_count =
690 sizeof(blessed_list) / sizeof(struct witness_blessed);
694 * This global is set to 0 once it becomes safe to use the witness code.
696 static int witness_cold = 1;
699 * This global is set to 1 once the static lock orders have been enrolled
700 * so that a warning can be issued for any spin locks enrolled later.
702 static int witness_spin_warn = 0;
704 /* Trim useless garbage from filenames. */
706 fixup_filename(const char *file)
711 while (strncmp(file, "../", 3) == 0)
717 * The WITNESS-enabled diagnostic code. Note that the witness code does
718 * assume that the early boot is single-threaded at least until after this
719 * routine is completed.
722 witness_initialize(void *dummy __unused)
724 struct lock_object *lock;
725 struct witness_order_list_entry *order;
726 struct witness *w, *w1;
729 w_data = malloc(sizeof (struct witness) * WITNESS_COUNT, M_WITNESS,
733 * We have to release Giant before initializing its witness
734 * structure so that WITNESS doesn't get confused.
737 mtx_assert(&Giant, MA_NOTOWNED);
739 CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
740 mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
741 MTX_NOWITNESS | MTX_NOPROFILE);
742 for (i = WITNESS_COUNT - 1; i >= 0; i--) {
744 memset(w, 0, sizeof(*w));
745 w_data[i].w_index = i; /* Witness index never changes. */
748 KASSERT(STAILQ_FIRST(&w_free)->w_index == 0,
749 ("%s: Invalid list of free witness objects", __func__));
751 /* Witness with index 0 is not used to aid in debugging. */
752 STAILQ_REMOVE_HEAD(&w_free, w_list);
756 (sizeof(**w_rmatrix) * (WITNESS_COUNT+1) * (WITNESS_COUNT+1)));
758 for (i = 0; i < LOCK_CHILDCOUNT; i++)
759 witness_lock_list_free(&w_locklistdata[i]);
760 witness_init_hash_tables();
762 /* First add in all the specified order lists. */
763 for (order = order_lists; order->w_name != NULL; order++) {
764 w = enroll(order->w_name, order->w_class);
767 w->w_file = "order list";
768 for (order++; order->w_name != NULL; order++) {
769 w1 = enroll(order->w_name, order->w_class);
772 w1->w_file = "order list";
777 witness_spin_warn = 1;
779 /* Iterate through all locks and add them to witness. */
780 for (i = 0; pending_locks[i].wh_lock != NULL; i++) {
781 lock = pending_locks[i].wh_lock;
782 KASSERT(lock->lo_flags & LO_WITNESS,
783 ("%s: lock %s is on pending list but not LO_WITNESS",
784 __func__, lock->lo_name));
785 lock->lo_witness = enroll(pending_locks[i].wh_type,
789 /* Mark the witness code as being ready for use. */
794 SYSINIT(witness_init, SI_SUB_WITNESS, SI_ORDER_FIRST, witness_initialize,
798 witness_init(struct lock_object *lock, const char *type)
800 struct lock_class *class;
802 /* Various sanity checks. */
803 class = LOCK_CLASS(lock);
804 if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
805 (class->lc_flags & LC_RECURSABLE) == 0)
806 kassert_panic("%s: lock (%s) %s can not be recursable",
807 __func__, class->lc_name, lock->lo_name);
808 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
809 (class->lc_flags & LC_SLEEPABLE) == 0)
810 kassert_panic("%s: lock (%s) %s can not be sleepable",
811 __func__, class->lc_name, lock->lo_name);
812 if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
813 (class->lc_flags & LC_UPGRADABLE) == 0)
814 kassert_panic("%s: lock (%s) %s can not be upgradable",
815 __func__, class->lc_name, lock->lo_name);
818 * If we shouldn't watch this lock, then just clear lo_witness.
819 * Otherwise, if witness_cold is set, then it is too early to
820 * enroll this lock, so defer it to witness_initialize() by adding
821 * it to the pending_locks list. If it is not too early, then enroll
824 if (witness_watch < 1 || panicstr != NULL ||
825 (lock->lo_flags & LO_WITNESS) == 0)
826 lock->lo_witness = NULL;
827 else if (witness_cold) {
828 pending_locks[pending_cnt].wh_lock = lock;
829 pending_locks[pending_cnt++].wh_type = type;
830 if (pending_cnt > WITNESS_PENDLIST)
831 panic("%s: pending locks list is too small, "
832 "increase WITNESS_PENDLIST\n",
835 lock->lo_witness = enroll(type, class);
839 witness_destroy(struct lock_object *lock)
841 struct lock_class *class;
844 class = LOCK_CLASS(lock);
847 panic("lock (%s) %s destroyed while witness_cold",
848 class->lc_name, lock->lo_name);
850 /* XXX: need to verify that no one holds the lock */
851 if ((lock->lo_flags & LO_WITNESS) == 0 || lock->lo_witness == NULL)
853 w = lock->lo_witness;
855 mtx_lock_spin(&w_mtx);
856 MPASS(w->w_refcount > 0);
859 if (w->w_refcount == 0)
861 mtx_unlock_spin(&w_mtx);
866 witness_ddb_compute_levels(void)
871 * First clear all levels.
873 STAILQ_FOREACH(w, &w_all, w_list)
877 * Look for locks with no parents and level all their descendants.
879 STAILQ_FOREACH(w, &w_all, w_list) {
881 /* If the witness has ancestors (is not a root), skip it. */
882 if (w->w_num_ancestors > 0)
884 witness_ddb_level_descendants(w, 0);
889 witness_ddb_level_descendants(struct witness *w, int l)
893 if (w->w_ddb_level >= l)
899 for (i = 1; i <= w_max_used_index; i++) {
900 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
901 witness_ddb_level_descendants(&w_data[i], l);
906 witness_ddb_display_descendants(int(*prnt)(const char *fmt, ...),
907 struct witness *w, int indent)
911 for (i = 0; i < indent; i++)
913 prnt("%s (type: %s, depth: %d, active refs: %d)",
914 w->w_name, w->w_class->lc_name,
915 w->w_ddb_level, w->w_refcount);
916 if (w->w_displayed) {
917 prnt(" -- (already displayed)\n");
921 if (w->w_file != NULL && w->w_line != 0)
922 prnt(" -- last acquired @ %s:%d\n", fixup_filename(w->w_file),
925 prnt(" -- never acquired\n");
927 WITNESS_INDEX_ASSERT(w->w_index);
928 for (i = 1; i <= w_max_used_index; i++) {
931 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
932 witness_ddb_display_descendants(prnt, &w_data[i],
938 witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
939 struct witness_list *list)
943 STAILQ_FOREACH(w, list, w_typelist) {
944 if (w->w_file == NULL || w->w_ddb_level > 0)
947 /* This lock has no anscestors - display its descendants. */
948 witness_ddb_display_descendants(prnt, w, 0);
955 witness_ddb_display(int(*prnt)(const char *fmt, ...))
959 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
960 witness_ddb_compute_levels();
962 /* Clear all the displayed flags. */
963 STAILQ_FOREACH(w, &w_all, w_list)
967 * First, handle sleep locks which have been acquired at least
970 prnt("Sleep locks:\n");
971 witness_ddb_display_list(prnt, &w_sleep);
976 * Now do spin locks which have been acquired at least once.
978 prnt("\nSpin locks:\n");
979 witness_ddb_display_list(prnt, &w_spin);
984 * Finally, any locks which have not been acquired yet.
986 prnt("\nLocks which were never acquired:\n");
987 STAILQ_FOREACH(w, &w_all, w_list) {
988 if (w->w_file != NULL || w->w_refcount == 0)
990 prnt("%s (type: %s, depth: %d)\n", w->w_name,
991 w->w_class->lc_name, w->w_ddb_level);
999 witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
1002 if (witness_watch == -1 || panicstr != NULL)
1005 /* Require locks that witness knows about. */
1006 if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
1007 lock2->lo_witness == NULL)
1010 mtx_assert(&w_mtx, MA_NOTOWNED);
1011 mtx_lock_spin(&w_mtx);
1014 * If we already have either an explicit or implied lock order that
1015 * is the other way around, then return an error.
1017 if (witness_watch &&
1018 isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
1019 mtx_unlock_spin(&w_mtx);
1023 /* Try to add the new order. */
1024 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1025 lock2->lo_witness->w_name, lock1->lo_witness->w_name);
1026 itismychild(lock1->lo_witness, lock2->lo_witness);
1027 mtx_unlock_spin(&w_mtx);
1032 witness_checkorder(struct lock_object *lock, int flags, const char *file,
1033 int line, struct lock_object *interlock)
1035 struct lock_list_entry *lock_list, *lle;
1036 struct lock_instance *lock1, *lock2, *plock;
1037 struct lock_class *class, *iclass;
1038 struct witness *w, *w1;
1042 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL ||
1046 w = lock->lo_witness;
1047 class = LOCK_CLASS(lock);
1050 if (class->lc_flags & LC_SLEEPLOCK) {
1053 * Since spin locks include a critical section, this check
1054 * implicitly enforces a lock order of all sleep locks before
1057 if (td->td_critnest != 0 && !kdb_active)
1058 kassert_panic("acquiring blockable sleep lock with "
1059 "spinlock or critical section held (%s) %s @ %s:%d",
1060 class->lc_name, lock->lo_name,
1061 fixup_filename(file), line);
1064 * If this is the first lock acquired then just return as
1065 * no order checking is needed.
1067 lock_list = td->td_sleeplocks;
1068 if (lock_list == NULL || lock_list->ll_count == 0)
1073 * If this is the first lock, just return as no order
1074 * checking is needed. Avoid problems with thread
1075 * migration pinning the thread while checking if
1076 * spinlocks are held. If at least one spinlock is held
1077 * the thread is in a safe path and it is allowed to
1081 lock_list = PCPU_GET(spinlocks);
1082 if (lock_list == NULL || lock_list->ll_count == 0) {
1090 * Check to see if we are recursing on a lock we already own. If
1091 * so, make sure that we don't mismatch exclusive and shared lock
1094 lock1 = find_instance(lock_list, lock);
1095 if (lock1 != NULL) {
1096 if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
1097 (flags & LOP_EXCLUSIVE) == 0) {
1098 printf("shared lock of (%s) %s @ %s:%d\n",
1099 class->lc_name, lock->lo_name,
1100 fixup_filename(file), line);
1101 printf("while exclusively locked from %s:%d\n",
1102 fixup_filename(lock1->li_file), lock1->li_line);
1103 kassert_panic("excl->share");
1105 if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
1106 (flags & LOP_EXCLUSIVE) != 0) {
1107 printf("exclusive lock of (%s) %s @ %s:%d\n",
1108 class->lc_name, lock->lo_name,
1109 fixup_filename(file), line);
1110 printf("while share locked from %s:%d\n",
1111 fixup_filename(lock1->li_file), lock1->li_line);
1112 kassert_panic("share->excl");
1117 /* Warn if the interlock is not locked exactly once. */
1118 if (interlock != NULL) {
1119 iclass = LOCK_CLASS(interlock);
1120 lock1 = find_instance(lock_list, interlock);
1122 kassert_panic("interlock (%s) %s not locked @ %s:%d",
1123 iclass->lc_name, interlock->lo_name,
1124 fixup_filename(file), line);
1125 else if ((lock1->li_flags & LI_RECURSEMASK) != 0)
1126 kassert_panic("interlock (%s) %s recursed @ %s:%d",
1127 iclass->lc_name, interlock->lo_name,
1128 fixup_filename(file), line);
1132 * Find the previously acquired lock, but ignore interlocks.
1134 plock = &lock_list->ll_children[lock_list->ll_count - 1];
1135 if (interlock != NULL && plock->li_lock == interlock) {
1136 if (lock_list->ll_count > 1)
1138 &lock_list->ll_children[lock_list->ll_count - 2];
1140 lle = lock_list->ll_next;
1143 * The interlock is the only lock we hold, so
1148 plock = &lle->ll_children[lle->ll_count - 1];
1153 * Try to perform most checks without a lock. If this succeeds we
1154 * can skip acquiring the lock and return success.
1156 w1 = plock->li_lock->lo_witness;
1157 if (witness_lock_order_check(w1, w))
1161 * Check for duplicate locks of the same type. Note that we only
1162 * have to check for this on the last lock we just acquired. Any
1163 * other cases will be caught as lock order violations.
1165 mtx_lock_spin(&w_mtx);
1166 witness_lock_order_add(w1, w);
1169 if (!(lock->lo_flags & LO_DUPOK) && !(flags & LOP_DUPOK) &&
1170 !(w_rmatrix[i][i] & WITNESS_REVERSAL)) {
1171 w_rmatrix[i][i] |= WITNESS_REVERSAL;
1173 mtx_unlock_spin(&w_mtx);
1175 "acquiring duplicate lock of same type: \"%s\"\n",
1177 printf(" 1st %s @ %s:%d\n", plock->li_lock->lo_name,
1178 fixup_filename(plock->li_file), plock->li_line);
1179 printf(" 2nd %s @ %s:%d\n", lock->lo_name,
1180 fixup_filename(file), line);
1181 witness_debugger(1);
1183 mtx_unlock_spin(&w_mtx);
1186 mtx_assert(&w_mtx, MA_OWNED);
1189 * If we know that the lock we are acquiring comes after
1190 * the lock we most recently acquired in the lock order tree,
1191 * then there is no need for any further checks.
1193 if (isitmychild(w1, w))
1196 for (j = 0, lle = lock_list; lle != NULL; lle = lle->ll_next) {
1197 for (i = lle->ll_count - 1; i >= 0; i--, j++) {
1199 MPASS(j < WITNESS_COUNT);
1200 lock1 = &lle->ll_children[i];
1203 * Ignore the interlock.
1205 if (interlock == lock1->li_lock)
1209 * If this lock doesn't undergo witness checking,
1212 w1 = lock1->li_lock->lo_witness;
1214 KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
1215 ("lock missing witness structure"));
1220 * If we are locking Giant and this is a sleepable
1221 * lock, then skip it.
1223 if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0 &&
1224 lock == &Giant.lock_object)
1228 * If we are locking a sleepable lock and this lock
1229 * is Giant, then skip it.
1231 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1232 lock1->li_lock == &Giant.lock_object)
1236 * If we are locking a sleepable lock and this lock
1237 * isn't sleepable, we want to treat it as a lock
1238 * order violation to enfore a general lock order of
1239 * sleepable locks before non-sleepable locks.
1241 if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1242 (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1246 * If we are locking Giant and this is a non-sleepable
1247 * lock, then treat it as a reversal.
1249 if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0 &&
1250 lock == &Giant.lock_object)
1254 * Check the lock order hierarchy for a reveresal.
1256 if (!isitmydescendant(w, w1))
1261 * We have a lock order violation, check to see if it
1262 * is allowed or has already been yelled about.
1267 * If the lock order is blessed, just bail. We don't
1268 * look for other lock order violations though, which
1275 /* Bail if this violation is known */
1276 if (w_rmatrix[w1->w_index][w->w_index] & WITNESS_REVERSAL)
1279 /* Record this as a violation */
1280 w_rmatrix[w1->w_index][w->w_index] |= WITNESS_REVERSAL;
1281 w_rmatrix[w->w_index][w1->w_index] |= WITNESS_REVERSAL;
1282 w->w_reversed = w1->w_reversed = 1;
1283 witness_increment_graph_generation();
1284 mtx_unlock_spin(&w_mtx);
1286 #ifdef WITNESS_NO_VNODE
1288 * There are known LORs between VNODE locks. They are
1289 * not an indication of a bug. VNODE locks are flagged
1290 * as such (LO_IS_VNODE) and we don't yell if the LOR
1291 * is between 2 VNODE locks.
1293 if ((lock->lo_flags & LO_IS_VNODE) != 0 &&
1294 (lock1->li_lock->lo_flags & LO_IS_VNODE) != 0)
1299 * Ok, yell about it.
1301 if (((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1302 (lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0))
1304 "lock order reversal: (sleepable after non-sleepable)\n");
1305 else if ((lock1->li_lock->lo_flags & LO_SLEEPABLE) == 0
1306 && lock == &Giant.lock_object)
1308 "lock order reversal: (Giant after non-sleepable)\n");
1310 printf("lock order reversal:\n");
1313 * Try to locate an earlier lock with
1314 * witness w in our list.
1317 lock2 = &lle->ll_children[i];
1318 MPASS(lock2->li_lock != NULL);
1319 if (lock2->li_lock->lo_witness == w)
1321 if (i == 0 && lle->ll_next != NULL) {
1323 i = lle->ll_count - 1;
1324 MPASS(i >= 0 && i < LOCK_NCHILDREN);
1329 printf(" 1st %p %s (%s) @ %s:%d\n",
1330 lock1->li_lock, lock1->li_lock->lo_name,
1331 w1->w_name, fixup_filename(lock1->li_file),
1333 printf(" 2nd %p %s (%s) @ %s:%d\n", lock,
1334 lock->lo_name, w->w_name,
1335 fixup_filename(file), line);
1337 printf(" 1st %p %s (%s) @ %s:%d\n",
1338 lock2->li_lock, lock2->li_lock->lo_name,
1339 lock2->li_lock->lo_witness->w_name,
1340 fixup_filename(lock2->li_file),
1342 printf(" 2nd %p %s (%s) @ %s:%d\n",
1343 lock1->li_lock, lock1->li_lock->lo_name,
1344 w1->w_name, fixup_filename(lock1->li_file),
1346 printf(" 3rd %p %s (%s) @ %s:%d\n", lock,
1347 lock->lo_name, w->w_name,
1348 fixup_filename(file), line);
1350 witness_debugger(1);
1356 * If requested, build a new lock order. However, don't build a new
1357 * relationship between a sleepable lock and Giant if it is in the
1358 * wrong direction. The correct lock order is that sleepable locks
1359 * always come before Giant.
1361 if (flags & LOP_NEWORDER &&
1362 !(plock->li_lock == &Giant.lock_object &&
1363 (lock->lo_flags & LO_SLEEPABLE) != 0)) {
1364 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1365 w->w_name, plock->li_lock->lo_witness->w_name);
1366 itismychild(plock->li_lock->lo_witness, w);
1369 mtx_unlock_spin(&w_mtx);
1373 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
1375 struct lock_list_entry **lock_list, *lle;
1376 struct lock_instance *instance;
1380 if (witness_cold || witness_watch == -1 || lock->lo_witness == NULL ||
1383 w = lock->lo_witness;
1386 /* Determine lock list for this lock. */
1387 if (LOCK_CLASS(lock)->lc_flags & LC_SLEEPLOCK)
1388 lock_list = &td->td_sleeplocks;
1390 lock_list = PCPU_PTR(spinlocks);
1392 /* Check to see if we are recursing on a lock we already own. */
1393 instance = find_instance(*lock_list, lock);
1394 if (instance != NULL) {
1395 instance->li_flags++;
1396 CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1397 td->td_proc->p_pid, lock->lo_name,
1398 instance->li_flags & LI_RECURSEMASK);
1399 instance->li_file = file;
1400 instance->li_line = line;
1404 /* Update per-witness last file and line acquire. */
1408 /* Find the next open lock instance in the list and fill it. */
1410 if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1411 lle = witness_lock_list_get();
1414 lle->ll_next = *lock_list;
1415 CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1416 td->td_proc->p_pid, lle);
1419 instance = &lle->ll_children[lle->ll_count++];
1420 instance->li_lock = lock;
1421 instance->li_line = line;
1422 instance->li_file = file;
1423 if ((flags & LOP_EXCLUSIVE) != 0)
1424 instance->li_flags = LI_EXCLUSIVE;
1426 instance->li_flags = 0;
1427 CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1428 td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1432 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1434 struct lock_instance *instance;
1435 struct lock_class *class;
1437 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1438 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1440 class = LOCK_CLASS(lock);
1441 if (witness_watch) {
1442 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1444 "upgrade of non-upgradable lock (%s) %s @ %s:%d",
1445 class->lc_name, lock->lo_name,
1446 fixup_filename(file), line);
1447 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1449 "upgrade of non-sleep lock (%s) %s @ %s:%d",
1450 class->lc_name, lock->lo_name,
1451 fixup_filename(file), line);
1453 instance = find_instance(curthread->td_sleeplocks, lock);
1454 if (instance == NULL) {
1455 kassert_panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1456 class->lc_name, lock->lo_name,
1457 fixup_filename(file), line);
1460 if (witness_watch) {
1461 if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1463 "upgrade of exclusive lock (%s) %s @ %s:%d",
1464 class->lc_name, lock->lo_name,
1465 fixup_filename(file), line);
1466 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1468 "upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1469 class->lc_name, lock->lo_name,
1470 instance->li_flags & LI_RECURSEMASK,
1471 fixup_filename(file), line);
1473 instance->li_flags |= LI_EXCLUSIVE;
1477 witness_downgrade(struct lock_object *lock, int flags, const char *file,
1480 struct lock_instance *instance;
1481 struct lock_class *class;
1483 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1484 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
1486 class = LOCK_CLASS(lock);
1487 if (witness_watch) {
1488 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1490 "downgrade of non-upgradable lock (%s) %s @ %s:%d",
1491 class->lc_name, lock->lo_name,
1492 fixup_filename(file), line);
1493 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1495 "downgrade of non-sleep lock (%s) %s @ %s:%d",
1496 class->lc_name, lock->lo_name,
1497 fixup_filename(file), line);
1499 instance = find_instance(curthread->td_sleeplocks, lock);
1500 if (instance == NULL) {
1501 kassert_panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1502 class->lc_name, lock->lo_name,
1503 fixup_filename(file), line);
1506 if (witness_watch) {
1507 if ((instance->li_flags & LI_EXCLUSIVE) == 0)
1509 "downgrade of shared lock (%s) %s @ %s:%d",
1510 class->lc_name, lock->lo_name,
1511 fixup_filename(file), line);
1512 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1514 "downgrade of recursed lock (%s) %s r=%d @ %s:%d",
1515 class->lc_name, lock->lo_name,
1516 instance->li_flags & LI_RECURSEMASK,
1517 fixup_filename(file), line);
1519 instance->li_flags &= ~LI_EXCLUSIVE;
1523 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
1525 struct lock_list_entry **lock_list, *lle;
1526 struct lock_instance *instance;
1527 struct lock_class *class;
1532 if (witness_cold || lock->lo_witness == NULL || panicstr != NULL)
1535 class = LOCK_CLASS(lock);
1537 /* Find lock instance associated with this lock. */
1538 if (class->lc_flags & LC_SLEEPLOCK)
1539 lock_list = &td->td_sleeplocks;
1541 lock_list = PCPU_PTR(spinlocks);
1543 for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
1544 for (i = 0; i < (*lock_list)->ll_count; i++) {
1545 instance = &(*lock_list)->ll_children[i];
1546 if (instance->li_lock == lock)
1551 * When disabling WITNESS through witness_watch we could end up in
1552 * having registered locks in the td_sleeplocks queue.
1553 * We have to make sure we flush these queues, so just search for
1554 * eventual register locks and remove them.
1556 if (witness_watch > 0) {
1557 kassert_panic("lock (%s) %s not locked @ %s:%d", class->lc_name,
1558 lock->lo_name, fixup_filename(file), line);
1565 /* First, check for shared/exclusive mismatches. */
1566 if ((instance->li_flags & LI_EXCLUSIVE) != 0 && witness_watch > 0 &&
1567 (flags & LOP_EXCLUSIVE) == 0) {
1568 printf("shared unlock of (%s) %s @ %s:%d\n", class->lc_name,
1569 lock->lo_name, fixup_filename(file), line);
1570 printf("while exclusively locked from %s:%d\n",
1571 fixup_filename(instance->li_file), instance->li_line);
1572 kassert_panic("excl->ushare");
1574 if ((instance->li_flags & LI_EXCLUSIVE) == 0 && witness_watch > 0 &&
1575 (flags & LOP_EXCLUSIVE) != 0) {
1576 printf("exclusive unlock of (%s) %s @ %s:%d\n", class->lc_name,
1577 lock->lo_name, fixup_filename(file), line);
1578 printf("while share locked from %s:%d\n",
1579 fixup_filename(instance->li_file),
1581 kassert_panic("share->uexcl");
1583 /* If we are recursed, unrecurse. */
1584 if ((instance->li_flags & LI_RECURSEMASK) > 0) {
1585 CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
1586 td->td_proc->p_pid, instance->li_lock->lo_name,
1587 instance->li_flags);
1588 instance->li_flags--;
1591 /* The lock is now being dropped, check for NORELEASE flag */
1592 if ((instance->li_flags & LI_NORELEASE) != 0 && witness_watch > 0) {
1593 printf("forbidden unlock of (%s) %s @ %s:%d\n", class->lc_name,
1594 lock->lo_name, fixup_filename(file), line);
1595 kassert_panic("lock marked norelease");
1598 /* Otherwise, remove this item from the list. */
1600 CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
1601 td->td_proc->p_pid, instance->li_lock->lo_name,
1602 (*lock_list)->ll_count - 1);
1603 for (j = i; j < (*lock_list)->ll_count - 1; j++)
1604 (*lock_list)->ll_children[j] =
1605 (*lock_list)->ll_children[j + 1];
1606 (*lock_list)->ll_count--;
1610 * In order to reduce contention on w_mtx, we want to keep always an
1611 * head object into lists so that frequent allocation from the
1612 * free witness pool (and subsequent locking) is avoided.
1613 * In order to maintain the current code simple, when the head
1614 * object is totally unloaded it means also that we do not have
1615 * further objects in the list, so the list ownership needs to be
1616 * hand over to another object if the current head needs to be freed.
1618 if ((*lock_list)->ll_count == 0) {
1619 if (*lock_list == lle) {
1620 if (lle->ll_next == NULL)
1624 *lock_list = lle->ll_next;
1625 CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
1626 td->td_proc->p_pid, lle);
1627 witness_lock_list_free(lle);
1632 witness_thread_exit(struct thread *td)
1634 struct lock_list_entry *lle;
1637 lle = td->td_sleeplocks;
1638 if (lle == NULL || panicstr != NULL)
1640 if (lle->ll_count != 0) {
1641 for (n = 0; lle != NULL; lle = lle->ll_next)
1642 for (i = lle->ll_count - 1; i >= 0; i--) {
1644 printf("Thread %p exiting with the following locks held:\n",
1647 witness_list_lock(&lle->ll_children[i], printf);
1651 "Thread %p cannot exit while holding sleeplocks\n", td);
1653 witness_lock_list_free(lle);
1657 * Warn if any locks other than 'lock' are held. Flags can be passed in to
1658 * exempt Giant and sleepable locks from the checks as well. If any
1659 * non-exempt locks are held, then a supplied message is printed to the
1660 * console along with a list of the offending locks. If indicated in the
1661 * flags then a failure results in a panic as well.
1664 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1666 struct lock_list_entry *lock_list, *lle;
1667 struct lock_instance *lock1;
1672 if (witness_cold || witness_watch < 1 || panicstr != NULL)
1676 for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1677 for (i = lle->ll_count - 1; i >= 0; i--) {
1678 lock1 = &lle->ll_children[i];
1679 if (lock1->li_lock == lock)
1681 if (flags & WARN_GIANTOK &&
1682 lock1->li_lock == &Giant.lock_object)
1684 if (flags & WARN_SLEEPOK &&
1685 (lock1->li_lock->lo_flags & LO_SLEEPABLE) != 0)
1691 printf(" with the following");
1692 if (flags & WARN_SLEEPOK)
1693 printf(" non-sleepable");
1694 printf(" locks held:\n");
1697 witness_list_lock(lock1, printf);
1701 * Pin the thread in order to avoid problems with thread migration.
1702 * Once that all verifies are passed about spinlocks ownership,
1703 * the thread is in a safe path and it can be unpinned.
1706 lock_list = PCPU_GET(spinlocks);
1707 if (lock_list != NULL && lock_list->ll_count != 0) {
1711 * We should only have one spinlock and as long as
1712 * the flags cannot match for this locks class,
1713 * check if the first spinlock is the one curthread
1716 lock1 = &lock_list->ll_children[lock_list->ll_count - 1];
1717 if (lock_list->ll_count == 1 && lock_list->ll_next == NULL &&
1718 lock1->li_lock == lock && n == 0)
1724 printf(" with the following");
1725 if (flags & WARN_SLEEPOK)
1726 printf(" non-sleepable");
1727 printf(" locks held:\n");
1728 n += witness_list_locks(&lock_list, printf);
1731 if (flags & WARN_PANIC && n)
1732 kassert_panic("%s", __func__);
1734 witness_debugger(n);
1739 witness_file(struct lock_object *lock)
1743 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1745 w = lock->lo_witness;
1750 witness_line(struct lock_object *lock)
1754 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1756 w = lock->lo_witness;
1760 static struct witness *
1761 enroll(const char *description, struct lock_class *lock_class)
1764 struct witness_list *typelist;
1766 MPASS(description != NULL);
1768 if (witness_watch == -1 || panicstr != NULL)
1770 if ((lock_class->lc_flags & LC_SPINLOCK)) {
1771 if (witness_skipspin)
1775 } else if ((lock_class->lc_flags & LC_SLEEPLOCK)) {
1776 typelist = &w_sleep;
1778 kassert_panic("lock class %s is not sleep or spin",
1779 lock_class->lc_name);
1783 mtx_lock_spin(&w_mtx);
1784 w = witness_hash_get(description);
1787 if ((w = witness_get()) == NULL)
1789 MPASS(strlen(description) < MAX_W_NAME);
1790 strcpy(w->w_name, description);
1791 w->w_class = lock_class;
1793 STAILQ_INSERT_HEAD(&w_all, w, w_list);
1794 if (lock_class->lc_flags & LC_SPINLOCK) {
1795 STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1797 } else if (lock_class->lc_flags & LC_SLEEPLOCK) {
1798 STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1802 /* Insert new witness into the hash */
1803 witness_hash_put(w);
1804 witness_increment_graph_generation();
1805 mtx_unlock_spin(&w_mtx);
1809 mtx_unlock_spin(&w_mtx);
1810 if (lock_class != w->w_class)
1812 "lock (%s) %s does not match earlier (%s) lock",
1813 description, lock_class->lc_name,
1814 w->w_class->lc_name);
1819 depart(struct witness *w)
1821 struct witness_list *list;
1823 MPASS(w->w_refcount == 0);
1824 if (w->w_class->lc_flags & LC_SLEEPLOCK) {
1832 * Set file to NULL as it may point into a loadable module.
1836 witness_increment_graph_generation();
1841 adopt(struct witness *parent, struct witness *child)
1845 if (witness_cold == 0)
1846 mtx_assert(&w_mtx, MA_OWNED);
1848 /* If the relationship is already known, there's no work to be done. */
1849 if (isitmychild(parent, child))
1852 /* When the structure of the graph changes, bump up the generation. */
1853 witness_increment_graph_generation();
1856 * The hard part ... create the direct relationship, then propagate all
1857 * indirect relationships.
1859 pi = parent->w_index;
1860 ci = child->w_index;
1861 WITNESS_INDEX_ASSERT(pi);
1862 WITNESS_INDEX_ASSERT(ci);
1864 w_rmatrix[pi][ci] |= WITNESS_PARENT;
1865 w_rmatrix[ci][pi] |= WITNESS_CHILD;
1868 * If parent was not already an ancestor of child,
1869 * then we increment the descendant and ancestor counters.
1871 if ((w_rmatrix[pi][ci] & WITNESS_ANCESTOR) == 0) {
1872 parent->w_num_descendants++;
1873 child->w_num_ancestors++;
1877 * Find each ancestor of 'pi'. Note that 'pi' itself is counted as
1878 * an ancestor of 'pi' during this loop.
1880 for (i = 1; i <= w_max_used_index; i++) {
1881 if ((w_rmatrix[i][pi] & WITNESS_ANCESTOR_MASK) == 0 &&
1885 /* Find each descendant of 'i' and mark it as a descendant. */
1886 for (j = 1; j <= w_max_used_index; j++) {
1889 * Skip children that are already marked as
1890 * descendants of 'i'.
1892 if (w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK)
1896 * We are only interested in descendants of 'ci'. Note
1897 * that 'ci' itself is counted as a descendant of 'ci'.
1899 if ((w_rmatrix[ci][j] & WITNESS_ANCESTOR_MASK) == 0 &&
1902 w_rmatrix[i][j] |= WITNESS_ANCESTOR;
1903 w_rmatrix[j][i] |= WITNESS_DESCENDANT;
1904 w_data[i].w_num_descendants++;
1905 w_data[j].w_num_ancestors++;
1908 * Make sure we aren't marking a node as both an
1909 * ancestor and descendant. We should have caught
1910 * this as a lock order reversal earlier.
1912 if ((w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK) &&
1913 (w_rmatrix[i][j] & WITNESS_DESCENDANT_MASK)) {
1914 printf("witness rmatrix paradox! [%d][%d]=%d "
1915 "both ancestor and descendant\n",
1916 i, j, w_rmatrix[i][j]);
1918 printf("Witness disabled.\n");
1921 if ((w_rmatrix[j][i] & WITNESS_ANCESTOR_MASK) &&
1922 (w_rmatrix[j][i] & WITNESS_DESCENDANT_MASK)) {
1923 printf("witness rmatrix paradox! [%d][%d]=%d "
1924 "both ancestor and descendant\n",
1925 j, i, w_rmatrix[j][i]);
1927 printf("Witness disabled.\n");
1935 itismychild(struct witness *parent, struct witness *child)
1939 MPASS(child != NULL && parent != NULL);
1940 if (witness_cold == 0)
1941 mtx_assert(&w_mtx, MA_OWNED);
1943 if (!witness_lock_type_equal(parent, child)) {
1944 if (witness_cold == 0) {
1946 mtx_unlock_spin(&w_mtx);
1951 "%s: parent \"%s\" (%s) and child \"%s\" (%s) are not "
1952 "the same lock type", __func__, parent->w_name,
1953 parent->w_class->lc_name, child->w_name,
1954 child->w_class->lc_name);
1956 mtx_lock_spin(&w_mtx);
1958 adopt(parent, child);
1962 * Generic code for the isitmy*() functions. The rmask parameter is the
1963 * expected relationship of w1 to w2.
1966 _isitmyx(struct witness *w1, struct witness *w2, int rmask, const char *fname)
1968 unsigned char r1, r2;
1973 WITNESS_INDEX_ASSERT(i1);
1974 WITNESS_INDEX_ASSERT(i2);
1975 r1 = w_rmatrix[i1][i2] & WITNESS_RELATED_MASK;
1976 r2 = w_rmatrix[i2][i1] & WITNESS_RELATED_MASK;
1978 /* The flags on one better be the inverse of the flags on the other */
1979 if (!((WITNESS_ATOD(r1) == r2 && WITNESS_DTOA(r2) == r1) ||
1980 (WITNESS_DTOA(r1) == r2 && WITNESS_ATOD(r2) == r1))) {
1981 printf("%s: rmatrix mismatch between %s (index %d) and %s "
1982 "(index %d): w_rmatrix[%d][%d] == %hhx but "
1983 "w_rmatrix[%d][%d] == %hhx\n",
1984 fname, w1->w_name, i1, w2->w_name, i2, i1, i2, r1,
1987 printf("Witness disabled.\n");
1990 return (r1 & rmask);
1994 * Checks if @child is a direct child of @parent.
1997 isitmychild(struct witness *parent, struct witness *child)
2000 return (_isitmyx(parent, child, WITNESS_PARENT, __func__));
2004 * Checks if @descendant is a direct or inderect descendant of @ancestor.
2007 isitmydescendant(struct witness *ancestor, struct witness *descendant)
2010 return (_isitmyx(ancestor, descendant, WITNESS_ANCESTOR_MASK,
2016 blessed(struct witness *w1, struct witness *w2)
2019 struct witness_blessed *b;
2021 for (i = 0; i < blessed_count; i++) {
2022 b = &blessed_list[i];
2023 if (strcmp(w1->w_name, b->b_lock1) == 0) {
2024 if (strcmp(w2->w_name, b->b_lock2) == 0)
2028 if (strcmp(w1->w_name, b->b_lock2) == 0)
2029 if (strcmp(w2->w_name, b->b_lock1) == 0)
2036 static struct witness *
2042 if (witness_cold == 0)
2043 mtx_assert(&w_mtx, MA_OWNED);
2045 if (witness_watch == -1) {
2046 mtx_unlock_spin(&w_mtx);
2049 if (STAILQ_EMPTY(&w_free)) {
2051 mtx_unlock_spin(&w_mtx);
2052 printf("WITNESS: unable to allocate a new witness object\n");
2055 w = STAILQ_FIRST(&w_free);
2056 STAILQ_REMOVE_HEAD(&w_free, w_list);
2059 MPASS(index > 0 && index == w_max_used_index+1 &&
2060 index < WITNESS_COUNT);
2061 bzero(w, sizeof(*w));
2063 if (index > w_max_used_index)
2064 w_max_used_index = index;
2069 witness_free(struct witness *w)
2072 STAILQ_INSERT_HEAD(&w_free, w, w_list);
2076 static struct lock_list_entry *
2077 witness_lock_list_get(void)
2079 struct lock_list_entry *lle;
2081 if (witness_watch == -1)
2083 mtx_lock_spin(&w_mtx);
2084 lle = w_lock_list_free;
2087 mtx_unlock_spin(&w_mtx);
2088 printf("%s: witness exhausted\n", __func__);
2091 w_lock_list_free = lle->ll_next;
2092 mtx_unlock_spin(&w_mtx);
2093 bzero(lle, sizeof(*lle));
2098 witness_lock_list_free(struct lock_list_entry *lle)
2101 mtx_lock_spin(&w_mtx);
2102 lle->ll_next = w_lock_list_free;
2103 w_lock_list_free = lle;
2104 mtx_unlock_spin(&w_mtx);
2107 static struct lock_instance *
2108 find_instance(struct lock_list_entry *list, const struct lock_object *lock)
2110 struct lock_list_entry *lle;
2111 struct lock_instance *instance;
2114 for (lle = list; lle != NULL; lle = lle->ll_next)
2115 for (i = lle->ll_count - 1; i >= 0; i--) {
2116 instance = &lle->ll_children[i];
2117 if (instance->li_lock == lock)
2124 witness_list_lock(struct lock_instance *instance,
2125 int (*prnt)(const char *fmt, ...))
2127 struct lock_object *lock;
2129 lock = instance->li_lock;
2130 prnt("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
2131 "exclusive" : "shared", LOCK_CLASS(lock)->lc_name, lock->lo_name);
2132 if (lock->lo_witness->w_name != lock->lo_name)
2133 prnt(" (%s)", lock->lo_witness->w_name);
2134 prnt(" r = %d (%p) locked @ %s:%d\n",
2135 instance->li_flags & LI_RECURSEMASK, lock,
2136 fixup_filename(instance->li_file), instance->li_line);
2141 witness_thread_has_locks(struct thread *td)
2144 if (td->td_sleeplocks == NULL)
2146 return (td->td_sleeplocks->ll_count != 0);
2150 witness_proc_has_locks(struct proc *p)
2154 FOREACH_THREAD_IN_PROC(p, td) {
2155 if (witness_thread_has_locks(td))
2163 witness_list_locks(struct lock_list_entry **lock_list,
2164 int (*prnt)(const char *fmt, ...))
2166 struct lock_list_entry *lle;
2170 for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
2171 for (i = lle->ll_count - 1; i >= 0; i--) {
2172 witness_list_lock(&lle->ll_children[i], prnt);
2179 * This is a bit risky at best. We call this function when we have timed
2180 * out acquiring a spin lock, and we assume that the other CPU is stuck
2181 * with this lock held. So, we go groveling around in the other CPU's
2182 * per-cpu data to try to find the lock instance for this spin lock to
2183 * see when it was last acquired.
2186 witness_display_spinlock(struct lock_object *lock, struct thread *owner,
2187 int (*prnt)(const char *fmt, ...))
2189 struct lock_instance *instance;
2192 if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
2194 pc = pcpu_find(owner->td_oncpu);
2195 instance = find_instance(pc->pc_spinlocks, lock);
2196 if (instance != NULL)
2197 witness_list_lock(instance, prnt);
2201 witness_save(struct lock_object *lock, const char **filep, int *linep)
2203 struct lock_list_entry *lock_list;
2204 struct lock_instance *instance;
2205 struct lock_class *class;
2208 * This function is used independently in locking code to deal with
2209 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2212 if (SCHEDULER_STOPPED())
2214 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2215 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2217 class = LOCK_CLASS(lock);
2218 if (class->lc_flags & LC_SLEEPLOCK)
2219 lock_list = curthread->td_sleeplocks;
2221 if (witness_skipspin)
2223 lock_list = PCPU_GET(spinlocks);
2225 instance = find_instance(lock_list, lock);
2226 if (instance == NULL) {
2227 kassert_panic("%s: lock (%s) %s not locked", __func__,
2228 class->lc_name, lock->lo_name);
2231 *filep = instance->li_file;
2232 *linep = instance->li_line;
2236 witness_restore(struct lock_object *lock, const char *file, int line)
2238 struct lock_list_entry *lock_list;
2239 struct lock_instance *instance;
2240 struct lock_class *class;
2243 * This function is used independently in locking code to deal with
2244 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2247 if (SCHEDULER_STOPPED())
2249 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2250 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2252 class = LOCK_CLASS(lock);
2253 if (class->lc_flags & LC_SLEEPLOCK)
2254 lock_list = curthread->td_sleeplocks;
2256 if (witness_skipspin)
2258 lock_list = PCPU_GET(spinlocks);
2260 instance = find_instance(lock_list, lock);
2261 if (instance == NULL)
2262 kassert_panic("%s: lock (%s) %s not locked", __func__,
2263 class->lc_name, lock->lo_name);
2264 lock->lo_witness->w_file = file;
2265 lock->lo_witness->w_line = line;
2266 if (instance == NULL)
2268 instance->li_file = file;
2269 instance->li_line = line;
2273 witness_assert(const struct lock_object *lock, int flags, const char *file,
2276 #ifdef INVARIANT_SUPPORT
2277 struct lock_instance *instance;
2278 struct lock_class *class;
2280 if (lock->lo_witness == NULL || witness_watch < 1 || panicstr != NULL)
2282 class = LOCK_CLASS(lock);
2283 if ((class->lc_flags & LC_SLEEPLOCK) != 0)
2284 instance = find_instance(curthread->td_sleeplocks, lock);
2285 else if ((class->lc_flags & LC_SPINLOCK) != 0)
2286 instance = find_instance(PCPU_GET(spinlocks), lock);
2288 kassert_panic("Lock (%s) %s is not sleep or spin!",
2289 class->lc_name, lock->lo_name);
2294 if (instance != NULL)
2295 kassert_panic("Lock (%s) %s locked @ %s:%d.",
2296 class->lc_name, lock->lo_name,
2297 fixup_filename(file), line);
2300 case LA_LOCKED | LA_RECURSED:
2301 case LA_LOCKED | LA_NOTRECURSED:
2303 case LA_SLOCKED | LA_RECURSED:
2304 case LA_SLOCKED | LA_NOTRECURSED:
2306 case LA_XLOCKED | LA_RECURSED:
2307 case LA_XLOCKED | LA_NOTRECURSED:
2308 if (instance == NULL) {
2309 kassert_panic("Lock (%s) %s not locked @ %s:%d.",
2310 class->lc_name, lock->lo_name,
2311 fixup_filename(file), line);
2314 if ((flags & LA_XLOCKED) != 0 &&
2315 (instance->li_flags & LI_EXCLUSIVE) == 0)
2317 "Lock (%s) %s not exclusively locked @ %s:%d.",
2318 class->lc_name, lock->lo_name,
2319 fixup_filename(file), line);
2320 if ((flags & LA_SLOCKED) != 0 &&
2321 (instance->li_flags & LI_EXCLUSIVE) != 0)
2323 "Lock (%s) %s exclusively locked @ %s:%d.",
2324 class->lc_name, lock->lo_name,
2325 fixup_filename(file), line);
2326 if ((flags & LA_RECURSED) != 0 &&
2327 (instance->li_flags & LI_RECURSEMASK) == 0)
2328 kassert_panic("Lock (%s) %s not recursed @ %s:%d.",
2329 class->lc_name, lock->lo_name,
2330 fixup_filename(file), line);
2331 if ((flags & LA_NOTRECURSED) != 0 &&
2332 (instance->li_flags & LI_RECURSEMASK) != 0)
2333 kassert_panic("Lock (%s) %s recursed @ %s:%d.",
2334 class->lc_name, lock->lo_name,
2335 fixup_filename(file), line);
2338 kassert_panic("Invalid lock assertion at %s:%d.",
2339 fixup_filename(file), line);
2342 #endif /* INVARIANT_SUPPORT */
2346 witness_setflag(struct lock_object *lock, int flag, int set)
2348 struct lock_list_entry *lock_list;
2349 struct lock_instance *instance;
2350 struct lock_class *class;
2352 if (lock->lo_witness == NULL || witness_watch == -1 || panicstr != NULL)
2354 class = LOCK_CLASS(lock);
2355 if (class->lc_flags & LC_SLEEPLOCK)
2356 lock_list = curthread->td_sleeplocks;
2358 if (witness_skipspin)
2360 lock_list = PCPU_GET(spinlocks);
2362 instance = find_instance(lock_list, lock);
2363 if (instance == NULL) {
2364 kassert_panic("%s: lock (%s) %s not locked", __func__,
2365 class->lc_name, lock->lo_name);
2370 instance->li_flags |= flag;
2372 instance->li_flags &= ~flag;
2376 witness_norelease(struct lock_object *lock)
2379 witness_setflag(lock, LI_NORELEASE, 1);
2383 witness_releaseok(struct lock_object *lock)
2386 witness_setflag(lock, LI_NORELEASE, 0);
2391 witness_ddb_list(struct thread *td)
2394 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2395 KASSERT(kdb_active, ("%s: not in the debugger", __func__));
2397 if (witness_watch < 1)
2400 witness_list_locks(&td->td_sleeplocks, db_printf);
2403 * We only handle spinlocks if td == curthread. This is somewhat broken
2404 * if td is currently executing on some other CPU and holds spin locks
2405 * as we won't display those locks. If we had a MI way of getting
2406 * the per-cpu data for a given cpu then we could use
2407 * td->td_oncpu to get the list of spinlocks for this thread
2410 * That still wouldn't really fix this unless we locked the scheduler
2411 * lock or stopped the other CPU to make sure it wasn't changing the
2412 * list out from under us. It is probably best to just not try to
2413 * handle threads on other CPU's for now.
2415 if (td == curthread && PCPU_GET(spinlocks) != NULL)
2416 witness_list_locks(PCPU_PTR(spinlocks), db_printf);
2419 DB_SHOW_COMMAND(locks, db_witness_list)
2424 td = db_lookup_thread(addr, TRUE);
2427 witness_ddb_list(td);
2430 DB_SHOW_ALL_COMMAND(locks, db_witness_list_all)
2436 * It would be nice to list only threads and processes that actually
2437 * held sleep locks, but that information is currently not exported
2440 FOREACH_PROC_IN_SYSTEM(p) {
2441 if (!witness_proc_has_locks(p))
2443 FOREACH_THREAD_IN_PROC(p, td) {
2444 if (!witness_thread_has_locks(td))
2446 db_printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
2447 p->p_comm, td, td->td_tid);
2448 witness_ddb_list(td);
2454 DB_SHOW_ALIAS(alllocks, db_witness_list_all)
2456 DB_SHOW_COMMAND(witness, db_witness_display)
2459 witness_ddb_display(db_printf);
2464 sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)
2466 struct witness_lock_order_data *data1, *data2, *tmp_data1, *tmp_data2;
2467 struct witness *tmp_w1, *tmp_w2, *w1, *w2;
2469 u_int w_rmatrix1, w_rmatrix2;
2470 int error, generation, i, j;
2476 if (witness_watch < 1) {
2477 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2481 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2485 sb = sbuf_new(NULL, NULL, BADSTACK_SBUF_SIZE, SBUF_AUTOEXTEND);
2489 /* Allocate and init temporary storage space. */
2490 tmp_w1 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2491 tmp_w2 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2492 tmp_data1 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2494 tmp_data2 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2496 stack_zero(&tmp_data1->wlod_stack);
2497 stack_zero(&tmp_data2->wlod_stack);
2500 mtx_lock_spin(&w_mtx);
2501 generation = w_generation;
2502 mtx_unlock_spin(&w_mtx);
2503 sbuf_printf(sb, "Number of known direct relationships is %d\n",
2504 w_lohash.wloh_count);
2505 for (i = 1; i < w_max_used_index; i++) {
2506 mtx_lock_spin(&w_mtx);
2507 if (generation != w_generation) {
2508 mtx_unlock_spin(&w_mtx);
2510 /* The graph has changed, try again. */
2517 if (w1->w_reversed == 0) {
2518 mtx_unlock_spin(&w_mtx);
2522 /* Copy w1 locally so we can release the spin lock. */
2524 mtx_unlock_spin(&w_mtx);
2526 if (tmp_w1->w_reversed == 0)
2528 for (j = 1; j < w_max_used_index; j++) {
2529 if ((w_rmatrix[i][j] & WITNESS_REVERSAL) == 0 || i > j)
2532 mtx_lock_spin(&w_mtx);
2533 if (generation != w_generation) {
2534 mtx_unlock_spin(&w_mtx);
2536 /* The graph has changed, try again. */
2543 data1 = witness_lock_order_get(w1, w2);
2544 data2 = witness_lock_order_get(w2, w1);
2547 * Copy information locally so we can release the
2551 w_rmatrix1 = (unsigned int)w_rmatrix[i][j];
2552 w_rmatrix2 = (unsigned int)w_rmatrix[j][i];
2555 stack_zero(&tmp_data1->wlod_stack);
2556 stack_copy(&data1->wlod_stack,
2557 &tmp_data1->wlod_stack);
2559 if (data2 && data2 != data1) {
2560 stack_zero(&tmp_data2->wlod_stack);
2561 stack_copy(&data2->wlod_stack,
2562 &tmp_data2->wlod_stack);
2564 mtx_unlock_spin(&w_mtx);
2567 "\nLock order reversal between \"%s\"(%s) and \"%s\"(%s)!\n",
2568 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2569 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2572 "w_rmatrix[%s][%s] == %x, w_rmatrix[%s][%s] == %x\n",
2573 tmp_w1->name, tmp_w2->w_name, w_rmatrix1,
2574 tmp_w2->name, tmp_w1->w_name, w_rmatrix2);
2578 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2579 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2580 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2581 stack_sbuf_print(sb, &tmp_data1->wlod_stack);
2582 sbuf_printf(sb, "\n");
2584 if (data2 && data2 != data1) {
2586 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2587 tmp_w2->w_name, tmp_w2->w_class->lc_name,
2588 tmp_w1->w_name, tmp_w1->w_class->lc_name);
2589 stack_sbuf_print(sb, &tmp_data2->wlod_stack);
2590 sbuf_printf(sb, "\n");
2594 mtx_lock_spin(&w_mtx);
2595 if (generation != w_generation) {
2596 mtx_unlock_spin(&w_mtx);
2599 * The graph changed while we were printing stack data,
2606 mtx_unlock_spin(&w_mtx);
2608 /* Free temporary storage space. */
2609 free(tmp_data1, M_TEMP);
2610 free(tmp_data2, M_TEMP);
2611 free(tmp_w1, M_TEMP);
2612 free(tmp_w2, M_TEMP);
2615 error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
2622 sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
2628 if (witness_watch < 1) {
2629 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2633 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2638 error = sysctl_wire_old_buffer(req, 0);
2641 sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
2644 sbuf_printf(sb, "\n");
2646 mtx_lock_spin(&w_mtx);
2647 STAILQ_FOREACH(w, &w_all, w_list)
2649 STAILQ_FOREACH(w, &w_all, w_list)
2650 witness_add_fullgraph(sb, w);
2651 mtx_unlock_spin(&w_mtx);
2654 * Close the sbuf and return to userland.
2656 error = sbuf_finish(sb);
2663 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
2667 value = witness_watch;
2668 error = sysctl_handle_int(oidp, &value, 0, req);
2669 if (error != 0 || req->newptr == NULL)
2671 if (value > 1 || value < -1 ||
2672 (witness_watch == -1 && value != witness_watch))
2674 witness_watch = value;
2679 witness_add_fullgraph(struct sbuf *sb, struct witness *w)
2683 if (w->w_displayed != 0 || (w->w_file == NULL && w->w_line == 0))
2687 WITNESS_INDEX_ASSERT(w->w_index);
2688 for (i = 1; i <= w_max_used_index; i++) {
2689 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT) {
2690 sbuf_printf(sb, "\"%s\",\"%s\"\n", w->w_name,
2692 witness_add_fullgraph(sb, &w_data[i]);
2698 * A simple hash function. Takes a key pointer and a key size. If size == 0,
2699 * interprets the key as a string and reads until the null
2700 * terminator. Otherwise, reads the first size bytes. Returns an unsigned 32-bit
2701 * hash value computed from the key.
2704 witness_hash_djb2(const uint8_t *key, uint32_t size)
2706 unsigned int hash = 5381;
2709 /* hash = hash * 33 + key[i] */
2711 for (i = 0; i < size; i++)
2712 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2714 for (i = 0; key[i] != 0; i++)
2715 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2722 * Initializes the two witness hash tables. Called exactly once from
2723 * witness_initialize().
2726 witness_init_hash_tables(void)
2730 MPASS(witness_cold);
2732 /* Initialize the hash tables. */
2733 for (i = 0; i < WITNESS_HASH_SIZE; i++)
2734 w_hash.wh_array[i] = NULL;
2736 w_hash.wh_size = WITNESS_HASH_SIZE;
2737 w_hash.wh_count = 0;
2739 /* Initialize the lock order data hash. */
2741 for (i = 0; i < WITNESS_LO_DATA_COUNT; i++) {
2742 memset(&w_lodata[i], 0, sizeof(w_lodata[i]));
2743 w_lodata[i].wlod_next = w_lofree;
2744 w_lofree = &w_lodata[i];
2746 w_lohash.wloh_size = WITNESS_LO_HASH_SIZE;
2747 w_lohash.wloh_count = 0;
2748 for (i = 0; i < WITNESS_LO_HASH_SIZE; i++)
2749 w_lohash.wloh_array[i] = NULL;
2752 static struct witness *
2753 witness_hash_get(const char *key)
2759 if (witness_cold == 0)
2760 mtx_assert(&w_mtx, MA_OWNED);
2761 hash = witness_hash_djb2(key, 0) % w_hash.wh_size;
2762 w = w_hash.wh_array[hash];
2764 if (strcmp(w->w_name, key) == 0)
2774 witness_hash_put(struct witness *w)
2779 MPASS(w->w_name != NULL);
2780 if (witness_cold == 0)
2781 mtx_assert(&w_mtx, MA_OWNED);
2782 KASSERT(witness_hash_get(w->w_name) == NULL,
2783 ("%s: trying to add a hash entry that already exists!", __func__));
2784 KASSERT(w->w_hash_next == NULL,
2785 ("%s: w->w_hash_next != NULL", __func__));
2787 hash = witness_hash_djb2(w->w_name, 0) % w_hash.wh_size;
2788 w->w_hash_next = w_hash.wh_array[hash];
2789 w_hash.wh_array[hash] = w;
2794 static struct witness_lock_order_data *
2795 witness_lock_order_get(struct witness *parent, struct witness *child)
2797 struct witness_lock_order_data *data = NULL;
2798 struct witness_lock_order_key key;
2801 MPASS(parent != NULL && child != NULL);
2802 key.from = parent->w_index;
2803 key.to = child->w_index;
2804 WITNESS_INDEX_ASSERT(key.from);
2805 WITNESS_INDEX_ASSERT(key.to);
2806 if ((w_rmatrix[parent->w_index][child->w_index]
2807 & WITNESS_LOCK_ORDER_KNOWN) == 0)
2810 hash = witness_hash_djb2((const char*)&key,
2811 sizeof(key)) % w_lohash.wloh_size;
2812 data = w_lohash.wloh_array[hash];
2813 while (data != NULL) {
2814 if (witness_lock_order_key_equal(&data->wlod_key, &key))
2816 data = data->wlod_next;
2824 * Verify that parent and child have a known relationship, are not the same,
2825 * and child is actually a child of parent. This is done without w_mtx
2826 * to avoid contention in the common case.
2829 witness_lock_order_check(struct witness *parent, struct witness *child)
2832 if (parent != child &&
2833 w_rmatrix[parent->w_index][child->w_index]
2834 & WITNESS_LOCK_ORDER_KNOWN &&
2835 isitmychild(parent, child))
2842 witness_lock_order_add(struct witness *parent, struct witness *child)
2844 struct witness_lock_order_data *data = NULL;
2845 struct witness_lock_order_key key;
2848 MPASS(parent != NULL && child != NULL);
2849 key.from = parent->w_index;
2850 key.to = child->w_index;
2851 WITNESS_INDEX_ASSERT(key.from);
2852 WITNESS_INDEX_ASSERT(key.to);
2853 if (w_rmatrix[parent->w_index][child->w_index]
2854 & WITNESS_LOCK_ORDER_KNOWN)
2857 hash = witness_hash_djb2((const char*)&key,
2858 sizeof(key)) % w_lohash.wloh_size;
2859 w_rmatrix[parent->w_index][child->w_index] |= WITNESS_LOCK_ORDER_KNOWN;
2863 w_lofree = data->wlod_next;
2864 data->wlod_next = w_lohash.wloh_array[hash];
2865 data->wlod_key = key;
2866 w_lohash.wloh_array[hash] = data;
2867 w_lohash.wloh_count++;
2868 stack_zero(&data->wlod_stack);
2869 stack_save(&data->wlod_stack);
2873 /* Call this whenver the structure of the witness graph changes. */
2875 witness_increment_graph_generation(void)
2878 if (witness_cold == 0)
2879 mtx_assert(&w_mtx, MA_OWNED);
2885 _witness_debugger(int cond, const char *msg)
2888 if (witness_trace && cond)
2890 if (witness_kdb && cond)
2891 kdb_enter(KDB_WHY_WITNESS, msg);