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