]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_sx.c
MFC r301157:
[FreeBSD/stable/10.git] / sys / kern / kern_sx.c
1 /*-
2  * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
3  * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice(s), this list of conditions and the following disclaimer as
11  *    the first lines of this file unmodified other than the possible
12  *    addition of one or more copyright notices.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice(s), this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27  * DAMAGE.
28  */
29
30 /*
31  * Shared/exclusive locks.  This implementation attempts to ensure
32  * deterministic lock granting behavior, so that slocks and xlocks are
33  * interleaved.
34  *
35  * Priority propagation will not generally raise the priority of lock holders,
36  * so should not be relied upon in combination with sx locks.
37  */
38
39 #include "opt_ddb.h"
40 #include "opt_hwpmc_hooks.h"
41 #include "opt_kdtrace.h"
42 #include "opt_no_adaptive_sx.h"
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kdb.h>
50 #include <sys/ktr.h>
51 #include <sys/lock.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/sched.h>
55 #include <sys/sleepqueue.h>
56 #include <sys/sx.h>
57 #include <sys/sysctl.h>
58
59 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
60 #include <machine/cpu.h>
61 #endif
62
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66
67 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
68 #define ADAPTIVE_SX
69 #endif
70
71 CTASSERT((SX_NOADAPTIVE & LO_CLASSFLAGS) == SX_NOADAPTIVE);
72
73 #ifdef HWPMC_HOOKS
74 #include <sys/pmckern.h>
75 PMC_SOFT_DECLARE( , , lock, failed);
76 #endif
77
78 /* Handy macros for sleep queues. */
79 #define SQ_EXCLUSIVE_QUEUE      0
80 #define SQ_SHARED_QUEUE         1
81
82 /*
83  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
84  * drop Giant anytime we have to sleep or if we adaptively spin.
85  */
86 #define GIANT_DECLARE                                                   \
87         int _giantcnt = 0;                                              \
88         WITNESS_SAVE_DECL(Giant)                                        \
89
90 #define GIANT_SAVE() do {                                               \
91         if (mtx_owned(&Giant)) {                                        \
92                 WITNESS_SAVE(&Giant.lock_object, Giant);                \
93                 while (mtx_owned(&Giant)) {                             \
94                         _giantcnt++;                                    \
95                         mtx_unlock(&Giant);                             \
96                 }                                                       \
97         }                                                               \
98 } while (0)
99
100 #define GIANT_RESTORE() do {                                            \
101         if (_giantcnt > 0) {                                            \
102                 mtx_assert(&Giant, MA_NOTOWNED);                        \
103                 while (_giantcnt--)                                     \
104                         mtx_lock(&Giant);                               \
105                 WITNESS_RESTORE(&Giant.lock_object, Giant);             \
106         }                                                               \
107 } while (0)
108
109 /*
110  * Returns true if an exclusive lock is recursed.  It assumes
111  * curthread currently has an exclusive lock.
112  */
113 #define sx_recurse              lock_object.lo_data
114 #define sx_recursed(sx)         ((sx)->sx_recurse != 0)
115
116 static void     assert_sx(const struct lock_object *lock, int what);
117 #ifdef DDB
118 static void     db_show_sx(const struct lock_object *lock);
119 #endif
120 static void     lock_sx(struct lock_object *lock, uintptr_t how);
121 #ifdef KDTRACE_HOOKS
122 static int      owner_sx(const struct lock_object *lock, struct thread **owner);
123 #endif
124 static uintptr_t unlock_sx(struct lock_object *lock);
125
126 struct lock_class lock_class_sx = {
127         .lc_name = "sx",
128         .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
129         .lc_assert = assert_sx,
130 #ifdef DDB
131         .lc_ddb_show = db_show_sx,
132 #endif
133         .lc_lock = lock_sx,
134         .lc_unlock = unlock_sx,
135 #ifdef KDTRACE_HOOKS
136         .lc_owner = owner_sx,
137 #endif
138 };
139
140 #ifndef INVARIANTS
141 #define _sx_assert(sx, what, file, line)
142 #endif
143
144 #ifdef ADAPTIVE_SX
145 static u_int asx_retries = 10;
146 static u_int asx_loops = 10000;
147 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
148 SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
149 SYSCTL_UINT(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
150 #endif
151
152 void
153 assert_sx(const struct lock_object *lock, int what)
154 {
155
156         sx_assert((const struct sx *)lock, what);
157 }
158
159 void
160 lock_sx(struct lock_object *lock, uintptr_t how)
161 {
162         struct sx *sx;
163
164         sx = (struct sx *)lock;
165         if (how)
166                 sx_slock(sx);
167         else
168                 sx_xlock(sx);
169 }
170
171 uintptr_t
172 unlock_sx(struct lock_object *lock)
173 {
174         struct sx *sx;
175
176         sx = (struct sx *)lock;
177         sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
178         if (sx_xlocked(sx)) {
179                 sx_xunlock(sx);
180                 return (0);
181         } else {
182                 sx_sunlock(sx);
183                 return (1);
184         }
185 }
186
187 #ifdef KDTRACE_HOOKS
188 int
189 owner_sx(const struct lock_object *lock, struct thread **owner)
190 {
191         const struct sx *sx = (const struct sx *)lock;
192         uintptr_t x = sx->sx_lock;
193
194         *owner = (struct thread *)SX_OWNER(x);
195         return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
196             (*owner != NULL));
197 }
198 #endif
199
200 void
201 sx_sysinit(void *arg)
202 {
203         struct sx_args *sargs = arg;
204
205         sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
206 }
207
208 void
209 sx_init_flags(struct sx *sx, const char *description, int opts)
210 {
211         int flags;
212
213         MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
214             SX_NOPROFILE | SX_NOADAPTIVE)) == 0);
215         ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
216             ("%s: sx_lock not aligned for %s: %p", __func__, description,
217             &sx->sx_lock));
218
219         flags = LO_SLEEPABLE | LO_UPGRADABLE;
220         if (opts & SX_DUPOK)
221                 flags |= LO_DUPOK;
222         if (opts & SX_NOPROFILE)
223                 flags |= LO_NOPROFILE;
224         if (!(opts & SX_NOWITNESS))
225                 flags |= LO_WITNESS;
226         if (opts & SX_RECURSE)
227                 flags |= LO_RECURSABLE;
228         if (opts & SX_QUIET)
229                 flags |= LO_QUIET;
230
231         flags |= opts & SX_NOADAPTIVE;
232         lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
233         sx->sx_lock = SX_LOCK_UNLOCKED;
234         sx->sx_recurse = 0;
235 }
236
237 void
238 sx_destroy(struct sx *sx)
239 {
240
241         KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
242         KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
243         sx->sx_lock = SX_LOCK_DESTROYED;
244         lock_destroy(&sx->lock_object);
245 }
246
247 int
248 _sx_slock(struct sx *sx, int opts, const char *file, int line)
249 {
250         int error = 0;
251
252         if (SCHEDULER_STOPPED())
253                 return (0);
254         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
255             ("sx_slock() by idle thread %p on sx %s @ %s:%d",
256             curthread, sx->lock_object.lo_name, file, line));
257         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
258             ("sx_slock() of destroyed sx @ %s:%d", file, line));
259         WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
260         error = __sx_slock(sx, opts, file, line);
261         if (!error) {
262                 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
263                 WITNESS_LOCK(&sx->lock_object, 0, file, line);
264                 curthread->td_locks++;
265         }
266
267         return (error);
268 }
269
270 int
271 sx_try_slock_(struct sx *sx, const char *file, int line)
272 {
273         uintptr_t x;
274
275         if (SCHEDULER_STOPPED())
276                 return (1);
277
278         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
279             ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
280             curthread, sx->lock_object.lo_name, file, line));
281
282         for (;;) {
283                 x = sx->sx_lock;
284                 KASSERT(x != SX_LOCK_DESTROYED,
285                     ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
286                 if (!(x & SX_LOCK_SHARED))
287                         break;
288                 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, x + SX_ONE_SHARER)) {
289                         LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
290                         WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
291                         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE,
292                             sx, 0, 0, file, line);
293                         curthread->td_locks++;
294                         return (1);
295                 }
296         }
297
298         LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
299         return (0);
300 }
301
302 int
303 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
304 {
305         int error = 0;
306
307         if (SCHEDULER_STOPPED())
308                 return (0);
309         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
310             ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
311             curthread, sx->lock_object.lo_name, file, line));
312         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
313             ("sx_xlock() of destroyed sx @ %s:%d", file, line));
314         WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
315             line, NULL);
316         error = __sx_xlock(sx, curthread, opts, file, line);
317         if (!error) {
318                 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
319                     file, line);
320                 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
321                 curthread->td_locks++;
322         }
323
324         return (error);
325 }
326
327 int
328 sx_try_xlock_(struct sx *sx, const char *file, int line)
329 {
330         int rval;
331
332         if (SCHEDULER_STOPPED())
333                 return (1);
334
335         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
336             ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
337             curthread, sx->lock_object.lo_name, file, line));
338         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
339             ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
340
341         if (sx_xlocked(sx) &&
342             (sx->lock_object.lo_flags & LO_RECURSABLE) != 0) {
343                 sx->sx_recurse++;
344                 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
345                 rval = 1;
346         } else
347                 rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
348                     (uintptr_t)curthread);
349         LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
350         if (rval) {
351                 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
352                     file, line);
353                 if (!sx_recursed(sx))
354                         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE,
355                             sx, 0, 0, file, line);
356                 curthread->td_locks++;
357         }
358
359         return (rval);
360 }
361
362 void
363 _sx_sunlock(struct sx *sx, const char *file, int line)
364 {
365
366         if (SCHEDULER_STOPPED())
367                 return;
368         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
369             ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
370         _sx_assert(sx, SA_SLOCKED, file, line);
371         WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
372         LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
373         __sx_sunlock(sx, file, line);
374         LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_SUNLOCK_RELEASE, sx);
375         curthread->td_locks--;
376 }
377
378 void
379 _sx_xunlock(struct sx *sx, const char *file, int line)
380 {
381
382         if (SCHEDULER_STOPPED())
383                 return;
384         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
385             ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
386         _sx_assert(sx, SA_XLOCKED, file, line);
387         WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
388         LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
389             line);
390         if (!sx_recursed(sx))
391                 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_XUNLOCK_RELEASE, sx);
392         __sx_xunlock(sx, curthread, file, line);
393         curthread->td_locks--;
394 }
395
396 /*
397  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
398  * This will only succeed if this thread holds a single shared lock.
399  * Return 1 if if the upgrade succeed, 0 otherwise.
400  */
401 int
402 sx_try_upgrade_(struct sx *sx, const char *file, int line)
403 {
404         uintptr_t x;
405         int success;
406
407         if (SCHEDULER_STOPPED())
408                 return (1);
409
410         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
411             ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
412         _sx_assert(sx, SA_SLOCKED, file, line);
413
414         /*
415          * Try to switch from one shared lock to an exclusive lock.  We need
416          * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
417          * we will wake up the exclusive waiters when we drop the lock.
418          */
419         x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
420         success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
421             (uintptr_t)curthread | x);
422         LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
423         if (success) {
424                 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
425                     file, line);
426                 LOCKSTAT_RECORD0(LS_SX_TRYUPGRADE_UPGRADE, sx);
427         }
428         return (success);
429 }
430
431 /*
432  * Downgrade an unrecursed exclusive lock into a single shared lock.
433  */
434 void
435 sx_downgrade_(struct sx *sx, const char *file, int line)
436 {
437         uintptr_t x;
438         int wakeup_swapper;
439
440         if (SCHEDULER_STOPPED())
441                 return;
442
443         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
444             ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
445         _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
446 #ifndef INVARIANTS
447         if (sx_recursed(sx))
448                 panic("downgrade of a recursed lock");
449 #endif
450
451         WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
452
453         /*
454          * Try to switch from an exclusive lock with no shared waiters
455          * to one sharer with no shared waiters.  If there are
456          * exclusive waiters, we don't need to lock the sleep queue so
457          * long as we preserve the flag.  We do one quick try and if
458          * that fails we grab the sleepq lock to keep the flags from
459          * changing and do it the slow way.
460          *
461          * We have to lock the sleep queue if there are shared waiters
462          * so we can wake them up.
463          */
464         x = sx->sx_lock;
465         if (!(x & SX_LOCK_SHARED_WAITERS) &&
466             atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
467             (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
468                 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
469                 return;
470         }
471
472         /*
473          * Lock the sleep queue so we can read the waiters bits
474          * without any races and wakeup any shared waiters.
475          */
476         sleepq_lock(&sx->lock_object);
477
478         /*
479          * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
480          * shared lock.  If there are any shared waiters, wake them up.
481          */
482         wakeup_swapper = 0;
483         x = sx->sx_lock;
484         atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
485             (x & SX_LOCK_EXCLUSIVE_WAITERS));
486         if (x & SX_LOCK_SHARED_WAITERS)
487                 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
488                     0, SQ_SHARED_QUEUE);
489         sleepq_release(&sx->lock_object);
490
491         LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
492         LOCKSTAT_RECORD0(LS_SX_DOWNGRADE_DOWNGRADE, sx);
493
494         if (wakeup_swapper)
495                 kick_proc0();
496 }
497
498 /*
499  * This function represents the so-called 'hard case' for sx_xlock
500  * operation.  All 'easy case' failures are redirected to this.  Note
501  * that ideally this would be a static function, but it needs to be
502  * accessible from at least sx.h.
503  */
504 int
505 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
506     int line)
507 {
508         GIANT_DECLARE;
509 #ifdef ADAPTIVE_SX
510         volatile struct thread *owner;
511         u_int i, spintries = 0;
512 #endif
513         uintptr_t x;
514 #ifdef LOCK_PROFILING
515         uint64_t waittime = 0;
516         int contested = 0;
517 #endif
518         int error = 0;
519 #ifdef  KDTRACE_HOOKS
520         uintptr_t state;
521         uint64_t spin_cnt = 0;
522         uint64_t sleep_cnt = 0;
523         int64_t sleep_time = 0;
524         int64_t all_time = 0;
525 #endif
526
527         if (SCHEDULER_STOPPED())
528                 return (0);
529
530         /* If we already hold an exclusive lock, then recurse. */
531         if (sx_xlocked(sx)) {
532                 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
533             ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
534                     sx->lock_object.lo_name, file, line));
535                 sx->sx_recurse++;
536                 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
537                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
538                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
539                 return (0);
540         }
541
542         if (LOCK_LOG_TEST(&sx->lock_object, 0))
543                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
544                     sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
545
546 #ifdef KDTRACE_HOOKS
547         all_time -= lockstat_nsecs(&sx->lock_object);
548         state = sx->sx_lock;
549 #endif
550         for (;;) {
551                 if (sx->sx_lock == SX_LOCK_UNLOCKED &&
552                     atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid))
553                         break;
554 #ifdef KDTRACE_HOOKS
555                 spin_cnt++;
556 #endif
557 #ifdef HWPMC_HOOKS
558                 PMC_SOFT_CALL( , , lock, failed);
559 #endif
560                 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
561                     &waittime);
562 #ifdef ADAPTIVE_SX
563                 /*
564                  * If the lock is write locked and the owner is
565                  * running on another CPU, spin until the owner stops
566                  * running or the state of the lock changes.
567                  */
568                 x = sx->sx_lock;
569                 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
570                         if ((x & SX_LOCK_SHARED) == 0) {
571                                 x = SX_OWNER(x);
572                                 owner = (struct thread *)x;
573                                 if (TD_IS_RUNNING(owner)) {
574                                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
575                                                 CTR3(KTR_LOCK,
576                                             "%s: spinning on %p held by %p",
577                                                     __func__, sx, owner);
578                                         KTR_STATE1(KTR_SCHED, "thread",
579                                             sched_tdname(curthread), "spinning",
580                                             "lockname:\"%s\"",
581                                             sx->lock_object.lo_name);
582                                         GIANT_SAVE();
583                                         while (SX_OWNER(sx->sx_lock) == x &&
584                                             TD_IS_RUNNING(owner)) {
585                                                 cpu_spinwait();
586 #ifdef KDTRACE_HOOKS
587                                                 spin_cnt++;
588 #endif
589                                         }
590                                         KTR_STATE0(KTR_SCHED, "thread",
591                                             sched_tdname(curthread), "running");
592                                         continue;
593                                 }
594                         } else if (SX_SHARERS(x) && spintries < asx_retries) {
595                                 KTR_STATE1(KTR_SCHED, "thread",
596                                     sched_tdname(curthread), "spinning",
597                                     "lockname:\"%s\"", sx->lock_object.lo_name);
598                                 GIANT_SAVE();
599                                 spintries++;
600                                 for (i = 0; i < asx_loops; i++) {
601                                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
602                                                 CTR4(KTR_LOCK,
603                                     "%s: shared spinning on %p with %u and %u",
604                                                     __func__, sx, spintries, i);
605                                         x = sx->sx_lock;
606                                         if ((x & SX_LOCK_SHARED) == 0 ||
607                                             SX_SHARERS(x) == 0)
608                                                 break;
609                                         cpu_spinwait();
610 #ifdef KDTRACE_HOOKS
611                                         spin_cnt++;
612 #endif
613                                 }
614                                 KTR_STATE0(KTR_SCHED, "thread",
615                                     sched_tdname(curthread), "running");
616                                 if (i != asx_loops)
617                                         continue;
618                         }
619                 }
620 #endif
621
622                 sleepq_lock(&sx->lock_object);
623                 x = sx->sx_lock;
624
625                 /*
626                  * If the lock was released while spinning on the
627                  * sleep queue chain lock, try again.
628                  */
629                 if (x == SX_LOCK_UNLOCKED) {
630                         sleepq_release(&sx->lock_object);
631                         continue;
632                 }
633
634 #ifdef ADAPTIVE_SX
635                 /*
636                  * The current lock owner might have started executing
637                  * on another CPU (or the lock could have changed
638                  * owners) while we were waiting on the sleep queue
639                  * chain lock.  If so, drop the sleep queue lock and try
640                  * again.
641                  */
642                 if (!(x & SX_LOCK_SHARED) &&
643                     (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
644                         owner = (struct thread *)SX_OWNER(x);
645                         if (TD_IS_RUNNING(owner)) {
646                                 sleepq_release(&sx->lock_object);
647                                 continue;
648                         }
649                 }
650 #endif
651
652                 /*
653                  * If an exclusive lock was released with both shared
654                  * and exclusive waiters and a shared waiter hasn't
655                  * woken up and acquired the lock yet, sx_lock will be
656                  * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
657                  * If we see that value, try to acquire it once.  Note
658                  * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
659                  * as there are other exclusive waiters still.  If we
660                  * fail, restart the loop.
661                  */
662                 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
663                         if (atomic_cmpset_acq_ptr(&sx->sx_lock,
664                             SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
665                             tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
666                                 sleepq_release(&sx->lock_object);
667                                 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
668                                     __func__, sx);
669                                 break;
670                         }
671                         sleepq_release(&sx->lock_object);
672                         continue;
673                 }
674
675                 /*
676                  * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
677                  * than loop back and retry.
678                  */
679                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
680                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
681                             x | SX_LOCK_EXCLUSIVE_WAITERS)) {
682                                 sleepq_release(&sx->lock_object);
683                                 continue;
684                         }
685                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
686                                 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
687                                     __func__, sx);
688                 }
689
690                 /*
691                  * Since we have been unable to acquire the exclusive
692                  * lock and the exclusive waiters flag is set, we have
693                  * to sleep.
694                  */
695                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
696                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
697                             __func__, sx);
698
699 #ifdef KDTRACE_HOOKS
700                 sleep_time -= lockstat_nsecs(&sx->lock_object);
701 #endif
702                 GIANT_SAVE();
703                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
704                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
705                     SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
706                 if (!(opts & SX_INTERRUPTIBLE))
707                         sleepq_wait(&sx->lock_object, 0);
708                 else
709                         error = sleepq_wait_sig(&sx->lock_object, 0);
710 #ifdef KDTRACE_HOOKS
711                 sleep_time += lockstat_nsecs(&sx->lock_object);
712                 sleep_cnt++;
713 #endif
714                 if (error) {
715                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
716                                 CTR2(KTR_LOCK,
717                         "%s: interruptible sleep by %p suspended by signal",
718                                     __func__, sx);
719                         break;
720                 }
721                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
722                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
723                             __func__, sx);
724         }
725 #ifdef KDTRACE_HOOKS
726         all_time += lockstat_nsecs(&sx->lock_object);
727         if (sleep_time)
728                 LOCKSTAT_RECORD4(LS_SX_XLOCK_BLOCK, sx, sleep_time,
729                     LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
730                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
731         if (spin_cnt > sleep_cnt)
732                 LOCKSTAT_RECORD4(LS_SX_XLOCK_SPIN, sx, all_time - sleep_time,
733                     LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
734                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
735 #endif
736         if (!error)
737                 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE, sx,
738                     contested, waittime, file, line);
739         GIANT_RESTORE();
740         return (error);
741 }
742
743 /*
744  * This function represents the so-called 'hard case' for sx_xunlock
745  * operation.  All 'easy case' failures are redirected to this.  Note
746  * that ideally this would be a static function, but it needs to be
747  * accessible from at least sx.h.
748  */
749 void
750 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
751 {
752         uintptr_t x;
753         int queue, wakeup_swapper;
754
755         if (SCHEDULER_STOPPED())
756                 return;
757
758         MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
759
760         /* If the lock is recursed, then unrecurse one level. */
761         if (sx_xlocked(sx) && sx_recursed(sx)) {
762                 if ((--sx->sx_recurse) == 0)
763                         atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
764                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
765                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
766                 return;
767         }
768         MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
769             SX_LOCK_EXCLUSIVE_WAITERS));
770         if (LOCK_LOG_TEST(&sx->lock_object, 0))
771                 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
772
773         sleepq_lock(&sx->lock_object);
774         x = SX_LOCK_UNLOCKED;
775
776         /*
777          * The wake up algorithm here is quite simple and probably not
778          * ideal.  It gives precedence to shared waiters if they are
779          * present.  For this condition, we have to preserve the
780          * state of the exclusive waiters flag.
781          * If interruptible sleeps left the shared queue empty avoid a
782          * starvation for the threads sleeping on the exclusive queue by giving
783          * them precedence and cleaning up the shared waiters bit anyway.
784          */
785         if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
786             sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
787                 queue = SQ_SHARED_QUEUE;
788                 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
789         } else
790                 queue = SQ_EXCLUSIVE_QUEUE;
791
792         /* Wake up all the waiters for the specific queue. */
793         if (LOCK_LOG_TEST(&sx->lock_object, 0))
794                 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
795                     __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
796                     "exclusive");
797         atomic_store_rel_ptr(&sx->sx_lock, x);
798         wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
799             queue);
800         sleepq_release(&sx->lock_object);
801         if (wakeup_swapper)
802                 kick_proc0();
803 }
804
805 /*
806  * This function represents the so-called 'hard case' for sx_slock
807  * operation.  All 'easy case' failures are redirected to this.  Note
808  * that ideally this would be a static function, but it needs to be
809  * accessible from at least sx.h.
810  */
811 int
812 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
813 {
814         GIANT_DECLARE;
815 #ifdef ADAPTIVE_SX
816         volatile struct thread *owner;
817 #endif
818 #ifdef LOCK_PROFILING
819         uint64_t waittime = 0;
820         int contested = 0;
821 #endif
822         uintptr_t x;
823         int error = 0;
824 #ifdef KDTRACE_HOOKS
825         uintptr_t state;
826         uint64_t spin_cnt = 0;
827         uint64_t sleep_cnt = 0;
828         int64_t sleep_time = 0;
829         int64_t all_time = 0;
830 #endif
831
832         if (SCHEDULER_STOPPED())
833                 return (0);
834
835 #ifdef KDTRACE_HOOKS
836         state = sx->sx_lock;
837         all_time -= lockstat_nsecs(&sx->lock_object);
838 #endif
839
840         /*
841          * As with rwlocks, we don't make any attempt to try to block
842          * shared locks once there is an exclusive waiter.
843          */
844         for (;;) {
845 #ifdef KDTRACE_HOOKS
846                 spin_cnt++;
847 #endif
848                 x = sx->sx_lock;
849
850                 /*
851                  * If no other thread has an exclusive lock then try to bump up
852                  * the count of sharers.  Since we have to preserve the state
853                  * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
854                  * shared lock loop back and retry.
855                  */
856                 if (x & SX_LOCK_SHARED) {
857                         MPASS(!(x & SX_LOCK_SHARED_WAITERS));
858                         if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
859                             x + SX_ONE_SHARER)) {
860                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
861                                         CTR4(KTR_LOCK,
862                                             "%s: %p succeed %p -> %p", __func__,
863                                             sx, (void *)x,
864                                             (void *)(x + SX_ONE_SHARER));
865                                 break;
866                         }
867                         continue;
868                 }
869 #ifdef HWPMC_HOOKS
870                 PMC_SOFT_CALL( , , lock, failed);
871 #endif
872                 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
873                     &waittime);
874
875 #ifdef ADAPTIVE_SX
876                 /*
877                  * If the owner is running on another CPU, spin until
878                  * the owner stops running or the state of the lock
879                  * changes.
880                  */
881                 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
882                         x = SX_OWNER(x);
883                         owner = (struct thread *)x;
884                         if (TD_IS_RUNNING(owner)) {
885                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
886                                         CTR3(KTR_LOCK,
887                                             "%s: spinning on %p held by %p",
888                                             __func__, sx, owner);
889                                 KTR_STATE1(KTR_SCHED, "thread",
890                                     sched_tdname(curthread), "spinning",
891                                     "lockname:\"%s\"", sx->lock_object.lo_name);
892                                 GIANT_SAVE();
893                                 while (SX_OWNER(sx->sx_lock) == x &&
894                                     TD_IS_RUNNING(owner)) {
895 #ifdef KDTRACE_HOOKS
896                                         spin_cnt++;
897 #endif
898                                         cpu_spinwait();
899                                 }
900                                 KTR_STATE0(KTR_SCHED, "thread",
901                                     sched_tdname(curthread), "running");
902                                 continue;
903                         }
904                 }
905 #endif
906
907                 /*
908                  * Some other thread already has an exclusive lock, so
909                  * start the process of blocking.
910                  */
911                 sleepq_lock(&sx->lock_object);
912                 x = sx->sx_lock;
913
914                 /*
915                  * The lock could have been released while we spun.
916                  * In this case loop back and retry.
917                  */
918                 if (x & SX_LOCK_SHARED) {
919                         sleepq_release(&sx->lock_object);
920                         continue;
921                 }
922
923 #ifdef ADAPTIVE_SX
924                 /*
925                  * If the owner is running on another CPU, spin until
926                  * the owner stops running or the state of the lock
927                  * changes.
928                  */
929                 if (!(x & SX_LOCK_SHARED) &&
930                     (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
931                         owner = (struct thread *)SX_OWNER(x);
932                         if (TD_IS_RUNNING(owner)) {
933                                 sleepq_release(&sx->lock_object);
934                                 continue;
935                         }
936                 }
937 #endif
938
939                 /*
940                  * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
941                  * fail to set it drop the sleep queue lock and loop
942                  * back.
943                  */
944                 if (!(x & SX_LOCK_SHARED_WAITERS)) {
945                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
946                             x | SX_LOCK_SHARED_WAITERS)) {
947                                 sleepq_release(&sx->lock_object);
948                                 continue;
949                         }
950                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
951                                 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
952                                     __func__, sx);
953                 }
954
955                 /*
956                  * Since we have been unable to acquire the shared lock,
957                  * we have to sleep.
958                  */
959                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
960                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
961                             __func__, sx);
962
963 #ifdef KDTRACE_HOOKS
964                 sleep_time -= lockstat_nsecs(&sx->lock_object);
965 #endif
966                 GIANT_SAVE();
967                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
968                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
969                     SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
970                 if (!(opts & SX_INTERRUPTIBLE))
971                         sleepq_wait(&sx->lock_object, 0);
972                 else
973                         error = sleepq_wait_sig(&sx->lock_object, 0);
974 #ifdef KDTRACE_HOOKS
975                 sleep_time += lockstat_nsecs(&sx->lock_object);
976                 sleep_cnt++;
977 #endif
978                 if (error) {
979                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
980                                 CTR2(KTR_LOCK,
981                         "%s: interruptible sleep by %p suspended by signal",
982                                     __func__, sx);
983                         break;
984                 }
985                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
986                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
987                             __func__, sx);
988         }
989 #ifdef KDTRACE_HOOKS
990         all_time += lockstat_nsecs(&sx->lock_object);
991         if (sleep_time)
992                 LOCKSTAT_RECORD4(LS_SX_SLOCK_BLOCK, sx, sleep_time,
993                     LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
994                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
995         if (spin_cnt > sleep_cnt)
996                 LOCKSTAT_RECORD4(LS_SX_SLOCK_SPIN, sx, all_time - sleep_time,
997                     LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
998                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
999 #endif
1000         if (error == 0)
1001                 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE, sx,
1002                     contested, waittime, file, line);
1003         GIANT_RESTORE();
1004         return (error);
1005 }
1006
1007 /*
1008  * This function represents the so-called 'hard case' for sx_sunlock
1009  * operation.  All 'easy case' failures are redirected to this.  Note
1010  * that ideally this would be a static function, but it needs to be
1011  * accessible from at least sx.h.
1012  */
1013 void
1014 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
1015 {
1016         uintptr_t x;
1017         int wakeup_swapper;
1018
1019         if (SCHEDULER_STOPPED())
1020                 return;
1021
1022         for (;;) {
1023                 x = sx->sx_lock;
1024
1025                 /*
1026                  * We should never have sharers while at least one thread
1027                  * holds a shared lock.
1028                  */
1029                 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1030                     ("%s: waiting sharers", __func__));
1031
1032                 /*
1033                  * See if there is more than one shared lock held.  If
1034                  * so, just drop one and return.
1035                  */
1036                 if (SX_SHARERS(x) > 1) {
1037                         if (atomic_cmpset_rel_ptr(&sx->sx_lock, x,
1038                             x - SX_ONE_SHARER)) {
1039                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1040                                         CTR4(KTR_LOCK,
1041                                             "%s: %p succeeded %p -> %p",
1042                                             __func__, sx, (void *)x,
1043                                             (void *)(x - SX_ONE_SHARER));
1044                                 break;
1045                         }
1046                         continue;
1047                 }
1048
1049                 /*
1050                  * If there aren't any waiters for an exclusive lock,
1051                  * then try to drop it quickly.
1052                  */
1053                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1054                         MPASS(x == SX_SHARERS_LOCK(1));
1055                         if (atomic_cmpset_rel_ptr(&sx->sx_lock,
1056                             SX_SHARERS_LOCK(1), SX_LOCK_UNLOCKED)) {
1057                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1058                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
1059                                             __func__, sx);
1060                                 break;
1061                         }
1062                         continue;
1063                 }
1064
1065                 /*
1066                  * At this point, there should just be one sharer with
1067                  * exclusive waiters.
1068                  */
1069                 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1070
1071                 sleepq_lock(&sx->lock_object);
1072
1073                 /*
1074                  * Wake up semantic here is quite simple:
1075                  * Just wake up all the exclusive waiters.
1076                  * Note that the state of the lock could have changed,
1077                  * so if it fails loop back and retry.
1078                  */
1079                 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1080                     SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1081                     SX_LOCK_UNLOCKED)) {
1082                         sleepq_release(&sx->lock_object);
1083                         continue;
1084                 }
1085                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1086                         CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1087                             "exclusive queue", __func__, sx);
1088                 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1089                     0, SQ_EXCLUSIVE_QUEUE);
1090                 sleepq_release(&sx->lock_object);
1091                 if (wakeup_swapper)
1092                         kick_proc0();
1093                 break;
1094         }
1095 }
1096
1097 #ifdef INVARIANT_SUPPORT
1098 #ifndef INVARIANTS
1099 #undef  _sx_assert
1100 #endif
1101
1102 /*
1103  * In the non-WITNESS case, sx_assert() can only detect that at least
1104  * *some* thread owns an slock, but it cannot guarantee that *this*
1105  * thread owns an slock.
1106  */
1107 void
1108 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1109 {
1110 #ifndef WITNESS
1111         int slocked = 0;
1112 #endif
1113
1114         if (panicstr != NULL)
1115                 return;
1116         switch (what) {
1117         case SA_SLOCKED:
1118         case SA_SLOCKED | SA_NOTRECURSED:
1119         case SA_SLOCKED | SA_RECURSED:
1120 #ifndef WITNESS
1121                 slocked = 1;
1122                 /* FALLTHROUGH */
1123 #endif
1124         case SA_LOCKED:
1125         case SA_LOCKED | SA_NOTRECURSED:
1126         case SA_LOCKED | SA_RECURSED:
1127 #ifdef WITNESS
1128                 witness_assert(&sx->lock_object, what, file, line);
1129 #else
1130                 /*
1131                  * If some other thread has an exclusive lock or we
1132                  * have one and are asserting a shared lock, fail.
1133                  * Also, if no one has a lock at all, fail.
1134                  */
1135                 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1136                     (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1137                     sx_xholder(sx) != curthread)))
1138                         panic("Lock %s not %slocked @ %s:%d\n",
1139                             sx->lock_object.lo_name, slocked ? "share " : "",
1140                             file, line);
1141
1142                 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1143                         if (sx_recursed(sx)) {
1144                                 if (what & SA_NOTRECURSED)
1145                                         panic("Lock %s recursed @ %s:%d\n",
1146                                             sx->lock_object.lo_name, file,
1147                                             line);
1148                         } else if (what & SA_RECURSED)
1149                                 panic("Lock %s not recursed @ %s:%d\n",
1150                                     sx->lock_object.lo_name, file, line);
1151                 }
1152 #endif
1153                 break;
1154         case SA_XLOCKED:
1155         case SA_XLOCKED | SA_NOTRECURSED:
1156         case SA_XLOCKED | SA_RECURSED:
1157                 if (sx_xholder(sx) != curthread)
1158                         panic("Lock %s not exclusively locked @ %s:%d\n",
1159                             sx->lock_object.lo_name, file, line);
1160                 if (sx_recursed(sx)) {
1161                         if (what & SA_NOTRECURSED)
1162                                 panic("Lock %s recursed @ %s:%d\n",
1163                                     sx->lock_object.lo_name, file, line);
1164                 } else if (what & SA_RECURSED)
1165                         panic("Lock %s not recursed @ %s:%d\n",
1166                             sx->lock_object.lo_name, file, line);
1167                 break;
1168         case SA_UNLOCKED:
1169 #ifdef WITNESS
1170                 witness_assert(&sx->lock_object, what, file, line);
1171 #else
1172                 /*
1173                  * If we hold an exclusve lock fail.  We can't
1174                  * reliably check to see if we hold a shared lock or
1175                  * not.
1176                  */
1177                 if (sx_xholder(sx) == curthread)
1178                         panic("Lock %s exclusively locked @ %s:%d\n",
1179                             sx->lock_object.lo_name, file, line);
1180 #endif
1181                 break;
1182         default:
1183                 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1184                     line);
1185         }
1186 }
1187 #endif  /* INVARIANT_SUPPORT */
1188
1189 #ifdef DDB
1190 static void
1191 db_show_sx(const struct lock_object *lock)
1192 {
1193         struct thread *td;
1194         const struct sx *sx;
1195
1196         sx = (const struct sx *)lock;
1197
1198         db_printf(" state: ");
1199         if (sx->sx_lock == SX_LOCK_UNLOCKED)
1200                 db_printf("UNLOCKED\n");
1201         else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1202                 db_printf("DESTROYED\n");
1203                 return;
1204         } else if (sx->sx_lock & SX_LOCK_SHARED)
1205                 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1206         else {
1207                 td = sx_xholder(sx);
1208                 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1209                     td->td_tid, td->td_proc->p_pid, td->td_name);
1210                 if (sx_recursed(sx))
1211                         db_printf(" recursed: %d\n", sx->sx_recurse);
1212         }
1213
1214         db_printf(" waiters: ");
1215         switch(sx->sx_lock &
1216             (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1217         case SX_LOCK_SHARED_WAITERS:
1218                 db_printf("shared\n");
1219                 break;
1220         case SX_LOCK_EXCLUSIVE_WAITERS:
1221                 db_printf("exclusive\n");
1222                 break;
1223         case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1224                 db_printf("exclusive and shared\n");
1225                 break;
1226         default:
1227                 db_printf("none\n");
1228         }
1229 }
1230
1231 /*
1232  * Check to see if a thread that is blocked on a sleep queue is actually
1233  * blocked on an sx lock.  If so, output some details and return true.
1234  * If the lock has an exclusive owner, return that in *ownerp.
1235  */
1236 int
1237 sx_chain(struct thread *td, struct thread **ownerp)
1238 {
1239         struct sx *sx;
1240
1241         /*
1242          * Check to see if this thread is blocked on an sx lock.
1243          * First, we check the lock class.  If that is ok, then we
1244          * compare the lock name against the wait message.
1245          */
1246         sx = td->td_wchan;
1247         if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1248             sx->lock_object.lo_name != td->td_wmesg)
1249                 return (0);
1250
1251         /* We think we have an sx lock, so output some details. */
1252         db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1253         *ownerp = sx_xholder(sx);
1254         if (sx->sx_lock & SX_LOCK_SHARED)
1255                 db_printf("SLOCK (count %ju)\n",
1256                     (uintmax_t)SX_SHARERS(sx->sx_lock));
1257         else
1258                 db_printf("XLOCK\n");
1259         return (1);
1260 }
1261 #endif