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