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