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