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