The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/subr_witness.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 2ce8a5c05e2f77fc222d209a5b1a448e


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.