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