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