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