1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 2008 Isilon Systems, Inc.
5 * Copyright (c) 2008 Ilya Maykov <ivmaykov@gmail.com>
6 * Copyright (c) 1998 Berkeley Software Design, Inc.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Berkeley Software Design Inc's name may not be used to endorse or
18 * promote products derived from this software without specific prior
19 * written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
34 * and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
35 */
36
37 /*
38 * Implementation of the `witness' lock verifier. Originally implemented for
39 * mutexes in BSD/OS. Extended to handle generic lock objects and lock
40 * classes in FreeBSD.
41 */
42
43 /*
44 * Main Entry: witness
45 * Pronunciation: 'wit-n&s
46 * Function: noun
47 * Etymology: Middle English witnesse, from Old English witnes knowledge,
48 * testimony, witness, from 2wit
49 * Date: before 12th century
50 * 1 : attestation of a fact or event : TESTIMONY
51 * 2 : one that gives evidence; specifically : one who testifies in
52 * a cause or before a judicial tribunal
53 * 3 : one asked to be present at a transaction so as to be able to
54 * testify to its having taken place
55 * 4 : one who has personal knowledge of something
56 * 5 a : something serving as evidence or proof : SIGN
57 * b : public affirmation by word or example of usually
58 * religious faith or conviction <the heroic witness to divine
59 * life -- Pilot>
60 * 6 capitalized : a member of the Jehovah's Witnesses
61 */
62
63 /*
64 * Special rules concerning Giant and lock orders:
65 *
66 * 1) Giant must be acquired before any other mutexes. Stated another way,
67 * no other mutex may be held when Giant is acquired.
68 *
69 * 2) Giant must be released when blocking on a sleepable lock.
70 *
71 * This rule is less obvious, but is a result of Giant providing the same
72 * semantics as spl(). Basically, when a thread sleeps, it must release
73 * Giant. When a thread blocks on a sleepable lock, it sleeps. Hence rule
74 * 2).
75 *
76 * 3) Giant may be acquired before or after sleepable locks.
77 *
78 * This rule is also not quite as obvious. Giant may be acquired after
79 * a sleepable lock because it is a non-sleepable lock and non-sleepable
80 * locks may always be acquired while holding a sleepable lock. The second
81 * case, Giant before a sleepable lock, follows from rule 2) above. Suppose
82 * you have two threads T1 and T2 and a sleepable lock X. Suppose that T1
83 * acquires X and blocks on Giant. Then suppose that T2 acquires Giant and
84 * blocks on X. When T2 blocks on X, T2 will release Giant allowing T1 to
85 * execute. Thus, acquiring Giant both before and after a sleepable lock
86 * will not result in a lock order reversal.
87 */
88
89 #include <sys/cdefs.h>
90 #include "opt_ddb.h"
91 #include "opt_hwpmc_hooks.h"
92 #include "opt_stack.h"
93 #include "opt_witness.h"
94
95 #include <sys/param.h>
96 #include <sys/bus.h>
97 #include <sys/kdb.h>
98 #include <sys/kernel.h>
99 #include <sys/ktr.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/stdarg.h>
109 #include <sys/sysctl.h>
110 #include <sys/syslog.h>
111 #include <sys/systm.h>
112
113 #ifdef DDB
114 #include <ddb/ddb.h>
115 #endif
116
117 #if !defined(DDB) && !defined(STACK)
118 #error "DDB or STACK options are required for WITNESS"
119 #endif
120
121 /* Note that these traces do not work with KTR_ALQ. */
122 #if 0
123 #define KTR_WITNESS KTR_SUBSYS
124 #else
125 #define KTR_WITNESS 0
126 #endif
127
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. */
131 #define LI_SLEEPABLE 0x00040000 /* Lock may be held while sleeping. */
132
133 #ifndef WITNESS_COUNT
134 #define WITNESS_COUNT 1536
135 #endif
136 #define WITNESS_HASH_SIZE 251 /* Prime, gives load factor < 2 */
137 #define WITNESS_PENDLIST (512 + (MAXCPU * 4))
138
139 /* Allocate 256 KB of stack data space */
140 #define WITNESS_LO_DATA_COUNT 2048
141
142 /* Prime, gives load factor of ~2 at full load */
143 #define WITNESS_LO_HASH_SIZE 1021
144
145 /*
146 * XXX: This is somewhat bogus, as we assume here that at most 2048 threads
147 * will hold LOCK_NCHILDREN locks. We handle failure ok, and we should
148 * probably be safe for the most part, but it's still a SWAG.
149 */
150 #define LOCK_NCHILDREN 5
151 #define LOCK_CHILDCOUNT 2048
152
153 #define MAX_W_NAME 64
154
155 #define FULLGRAPH_SBUF_SIZE 512
156
157 /*
158 * These flags go in the witness relationship matrix and describe the
159 * relationship between any two struct witness objects.
160 */
161 #define WITNESS_UNRELATED 0x00 /* No lock order relation. */
162 #define WITNESS_PARENT 0x01 /* Parent, aka direct ancestor. */
163 #define WITNESS_ANCESTOR 0x02 /* Direct or indirect ancestor. */
164 #define WITNESS_CHILD 0x04 /* Child, aka direct descendant. */
165 #define WITNESS_DESCENDANT 0x08 /* Direct or indirect descendant. */
166 #define WITNESS_ANCESTOR_MASK (WITNESS_PARENT | WITNESS_ANCESTOR)
167 #define WITNESS_DESCENDANT_MASK (WITNESS_CHILD | WITNESS_DESCENDANT)
168 #define WITNESS_RELATED_MASK (WITNESS_ANCESTOR_MASK | WITNESS_DESCENDANT_MASK)
169 #define WITNESS_REVERSAL 0x10 /* A lock order reversal has been observed. */
170 #define WITNESS_RESERVED1 0x20 /* Unused flag, reserved. */
171 #define WITNESS_RESERVED2 0x40 /* Unused flag, reserved. */
172 #define WITNESS_LOCK_ORDER_KNOWN 0x80 /* This lock order is known. */
173
174 /* Descendant to ancestor flags */
175 #define WITNESS_DTOA(x) (((x) & WITNESS_RELATED_MASK) >> 2)
176
177 /* Ancestor to descendant flags */
178 #define WITNESS_ATOD(x) (((x) & WITNESS_RELATED_MASK) << 2)
179
180 #define WITNESS_INDEX_ASSERT(i) \
181 MPASS((i) > 0 && (i) <= w_max_used_index && (i) < witness_count)
182
183 static MALLOC_DEFINE(M_WITNESS, "Witness", "Witness");
184
185 /*
186 * Lock instances. A lock instance is the data associated with a lock while
187 * it is held by witness. For example, a lock instance will hold the
188 * recursion count of a lock. Lock instances are held in lists. Spin locks
189 * are held in a per-cpu list while sleep locks are held in per-thread list.
190 */
191 struct lock_instance {
192 struct lock_object *li_lock;
193 const char *li_file;
194 int li_line;
195 u_int li_flags;
196 };
197
198 /*
199 * A simple list type used to build the list of locks held by a thread
200 * or CPU. We can't simply embed the list in struct lock_object since a
201 * lock may be held by more than one thread if it is a shared lock. Locks
202 * are added to the head of the list, so we fill up each list entry from
203 * "the back" logically. To ease some of the arithmetic, we actually fill
204 * in each list entry the normal way (children[0] then children[1], etc.) but
205 * when we traverse the list we read children[count-1] as the first entry
206 * down to children[0] as the final entry.
207 */
208 struct lock_list_entry {
209 struct lock_list_entry *ll_next;
210 struct lock_instance ll_children[LOCK_NCHILDREN];
211 u_int ll_count;
212 };
213
214 /*
215 * The main witness structure. One of these per named lock type in the system
216 * (for example, "vnode interlock").
217 */
218 struct witness {
219 char w_name[MAX_W_NAME];
220 uint32_t w_index; /* Index in the relationship matrix */
221 struct lock_class *w_class;
222 STAILQ_ENTRY(witness) w_list; /* List of all witnesses. */
223 STAILQ_ENTRY(witness) w_typelist; /* Witnesses of a type. */
224 struct witness *w_hash_next; /* Linked list in hash buckets. */
225 const char *w_file; /* File where last acquired */
226 uint32_t w_line; /* Line where last acquired */
227 uint32_t w_refcount;
228 uint16_t w_num_ancestors; /* direct/indirect ancestor count */
229 uint16_t w_num_descendants; /* direct/indirect descendant count */
230 int16_t w_ddb_level;
231 unsigned w_displayed:1;
232 unsigned w_reversed:1;
233 };
234
235 STAILQ_HEAD(witness_list, witness);
236
237 /*
238 * The witness hash table. Keys are witness names (const char *), elements are
239 * witness objects (struct witness *).
240 */
241 struct witness_hash {
242 struct witness *wh_array[WITNESS_HASH_SIZE];
243 uint32_t wh_size;
244 uint32_t wh_count;
245 };
246
247 /*
248 * Key type for the lock order data hash table.
249 */
250 struct witness_lock_order_key {
251 uint16_t from;
252 uint16_t to;
253 };
254
255 struct witness_lock_order_data {
256 struct stack wlod_stack;
257 struct witness_lock_order_key wlod_key;
258 struct witness_lock_order_data *wlod_next;
259 };
260
261 /*
262 * The witness lock order data hash table. Keys are witness index tuples
263 * (struct witness_lock_order_key), elements are lock order data objects
264 * (struct witness_lock_order_data).
265 */
266 struct witness_lock_order_hash {
267 struct witness_lock_order_data *wloh_array[WITNESS_LO_HASH_SIZE];
268 u_int wloh_size;
269 u_int wloh_count;
270 };
271
272 struct witness_blessed {
273 const char *b_lock1;
274 const char *b_lock2;
275 };
276
277 struct witness_pendhelp {
278 const char *wh_type;
279 struct lock_object *wh_lock;
280 };
281
282 struct witness_order_list_entry {
283 const char *w_name;
284 struct lock_class *w_class;
285 };
286
287 /*
288 * Returns 0 if one of the locks is a spin lock and the other is not.
289 * Returns 1 otherwise.
290 */
291 static __inline int
witness_lock_type_equal(struct witness * w1,struct witness * w2)292 witness_lock_type_equal(struct witness *w1, struct witness *w2)
293 {
294 return ((w1->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)) ==
295 (w2->w_class->lc_flags & (LC_SLEEPLOCK | LC_SPINLOCK)));
296 }
297
298 static __inline int
witness_lock_order_key_equal(const struct witness_lock_order_key * a,const struct witness_lock_order_key * b)299 witness_lock_order_key_equal(const struct witness_lock_order_key *a,
300 const struct witness_lock_order_key *b)
301 {
302 return (a->from == b->from && a->to == b->to);
303 }
304
305 static int _isitmyx(struct witness *w1, struct witness *w2, int rmask,
306 const char *fname);
307 static void adopt(struct witness *parent, struct witness *child);
308 static int blessed(struct witness *, struct witness *);
309 static void depart(struct witness *w);
310 static struct witness *enroll(const char *description,
311 struct lock_class *lock_class);
312 static struct lock_instance *find_instance(struct lock_list_entry *list,
313 const struct lock_object *lock);
314 static int isitmychild(struct witness *parent, struct witness *child);
315 static int isitmydescendant(struct witness *parent, struct witness *child);
316 static void itismychild(struct witness *parent, struct witness *child);
317 static int sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS);
318 static int sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS);
319 static int sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS);
320 static int sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS);
321 static void witness_add_fullgraph(struct sbuf *sb, struct witness *parent);
322 #ifdef DDB
323 static void witness_ddb_compute_levels(void);
324 static void witness_ddb_display(int(*)(const char *fmt, ...));
325 static void witness_ddb_display_descendants(int(*)(const char *fmt, ...),
326 struct witness *, int indent);
327 static void witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
328 struct witness_list *list);
329 static void witness_ddb_level_descendants(struct witness *parent, int l);
330 static void witness_ddb_list(struct thread *td);
331 #endif
332 static void witness_enter_debugger(const char *msg);
333 static void witness_debugger(int cond, const char *msg);
334 static void witness_free(struct witness *m);
335 static struct witness *witness_get(void);
336 static uint32_t witness_hash_djb2(const uint8_t *key, uint32_t size);
337 static struct witness *witness_hash_get(const char *key);
338 static void witness_hash_put(struct witness *w);
339 static void witness_init_hash_tables(void);
340 static void witness_increment_graph_generation(void);
341 static void witness_lock_list_free(struct lock_list_entry *lle);
342 static struct lock_list_entry *witness_lock_list_get(void);
343 static int witness_lock_order_add(struct witness *parent,
344 struct witness *child);
345 static int witness_lock_order_check(struct witness *parent,
346 struct witness *child);
347 static struct witness_lock_order_data *witness_lock_order_get(
348 struct witness *parent,
349 struct witness *child);
350 static void witness_list_lock(struct lock_instance *instance,
351 int (*prnt)(const char *fmt, ...));
352 static int witness_output(const char *fmt, ...) __printflike(1, 2);
353 static int witness_output_drain(void *arg __unused, const char *data,
354 int len);
355 static int witness_voutput(const char *fmt, va_list ap) __printflike(1, 0);
356 static void witness_setflag(struct lock_object *lock, int flag, int set);
357
358 FEATURE(witness, "kernel has witness(9) support");
359
360 static SYSCTL_NODE(_debug, OID_AUTO, witness, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
361 "Witness Locking");
362
363 /*
364 * If set to 0, lock order checking is disabled. If set to -1,
365 * witness is completely disabled. Otherwise witness performs full
366 * lock order checking for all locks. At runtime, lock order checking
367 * may be toggled. However, witness cannot be reenabled once it is
368 * completely disabled.
369 */
370 static int witness_watch = 1;
371 SYSCTL_PROC(_debug_witness, OID_AUTO, watch,
372 CTLFLAG_RWTUN | CTLTYPE_INT | CTLFLAG_MPSAFE, NULL, 0,
373 sysctl_debug_witness_watch, "I",
374 "witness is watching lock operations");
375
376 #ifdef KDB
377 /*
378 * When KDB is enabled and witness_kdb is 1, it will cause the system
379 * to drop into kdebug() when:
380 * - a lock hierarchy violation occurs
381 * - locks are held when going to sleep.
382 */
383 #ifdef WITNESS_KDB
384 int witness_kdb = 1;
385 #else
386 int witness_kdb = 0;
387 #endif
388 SYSCTL_INT(_debug_witness, OID_AUTO, kdb, CTLFLAG_RWTUN, &witness_kdb, 0, "");
389 #endif /* KDB */
390
391 #if defined(DDB) || defined(KDB)
392 /*
393 * When DDB or KDB is enabled and witness_trace is 1, it will cause the system
394 * to print a stack trace:
395 * - a lock hierarchy violation occurs
396 * - locks are held when going to sleep.
397 */
398 int witness_trace = 1;
399 SYSCTL_INT(_debug_witness, OID_AUTO, trace, CTLFLAG_RWTUN, &witness_trace, 0, "");
400 #endif /* DDB || KDB */
401
402 #ifdef WITNESS_SKIPSPIN
403 int witness_skipspin = 1;
404 #else
405 int witness_skipspin = 0;
406 #endif
407 SYSCTL_INT(_debug_witness, OID_AUTO, skipspin, CTLFLAG_RDTUN, &witness_skipspin, 0, "");
408
409 int badstack_sbuf_size;
410
411 int witness_count = WITNESS_COUNT;
412 SYSCTL_INT(_debug_witness, OID_AUTO, witness_count, CTLFLAG_RDTUN,
413 &witness_count, 0, "");
414
415 /*
416 * Output channel for witness messages. By default we print to the console.
417 */
418 enum witness_channel {
419 WITNESS_CONSOLE,
420 WITNESS_LOG,
421 WITNESS_NONE,
422 };
423
424 static enum witness_channel witness_channel = WITNESS_CONSOLE;
425 SYSCTL_PROC(_debug_witness, OID_AUTO, output_channel,
426 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, NULL, 0,
427 sysctl_debug_witness_channel, "A",
428 "Output channel for warnings");
429
430 /*
431 * Call this to print out the relations between locks.
432 */
433 SYSCTL_PROC(_debug_witness, OID_AUTO, fullgraph,
434 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
435 sysctl_debug_witness_fullgraph, "A",
436 "Show locks relation graphs");
437
438 /*
439 * Call this to print out the witness faulty stacks.
440 */
441 SYSCTL_PROC(_debug_witness, OID_AUTO, badstacks,
442 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
443 sysctl_debug_witness_badstacks, "A",
444 "Show bad witness stacks");
445
446 static struct mtx w_mtx;
447
448 /* w_list */
449 static struct witness_list w_free = STAILQ_HEAD_INITIALIZER(w_free);
450 static struct witness_list w_all = STAILQ_HEAD_INITIALIZER(w_all);
451
452 /* w_typelist */
453 static struct witness_list w_spin = STAILQ_HEAD_INITIALIZER(w_spin);
454 static struct witness_list w_sleep = STAILQ_HEAD_INITIALIZER(w_sleep);
455
456 /* lock list */
457 static struct lock_list_entry *w_lock_list_free = NULL;
458 static struct witness_pendhelp pending_locks[WITNESS_PENDLIST];
459 static u_int pending_cnt;
460
461 static int w_free_cnt, w_spin_cnt, w_sleep_cnt;
462 SYSCTL_INT(_debug_witness, OID_AUTO, free_cnt, CTLFLAG_RD, &w_free_cnt, 0, "");
463 SYSCTL_INT(_debug_witness, OID_AUTO, spin_cnt, CTLFLAG_RD, &w_spin_cnt, 0, "");
464 SYSCTL_INT(_debug_witness, OID_AUTO, sleep_cnt, CTLFLAG_RD, &w_sleep_cnt, 0,
465 "");
466
467 static struct witness *w_data;
468 static uint8_t **w_rmatrix;
469 static struct lock_list_entry w_locklistdata[LOCK_CHILDCOUNT];
470 static struct witness_hash w_hash; /* The witness hash table. */
471
472 /* The lock order data hash */
473 static struct witness_lock_order_data w_lodata[WITNESS_LO_DATA_COUNT];
474 static struct witness_lock_order_data *w_lofree = NULL;
475 static struct witness_lock_order_hash w_lohash;
476 static int w_max_used_index = 0;
477 static unsigned int w_generation = 0;
478 static const char w_notrunning[] = "Witness not running\n";
479 static const char w_stillcold[] = "Witness is still cold\n";
480 #ifdef __i386__
481 static const char w_notallowed[] = "The sysctl is disabled on the arch\n";
482 #endif
483
484 static struct witness_order_list_entry order_lists[] = {
485 /*
486 * sx locks
487 */
488 { "proctree", &lock_class_sx },
489 { "allproc", &lock_class_sx },
490 { "allprison", &lock_class_sx },
491 { NULL, NULL },
492 /*
493 * Various mutexes
494 */
495 { "Giant", &lock_class_mtx_sleep },
496 { "pipe mutex", &lock_class_mtx_sleep },
497 { "sigio lock", &lock_class_mtx_sleep },
498 { "process group", &lock_class_mtx_sleep },
499 #ifdef HWPMC_HOOKS
500 { "pmc-sleep", &lock_class_mtx_sleep },
501 #endif
502 { "process lock", &lock_class_mtx_sleep },
503 { "session", &lock_class_mtx_sleep },
504 { "uidinfo hash", &lock_class_rw },
505 { "time lock", &lock_class_mtx_sleep },
506 { NULL, NULL },
507 /*
508 * umtx
509 */
510 { "umtx lock", &lock_class_mtx_sleep },
511 { NULL, NULL },
512 /*
513 * Sockets
514 */
515 { "accept", &lock_class_mtx_sleep },
516 { "so_snd", &lock_class_mtx_sleep },
517 { "so_rcv", &lock_class_mtx_sleep },
518 { "sellck", &lock_class_mtx_sleep },
519 { NULL, NULL },
520 /*
521 * Routing
522 */
523 { "so_rcv", &lock_class_mtx_sleep },
524 { "radix node head", &lock_class_rm },
525 { "ifaddr", &lock_class_mtx_sleep },
526 { NULL, NULL },
527 /*
528 * IPv4 multicast:
529 * protocol locks before interface locks, after UDP locks.
530 */
531 { "in_multi_sx", &lock_class_sx },
532 { "udpinp", &lock_class_rw },
533 { "in_multi_list_mtx", &lock_class_mtx_sleep },
534 { "igmp_mtx", &lock_class_mtx_sleep },
535 { "if_addr_lock", &lock_class_mtx_sleep },
536 { NULL, NULL },
537 /*
538 * IPv6 multicast:
539 * protocol locks before interface locks, after UDP locks.
540 */
541 { "in6_multi_sx", &lock_class_sx },
542 { "udpinp", &lock_class_rw },
543 { "in6_multi_list_mtx", &lock_class_mtx_sleep },
544 { "mld_mtx", &lock_class_mtx_sleep },
545 { "if_addr_lock", &lock_class_mtx_sleep },
546 { NULL, NULL },
547 /*
548 * UNIX Domain Sockets
549 */
550 { "unp_link_rwlock", &lock_class_rw },
551 { "unp_list_lock", &lock_class_mtx_sleep },
552 { "unp", &lock_class_mtx_sleep },
553 { "so_snd", &lock_class_mtx_sleep },
554 { NULL, NULL },
555 /*
556 * UDP/IP
557 */
558 { "udpinp", &lock_class_rw },
559 { "udp", &lock_class_mtx_sleep },
560 { "so_snd", &lock_class_mtx_sleep },
561 { NULL, NULL },
562 /*
563 * TCP/IP
564 */
565 { "tcpinp", &lock_class_rw },
566 { "tcp", &lock_class_mtx_sleep },
567 { "so_snd", &lock_class_mtx_sleep },
568 { NULL, NULL },
569 /*
570 * BPF
571 */
572 { "bpf global lock", &lock_class_sx },
573 { "bpf cdev lock", &lock_class_mtx_sleep },
574 { NULL, NULL },
575 /*
576 * NFS server
577 */
578 { "nfsd_mtx", &lock_class_mtx_sleep },
579 { "so_snd", &lock_class_mtx_sleep },
580 { NULL, NULL },
581
582 /*
583 * IEEE 802.11
584 */
585 { "802.11 com lock", &lock_class_mtx_sleep},
586 { NULL, NULL },
587 /*
588 * Network drivers
589 */
590 { "network driver", &lock_class_mtx_sleep},
591 { NULL, NULL },
592
593 /*
594 * Netgraph
595 */
596 { "ng_node", &lock_class_mtx_sleep },
597 { "ng_worklist", &lock_class_mtx_sleep },
598 { NULL, NULL },
599 /*
600 * CDEV
601 */
602 { "vm map (system)", &lock_class_mtx_sleep },
603 { "vnode interlock", &lock_class_mtx_sleep },
604 { "cdev", &lock_class_mtx_sleep },
605 { "devthrd", &lock_class_mtx_sleep },
606 { NULL, NULL },
607 /*
608 * VM
609 */
610 { "vm map (user)", &lock_class_sx },
611 { "vm object", &lock_class_rw },
612 { "vm page", &lock_class_mtx_sleep },
613 { "pmap pv global", &lock_class_rw },
614 { "pmap", &lock_class_mtx_sleep },
615 { "pmap pv list", &lock_class_rw },
616 { "vm page free queue", &lock_class_mtx_sleep },
617 { "vm pagequeue", &lock_class_mtx_sleep },
618 { NULL, NULL },
619 /*
620 * kqueue/VFS interaction
621 */
622 { "kqueue", &lock_class_mtx_sleep },
623 { "struct mount mtx", &lock_class_mtx_sleep },
624 { "vnode interlock", &lock_class_mtx_sleep },
625 { NULL, NULL },
626 /*
627 * VFS namecache
628 */
629 { "ncvn", &lock_class_mtx_sleep },
630 { "ncbuc", &lock_class_mtx_sleep },
631 { "vnode interlock", &lock_class_mtx_sleep },
632 { "ncneg", &lock_class_mtx_sleep },
633 { NULL, NULL },
634 /*
635 * ZFS locking
636 */
637 { "dn->dn_mtx", &lock_class_sx },
638 { "dr->dt.di.dr_mtx", &lock_class_sx },
639 { "db->db_mtx", &lock_class_sx },
640 { NULL, NULL },
641 /*
642 * TCP log locks
643 */
644 { "TCP ID tree", &lock_class_rw },
645 { "tcp log id bucket", &lock_class_mtx_sleep },
646 { "tcpinp", &lock_class_rw },
647 { "TCP log expireq", &lock_class_mtx_sleep },
648 { NULL, NULL },
649 /*
650 * spin locks
651 */
652 #ifdef SMP
653 { "ap boot", &lock_class_mtx_spin },
654 #endif
655 { "rm.mutex_mtx", &lock_class_mtx_spin },
656 #ifdef __i386__
657 { "cy", &lock_class_mtx_spin },
658 #endif
659 { "scc_hwmtx", &lock_class_mtx_spin },
660 { "uart_hwmtx", &lock_class_mtx_spin },
661 { "fast_taskqueue", &lock_class_mtx_spin },
662 { "intr table", &lock_class_mtx_spin },
663 { "process slock", &lock_class_mtx_spin },
664 { "syscons video lock", &lock_class_mtx_spin },
665 { "sleepq chain", &lock_class_mtx_spin },
666 { "rm_spinlock", &lock_class_mtx_spin },
667 { "turnstile chain", &lock_class_mtx_spin },
668 { "turnstile lock", &lock_class_mtx_spin },
669 { "sched lock", &lock_class_mtx_spin },
670 { "td_contested", &lock_class_mtx_spin },
671 { "callout", &lock_class_mtx_spin },
672 { "entropy harvest mutex", &lock_class_mtx_spin },
673 #ifdef SMP
674 { "smp rendezvous", &lock_class_mtx_spin },
675 #endif
676 #ifdef __powerpc__
677 { "tlb0", &lock_class_mtx_spin },
678 #endif
679 { NULL, NULL },
680 { "sched lock", &lock_class_mtx_spin },
681 #ifdef HWPMC_HOOKS
682 { "pmc-per-proc", &lock_class_mtx_spin },
683 #endif
684 { NULL, NULL },
685 /*
686 * leaf locks
687 */
688 { "intrcnt", &lock_class_mtx_spin },
689 { "icu", &lock_class_mtx_spin },
690 #ifdef __i386__
691 { "allpmaps", &lock_class_mtx_spin },
692 { "descriptor tables", &lock_class_mtx_spin },
693 #endif
694 { "clk", &lock_class_mtx_spin },
695 { "cpuset", &lock_class_mtx_spin },
696 { "mprof lock", &lock_class_mtx_spin },
697 { "zombie lock", &lock_class_mtx_spin },
698 { "ALD Queue", &lock_class_mtx_spin },
699 #if defined(__i386__) || defined(__amd64__)
700 { "pcicfg", &lock_class_mtx_spin },
701 { "NDIS thread lock", &lock_class_mtx_spin },
702 #endif
703 { "tw_osl_io_lock", &lock_class_mtx_spin },
704 { "tw_osl_q_lock", &lock_class_mtx_spin },
705 { "tw_cl_io_lock", &lock_class_mtx_spin },
706 { "tw_cl_intr_lock", &lock_class_mtx_spin },
707 { "tw_cl_gen_lock", &lock_class_mtx_spin },
708 #ifdef HWPMC_HOOKS
709 { "pmc-leaf", &lock_class_mtx_spin },
710 #endif
711 { "blocked lock", &lock_class_mtx_spin },
712 { NULL, NULL },
713 { NULL, NULL }
714 };
715
716 /*
717 * Pairs of locks which have been blessed. Witness does not complain about
718 * order problems with blessed lock pairs. Please do not add an entry to the
719 * table without an explanatory comment.
720 */
721 static struct witness_blessed blessed_list[] = {
722 /*
723 * See the comment in ufs_dirhash.c. Basically, a vnode lock serializes
724 * both lock orders, so a deadlock cannot happen as a result of this
725 * LOR.
726 */
727 { "dirhash", "bufwait" },
728
729 /*
730 * A UFS vnode may be locked in vget() while a buffer belonging to the
731 * parent directory vnode is locked.
732 */
733 { "ufs", "bufwait" },
734
735 /*
736 * The tarfs decompression stream vnode may be locked while a
737 * buffer belonging to a tarfs data vnode is locked.
738 */
739 { "tarfs", "bufwait" },
740 };
741
742 /*
743 * This global is set to 0 once it becomes safe to use the witness code.
744 */
745 static int witness_cold = 1;
746
747 /*
748 * This global is set to 1 once the static lock orders have been enrolled
749 * so that a warning can be issued for any spin locks enrolled later.
750 */
751 static int witness_spin_warn = 0;
752
753 /* Trim useless garbage from filenames. */
754 static const char *
fixup_filename(const char * file)755 fixup_filename(const char *file)
756 {
757 if (file == NULL)
758 return (NULL);
759 while (strncmp(file, "../", 3) == 0)
760 file += 3;
761 return (file);
762 }
763
764 /*
765 * Calculate the size of early witness structures.
766 */
767 int
witness_startup_count(void)768 witness_startup_count(void)
769 {
770 int sz;
771
772 sz = sizeof(struct witness) * witness_count;
773 sz += sizeof(*w_rmatrix) * (witness_count + 1);
774 sz += sizeof(*w_rmatrix[0]) * (witness_count + 1) *
775 (witness_count + 1);
776
777 return (sz);
778 }
779
780 /*
781 * The WITNESS-enabled diagnostic code. Note that the witness code does
782 * assume that the early boot is single-threaded at least until after this
783 * routine is completed.
784 */
785 void
witness_startup(void * mem)786 witness_startup(void *mem)
787 {
788 struct lock_object *lock;
789 struct witness_order_list_entry *order;
790 struct witness *w, *w1;
791 uintptr_t p;
792 int i;
793
794 p = (uintptr_t)mem;
795 w_data = (void *)p;
796 p += sizeof(struct witness) * witness_count;
797
798 w_rmatrix = (void *)p;
799 p += sizeof(*w_rmatrix) * (witness_count + 1);
800
801 for (i = 0; i < witness_count + 1; i++) {
802 w_rmatrix[i] = (void *)p;
803 p += sizeof(*w_rmatrix[i]) * (witness_count + 1);
804 }
805 badstack_sbuf_size = witness_count * 256;
806
807 /*
808 * We have to release Giant before initializing its witness
809 * structure so that WITNESS doesn't get confused.
810 */
811 mtx_unlock(&Giant);
812 mtx_assert(&Giant, MA_NOTOWNED);
813
814 CTR1(KTR_WITNESS, "%s: initializing witness", __func__);
815 mtx_init(&w_mtx, "witness lock", NULL, MTX_SPIN | MTX_QUIET |
816 MTX_NOWITNESS | MTX_NOPROFILE);
817 for (i = witness_count - 1; i >= 0; i--) {
818 w = &w_data[i];
819 memset(w, 0, sizeof(*w));
820 w_data[i].w_index = i; /* Witness index never changes. */
821 witness_free(w);
822 }
823 KASSERT(STAILQ_FIRST(&w_free)->w_index == 0,
824 ("%s: Invalid list of free witness objects", __func__));
825
826 /* Witness with index 0 is not used to aid in debugging. */
827 STAILQ_REMOVE_HEAD(&w_free, w_list);
828 w_free_cnt--;
829
830 for (i = 0; i < witness_count; i++) {
831 memset(w_rmatrix[i], 0, sizeof(*w_rmatrix[i]) *
832 (witness_count + 1));
833 }
834
835 for (i = 0; i < LOCK_CHILDCOUNT; i++)
836 witness_lock_list_free(&w_locklistdata[i]);
837 witness_init_hash_tables();
838
839 /* First add in all the specified order lists. */
840 for (order = order_lists; order->w_name != NULL; order++) {
841 w = enroll(order->w_name, order->w_class);
842 if (w == NULL)
843 continue;
844 w->w_file = "order list";
845 for (order++; order->w_name != NULL; order++) {
846 w1 = enroll(order->w_name, order->w_class);
847 if (w1 == NULL)
848 continue;
849 w1->w_file = "order list";
850 itismychild(w, w1);
851 w = w1;
852 }
853 }
854 witness_spin_warn = 1;
855
856 /* Iterate through all locks and add them to witness. */
857 for (i = 0; pending_locks[i].wh_lock != NULL; i++) {
858 lock = pending_locks[i].wh_lock;
859 KASSERT(lock->lo_flags & LO_WITNESS,
860 ("%s: lock %s is on pending list but not LO_WITNESS",
861 __func__, lock->lo_name));
862 lock->lo_witness = enroll(pending_locks[i].wh_type,
863 LOCK_CLASS(lock));
864 }
865
866 /* Mark the witness code as being ready for use. */
867 witness_cold = 0;
868
869 mtx_lock(&Giant);
870 }
871
872 void
witness_init(struct lock_object * lock,const char * type)873 witness_init(struct lock_object *lock, const char *type)
874 {
875 struct lock_class *class;
876
877 /* Various sanity checks. */
878 class = LOCK_CLASS(lock);
879 if ((lock->lo_flags & LO_RECURSABLE) != 0 &&
880 (class->lc_flags & LC_RECURSABLE) == 0)
881 kassert_panic("%s: lock (%s) %s can not be recursable",
882 __func__, class->lc_name, lock->lo_name);
883 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
884 (class->lc_flags & LC_SLEEPABLE) == 0)
885 kassert_panic("%s: lock (%s) %s can not be sleepable",
886 __func__, class->lc_name, lock->lo_name);
887 if ((lock->lo_flags & LO_UPGRADABLE) != 0 &&
888 (class->lc_flags & LC_UPGRADABLE) == 0)
889 kassert_panic("%s: lock (%s) %s can not be upgradable",
890 __func__, class->lc_name, lock->lo_name);
891
892 /*
893 * If we shouldn't watch this lock, then just clear lo_witness.
894 * Otherwise, if witness_cold is set, then it is too early to
895 * enroll this lock, so defer it to witness_initialize() by adding
896 * it to the pending_locks list. If it is not too early, then enroll
897 * the lock now.
898 */
899 if (witness_watch < 1 || KERNEL_PANICKED() ||
900 (lock->lo_flags & LO_WITNESS) == 0)
901 lock->lo_witness = NULL;
902 else if (witness_cold) {
903 pending_locks[pending_cnt].wh_lock = lock;
904 pending_locks[pending_cnt++].wh_type = type;
905 if (pending_cnt > WITNESS_PENDLIST)
906 panic("%s: pending locks list is too small, "
907 "increase WITNESS_PENDLIST\n",
908 __func__);
909 } else
910 lock->lo_witness = enroll(type, class);
911 }
912
913 void
witness_destroy(struct lock_object * lock)914 witness_destroy(struct lock_object *lock)
915 {
916 struct lock_class *class;
917 struct witness *w;
918
919 class = LOCK_CLASS(lock);
920
921 if (witness_cold)
922 panic("lock (%s) %s destroyed while witness_cold",
923 class->lc_name, lock->lo_name);
924
925 /* XXX: need to verify that no one holds the lock */
926 if ((lock->lo_flags & LO_WITNESS) == 0 || lock->lo_witness == NULL)
927 return;
928 w = lock->lo_witness;
929
930 mtx_lock_spin(&w_mtx);
931 MPASS(w->w_refcount > 0);
932 w->w_refcount--;
933
934 if (w->w_refcount == 0)
935 depart(w);
936 mtx_unlock_spin(&w_mtx);
937 }
938
939 #ifdef DDB
940 static void
witness_ddb_compute_levels(void)941 witness_ddb_compute_levels(void)
942 {
943 struct witness *w;
944
945 /*
946 * First clear all levels.
947 */
948 STAILQ_FOREACH(w, &w_all, w_list)
949 w->w_ddb_level = -1;
950
951 /*
952 * Look for locks with no parents and level all their descendants.
953 */
954 STAILQ_FOREACH(w, &w_all, w_list) {
955 /* If the witness has ancestors (is not a root), skip it. */
956 if (w->w_num_ancestors > 0)
957 continue;
958 witness_ddb_level_descendants(w, 0);
959 }
960 }
961
962 static void
witness_ddb_level_descendants(struct witness * w,int l)963 witness_ddb_level_descendants(struct witness *w, int l)
964 {
965 int i;
966
967 if (w->w_ddb_level >= l)
968 return;
969
970 w->w_ddb_level = l;
971 l++;
972
973 for (i = 1; i <= w_max_used_index; i++) {
974 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
975 witness_ddb_level_descendants(&w_data[i], l);
976 }
977 }
978
979 static void
witness_ddb_display_descendants(int (* prnt)(const char * fmt,...),struct witness * w,int indent)980 witness_ddb_display_descendants(int(*prnt)(const char *fmt, ...),
981 struct witness *w, int indent)
982 {
983 int i;
984
985 for (i = 0; i < indent; i++)
986 prnt(" ");
987 prnt("%s (type: %s, depth: %d, active refs: %d)",
988 w->w_name, w->w_class->lc_name,
989 w->w_ddb_level, w->w_refcount);
990 if (w->w_displayed) {
991 prnt(" -- (already displayed)\n");
992 return;
993 }
994 w->w_displayed = 1;
995 if (w->w_file != NULL && w->w_line != 0)
996 prnt(" -- last acquired @ %s:%d\n", fixup_filename(w->w_file),
997 w->w_line);
998 else
999 prnt(" -- never acquired\n");
1000 indent++;
1001 WITNESS_INDEX_ASSERT(w->w_index);
1002 for (i = 1; i <= w_max_used_index; i++) {
1003 if (db_pager_quit)
1004 return;
1005 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT)
1006 witness_ddb_display_descendants(prnt, &w_data[i],
1007 indent);
1008 }
1009 }
1010
1011 static void
witness_ddb_display_list(int (* prnt)(const char * fmt,...),struct witness_list * list)1012 witness_ddb_display_list(int(*prnt)(const char *fmt, ...),
1013 struct witness_list *list)
1014 {
1015 struct witness *w;
1016
1017 STAILQ_FOREACH(w, list, w_typelist) {
1018 if (w->w_file == NULL || w->w_ddb_level > 0)
1019 continue;
1020
1021 /* This lock has no anscestors - display its descendants. */
1022 witness_ddb_display_descendants(prnt, w, 0);
1023 if (db_pager_quit)
1024 return;
1025 }
1026 }
1027
1028 static void
witness_ddb_display(int (* prnt)(const char * fmt,...))1029 witness_ddb_display(int(*prnt)(const char *fmt, ...))
1030 {
1031 struct witness *w;
1032
1033 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1034 witness_ddb_compute_levels();
1035
1036 /* Clear all the displayed flags. */
1037 STAILQ_FOREACH(w, &w_all, w_list)
1038 w->w_displayed = 0;
1039
1040 /*
1041 * First, handle sleep locks which have been acquired at least
1042 * once.
1043 */
1044 prnt("Sleep locks:\n");
1045 witness_ddb_display_list(prnt, &w_sleep);
1046 if (db_pager_quit)
1047 return;
1048
1049 /*
1050 * Now do spin locks which have been acquired at least once.
1051 */
1052 prnt("\nSpin locks:\n");
1053 witness_ddb_display_list(prnt, &w_spin);
1054 if (db_pager_quit)
1055 return;
1056
1057 /*
1058 * Finally, any locks which have not been acquired yet.
1059 */
1060 prnt("\nLocks which were never acquired:\n");
1061 STAILQ_FOREACH(w, &w_all, w_list) {
1062 if (w->w_file != NULL || w->w_refcount == 0)
1063 continue;
1064 prnt("%s (type: %s, depth: %d)\n", w->w_name,
1065 w->w_class->lc_name, w->w_ddb_level);
1066 if (db_pager_quit)
1067 return;
1068 }
1069 }
1070 #endif /* DDB */
1071
1072 int
witness_defineorder(struct lock_object * lock1,struct lock_object * lock2)1073 witness_defineorder(struct lock_object *lock1, struct lock_object *lock2)
1074 {
1075 if (witness_watch == -1 || KERNEL_PANICKED())
1076 return (0);
1077
1078 /* Require locks that witness knows about. */
1079 if (lock1 == NULL || lock1->lo_witness == NULL || lock2 == NULL ||
1080 lock2->lo_witness == NULL)
1081 return (EINVAL);
1082
1083 mtx_assert(&w_mtx, MA_NOTOWNED);
1084 mtx_lock_spin(&w_mtx);
1085
1086 /*
1087 * If we already have either an explicit or implied lock order that
1088 * is the other way around, then return an error.
1089 */
1090 if (witness_watch &&
1091 isitmydescendant(lock2->lo_witness, lock1->lo_witness)) {
1092 mtx_unlock_spin(&w_mtx);
1093 return (EDOOFUS);
1094 }
1095
1096 /* Try to add the new order. */
1097 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1098 lock2->lo_witness->w_name, lock1->lo_witness->w_name);
1099 itismychild(lock1->lo_witness, lock2->lo_witness);
1100 mtx_unlock_spin(&w_mtx);
1101 return (0);
1102 }
1103
1104 void
witness_checkorder(struct lock_object * lock,int flags,const char * file,int line,struct lock_object * interlock)1105 witness_checkorder(struct lock_object *lock, int flags, const char *file,
1106 int line, struct lock_object *interlock)
1107 {
1108 struct lock_list_entry *lock_list, *lle;
1109 struct lock_instance *lock1, *lock2, *plock;
1110 struct lock_class *class, *iclass;
1111 struct witness *w, *w1;
1112 struct thread *td;
1113 int i, j;
1114
1115 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL ||
1116 KERNEL_PANICKED())
1117 return;
1118
1119 w = lock->lo_witness;
1120 class = LOCK_CLASS(lock);
1121 td = curthread;
1122
1123 if (class->lc_flags & LC_SLEEPLOCK) {
1124 /*
1125 * Since spin locks include a critical section, this check
1126 * implicitly enforces a lock order of all sleep locks before
1127 * all spin locks.
1128 */
1129 if (td->td_critnest != 0 && !kdb_active)
1130 kassert_panic("acquiring blockable sleep lock with "
1131 "spinlock or critical section held (%s) %s @ %s:%d",
1132 class->lc_name, lock->lo_name,
1133 fixup_filename(file), line);
1134
1135 /*
1136 * If this is the first lock acquired then just return as
1137 * no order checking is needed.
1138 */
1139 lock_list = td->td_sleeplocks;
1140 if (lock_list == NULL || lock_list->ll_count == 0)
1141 return;
1142 } else {
1143 /*
1144 * If this is the first lock, just return as no order
1145 * checking is needed. Avoid problems with thread
1146 * migration pinning the thread while checking if
1147 * spinlocks are held. If at least one spinlock is held
1148 * the thread is in a safe path and it is allowed to
1149 * unpin it.
1150 */
1151 sched_pin();
1152 lock_list = PCPU_GET(spinlocks);
1153 if (lock_list == NULL || lock_list->ll_count == 0) {
1154 sched_unpin();
1155 return;
1156 }
1157 sched_unpin();
1158 }
1159
1160 /*
1161 * Check to see if we are recursing on a lock we already own. If
1162 * so, make sure that we don't mismatch exclusive and shared lock
1163 * acquires.
1164 */
1165 lock1 = find_instance(lock_list, lock);
1166 if (lock1 != NULL) {
1167 if ((lock1->li_flags & LI_EXCLUSIVE) != 0 &&
1168 (flags & LOP_EXCLUSIVE) == 0) {
1169 witness_output("shared lock of (%s) %s @ %s:%d\n",
1170 class->lc_name, lock->lo_name,
1171 fixup_filename(file), line);
1172 witness_output("while exclusively locked from %s:%d\n",
1173 fixup_filename(lock1->li_file), lock1->li_line);
1174 kassert_panic("excl->share");
1175 }
1176 if ((lock1->li_flags & LI_EXCLUSIVE) == 0 &&
1177 (flags & LOP_EXCLUSIVE) != 0) {
1178 witness_output("exclusive lock of (%s) %s @ %s:%d\n",
1179 class->lc_name, lock->lo_name,
1180 fixup_filename(file), line);
1181 witness_output("while share locked from %s:%d\n",
1182 fixup_filename(lock1->li_file), lock1->li_line);
1183 kassert_panic("share->excl");
1184 }
1185 return;
1186 }
1187
1188 /* Warn if the interlock is not locked exactly once. */
1189 if (interlock != NULL) {
1190 iclass = LOCK_CLASS(interlock);
1191 lock1 = find_instance(lock_list, interlock);
1192 if (lock1 == NULL)
1193 kassert_panic("interlock (%s) %s not locked @ %s:%d",
1194 iclass->lc_name, interlock->lo_name,
1195 fixup_filename(file), line);
1196 else if ((lock1->li_flags & LI_RECURSEMASK) != 0)
1197 kassert_panic("interlock (%s) %s recursed @ %s:%d",
1198 iclass->lc_name, interlock->lo_name,
1199 fixup_filename(file), line);
1200 }
1201
1202 /*
1203 * Find the previously acquired lock, but ignore interlocks.
1204 */
1205 plock = &lock_list->ll_children[lock_list->ll_count - 1];
1206 if (interlock != NULL && plock->li_lock == interlock) {
1207 if (lock_list->ll_count > 1)
1208 plock =
1209 &lock_list->ll_children[lock_list->ll_count - 2];
1210 else {
1211 lle = lock_list->ll_next;
1212
1213 /*
1214 * The interlock is the only lock we hold, so
1215 * simply return.
1216 */
1217 if (lle == NULL)
1218 return;
1219 plock = &lle->ll_children[lle->ll_count - 1];
1220 }
1221 }
1222
1223 /*
1224 * Try to perform most checks without a lock. If this succeeds we
1225 * can skip acquiring the lock and return success. Otherwise we redo
1226 * the check with the lock held to handle races with concurrent updates.
1227 */
1228 w1 = plock->li_lock->lo_witness;
1229 if (witness_lock_order_check(w1, w))
1230 return;
1231
1232 mtx_lock_spin(&w_mtx);
1233 if (witness_lock_order_check(w1, w)) {
1234 mtx_unlock_spin(&w_mtx);
1235 return;
1236 }
1237 witness_lock_order_add(w1, w);
1238
1239 /*
1240 * Check for duplicate locks of the same type. Note that we only
1241 * have to check for this on the last lock we just acquired. Any
1242 * other cases will be caught as lock order violations.
1243 */
1244 if (w1 == w) {
1245 i = w->w_index;
1246 if (!(lock->lo_flags & LO_DUPOK) && !(flags & LOP_DUPOK) &&
1247 !(w_rmatrix[i][i] & WITNESS_REVERSAL)) {
1248 w_rmatrix[i][i] |= WITNESS_REVERSAL;
1249 w->w_reversed = 1;
1250 mtx_unlock_spin(&w_mtx);
1251 witness_output(
1252 "acquiring duplicate lock of same type: \"%s\"\n",
1253 w->w_name);
1254 witness_output(" 1st %s @ %s:%d\n", plock->li_lock->lo_name,
1255 fixup_filename(plock->li_file), plock->li_line);
1256 witness_output(" 2nd %s @ %s:%d\n", lock->lo_name,
1257 fixup_filename(file), line);
1258 witness_debugger(1, __func__);
1259 } else
1260 mtx_unlock_spin(&w_mtx);
1261 return;
1262 }
1263 mtx_assert(&w_mtx, MA_OWNED);
1264
1265 /*
1266 * If we know that the lock we are acquiring comes after
1267 * the lock we most recently acquired in the lock order tree,
1268 * then there is no need for any further checks.
1269 */
1270 if (isitmychild(w1, w))
1271 goto out;
1272
1273 for (j = 0, lle = lock_list; lle != NULL; lle = lle->ll_next) {
1274 for (i = lle->ll_count - 1; i >= 0; i--, j++) {
1275 struct stack pstack;
1276 bool pstackv, trace;
1277
1278 MPASS(j < LOCK_CHILDCOUNT * LOCK_NCHILDREN);
1279 lock1 = &lle->ll_children[i];
1280
1281 /*
1282 * Ignore the interlock.
1283 */
1284 if (interlock == lock1->li_lock)
1285 continue;
1286
1287 /*
1288 * If this lock doesn't undergo witness checking,
1289 * then skip it.
1290 */
1291 w1 = lock1->li_lock->lo_witness;
1292 if (w1 == NULL) {
1293 KASSERT((lock1->li_lock->lo_flags & LO_WITNESS) == 0,
1294 ("lock missing witness structure"));
1295 continue;
1296 }
1297
1298 /*
1299 * If we are locking Giant and this is a sleepable
1300 * lock, then skip it.
1301 */
1302 if ((lock1->li_flags & LI_SLEEPABLE) != 0 &&
1303 lock == &Giant.lock_object)
1304 continue;
1305
1306 /*
1307 * If we are locking a sleepable lock and this lock
1308 * is Giant, then skip it.
1309 */
1310 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1311 (flags & LOP_NOSLEEP) == 0 &&
1312 lock1->li_lock == &Giant.lock_object)
1313 continue;
1314
1315 /*
1316 * If we are locking a sleepable lock and this lock
1317 * isn't sleepable, we want to treat it as a lock
1318 * order violation to enfore a general lock order of
1319 * sleepable locks before non-sleepable locks.
1320 */
1321 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1322 (flags & LOP_NOSLEEP) == 0 &&
1323 (lock1->li_flags & LI_SLEEPABLE) == 0)
1324 goto reversal;
1325
1326 /*
1327 * If we are locking Giant and this is a non-sleepable
1328 * lock, then treat it as a reversal.
1329 */
1330 if ((lock1->li_flags & LI_SLEEPABLE) == 0 &&
1331 lock == &Giant.lock_object)
1332 goto reversal;
1333
1334 /*
1335 * Check the lock order hierarchy for a reveresal.
1336 */
1337 if (!isitmydescendant(w, w1))
1338 continue;
1339 reversal:
1340
1341 /*
1342 * We have a lock order violation, check to see if it
1343 * is allowed or has already been yelled about.
1344 */
1345
1346 /* Bail if this violation is known */
1347 if (w_rmatrix[w1->w_index][w->w_index] & WITNESS_REVERSAL)
1348 goto out;
1349
1350 /* Record this as a violation */
1351 w_rmatrix[w1->w_index][w->w_index] |= WITNESS_REVERSAL;
1352 w_rmatrix[w->w_index][w1->w_index] |= WITNESS_REVERSAL;
1353 w->w_reversed = w1->w_reversed = 1;
1354 witness_increment_graph_generation();
1355
1356 /*
1357 * If the lock order is blessed, bail before logging
1358 * anything. We don't look for other lock order
1359 * violations though, which may be a bug.
1360 */
1361 if (blessed(w, w1))
1362 goto out;
1363
1364 trace = atomic_load_int(&witness_trace);
1365 if (trace) {
1366 struct witness_lock_order_data *data;
1367
1368 pstackv = false;
1369 data = witness_lock_order_get(w, w1);
1370 if (data != NULL) {
1371 stack_copy(&data->wlod_stack,
1372 &pstack);
1373 pstackv = true;
1374 }
1375 }
1376 mtx_unlock_spin(&w_mtx);
1377
1378 #ifdef WITNESS_NO_VNODE
1379 /*
1380 * There are known LORs between VNODE locks. They are
1381 * not an indication of a bug. VNODE locks are flagged
1382 * as such (LO_IS_VNODE) and we don't yell if the LOR
1383 * is between 2 VNODE locks.
1384 */
1385 if ((lock->lo_flags & LO_IS_VNODE) != 0 &&
1386 (lock1->li_lock->lo_flags & LO_IS_VNODE) != 0)
1387 return;
1388 #endif
1389
1390 /*
1391 * Ok, yell about it.
1392 */
1393 if ((lock->lo_flags & LO_SLEEPABLE) != 0 &&
1394 (flags & LOP_NOSLEEP) == 0 &&
1395 (lock1->li_flags & LI_SLEEPABLE) == 0)
1396 witness_output(
1397 "lock order reversal: (sleepable after non-sleepable)\n");
1398 else if ((lock1->li_flags & LI_SLEEPABLE) == 0
1399 && lock == &Giant.lock_object)
1400 witness_output(
1401 "lock order reversal: (Giant after non-sleepable)\n");
1402 else
1403 witness_output("lock order reversal:\n");
1404
1405 /*
1406 * Try to locate an earlier lock with
1407 * witness w in our list.
1408 */
1409 do {
1410 lock2 = &lle->ll_children[i];
1411 MPASS(lock2->li_lock != NULL);
1412 if (lock2->li_lock->lo_witness == w)
1413 break;
1414 if (i == 0 && lle->ll_next != NULL) {
1415 lle = lle->ll_next;
1416 i = lle->ll_count - 1;
1417 MPASS(i >= 0 && i < LOCK_NCHILDREN);
1418 } else
1419 i--;
1420 } while (i >= 0);
1421 if (i < 0) {
1422 witness_output(" 1st %p %s (%s, %s) @ %s:%d\n",
1423 lock1->li_lock, lock1->li_lock->lo_name,
1424 w1->w_name, w1->w_class->lc_name,
1425 fixup_filename(lock1->li_file),
1426 lock1->li_line);
1427 witness_output(" 2nd %p %s (%s, %s) @ %s:%d\n",
1428 lock, lock->lo_name, w->w_name,
1429 w->w_class->lc_name, fixup_filename(file),
1430 line);
1431 } else {
1432 struct witness *w2 = lock2->li_lock->lo_witness;
1433
1434 witness_output(" 1st %p %s (%s, %s) @ %s:%d\n",
1435 lock2->li_lock, lock2->li_lock->lo_name,
1436 w2->w_name, w2->w_class->lc_name,
1437 fixup_filename(lock2->li_file),
1438 lock2->li_line);
1439 witness_output(" 2nd %p %s (%s, %s) @ %s:%d\n",
1440 lock1->li_lock, lock1->li_lock->lo_name,
1441 w1->w_name, w1->w_class->lc_name,
1442 fixup_filename(lock1->li_file),
1443 lock1->li_line);
1444 witness_output(" 3rd %p %s (%s, %s) @ %s:%d\n", lock,
1445 lock->lo_name, w->w_name,
1446 w->w_class->lc_name, fixup_filename(file),
1447 line);
1448 }
1449 if (trace) {
1450 char buf[64];
1451 struct sbuf sb;
1452
1453 sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1454 sbuf_set_drain(&sb, witness_output_drain,
1455 NULL);
1456
1457 if (pstackv) {
1458 sbuf_printf(&sb,
1459 "lock order %s -> %s established at:\n",
1460 w->w_name, w1->w_name);
1461 stack_sbuf_print_flags(&sb, &pstack,
1462 M_NOWAIT, STACK_SBUF_FMT_LONG);
1463 }
1464
1465 sbuf_printf(&sb,
1466 "lock order %s -> %s attempted at:\n",
1467 w1->w_name, w->w_name);
1468 stack_save(&pstack);
1469 stack_sbuf_print_flags(&sb, &pstack, M_NOWAIT,
1470 STACK_SBUF_FMT_LONG);
1471
1472 sbuf_finish(&sb);
1473 sbuf_delete(&sb);
1474 }
1475 witness_enter_debugger(__func__);
1476 return;
1477 }
1478 }
1479
1480 /*
1481 * If requested, build a new lock order. However, don't build a new
1482 * relationship between a sleepable lock and Giant if it is in the
1483 * wrong direction. The correct lock order is that sleepable locks
1484 * always come before Giant.
1485 */
1486 if (flags & LOP_NEWORDER &&
1487 !(plock->li_lock == &Giant.lock_object &&
1488 (lock->lo_flags & LO_SLEEPABLE) != 0 &&
1489 (flags & LOP_NOSLEEP) == 0)) {
1490 CTR3(KTR_WITNESS, "%s: adding %s as a child of %s", __func__,
1491 w->w_name, plock->li_lock->lo_witness->w_name);
1492 itismychild(plock->li_lock->lo_witness, w);
1493 }
1494 out:
1495 mtx_unlock_spin(&w_mtx);
1496 }
1497
1498 void
witness_lock(struct lock_object * lock,int flags,const char * file,int line)1499 witness_lock(struct lock_object *lock, int flags, const char *file, int line)
1500 {
1501 struct lock_list_entry **lock_list, *lle;
1502 struct lock_instance *instance;
1503 struct witness *w;
1504 struct thread *td;
1505
1506 if (witness_cold || witness_watch == -1 || lock->lo_witness == NULL ||
1507 KERNEL_PANICKED())
1508 return;
1509 w = lock->lo_witness;
1510 td = curthread;
1511
1512 /* Determine lock list for this lock. */
1513 if (LOCK_CLASS(lock)->lc_flags & LC_SLEEPLOCK)
1514 lock_list = &td->td_sleeplocks;
1515 else
1516 lock_list = PCPU_PTR(spinlocks);
1517
1518 /* Update per-witness last file and line acquire. */
1519 w->w_file = file;
1520 w->w_line = line;
1521
1522 /* Check to see if we are recursing on a lock we already own. */
1523 instance = find_instance(*lock_list, lock);
1524 if (instance != NULL) {
1525 instance->li_flags++;
1526 CTR4(KTR_WITNESS, "%s: pid %d recursed on %s r=%d", __func__,
1527 td->td_proc->p_pid, lock->lo_name,
1528 instance->li_flags & LI_RECURSEMASK);
1529 return;
1530 }
1531
1532 /* Find the next open lock instance in the list and fill it. */
1533 lle = *lock_list;
1534 if (lle == NULL || lle->ll_count == LOCK_NCHILDREN) {
1535 lle = witness_lock_list_get();
1536 if (lle == NULL)
1537 return;
1538 lle->ll_next = *lock_list;
1539 CTR3(KTR_WITNESS, "%s: pid %d added lle %p", __func__,
1540 td->td_proc->p_pid, lle);
1541 *lock_list = lle;
1542 }
1543 instance = &lle->ll_children[lle->ll_count++];
1544 instance->li_lock = lock;
1545 instance->li_line = line;
1546 instance->li_file = file;
1547 instance->li_flags = 0;
1548 if ((flags & LOP_EXCLUSIVE) != 0)
1549 instance->li_flags |= LI_EXCLUSIVE;
1550 if ((lock->lo_flags & LO_SLEEPABLE) != 0 && (flags & LOP_NOSLEEP) == 0)
1551 instance->li_flags |= LI_SLEEPABLE;
1552 CTR4(KTR_WITNESS, "%s: pid %d added %s as lle[%d]", __func__,
1553 td->td_proc->p_pid, lock->lo_name, lle->ll_count - 1);
1554 }
1555
1556 void
witness_upgrade(struct lock_object * lock,int flags,const char * file,int line)1557 witness_upgrade(struct lock_object *lock, int flags, const char *file, int line)
1558 {
1559 struct lock_instance *instance;
1560 struct lock_class *class;
1561
1562 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1563 if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
1564 return;
1565 class = LOCK_CLASS(lock);
1566 if (witness_watch) {
1567 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1568 kassert_panic(
1569 "upgrade of non-upgradable lock (%s) %s @ %s:%d",
1570 class->lc_name, lock->lo_name,
1571 fixup_filename(file), line);
1572 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1573 kassert_panic(
1574 "upgrade of non-sleep lock (%s) %s @ %s:%d",
1575 class->lc_name, lock->lo_name,
1576 fixup_filename(file), line);
1577 }
1578 instance = find_instance(curthread->td_sleeplocks, lock);
1579 if (instance == NULL) {
1580 kassert_panic("upgrade of unlocked lock (%s) %s @ %s:%d",
1581 class->lc_name, lock->lo_name,
1582 fixup_filename(file), line);
1583 return;
1584 }
1585 if (witness_watch) {
1586 if ((instance->li_flags & LI_EXCLUSIVE) != 0)
1587 kassert_panic(
1588 "upgrade of exclusive lock (%s) %s @ %s:%d",
1589 class->lc_name, lock->lo_name,
1590 fixup_filename(file), line);
1591 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1592 kassert_panic(
1593 "upgrade of recursed lock (%s) %s r=%d @ %s:%d",
1594 class->lc_name, lock->lo_name,
1595 instance->li_flags & LI_RECURSEMASK,
1596 fixup_filename(file), line);
1597 }
1598 instance->li_flags |= LI_EXCLUSIVE;
1599 }
1600
1601 void
witness_downgrade(struct lock_object * lock,int flags,const char * file,int line)1602 witness_downgrade(struct lock_object *lock, int flags, const char *file,
1603 int line)
1604 {
1605 struct lock_instance *instance;
1606 struct lock_class *class;
1607
1608 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
1609 if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
1610 return;
1611 class = LOCK_CLASS(lock);
1612 if (witness_watch) {
1613 if ((lock->lo_flags & LO_UPGRADABLE) == 0)
1614 kassert_panic(
1615 "downgrade of non-upgradable lock (%s) %s @ %s:%d",
1616 class->lc_name, lock->lo_name,
1617 fixup_filename(file), line);
1618 if ((class->lc_flags & LC_SLEEPLOCK) == 0)
1619 kassert_panic(
1620 "downgrade of non-sleep lock (%s) %s @ %s:%d",
1621 class->lc_name, lock->lo_name,
1622 fixup_filename(file), line);
1623 }
1624 instance = find_instance(curthread->td_sleeplocks, lock);
1625 if (instance == NULL) {
1626 kassert_panic("downgrade of unlocked lock (%s) %s @ %s:%d",
1627 class->lc_name, lock->lo_name,
1628 fixup_filename(file), line);
1629 return;
1630 }
1631 if (witness_watch) {
1632 if ((instance->li_flags & LI_EXCLUSIVE) == 0)
1633 kassert_panic(
1634 "downgrade of shared lock (%s) %s @ %s:%d",
1635 class->lc_name, lock->lo_name,
1636 fixup_filename(file), line);
1637 if ((instance->li_flags & LI_RECURSEMASK) != 0)
1638 kassert_panic(
1639 "downgrade of recursed lock (%s) %s r=%d @ %s:%d",
1640 class->lc_name, lock->lo_name,
1641 instance->li_flags & LI_RECURSEMASK,
1642 fixup_filename(file), line);
1643 }
1644 instance->li_flags &= ~LI_EXCLUSIVE;
1645 }
1646
1647 void
witness_unlock(struct lock_object * lock,int flags,const char * file,int line)1648 witness_unlock(struct lock_object *lock, int flags, const char *file, int line)
1649 {
1650 struct lock_list_entry **lock_list, *lle;
1651 struct lock_instance *instance;
1652 struct lock_class *class;
1653 struct thread *td;
1654 register_t s;
1655 int i, j;
1656
1657 if (witness_cold || lock->lo_witness == NULL || KERNEL_PANICKED())
1658 return;
1659 td = curthread;
1660 class = LOCK_CLASS(lock);
1661
1662 /* Find lock instance associated with this lock. */
1663 if (class->lc_flags & LC_SLEEPLOCK)
1664 lock_list = &td->td_sleeplocks;
1665 else
1666 lock_list = PCPU_PTR(spinlocks);
1667 lle = *lock_list;
1668 for (; *lock_list != NULL; lock_list = &(*lock_list)->ll_next)
1669 for (i = 0; i < (*lock_list)->ll_count; i++) {
1670 instance = &(*lock_list)->ll_children[i];
1671 if (instance->li_lock == lock)
1672 goto found;
1673 }
1674
1675 /*
1676 * When disabling WITNESS through witness_watch we could end up in
1677 * having registered locks in the td_sleeplocks queue.
1678 * We have to make sure we flush these queues, so just search for
1679 * eventual register locks and remove them.
1680 */
1681 if (witness_watch > 0) {
1682 kassert_panic("lock (%s) %s not locked @ %s:%d", class->lc_name,
1683 lock->lo_name, fixup_filename(file), line);
1684 return;
1685 } else {
1686 return;
1687 }
1688 found:
1689
1690 /* First, check for shared/exclusive mismatches. */
1691 if ((instance->li_flags & LI_EXCLUSIVE) != 0 && witness_watch > 0 &&
1692 (flags & LOP_EXCLUSIVE) == 0) {
1693 witness_output("shared unlock of (%s) %s @ %s:%d\n",
1694 class->lc_name, lock->lo_name, fixup_filename(file), line);
1695 witness_output("while exclusively locked from %s:%d\n",
1696 fixup_filename(instance->li_file), instance->li_line);
1697 kassert_panic("excl->ushare");
1698 }
1699 if ((instance->li_flags & LI_EXCLUSIVE) == 0 && witness_watch > 0 &&
1700 (flags & LOP_EXCLUSIVE) != 0) {
1701 witness_output("exclusive unlock of (%s) %s @ %s:%d\n",
1702 class->lc_name, lock->lo_name, fixup_filename(file), line);
1703 witness_output("while share locked from %s:%d\n",
1704 fixup_filename(instance->li_file),
1705 instance->li_line);
1706 kassert_panic("share->uexcl");
1707 }
1708 /* If we are recursed, unrecurse. */
1709 if ((instance->li_flags & LI_RECURSEMASK) > 0) {
1710 CTR4(KTR_WITNESS, "%s: pid %d unrecursed on %s r=%d", __func__,
1711 td->td_proc->p_pid, instance->li_lock->lo_name,
1712 instance->li_flags);
1713 instance->li_flags--;
1714 return;
1715 }
1716 /* The lock is now being dropped, check for NORELEASE flag */
1717 if ((instance->li_flags & LI_NORELEASE) != 0 && witness_watch > 0) {
1718 witness_output("forbidden unlock of (%s) %s @ %s:%d\n",
1719 class->lc_name, lock->lo_name, fixup_filename(file), line);
1720 kassert_panic("lock marked norelease");
1721 }
1722
1723 /* Otherwise, remove this item from the list. */
1724 s = intr_disable();
1725 CTR4(KTR_WITNESS, "%s: pid %d removed %s from lle[%d]", __func__,
1726 td->td_proc->p_pid, instance->li_lock->lo_name,
1727 (*lock_list)->ll_count - 1);
1728 for (j = i; j < (*lock_list)->ll_count - 1; j++)
1729 (*lock_list)->ll_children[j] =
1730 (*lock_list)->ll_children[j + 1];
1731 (*lock_list)->ll_count--;
1732 intr_restore(s);
1733
1734 /*
1735 * In order to reduce contention on w_mtx, we want to keep always an
1736 * head object into lists so that frequent allocation from the
1737 * free witness pool (and subsequent locking) is avoided.
1738 * In order to maintain the current code simple, when the head
1739 * object is totally unloaded it means also that we do not have
1740 * further objects in the list, so the list ownership needs to be
1741 * hand over to another object if the current head needs to be freed.
1742 */
1743 if ((*lock_list)->ll_count == 0) {
1744 if (*lock_list == lle) {
1745 if (lle->ll_next == NULL)
1746 return;
1747 } else
1748 lle = *lock_list;
1749 *lock_list = lle->ll_next;
1750 CTR3(KTR_WITNESS, "%s: pid %d removed lle %p", __func__,
1751 td->td_proc->p_pid, lle);
1752 witness_lock_list_free(lle);
1753 }
1754 }
1755
1756 void
witness_thread_exit(struct thread * td)1757 witness_thread_exit(struct thread *td)
1758 {
1759 struct lock_list_entry *lle;
1760 int i, n;
1761
1762 lle = td->td_sleeplocks;
1763 if (lle == NULL || KERNEL_PANICKED())
1764 return;
1765 if (lle->ll_count != 0) {
1766 for (n = 0; lle != NULL; lle = lle->ll_next)
1767 for (i = lle->ll_count - 1; i >= 0; i--) {
1768 if (n == 0)
1769 witness_output(
1770 "Thread %p exiting with the following locks held:\n", td);
1771 n++;
1772 witness_list_lock(&lle->ll_children[i],
1773 witness_output);
1774
1775 }
1776 kassert_panic(
1777 "Thread %p cannot exit while holding sleeplocks\n", td);
1778 }
1779 witness_lock_list_free(lle);
1780 }
1781
1782 /*
1783 * Warn if any locks other than 'lock' are held. Flags can be passed in to
1784 * exempt Giant and sleepable locks from the checks as well. If any
1785 * non-exempt locks are held, then a supplied message is printed to the
1786 * output channel along with a list of the offending locks. If indicated in the
1787 * flags then a failure results in a panic as well.
1788 */
1789 int
witness_warn(int flags,struct lock_object * lock,const char * fmt,...)1790 witness_warn(int flags, struct lock_object *lock, const char *fmt, ...)
1791 {
1792 struct lock_list_entry *lock_list, *lle;
1793 struct lock_instance *lock1;
1794 struct thread *td;
1795 va_list ap;
1796 int i, n;
1797
1798 if (witness_cold || witness_watch < 1 || KERNEL_PANICKED())
1799 return (0);
1800 n = 0;
1801 td = curthread;
1802 for (lle = td->td_sleeplocks; lle != NULL; lle = lle->ll_next)
1803 for (i = lle->ll_count - 1; i >= 0; i--) {
1804 lock1 = &lle->ll_children[i];
1805 if (lock1->li_lock == lock)
1806 continue;
1807 if (flags & WARN_GIANTOK &&
1808 lock1->li_lock == &Giant.lock_object)
1809 continue;
1810 if (flags & WARN_SLEEPOK &&
1811 (lock1->li_flags & LI_SLEEPABLE) != 0)
1812 continue;
1813 if (n == 0) {
1814 va_start(ap, fmt);
1815 vprintf(fmt, ap);
1816 va_end(ap);
1817 printf(" with the following %slocks held:\n",
1818 (flags & WARN_SLEEPOK) != 0 ?
1819 "non-sleepable " : "");
1820 }
1821 n++;
1822 witness_list_lock(lock1, printf);
1823 }
1824
1825 /*
1826 * Pin the thread in order to avoid problems with thread migration.
1827 * Once that all verifies are passed about spinlocks ownership,
1828 * the thread is in a safe path and it can be unpinned.
1829 */
1830 sched_pin();
1831 lock_list = PCPU_GET(spinlocks);
1832 if (lock_list != NULL && lock_list->ll_count != 0) {
1833 sched_unpin();
1834
1835 /*
1836 * We should only have one spinlock and as long as
1837 * the flags cannot match for this locks class,
1838 * check if the first spinlock is the one curthread
1839 * should hold.
1840 */
1841 lock1 = &lock_list->ll_children[lock_list->ll_count - 1];
1842 if (lock_list->ll_count == 1 && lock_list->ll_next == NULL &&
1843 lock1->li_lock == lock && n == 0)
1844 return (0);
1845
1846 va_start(ap, fmt);
1847 vprintf(fmt, ap);
1848 va_end(ap);
1849 printf(" with the following %slocks held:\n",
1850 (flags & WARN_SLEEPOK) != 0 ? "non-sleepable " : "");
1851 n += witness_list_locks(&lock_list, printf);
1852 } else
1853 sched_unpin();
1854 if (flags & WARN_PANIC && n)
1855 kassert_panic("%s", __func__);
1856 else
1857 witness_debugger(n, __func__);
1858 return (n);
1859 }
1860
1861 const char *
witness_file(struct lock_object * lock)1862 witness_file(struct lock_object *lock)
1863 {
1864 struct witness *w;
1865
1866 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1867 return ("?");
1868 w = lock->lo_witness;
1869 return (w->w_file);
1870 }
1871
1872 int
witness_line(struct lock_object * lock)1873 witness_line(struct lock_object *lock)
1874 {
1875 struct witness *w;
1876
1877 if (witness_cold || witness_watch < 1 || lock->lo_witness == NULL)
1878 return (0);
1879 w = lock->lo_witness;
1880 return (w->w_line);
1881 }
1882
1883 static struct witness *
enroll(const char * description,struct lock_class * lock_class)1884 enroll(const char *description, struct lock_class *lock_class)
1885 {
1886 struct witness *w;
1887
1888 MPASS(description != NULL);
1889
1890 if (witness_watch == -1 || KERNEL_PANICKED())
1891 return (NULL);
1892 if ((lock_class->lc_flags & LC_SPINLOCK)) {
1893 if (witness_skipspin)
1894 return (NULL);
1895 } else if ((lock_class->lc_flags & LC_SLEEPLOCK) == 0) {
1896 kassert_panic("lock class %s is not sleep or spin",
1897 lock_class->lc_name);
1898 return (NULL);
1899 }
1900
1901 mtx_lock_spin(&w_mtx);
1902 w = witness_hash_get(description);
1903 if (w)
1904 goto found;
1905 if ((w = witness_get()) == NULL)
1906 return (NULL);
1907 MPASS(strlen(description) < MAX_W_NAME);
1908 strcpy(w->w_name, description);
1909 w->w_class = lock_class;
1910 w->w_refcount = 1;
1911 STAILQ_INSERT_HEAD(&w_all, w, w_list);
1912 if (lock_class->lc_flags & LC_SPINLOCK) {
1913 STAILQ_INSERT_HEAD(&w_spin, w, w_typelist);
1914 w_spin_cnt++;
1915 } else if (lock_class->lc_flags & LC_SLEEPLOCK) {
1916 STAILQ_INSERT_HEAD(&w_sleep, w, w_typelist);
1917 w_sleep_cnt++;
1918 }
1919
1920 /* Insert new witness into the hash */
1921 witness_hash_put(w);
1922 witness_increment_graph_generation();
1923 mtx_unlock_spin(&w_mtx);
1924 return (w);
1925 found:
1926 w->w_refcount++;
1927 if (w->w_refcount == 1)
1928 w->w_class = lock_class;
1929 mtx_unlock_spin(&w_mtx);
1930 if (lock_class != w->w_class)
1931 kassert_panic(
1932 "lock (%s) %s does not match earlier (%s) lock",
1933 description, lock_class->lc_name,
1934 w->w_class->lc_name);
1935 return (w);
1936 }
1937
1938 static void
depart(struct witness * w)1939 depart(struct witness *w)
1940 {
1941 MPASS(w->w_refcount == 0);
1942 if (w->w_class->lc_flags & LC_SLEEPLOCK) {
1943 w_sleep_cnt--;
1944 } else {
1945 w_spin_cnt--;
1946 }
1947 /*
1948 * Set file to NULL as it may point into a loadable module.
1949 */
1950 w->w_file = NULL;
1951 w->w_line = 0;
1952 witness_increment_graph_generation();
1953 }
1954
1955 static void
adopt(struct witness * parent,struct witness * child)1956 adopt(struct witness *parent, struct witness *child)
1957 {
1958 int pi, ci, i, j;
1959
1960 if (witness_cold == 0)
1961 mtx_assert(&w_mtx, MA_OWNED);
1962
1963 /* If the relationship is already known, there's no work to be done. */
1964 if (isitmychild(parent, child))
1965 return;
1966
1967 /* When the structure of the graph changes, bump up the generation. */
1968 witness_increment_graph_generation();
1969
1970 /*
1971 * The hard part ... create the direct relationship, then propagate all
1972 * indirect relationships.
1973 */
1974 pi = parent->w_index;
1975 ci = child->w_index;
1976 WITNESS_INDEX_ASSERT(pi);
1977 WITNESS_INDEX_ASSERT(ci);
1978 MPASS(pi != ci);
1979 w_rmatrix[pi][ci] |= WITNESS_PARENT;
1980 w_rmatrix[ci][pi] |= WITNESS_CHILD;
1981
1982 /*
1983 * If parent was not already an ancestor of child,
1984 * then we increment the descendant and ancestor counters.
1985 */
1986 if ((w_rmatrix[pi][ci] & WITNESS_ANCESTOR) == 0) {
1987 parent->w_num_descendants++;
1988 child->w_num_ancestors++;
1989 }
1990
1991 /*
1992 * Find each ancestor of 'pi'. Note that 'pi' itself is counted as
1993 * an ancestor of 'pi' during this loop.
1994 */
1995 for (i = 1; i <= w_max_used_index; i++) {
1996 if ((w_rmatrix[i][pi] & WITNESS_ANCESTOR_MASK) == 0 &&
1997 (i != pi))
1998 continue;
1999
2000 /* Find each descendant of 'i' and mark it as a descendant. */
2001 for (j = 1; j <= w_max_used_index; j++) {
2002 /*
2003 * Skip children that are already marked as
2004 * descendants of 'i'.
2005 */
2006 if (w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK)
2007 continue;
2008
2009 /*
2010 * We are only interested in descendants of 'ci'. Note
2011 * that 'ci' itself is counted as a descendant of 'ci'.
2012 */
2013 if ((w_rmatrix[ci][j] & WITNESS_ANCESTOR_MASK) == 0 &&
2014 (j != ci))
2015 continue;
2016 w_rmatrix[i][j] |= WITNESS_ANCESTOR;
2017 w_rmatrix[j][i] |= WITNESS_DESCENDANT;
2018 w_data[i].w_num_descendants++;
2019 w_data[j].w_num_ancestors++;
2020
2021 /*
2022 * Make sure we aren't marking a node as both an
2023 * ancestor and descendant. We should have caught
2024 * this as a lock order reversal earlier.
2025 */
2026 if ((w_rmatrix[i][j] & WITNESS_ANCESTOR_MASK) &&
2027 (w_rmatrix[i][j] & WITNESS_DESCENDANT_MASK)) {
2028 printf("witness rmatrix paradox! [%d][%d]=%d "
2029 "both ancestor and descendant\n",
2030 i, j, w_rmatrix[i][j]);
2031 kdb_backtrace();
2032 printf("Witness disabled.\n");
2033 witness_watch = -1;
2034 }
2035 if ((w_rmatrix[j][i] & WITNESS_ANCESTOR_MASK) &&
2036 (w_rmatrix[j][i] & WITNESS_DESCENDANT_MASK)) {
2037 printf("witness rmatrix paradox! [%d][%d]=%d "
2038 "both ancestor and descendant\n",
2039 j, i, w_rmatrix[j][i]);
2040 kdb_backtrace();
2041 printf("Witness disabled.\n");
2042 witness_watch = -1;
2043 }
2044 }
2045 }
2046 }
2047
2048 static void
itismychild(struct witness * parent,struct witness * child)2049 itismychild(struct witness *parent, struct witness *child)
2050 {
2051 int unlocked;
2052
2053 MPASS(child != NULL && parent != NULL);
2054 if (witness_cold == 0)
2055 mtx_assert(&w_mtx, MA_OWNED);
2056
2057 if (!witness_lock_type_equal(parent, child)) {
2058 if (witness_cold == 0) {
2059 unlocked = 1;
2060 mtx_unlock_spin(&w_mtx);
2061 } else {
2062 unlocked = 0;
2063 }
2064 kassert_panic(
2065 "%s: parent \"%s\" (%s) and child \"%s\" (%s) are not "
2066 "the same lock type", __func__, parent->w_name,
2067 parent->w_class->lc_name, child->w_name,
2068 child->w_class->lc_name);
2069 if (unlocked)
2070 mtx_lock_spin(&w_mtx);
2071 }
2072 adopt(parent, child);
2073 }
2074
2075 /*
2076 * Generic code for the isitmy*() functions. The rmask parameter is the
2077 * expected relationship of w1 to w2.
2078 */
2079 static int
_isitmyx(struct witness * w1,struct witness * w2,int rmask,const char * fname)2080 _isitmyx(struct witness *w1, struct witness *w2, int rmask, const char *fname)
2081 {
2082 unsigned char r1, r2;
2083 int i1, i2;
2084
2085 i1 = w1->w_index;
2086 i2 = w2->w_index;
2087 WITNESS_INDEX_ASSERT(i1);
2088 WITNESS_INDEX_ASSERT(i2);
2089 r1 = w_rmatrix[i1][i2] & WITNESS_RELATED_MASK;
2090 r2 = w_rmatrix[i2][i1] & WITNESS_RELATED_MASK;
2091
2092 /* The flags on one better be the inverse of the flags on the other */
2093 if (!((WITNESS_ATOD(r1) == r2 && WITNESS_DTOA(r2) == r1) ||
2094 (WITNESS_DTOA(r1) == r2 && WITNESS_ATOD(r2) == r1))) {
2095 /* Don't squawk if we're potentially racing with an update. */
2096 if (!mtx_owned(&w_mtx))
2097 return (0);
2098 printf("%s: rmatrix mismatch between %s (index %d) and %s "
2099 "(index %d): w_rmatrix[%d][%d] == %hhx but "
2100 "w_rmatrix[%d][%d] == %hhx\n",
2101 fname, w1->w_name, i1, w2->w_name, i2, i1, i2, r1,
2102 i2, i1, r2);
2103 kdb_backtrace();
2104 printf("Witness disabled.\n");
2105 witness_watch = -1;
2106 }
2107 return (r1 & rmask);
2108 }
2109
2110 /*
2111 * Checks if @child is a direct child of @parent.
2112 */
2113 static int
isitmychild(struct witness * parent,struct witness * child)2114 isitmychild(struct witness *parent, struct witness *child)
2115 {
2116 return (_isitmyx(parent, child, WITNESS_PARENT, __func__));
2117 }
2118
2119 /*
2120 * Checks if @descendant is a direct or inderect descendant of @ancestor.
2121 */
2122 static int
isitmydescendant(struct witness * ancestor,struct witness * descendant)2123 isitmydescendant(struct witness *ancestor, struct witness *descendant)
2124 {
2125 return (_isitmyx(ancestor, descendant, WITNESS_ANCESTOR_MASK,
2126 __func__));
2127 }
2128
2129 static int
blessed(struct witness * w1,struct witness * w2)2130 blessed(struct witness *w1, struct witness *w2)
2131 {
2132 int i;
2133 struct witness_blessed *b;
2134
2135 for (i = 0; i < nitems(blessed_list); i++) {
2136 b = &blessed_list[i];
2137 if (strcmp(w1->w_name, b->b_lock1) == 0) {
2138 if (strcmp(w2->w_name, b->b_lock2) == 0)
2139 return (1);
2140 continue;
2141 }
2142 if (strcmp(w1->w_name, b->b_lock2) == 0)
2143 if (strcmp(w2->w_name, b->b_lock1) == 0)
2144 return (1);
2145 }
2146 return (0);
2147 }
2148
2149 static struct witness *
witness_get(void)2150 witness_get(void)
2151 {
2152 struct witness *w;
2153 int index;
2154
2155 if (witness_cold == 0)
2156 mtx_assert(&w_mtx, MA_OWNED);
2157
2158 if (witness_watch == -1) {
2159 mtx_unlock_spin(&w_mtx);
2160 return (NULL);
2161 }
2162 if (STAILQ_EMPTY(&w_free)) {
2163 witness_watch = -1;
2164 mtx_unlock_spin(&w_mtx);
2165 printf("WITNESS: unable to allocate a new witness object\n");
2166 return (NULL);
2167 }
2168 w = STAILQ_FIRST(&w_free);
2169 STAILQ_REMOVE_HEAD(&w_free, w_list);
2170 w_free_cnt--;
2171 index = w->w_index;
2172 MPASS(index > 0 && index == w_max_used_index + 1 &&
2173 index < witness_count);
2174 bzero(w, sizeof(*w));
2175 w->w_index = index;
2176 if (index > w_max_used_index)
2177 w_max_used_index = index;
2178 return (w);
2179 }
2180
2181 static void
witness_free(struct witness * w)2182 witness_free(struct witness *w)
2183 {
2184 STAILQ_INSERT_HEAD(&w_free, w, w_list);
2185 w_free_cnt++;
2186 }
2187
2188 static struct lock_list_entry *
witness_lock_list_get(void)2189 witness_lock_list_get(void)
2190 {
2191 struct lock_list_entry *lle;
2192
2193 if (witness_watch == -1)
2194 return (NULL);
2195 mtx_lock_spin(&w_mtx);
2196 lle = w_lock_list_free;
2197 if (lle == NULL) {
2198 witness_watch = -1;
2199 mtx_unlock_spin(&w_mtx);
2200 printf("%s: witness exhausted\n", __func__);
2201 return (NULL);
2202 }
2203 w_lock_list_free = lle->ll_next;
2204 mtx_unlock_spin(&w_mtx);
2205 bzero(lle, sizeof(*lle));
2206 return (lle);
2207 }
2208
2209 static void
witness_lock_list_free(struct lock_list_entry * lle)2210 witness_lock_list_free(struct lock_list_entry *lle)
2211 {
2212 mtx_lock_spin(&w_mtx);
2213 lle->ll_next = w_lock_list_free;
2214 w_lock_list_free = lle;
2215 mtx_unlock_spin(&w_mtx);
2216 }
2217
2218 static struct lock_instance *
find_instance(struct lock_list_entry * list,const struct lock_object * lock)2219 find_instance(struct lock_list_entry *list, const struct lock_object *lock)
2220 {
2221 struct lock_list_entry *lle;
2222 struct lock_instance *instance;
2223 int i;
2224
2225 for (lle = list; lle != NULL; lle = lle->ll_next)
2226 for (i = lle->ll_count - 1; i >= 0; i--) {
2227 instance = &lle->ll_children[i];
2228 if (instance->li_lock == lock)
2229 return (instance);
2230 }
2231 return (NULL);
2232 }
2233
2234 static void
witness_list_lock(struct lock_instance * instance,int (* prnt)(const char * fmt,...))2235 witness_list_lock(struct lock_instance *instance,
2236 int (*prnt)(const char *fmt, ...))
2237 {
2238 struct lock_object *lock;
2239
2240 lock = instance->li_lock;
2241 prnt("%s %s %s", (instance->li_flags & LI_EXCLUSIVE) != 0 ?
2242 "exclusive" : "shared", LOCK_CLASS(lock)->lc_name, lock->lo_name);
2243 if (lock->lo_witness->w_name != lock->lo_name)
2244 prnt(" (%s)", lock->lo_witness->w_name);
2245 prnt(" r = %d (%p) locked @ %s:%d\n",
2246 instance->li_flags & LI_RECURSEMASK, lock,
2247 fixup_filename(instance->li_file), instance->li_line);
2248 }
2249
2250 static int
witness_output(const char * fmt,...)2251 witness_output(const char *fmt, ...)
2252 {
2253 va_list ap;
2254 int ret;
2255
2256 va_start(ap, fmt);
2257 ret = witness_voutput(fmt, ap);
2258 va_end(ap);
2259 return (ret);
2260 }
2261
2262 static int
witness_voutput(const char * fmt,va_list ap)2263 witness_voutput(const char *fmt, va_list ap)
2264 {
2265 int ret;
2266
2267 ret = 0;
2268 switch (witness_channel) {
2269 case WITNESS_CONSOLE:
2270 ret = vprintf(fmt, ap);
2271 break;
2272 case WITNESS_LOG:
2273 vlog(LOG_NOTICE, fmt, ap);
2274 break;
2275 case WITNESS_NONE:
2276 break;
2277 }
2278 return (ret);
2279 }
2280
2281 #ifdef DDB
2282 static int
witness_thread_has_locks(struct thread * td)2283 witness_thread_has_locks(struct thread *td)
2284 {
2285 if (td->td_sleeplocks == NULL)
2286 return (0);
2287 return (td->td_sleeplocks->ll_count != 0);
2288 }
2289
2290 static int
witness_proc_has_locks(struct proc * p)2291 witness_proc_has_locks(struct proc *p)
2292 {
2293 struct thread *td;
2294
2295 FOREACH_THREAD_IN_PROC(p, td) {
2296 if (witness_thread_has_locks(td))
2297 return (1);
2298 }
2299 return (0);
2300 }
2301 #endif
2302
2303 int
witness_list_locks(struct lock_list_entry ** lock_list,int (* prnt)(const char * fmt,...))2304 witness_list_locks(struct lock_list_entry **lock_list,
2305 int (*prnt)(const char *fmt, ...))
2306 {
2307 struct lock_list_entry *lle;
2308 int i, nheld;
2309
2310 nheld = 0;
2311 for (lle = *lock_list; lle != NULL; lle = lle->ll_next)
2312 for (i = lle->ll_count - 1; i >= 0; i--) {
2313 witness_list_lock(&lle->ll_children[i], prnt);
2314 nheld++;
2315 }
2316 return (nheld);
2317 }
2318
2319 /*
2320 * This is a bit risky at best. We call this function when we have timed
2321 * out acquiring a spin lock, and we assume that the other CPU is stuck
2322 * with this lock held. So, we go groveling around in the other CPU's
2323 * per-cpu data to try to find the lock instance for this spin lock to
2324 * see when it was last acquired.
2325 */
2326 void
witness_display_spinlock(struct lock_object * lock,struct thread * owner,int (* prnt)(const char * fmt,...))2327 witness_display_spinlock(struct lock_object *lock, struct thread *owner,
2328 int (*prnt)(const char *fmt, ...))
2329 {
2330 struct lock_instance *instance;
2331 struct pcpu *pc;
2332
2333 if (owner->td_critnest == 0 || owner->td_oncpu == NOCPU)
2334 return;
2335 pc = pcpu_find(owner->td_oncpu);
2336 instance = find_instance(pc->pc_spinlocks, lock);
2337 if (instance != NULL)
2338 witness_list_lock(instance, prnt);
2339 }
2340
2341 void
witness_save(struct lock_object * lock,const char ** filep,int * linep)2342 witness_save(struct lock_object *lock, const char **filep, int *linep)
2343 {
2344 struct lock_list_entry *lock_list;
2345 struct lock_instance *instance;
2346 struct lock_class *class;
2347
2348 /* Initialize for KMSAN's benefit. */
2349 *filep = NULL;
2350 *linep = 0;
2351
2352 /*
2353 * This function is used independently in locking code to deal with
2354 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2355 * is gone.
2356 */
2357 if (SCHEDULER_STOPPED())
2358 return;
2359 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2360 if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2361 return;
2362 class = LOCK_CLASS(lock);
2363 if (class->lc_flags & LC_SLEEPLOCK)
2364 lock_list = curthread->td_sleeplocks;
2365 else {
2366 if (witness_skipspin)
2367 return;
2368 lock_list = PCPU_GET(spinlocks);
2369 }
2370 instance = find_instance(lock_list, lock);
2371 if (instance == NULL) {
2372 kassert_panic("%s: lock (%s) %s not locked", __func__,
2373 class->lc_name, lock->lo_name);
2374 return;
2375 }
2376 *filep = instance->li_file;
2377 *linep = instance->li_line;
2378 }
2379
2380 void
witness_restore(struct lock_object * lock,const char * file,int line)2381 witness_restore(struct lock_object *lock, const char *file, int line)
2382 {
2383 struct lock_list_entry *lock_list;
2384 struct lock_instance *instance;
2385 struct lock_class *class;
2386
2387 /*
2388 * This function is used independently in locking code to deal with
2389 * Giant, SCHEDULER_STOPPED() check can be removed here after Giant
2390 * is gone.
2391 */
2392 if (SCHEDULER_STOPPED())
2393 return;
2394 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2395 if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2396 return;
2397 class = LOCK_CLASS(lock);
2398 if (class->lc_flags & LC_SLEEPLOCK)
2399 lock_list = curthread->td_sleeplocks;
2400 else {
2401 if (witness_skipspin)
2402 return;
2403 lock_list = PCPU_GET(spinlocks);
2404 }
2405 instance = find_instance(lock_list, lock);
2406 if (instance == NULL)
2407 kassert_panic("%s: lock (%s) %s not locked", __func__,
2408 class->lc_name, lock->lo_name);
2409 lock->lo_witness->w_file = file;
2410 lock->lo_witness->w_line = line;
2411 if (instance == NULL)
2412 return;
2413 instance->li_file = file;
2414 instance->li_line = line;
2415 }
2416
2417 static bool
witness_find_instance(const struct lock_object * lock,struct lock_instance ** instance)2418 witness_find_instance(const struct lock_object *lock,
2419 struct lock_instance **instance)
2420 {
2421 #ifdef INVARIANT_SUPPORT
2422 struct lock_class *class;
2423
2424 if (lock->lo_witness == NULL || witness_watch < 1 || KERNEL_PANICKED())
2425 return (false);
2426 class = LOCK_CLASS(lock);
2427 if ((class->lc_flags & LC_SLEEPLOCK) != 0) {
2428 *instance = find_instance(curthread->td_sleeplocks, lock);
2429 return (true);
2430 } else if ((class->lc_flags & LC_SPINLOCK) != 0) {
2431 *instance = find_instance(PCPU_GET(spinlocks), lock);
2432 return (true);
2433 } else {
2434 kassert_panic("Lock (%s) %s is not sleep or spin!",
2435 class->lc_name, lock->lo_name);
2436 return (false);
2437 }
2438 #else
2439 return (false);
2440 #endif
2441 }
2442
2443 void
witness_assert(const struct lock_object * lock,int flags,const char * file,int line)2444 witness_assert(const struct lock_object *lock, int flags, const char *file,
2445 int line)
2446 {
2447 #ifdef INVARIANT_SUPPORT
2448 struct lock_instance *instance;
2449 struct lock_class *class;
2450
2451 if (!witness_find_instance(lock, &instance))
2452 return;
2453 class = LOCK_CLASS(lock);
2454 switch (flags) {
2455 case LA_UNLOCKED:
2456 if (instance != NULL)
2457 kassert_panic("Lock (%s) %s locked @ %s:%d.",
2458 class->lc_name, lock->lo_name,
2459 fixup_filename(file), line);
2460 break;
2461 case LA_LOCKED:
2462 case LA_LOCKED | LA_RECURSED:
2463 case LA_LOCKED | LA_NOTRECURSED:
2464 case LA_SLOCKED:
2465 case LA_SLOCKED | LA_RECURSED:
2466 case LA_SLOCKED | LA_NOTRECURSED:
2467 case LA_XLOCKED:
2468 case LA_XLOCKED | LA_RECURSED:
2469 case LA_XLOCKED | LA_NOTRECURSED:
2470 if (instance == NULL) {
2471 kassert_panic("Lock (%s) %s not locked @ %s:%d.",
2472 class->lc_name, lock->lo_name,
2473 fixup_filename(file), line);
2474 break;
2475 }
2476 if ((flags & LA_XLOCKED) != 0 &&
2477 (instance->li_flags & LI_EXCLUSIVE) == 0)
2478 kassert_panic(
2479 "Lock (%s) %s not exclusively locked @ %s:%d.",
2480 class->lc_name, lock->lo_name,
2481 fixup_filename(file), line);
2482 if ((flags & LA_SLOCKED) != 0 &&
2483 (instance->li_flags & LI_EXCLUSIVE) != 0)
2484 kassert_panic(
2485 "Lock (%s) %s exclusively locked @ %s:%d.",
2486 class->lc_name, lock->lo_name,
2487 fixup_filename(file), line);
2488 if ((flags & LA_RECURSED) != 0 &&
2489 (instance->li_flags & LI_RECURSEMASK) == 0)
2490 kassert_panic("Lock (%s) %s not recursed @ %s:%d.",
2491 class->lc_name, lock->lo_name,
2492 fixup_filename(file), line);
2493 if ((flags & LA_NOTRECURSED) != 0 &&
2494 (instance->li_flags & LI_RECURSEMASK) != 0)
2495 kassert_panic("Lock (%s) %s recursed @ %s:%d.",
2496 class->lc_name, lock->lo_name,
2497 fixup_filename(file), line);
2498 break;
2499 default:
2500 kassert_panic("Invalid lock assertion at %s:%d.",
2501 fixup_filename(file), line);
2502 }
2503 #endif /* INVARIANT_SUPPORT */
2504 }
2505
2506 /*
2507 * Checks the ownership of the lock by curthread, consulting the witness list.
2508 * Returns:
2509 * 0 if witness is disabled or did not work
2510 * -1 if not owned
2511 * 1 if owned
2512 */
2513 int
witness_is_owned(const struct lock_object * lock)2514 witness_is_owned(const struct lock_object *lock)
2515 {
2516 #ifdef INVARIANT_SUPPORT
2517 struct lock_instance *instance;
2518
2519 if (!witness_find_instance(lock, &instance))
2520 return (0);
2521 return (instance == NULL ? -1 : 1);
2522 #else
2523 return (0);
2524 #endif
2525 }
2526
2527 static void
witness_setflag(struct lock_object * lock,int flag,int set)2528 witness_setflag(struct lock_object *lock, int flag, int set)
2529 {
2530 struct lock_list_entry *lock_list;
2531 struct lock_instance *instance;
2532 struct lock_class *class;
2533
2534 if (lock->lo_witness == NULL || witness_watch == -1 || KERNEL_PANICKED())
2535 return;
2536 class = LOCK_CLASS(lock);
2537 if (class->lc_flags & LC_SLEEPLOCK)
2538 lock_list = curthread->td_sleeplocks;
2539 else {
2540 if (witness_skipspin)
2541 return;
2542 lock_list = PCPU_GET(spinlocks);
2543 }
2544 instance = find_instance(lock_list, lock);
2545 if (instance == NULL) {
2546 kassert_panic("%s: lock (%s) %s not locked", __func__,
2547 class->lc_name, lock->lo_name);
2548 return;
2549 }
2550
2551 if (set)
2552 instance->li_flags |= flag;
2553 else
2554 instance->li_flags &= ~flag;
2555 }
2556
2557 void
witness_norelease(struct lock_object * lock)2558 witness_norelease(struct lock_object *lock)
2559 {
2560 witness_setflag(lock, LI_NORELEASE, 1);
2561 }
2562
2563 void
witness_releaseok(struct lock_object * lock)2564 witness_releaseok(struct lock_object *lock)
2565 {
2566 witness_setflag(lock, LI_NORELEASE, 0);
2567 }
2568
2569 #ifdef DDB
2570 static void
witness_ddb_list(struct thread * td)2571 witness_ddb_list(struct thread *td)
2572 {
2573 KASSERT(witness_cold == 0, ("%s: witness_cold", __func__));
2574 KASSERT(kdb_active, ("%s: not in the debugger", __func__));
2575
2576 if (witness_watch < 1)
2577 return;
2578
2579 witness_list_locks(&td->td_sleeplocks, db_printf);
2580
2581 /*
2582 * We only handle spinlocks if td == curthread. This is somewhat broken
2583 * if td is currently executing on some other CPU and holds spin locks
2584 * as we won't display those locks. If we had a MI way of getting
2585 * the per-cpu data for a given cpu then we could use
2586 * td->td_oncpu to get the list of spinlocks for this thread
2587 * and "fix" this.
2588 *
2589 * That still wouldn't really fix this unless we locked the scheduler
2590 * lock or stopped the other CPU to make sure it wasn't changing the
2591 * list out from under us. It is probably best to just not try to
2592 * handle threads on other CPU's for now.
2593 */
2594 if (td == curthread && PCPU_GET(spinlocks) != NULL)
2595 witness_list_locks(PCPU_PTR(spinlocks), db_printf);
2596 }
2597
DB_SHOW_COMMAND(locks,db_witness_list)2598 DB_SHOW_COMMAND(locks, db_witness_list)
2599 {
2600 struct thread *td;
2601
2602 if (have_addr)
2603 td = db_lookup_thread(addr, true);
2604 else
2605 td = kdb_thread;
2606 witness_ddb_list(td);
2607 }
2608
DB_SHOW_ALL_COMMAND(locks,db_witness_list_all)2609 DB_SHOW_ALL_COMMAND(locks, db_witness_list_all)
2610 {
2611 struct thread *td;
2612 struct proc *p;
2613
2614 /*
2615 * It would be nice to list only threads and processes that actually
2616 * held sleep locks, but that information is currently not exported
2617 * by WITNESS.
2618 */
2619 FOREACH_PROC_IN_SYSTEM(p) {
2620 if (!witness_proc_has_locks(p))
2621 continue;
2622 FOREACH_THREAD_IN_PROC(p, td) {
2623 if (!witness_thread_has_locks(td))
2624 continue;
2625 db_printf("Process %d (%s) thread %p (%d)\n", p->p_pid,
2626 p->p_comm, td, td->td_tid);
2627 witness_ddb_list(td);
2628 if (db_pager_quit)
2629 return;
2630 }
2631 }
2632 }
2633 DB_SHOW_ALIAS_FLAGS(alllocks, db_witness_list_all, DB_CMD_MEMSAFE);
2634
DB_SHOW_COMMAND_FLAGS(witness,db_witness_display,DB_CMD_MEMSAFE)2635 DB_SHOW_COMMAND_FLAGS(witness, db_witness_display, DB_CMD_MEMSAFE)
2636 {
2637 witness_ddb_display(db_printf);
2638 }
2639 #endif
2640
2641 static void
sbuf_print_witness_badstacks(struct sbuf * sb,size_t * oldidx)2642 sbuf_print_witness_badstacks(struct sbuf *sb, size_t *oldidx)
2643 {
2644 struct witness_lock_order_data *data1, *data2, *tmp_data1, *tmp_data2;
2645 struct witness *tmp_w1, *tmp_w2, *w1, *w2;
2646 int generation, i, j;
2647
2648 tmp_data1 = NULL;
2649 tmp_data2 = NULL;
2650 tmp_w1 = NULL;
2651 tmp_w2 = NULL;
2652
2653 /* Allocate and init temporary storage space. */
2654 tmp_w1 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2655 tmp_w2 = malloc(sizeof(struct witness), M_TEMP, M_WAITOK | M_ZERO);
2656 tmp_data1 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2657 M_WAITOK | M_ZERO);
2658 tmp_data2 = malloc(sizeof(struct witness_lock_order_data), M_TEMP,
2659 M_WAITOK | M_ZERO);
2660 stack_zero(&tmp_data1->wlod_stack);
2661 stack_zero(&tmp_data2->wlod_stack);
2662
2663 restart:
2664 mtx_lock_spin(&w_mtx);
2665 generation = w_generation;
2666 mtx_unlock_spin(&w_mtx);
2667 sbuf_printf(sb, "Number of known direct relationships is %d\n",
2668 w_lohash.wloh_count);
2669 for (i = 1; i < w_max_used_index; i++) {
2670 mtx_lock_spin(&w_mtx);
2671 if (generation != w_generation) {
2672 mtx_unlock_spin(&w_mtx);
2673
2674 /* The graph has changed, try again. */
2675 *oldidx = 0;
2676 sbuf_clear(sb);
2677 goto restart;
2678 }
2679
2680 w1 = &w_data[i];
2681 if (w1->w_reversed == 0) {
2682 mtx_unlock_spin(&w_mtx);
2683 continue;
2684 }
2685
2686 /* Copy w1 locally so we can release the spin lock. */
2687 *tmp_w1 = *w1;
2688 mtx_unlock_spin(&w_mtx);
2689
2690 if (tmp_w1->w_reversed == 0)
2691 continue;
2692 for (j = 1; j < w_max_used_index; j++) {
2693 if ((w_rmatrix[i][j] & WITNESS_REVERSAL) == 0 || i > j)
2694 continue;
2695
2696 mtx_lock_spin(&w_mtx);
2697 if (generation != w_generation) {
2698 mtx_unlock_spin(&w_mtx);
2699
2700 /* The graph has changed, try again. */
2701 *oldidx = 0;
2702 sbuf_clear(sb);
2703 goto restart;
2704 }
2705
2706 w2 = &w_data[j];
2707 data1 = witness_lock_order_get(w1, w2);
2708 data2 = witness_lock_order_get(w2, w1);
2709
2710 /*
2711 * Copy information locally so we can release the
2712 * spin lock.
2713 */
2714 *tmp_w2 = *w2;
2715
2716 if (data1) {
2717 stack_zero(&tmp_data1->wlod_stack);
2718 stack_copy(&data1->wlod_stack,
2719 &tmp_data1->wlod_stack);
2720 }
2721 if (data2 && data2 != data1) {
2722 stack_zero(&tmp_data2->wlod_stack);
2723 stack_copy(&data2->wlod_stack,
2724 &tmp_data2->wlod_stack);
2725 }
2726 mtx_unlock_spin(&w_mtx);
2727
2728 if (blessed(tmp_w1, tmp_w2))
2729 continue;
2730
2731 sbuf_printf(sb,
2732 "\nLock order reversal between \"%s\"(%s) and \"%s\"(%s)!\n",
2733 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2734 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2735 if (data1) {
2736 sbuf_printf(sb,
2737 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2738 tmp_w1->w_name, tmp_w1->w_class->lc_name,
2739 tmp_w2->w_name, tmp_w2->w_class->lc_name);
2740 stack_sbuf_print(sb, &tmp_data1->wlod_stack);
2741 sbuf_putc(sb, '\n');
2742 }
2743 if (data2 && data2 != data1) {
2744 sbuf_printf(sb,
2745 "Lock order \"%s\"(%s) -> \"%s\"(%s) first seen at:\n",
2746 tmp_w2->w_name, tmp_w2->w_class->lc_name,
2747 tmp_w1->w_name, tmp_w1->w_class->lc_name);
2748 stack_sbuf_print(sb, &tmp_data2->wlod_stack);
2749 sbuf_putc(sb, '\n');
2750 }
2751 }
2752 }
2753 mtx_lock_spin(&w_mtx);
2754 if (generation != w_generation) {
2755 mtx_unlock_spin(&w_mtx);
2756
2757 /*
2758 * The graph changed while we were printing stack data,
2759 * try again.
2760 */
2761 *oldidx = 0;
2762 sbuf_clear(sb);
2763 goto restart;
2764 }
2765 mtx_unlock_spin(&w_mtx);
2766
2767 /* Free temporary storage space. */
2768 free(tmp_data1, M_TEMP);
2769 free(tmp_data2, M_TEMP);
2770 free(tmp_w1, M_TEMP);
2771 free(tmp_w2, M_TEMP);
2772 }
2773
2774 static int
sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)2775 sysctl_debug_witness_badstacks(SYSCTL_HANDLER_ARGS)
2776 {
2777 struct sbuf *sb;
2778 int error;
2779
2780 if (witness_watch < 1) {
2781 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2782 return (error);
2783 }
2784 if (witness_cold) {
2785 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2786 return (error);
2787 }
2788 error = 0;
2789 sb = sbuf_new(NULL, NULL, badstack_sbuf_size, SBUF_AUTOEXTEND);
2790 if (sb == NULL)
2791 return (ENOMEM);
2792
2793 sbuf_print_witness_badstacks(sb, &req->oldidx);
2794
2795 sbuf_finish(sb);
2796 error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
2797 sbuf_delete(sb);
2798
2799 return (error);
2800 }
2801
2802 #ifdef DDB
2803 static int
sbuf_db_printf_drain(void * arg __unused,const char * data,int len)2804 sbuf_db_printf_drain(void *arg __unused, const char *data, int len)
2805 {
2806 return (db_printf("%.*s", len, data));
2807 }
2808
DB_SHOW_COMMAND_FLAGS(badstacks,db_witness_badstacks,DB_CMD_MEMSAFE)2809 DB_SHOW_COMMAND_FLAGS(badstacks, db_witness_badstacks, DB_CMD_MEMSAFE)
2810 {
2811 struct sbuf sb;
2812 char buffer[128];
2813 size_t dummy;
2814
2815 sbuf_new(&sb, buffer, sizeof(buffer), SBUF_FIXEDLEN);
2816 sbuf_set_drain(&sb, sbuf_db_printf_drain, NULL);
2817 sbuf_print_witness_badstacks(&sb, &dummy);
2818 sbuf_finish(&sb);
2819 }
2820 #endif
2821
2822 static int
sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS)2823 sysctl_debug_witness_channel(SYSCTL_HANDLER_ARGS)
2824 {
2825 static const struct {
2826 enum witness_channel channel;
2827 const char *name;
2828 } channels[] = {
2829 { WITNESS_CONSOLE, "console" },
2830 { WITNESS_LOG, "log" },
2831 { WITNESS_NONE, "none" },
2832 };
2833 char buf[16];
2834 u_int i;
2835 int error;
2836
2837 buf[0] = '\0';
2838 for (i = 0; i < nitems(channels); i++)
2839 if (witness_channel == channels[i].channel) {
2840 snprintf(buf, sizeof(buf), "%s", channels[i].name);
2841 break;
2842 }
2843
2844 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2845 if (error != 0 || req->newptr == NULL)
2846 return (error);
2847
2848 error = EINVAL;
2849 for (i = 0; i < nitems(channels); i++)
2850 if (strcmp(channels[i].name, buf) == 0) {
2851 witness_channel = channels[i].channel;
2852 error = 0;
2853 break;
2854 }
2855 return (error);
2856 }
2857
2858 static int
sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)2859 sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
2860 {
2861 struct witness *w;
2862 struct sbuf *sb;
2863 int error;
2864
2865 #ifdef __i386__
2866 error = SYSCTL_OUT(req, w_notallowed, sizeof(w_notallowed));
2867 return (error);
2868 #endif
2869
2870 if (witness_watch < 1) {
2871 error = SYSCTL_OUT(req, w_notrunning, sizeof(w_notrunning));
2872 return (error);
2873 }
2874 if (witness_cold) {
2875 error = SYSCTL_OUT(req, w_stillcold, sizeof(w_stillcold));
2876 return (error);
2877 }
2878 error = 0;
2879
2880 error = sysctl_wire_old_buffer(req, 0);
2881 if (error != 0)
2882 return (error);
2883 sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
2884 if (sb == NULL)
2885 return (ENOMEM);
2886 sbuf_putc(sb, '\n');
2887
2888 mtx_lock_spin(&w_mtx);
2889 STAILQ_FOREACH(w, &w_all, w_list)
2890 w->w_displayed = 0;
2891 STAILQ_FOREACH(w, &w_all, w_list)
2892 witness_add_fullgraph(sb, w);
2893 mtx_unlock_spin(&w_mtx);
2894
2895 /*
2896 * Close the sbuf and return to userland.
2897 */
2898 error = sbuf_finish(sb);
2899 sbuf_delete(sb);
2900
2901 return (error);
2902 }
2903
2904 static int
sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)2905 sysctl_debug_witness_watch(SYSCTL_HANDLER_ARGS)
2906 {
2907 int error, value;
2908
2909 value = witness_watch;
2910 error = sysctl_handle_int(oidp, &value, 0, req);
2911 if (error != 0 || req->newptr == NULL)
2912 return (error);
2913 if (value > 1 || value < -1 ||
2914 (witness_watch == -1 && value != witness_watch))
2915 return (EINVAL);
2916 witness_watch = value;
2917 return (0);
2918 }
2919
2920 static void
witness_add_fullgraph(struct sbuf * sb,struct witness * w)2921 witness_add_fullgraph(struct sbuf *sb, struct witness *w)
2922 {
2923 int i;
2924
2925 if (w->w_displayed != 0 || (w->w_file == NULL && w->w_line == 0))
2926 return;
2927 w->w_displayed = 1;
2928
2929 WITNESS_INDEX_ASSERT(w->w_index);
2930 for (i = 1; i <= w_max_used_index; i++) {
2931 if (w_rmatrix[w->w_index][i] & WITNESS_PARENT) {
2932 sbuf_printf(sb, "\"%s\",\"%s\"\n", w->w_name,
2933 w_data[i].w_name);
2934 witness_add_fullgraph(sb, &w_data[i]);
2935 }
2936 }
2937 }
2938
2939 /*
2940 * A simple hash function. Takes a key pointer and a key size. If size == 0,
2941 * interprets the key as a string and reads until the null
2942 * terminator. Otherwise, reads the first size bytes. Returns an unsigned 32-bit
2943 * hash value computed from the key.
2944 */
2945 static uint32_t
witness_hash_djb2(const uint8_t * key,uint32_t size)2946 witness_hash_djb2(const uint8_t *key, uint32_t size)
2947 {
2948 unsigned int hash = 5381;
2949 int i;
2950
2951 /* hash = hash * 33 + key[i] */
2952 if (size)
2953 for (i = 0; i < size; i++)
2954 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2955 else
2956 for (i = 0; key[i] != 0; i++)
2957 hash = ((hash << 5) + hash) + (unsigned int)key[i];
2958
2959 return (hash);
2960 }
2961
2962 /*
2963 * Initializes the two witness hash tables. Called exactly once from
2964 * witness_initialize().
2965 */
2966 static void
witness_init_hash_tables(void)2967 witness_init_hash_tables(void)
2968 {
2969 int i;
2970
2971 MPASS(witness_cold);
2972
2973 /* Initialize the hash tables. */
2974 for (i = 0; i < WITNESS_HASH_SIZE; i++)
2975 w_hash.wh_array[i] = NULL;
2976
2977 w_hash.wh_size = WITNESS_HASH_SIZE;
2978 w_hash.wh_count = 0;
2979
2980 /* Initialize the lock order data hash. */
2981 w_lofree = NULL;
2982 for (i = 0; i < WITNESS_LO_DATA_COUNT; i++) {
2983 memset(&w_lodata[i], 0, sizeof(w_lodata[i]));
2984 w_lodata[i].wlod_next = w_lofree;
2985 w_lofree = &w_lodata[i];
2986 }
2987 w_lohash.wloh_size = WITNESS_LO_HASH_SIZE;
2988 w_lohash.wloh_count = 0;
2989 for (i = 0; i < WITNESS_LO_HASH_SIZE; i++)
2990 w_lohash.wloh_array[i] = NULL;
2991 }
2992
2993 static struct witness *
witness_hash_get(const char * key)2994 witness_hash_get(const char *key)
2995 {
2996 struct witness *w;
2997 uint32_t hash;
2998
2999 MPASS(key != NULL);
3000 if (witness_cold == 0)
3001 mtx_assert(&w_mtx, MA_OWNED);
3002 hash = witness_hash_djb2(key, 0) % w_hash.wh_size;
3003 w = w_hash.wh_array[hash];
3004 while (w != NULL) {
3005 if (strcmp(w->w_name, key) == 0)
3006 goto out;
3007 w = w->w_hash_next;
3008 }
3009
3010 out:
3011 return (w);
3012 }
3013
3014 static void
witness_hash_put(struct witness * w)3015 witness_hash_put(struct witness *w)
3016 {
3017 uint32_t hash;
3018
3019 MPASS(w != NULL);
3020 MPASS(w->w_name != NULL);
3021 if (witness_cold == 0)
3022 mtx_assert(&w_mtx, MA_OWNED);
3023 KASSERT(witness_hash_get(w->w_name) == NULL,
3024 ("%s: trying to add a hash entry that already exists!", __func__));
3025 KASSERT(w->w_hash_next == NULL,
3026 ("%s: w->w_hash_next != NULL", __func__));
3027
3028 hash = witness_hash_djb2(w->w_name, 0) % w_hash.wh_size;
3029 w->w_hash_next = w_hash.wh_array[hash];
3030 w_hash.wh_array[hash] = w;
3031 w_hash.wh_count++;
3032 }
3033
3034 static struct witness_lock_order_data *
witness_lock_order_get(struct witness * parent,struct witness * child)3035 witness_lock_order_get(struct witness *parent, struct witness *child)
3036 {
3037 struct witness_lock_order_data *data = NULL;
3038 struct witness_lock_order_key key;
3039 unsigned int hash;
3040
3041 MPASS(parent != NULL && child != NULL);
3042 key.from = parent->w_index;
3043 key.to = child->w_index;
3044 WITNESS_INDEX_ASSERT(key.from);
3045 WITNESS_INDEX_ASSERT(key.to);
3046 if ((w_rmatrix[parent->w_index][child->w_index]
3047 & WITNESS_LOCK_ORDER_KNOWN) == 0)
3048 goto out;
3049
3050 hash = witness_hash_djb2((const char *)&key,
3051 sizeof(key)) % w_lohash.wloh_size;
3052 data = w_lohash.wloh_array[hash];
3053 while (data != NULL) {
3054 if (witness_lock_order_key_equal(&data->wlod_key, &key))
3055 break;
3056 data = data->wlod_next;
3057 }
3058
3059 out:
3060 return (data);
3061 }
3062
3063 /*
3064 * Verify that parent and child have a known relationship, are not the same,
3065 * and child is actually a child of parent. This is done without w_mtx
3066 * to avoid contention in the common case.
3067 */
3068 static int
witness_lock_order_check(struct witness * parent,struct witness * child)3069 witness_lock_order_check(struct witness *parent, struct witness *child)
3070 {
3071 if (parent != child &&
3072 w_rmatrix[parent->w_index][child->w_index]
3073 & WITNESS_LOCK_ORDER_KNOWN &&
3074 isitmychild(parent, child))
3075 return (1);
3076
3077 return (0);
3078 }
3079
3080 static int
witness_lock_order_add(struct witness * parent,struct witness * child)3081 witness_lock_order_add(struct witness *parent, struct witness *child)
3082 {
3083 struct witness_lock_order_data *data = NULL;
3084 struct witness_lock_order_key key;
3085 unsigned int hash;
3086
3087 MPASS(parent != NULL && child != NULL);
3088 key.from = parent->w_index;
3089 key.to = child->w_index;
3090 WITNESS_INDEX_ASSERT(key.from);
3091 WITNESS_INDEX_ASSERT(key.to);
3092 if (w_rmatrix[parent->w_index][child->w_index]
3093 & WITNESS_LOCK_ORDER_KNOWN)
3094 return (1);
3095
3096 hash = witness_hash_djb2((const char *)&key,
3097 sizeof(key)) % w_lohash.wloh_size;
3098 w_rmatrix[parent->w_index][child->w_index] |= WITNESS_LOCK_ORDER_KNOWN;
3099 data = w_lofree;
3100 if (data == NULL)
3101 return (0);
3102 w_lofree = data->wlod_next;
3103 data->wlod_next = w_lohash.wloh_array[hash];
3104 data->wlod_key = key;
3105 w_lohash.wloh_array[hash] = data;
3106 w_lohash.wloh_count++;
3107 stack_save(&data->wlod_stack);
3108 return (1);
3109 }
3110
3111 /* Call this whenever the structure of the witness graph changes. */
3112 static void
witness_increment_graph_generation(void)3113 witness_increment_graph_generation(void)
3114 {
3115 if (witness_cold == 0)
3116 mtx_assert(&w_mtx, MA_OWNED);
3117 w_generation++;
3118 }
3119
3120 static int
witness_output_drain(void * arg __unused,const char * data,int len)3121 witness_output_drain(void *arg __unused, const char *data, int len)
3122 {
3123 witness_output("%.*s", len, data);
3124 return (len);
3125 }
3126
3127 static void
witness_debugger(int cond,const char * msg)3128 witness_debugger(int cond, const char *msg)
3129 {
3130 char buf[32];
3131 struct sbuf sb;
3132 struct stack st;
3133
3134 if (!cond)
3135 return;
3136
3137 if (witness_trace) {
3138 sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
3139 sbuf_set_drain(&sb, witness_output_drain, NULL);
3140
3141 stack_save(&st);
3142 witness_output("stack backtrace:\n");
3143 stack_sbuf_print_ddb(&sb, &st);
3144
3145 sbuf_finish(&sb);
3146 }
3147
3148 witness_enter_debugger(msg);
3149 }
3150
3151 static void
witness_enter_debugger(const char * msg)3152 witness_enter_debugger(const char *msg)
3153 {
3154 #ifdef KDB
3155 if (witness_kdb)
3156 kdb_enter(KDB_WHY_WITNESS, msg);
3157 #endif
3158 }
3159