]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_sx.c
Update tcpdump to 4.9.0.
[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 tid, int opts, const char *file,
534     int line)
535 {
536         GIANT_DECLARE;
537 #ifdef ADAPTIVE_SX
538         volatile struct thread *owner;
539         u_int i, spintries = 0;
540 #endif
541         uintptr_t x;
542 #ifdef LOCK_PROFILING
543         uint64_t waittime = 0;
544         int contested = 0;
545 #endif
546         int error = 0;
547 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
548         struct lock_delay_arg lda;
549 #endif
550 #ifdef  KDTRACE_HOOKS
551         uintptr_t state;
552         u_int sleep_cnt = 0;
553         int64_t sleep_time = 0;
554         int64_t all_time = 0;
555 #endif
556
557         if (SCHEDULER_STOPPED())
558                 return (0);
559
560 #if defined(ADAPTIVE_SX)
561         lock_delay_arg_init(&lda, &sx_delay);
562 #elif defined(KDTRACE_HOOKS)
563         lock_delay_arg_init(&lda, NULL);
564 #endif
565
566         x = SX_READ_VALUE(sx);
567
568         /* If we already hold an exclusive lock, then recurse. */
569         if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
570                 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
571             ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
572                     sx->lock_object.lo_name, file, line));
573                 sx->sx_recurse++;
574                 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
575                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
576                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
577                 return (0);
578         }
579
580         if (LOCK_LOG_TEST(&sx->lock_object, 0))
581                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
582                     sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
583
584 #ifdef KDTRACE_HOOKS
585         all_time -= lockstat_nsecs(&sx->lock_object);
586         state = x;
587 #endif
588         for (;;) {
589                 if (x == SX_LOCK_UNLOCKED) {
590                         if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, tid))
591                                 break;
592                         x = SX_READ_VALUE(sx);
593                         continue;
594                 }
595 #ifdef KDTRACE_HOOKS
596                 lda.spin_cnt++;
597 #endif
598 #ifdef HWPMC_HOOKS
599                 PMC_SOFT_CALL( , , lock, failed);
600 #endif
601                 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
602                     &waittime);
603 #ifdef ADAPTIVE_SX
604                 /*
605                  * If the lock is write locked and the owner is
606                  * running on another CPU, spin until the owner stops
607                  * running or the state of the lock changes.
608                  */
609                 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
610                         if ((x & SX_LOCK_SHARED) == 0) {
611                                 owner = lv_sx_owner(x);
612                                 if (TD_IS_RUNNING(owner)) {
613                                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
614                                                 CTR3(KTR_LOCK,
615                                             "%s: spinning on %p held by %p",
616                                                     __func__, sx, owner);
617                                         KTR_STATE1(KTR_SCHED, "thread",
618                                             sched_tdname(curthread), "spinning",
619                                             "lockname:\"%s\"",
620                                             sx->lock_object.lo_name);
621                                         GIANT_SAVE();
622                                         do {
623                                                 lock_delay(&lda);
624                                                 x = SX_READ_VALUE(sx);
625                                                 owner = lv_sx_owner(x);
626                                         } while (owner != NULL &&
627                                                     TD_IS_RUNNING(owner));
628                                         KTR_STATE0(KTR_SCHED, "thread",
629                                             sched_tdname(curthread), "running");
630                                         continue;
631                                 }
632                         } else if (SX_SHARERS(x) && spintries < asx_retries) {
633                                 KTR_STATE1(KTR_SCHED, "thread",
634                                     sched_tdname(curthread), "spinning",
635                                     "lockname:\"%s\"", sx->lock_object.lo_name);
636                                 GIANT_SAVE();
637                                 spintries++;
638                                 for (i = 0; i < asx_loops; i++) {
639                                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
640                                                 CTR4(KTR_LOCK,
641                                     "%s: shared spinning on %p with %u and %u",
642                                                     __func__, sx, spintries, i);
643                                         x = sx->sx_lock;
644                                         if ((x & SX_LOCK_SHARED) == 0 ||
645                                             SX_SHARERS(x) == 0)
646                                                 break;
647                                         cpu_spinwait();
648 #ifdef KDTRACE_HOOKS
649                                         lda.spin_cnt++;
650 #endif
651                                 }
652                                 KTR_STATE0(KTR_SCHED, "thread",
653                                     sched_tdname(curthread), "running");
654                                 x = SX_READ_VALUE(sx);
655                                 if (i != asx_loops)
656                                         continue;
657                         }
658                 }
659 #endif
660
661                 sleepq_lock(&sx->lock_object);
662                 x = SX_READ_VALUE(sx);
663
664                 /*
665                  * If the lock was released while spinning on the
666                  * sleep queue chain lock, try again.
667                  */
668                 if (x == SX_LOCK_UNLOCKED) {
669                         sleepq_release(&sx->lock_object);
670                         continue;
671                 }
672
673 #ifdef ADAPTIVE_SX
674                 /*
675                  * The current lock owner might have started executing
676                  * on another CPU (or the lock could have changed
677                  * owners) while we were waiting on the sleep queue
678                  * chain lock.  If so, drop the sleep queue lock and try
679                  * again.
680                  */
681                 if (!(x & SX_LOCK_SHARED) &&
682                     (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
683                         owner = (struct thread *)SX_OWNER(x);
684                         if (TD_IS_RUNNING(owner)) {
685                                 sleepq_release(&sx->lock_object);
686                                 continue;
687                         }
688                 }
689 #endif
690
691                 /*
692                  * If an exclusive lock was released with both shared
693                  * and exclusive waiters and a shared waiter hasn't
694                  * woken up and acquired the lock yet, sx_lock will be
695                  * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
696                  * If we see that value, try to acquire it once.  Note
697                  * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
698                  * as there are other exclusive waiters still.  If we
699                  * fail, restart the loop.
700                  */
701                 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
702                         if (atomic_cmpset_acq_ptr(&sx->sx_lock,
703                             SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
704                             tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
705                                 sleepq_release(&sx->lock_object);
706                                 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
707                                     __func__, sx);
708                                 break;
709                         }
710                         sleepq_release(&sx->lock_object);
711                         x = SX_READ_VALUE(sx);
712                         continue;
713                 }
714
715                 /*
716                  * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
717                  * than loop back and retry.
718                  */
719                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
720                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
721                             x | SX_LOCK_EXCLUSIVE_WAITERS)) {
722                                 sleepq_release(&sx->lock_object);
723                                 x = SX_READ_VALUE(sx);
724                                 continue;
725                         }
726                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
727                                 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
728                                     __func__, sx);
729                 }
730
731                 /*
732                  * Since we have been unable to acquire the exclusive
733                  * lock and the exclusive waiters flag is set, we have
734                  * to sleep.
735                  */
736                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
737                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
738                             __func__, sx);
739
740 #ifdef KDTRACE_HOOKS
741                 sleep_time -= lockstat_nsecs(&sx->lock_object);
742 #endif
743                 GIANT_SAVE();
744                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
745                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
746                     SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
747                 if (!(opts & SX_INTERRUPTIBLE))
748                         sleepq_wait(&sx->lock_object, 0);
749                 else
750                         error = sleepq_wait_sig(&sx->lock_object, 0);
751 #ifdef KDTRACE_HOOKS
752                 sleep_time += lockstat_nsecs(&sx->lock_object);
753                 sleep_cnt++;
754 #endif
755                 if (error) {
756                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
757                                 CTR2(KTR_LOCK,
758                         "%s: interruptible sleep by %p suspended by signal",
759                                     __func__, sx);
760                         break;
761                 }
762                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
763                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
764                             __func__, sx);
765                 x = SX_READ_VALUE(sx);
766         }
767 #ifdef KDTRACE_HOOKS
768         all_time += lockstat_nsecs(&sx->lock_object);
769         if (sleep_time)
770                 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
771                     LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
772                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
773         if (lda.spin_cnt > sleep_cnt)
774                 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
775                     LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
776                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
777 #endif
778         if (!error)
779                 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
780                     contested, waittime, file, line, LOCKSTAT_WRITER);
781         GIANT_RESTORE();
782         return (error);
783 }
784
785 /*
786  * This function represents the so-called 'hard case' for sx_xunlock
787  * operation.  All 'easy case' failures are redirected to this.  Note
788  * that ideally this would be a static function, but it needs to be
789  * accessible from at least sx.h.
790  */
791 void
792 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
793 {
794         uintptr_t x;
795         int queue, wakeup_swapper;
796
797         if (SCHEDULER_STOPPED())
798                 return;
799
800         MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
801
802         /* If the lock is recursed, then unrecurse one level. */
803         if (sx_xlocked(sx) && sx_recursed(sx)) {
804                 if ((--sx->sx_recurse) == 0)
805                         atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
806                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
807                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
808                 return;
809         }
810         MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
811             SX_LOCK_EXCLUSIVE_WAITERS));
812         if (LOCK_LOG_TEST(&sx->lock_object, 0))
813                 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
814
815         sleepq_lock(&sx->lock_object);
816         x = SX_LOCK_UNLOCKED;
817
818         /*
819          * The wake up algorithm here is quite simple and probably not
820          * ideal.  It gives precedence to shared waiters if they are
821          * present.  For this condition, we have to preserve the
822          * state of the exclusive waiters flag.
823          * If interruptible sleeps left the shared queue empty avoid a
824          * starvation for the threads sleeping on the exclusive queue by giving
825          * them precedence and cleaning up the shared waiters bit anyway.
826          */
827         if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
828             sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
829                 queue = SQ_SHARED_QUEUE;
830                 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
831         } else
832                 queue = SQ_EXCLUSIVE_QUEUE;
833
834         /* Wake up all the waiters for the specific queue. */
835         if (LOCK_LOG_TEST(&sx->lock_object, 0))
836                 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
837                     __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
838                     "exclusive");
839         atomic_store_rel_ptr(&sx->sx_lock, x);
840         wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
841             queue);
842         sleepq_release(&sx->lock_object);
843         if (wakeup_swapper)
844                 kick_proc0();
845 }
846
847 /*
848  * This function represents the so-called 'hard case' for sx_slock
849  * operation.  All 'easy case' failures are redirected to this.  Note
850  * that ideally this would be a static function, but it needs to be
851  * accessible from at least sx.h.
852  */
853 int
854 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
855 {
856         GIANT_DECLARE;
857 #ifdef ADAPTIVE_SX
858         volatile struct thread *owner;
859 #endif
860 #ifdef LOCK_PROFILING
861         uint64_t waittime = 0;
862         int contested = 0;
863 #endif
864         uintptr_t x;
865         int error = 0;
866 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
867         struct lock_delay_arg lda;
868 #endif
869 #ifdef KDTRACE_HOOKS
870         uintptr_t state;
871         u_int sleep_cnt = 0;
872         int64_t sleep_time = 0;
873         int64_t all_time = 0;
874 #endif
875
876         if (SCHEDULER_STOPPED())
877                 return (0);
878
879 #if defined(ADAPTIVE_SX)
880         lock_delay_arg_init(&lda, &sx_delay);
881 #elif defined(KDTRACE_HOOKS)
882         lock_delay_arg_init(&lda, NULL);
883 #endif
884 #ifdef KDTRACE_HOOKS
885         all_time -= lockstat_nsecs(&sx->lock_object);
886 #endif
887         x = SX_READ_VALUE(sx);
888 #ifdef KDTRACE_HOOKS
889         state = x;
890 #endif
891
892         /*
893          * As with rwlocks, we don't make any attempt to try to block
894          * shared locks once there is an exclusive waiter.
895          */
896         for (;;) {
897                 /*
898                  * If no other thread has an exclusive lock then try to bump up
899                  * the count of sharers.  Since we have to preserve the state
900                  * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
901                  * shared lock loop back and retry.
902                  */
903                 if (x & SX_LOCK_SHARED) {
904                         MPASS(!(x & SX_LOCK_SHARED_WAITERS));
905                         if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
906                             x + SX_ONE_SHARER)) {
907                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
908                                         CTR4(KTR_LOCK,
909                                             "%s: %p succeed %p -> %p", __func__,
910                                             sx, (void *)x,
911                                             (void *)(x + SX_ONE_SHARER));
912                                 break;
913                         }
914                         x = SX_READ_VALUE(sx);
915                         continue;
916                 }
917 #ifdef KDTRACE_HOOKS
918                 lda.spin_cnt++;
919 #endif
920
921 #ifdef HWPMC_HOOKS
922                 PMC_SOFT_CALL( , , lock, failed);
923 #endif
924                 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
925                     &waittime);
926
927 #ifdef ADAPTIVE_SX
928                 /*
929                  * If the owner is running on another CPU, spin until
930                  * the owner stops running or the state of the lock
931                  * changes.
932                  */
933                 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
934                         owner = lv_sx_owner(x);
935                         if (TD_IS_RUNNING(owner)) {
936                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
937                                         CTR3(KTR_LOCK,
938                                             "%s: spinning on %p held by %p",
939                                             __func__, sx, owner);
940                                 KTR_STATE1(KTR_SCHED, "thread",
941                                     sched_tdname(curthread), "spinning",
942                                     "lockname:\"%s\"", sx->lock_object.lo_name);
943                                 GIANT_SAVE();
944                                 do {
945                                         lock_delay(&lda);
946                                         x = SX_READ_VALUE(sx);
947                                         owner = lv_sx_owner(x);
948                                 } while (owner != NULL && TD_IS_RUNNING(owner));
949                                 KTR_STATE0(KTR_SCHED, "thread",
950                                     sched_tdname(curthread), "running");
951                                 continue;
952                         }
953                 }
954 #endif
955
956                 /*
957                  * Some other thread already has an exclusive lock, so
958                  * start the process of blocking.
959                  */
960                 sleepq_lock(&sx->lock_object);
961                 x = SX_READ_VALUE(sx);
962
963                 /*
964                  * The lock could have been released while we spun.
965                  * In this case loop back and retry.
966                  */
967                 if (x & SX_LOCK_SHARED) {
968                         sleepq_release(&sx->lock_object);
969                         continue;
970                 }
971
972 #ifdef ADAPTIVE_SX
973                 /*
974                  * If the owner is running on another CPU, spin until
975                  * the owner stops running or the state of the lock
976                  * changes.
977                  */
978                 if (!(x & SX_LOCK_SHARED) &&
979                     (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
980                         owner = (struct thread *)SX_OWNER(x);
981                         if (TD_IS_RUNNING(owner)) {
982                                 sleepq_release(&sx->lock_object);
983                                 x = SX_READ_VALUE(sx);
984                                 continue;
985                         }
986                 }
987 #endif
988
989                 /*
990                  * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
991                  * fail to set it drop the sleep queue lock and loop
992                  * back.
993                  */
994                 if (!(x & SX_LOCK_SHARED_WAITERS)) {
995                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
996                             x | SX_LOCK_SHARED_WAITERS)) {
997                                 sleepq_release(&sx->lock_object);
998                                 x = SX_READ_VALUE(sx);
999                                 continue;
1000                         }
1001                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
1002                                 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1003                                     __func__, sx);
1004                 }
1005
1006                 /*
1007                  * Since we have been unable to acquire the shared lock,
1008                  * we have to sleep.
1009                  */
1010                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1011                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1012                             __func__, sx);
1013
1014 #ifdef KDTRACE_HOOKS
1015                 sleep_time -= lockstat_nsecs(&sx->lock_object);
1016 #endif
1017                 GIANT_SAVE();
1018                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1019                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1020                     SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1021                 if (!(opts & SX_INTERRUPTIBLE))
1022                         sleepq_wait(&sx->lock_object, 0);
1023                 else
1024                         error = sleepq_wait_sig(&sx->lock_object, 0);
1025 #ifdef KDTRACE_HOOKS
1026                 sleep_time += lockstat_nsecs(&sx->lock_object);
1027                 sleep_cnt++;
1028 #endif
1029                 if (error) {
1030                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
1031                                 CTR2(KTR_LOCK,
1032                         "%s: interruptible sleep by %p suspended by signal",
1033                                     __func__, sx);
1034                         break;
1035                 }
1036                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1037                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1038                             __func__, sx);
1039                 x = SX_READ_VALUE(sx);
1040         }
1041 #ifdef KDTRACE_HOOKS
1042         all_time += lockstat_nsecs(&sx->lock_object);
1043         if (sleep_time)
1044                 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1045                     LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1046                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1047         if (lda.spin_cnt > sleep_cnt)
1048                 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1049                     LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1050                     (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1051 #endif
1052         if (error == 0)
1053                 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1054                     contested, waittime, file, line, LOCKSTAT_READER);
1055         GIANT_RESTORE();
1056         return (error);
1057 }
1058
1059 /*
1060  * This function represents the so-called 'hard case' for sx_sunlock
1061  * operation.  All 'easy case' failures are redirected to this.  Note
1062  * that ideally this would be a static function, but it needs to be
1063  * accessible from at least sx.h.
1064  */
1065 void
1066 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
1067 {
1068         uintptr_t x;
1069         int wakeup_swapper;
1070
1071         if (SCHEDULER_STOPPED())
1072                 return;
1073
1074         x = SX_READ_VALUE(sx);
1075         for (;;) {
1076                 /*
1077                  * We should never have sharers while at least one thread
1078                  * holds a shared lock.
1079                  */
1080                 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1081                     ("%s: waiting sharers", __func__));
1082
1083                 /*
1084                  * See if there is more than one shared lock held.  If
1085                  * so, just drop one and return.
1086                  */
1087                 if (SX_SHARERS(x) > 1) {
1088                         if (atomic_cmpset_rel_ptr(&sx->sx_lock, x,
1089                             x - SX_ONE_SHARER)) {
1090                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1091                                         CTR4(KTR_LOCK,
1092                                             "%s: %p succeeded %p -> %p",
1093                                             __func__, sx, (void *)x,
1094                                             (void *)(x - SX_ONE_SHARER));
1095                                 break;
1096                         }
1097
1098                         x = SX_READ_VALUE(sx);
1099                         continue;
1100                 }
1101
1102                 /*
1103                  * If there aren't any waiters for an exclusive lock,
1104                  * then try to drop it quickly.
1105                  */
1106                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1107                         MPASS(x == SX_SHARERS_LOCK(1));
1108                         if (atomic_cmpset_rel_ptr(&sx->sx_lock,
1109                             SX_SHARERS_LOCK(1), SX_LOCK_UNLOCKED)) {
1110                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1111                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
1112                                             __func__, sx);
1113                                 break;
1114                         }
1115                         x = SX_READ_VALUE(sx);
1116                         continue;
1117                 }
1118
1119                 /*
1120                  * At this point, there should just be one sharer with
1121                  * exclusive waiters.
1122                  */
1123                 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1124
1125                 sleepq_lock(&sx->lock_object);
1126
1127                 /*
1128                  * Wake up semantic here is quite simple:
1129                  * Just wake up all the exclusive waiters.
1130                  * Note that the state of the lock could have changed,
1131                  * so if it fails loop back and retry.
1132                  */
1133                 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1134                     SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1135                     SX_LOCK_UNLOCKED)) {
1136                         sleepq_release(&sx->lock_object);
1137                         x = SX_READ_VALUE(sx);
1138                         continue;
1139                 }
1140                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1141                         CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1142                             "exclusive queue", __func__, sx);
1143                 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1144                     0, SQ_EXCLUSIVE_QUEUE);
1145                 sleepq_release(&sx->lock_object);
1146                 if (wakeup_swapper)
1147                         kick_proc0();
1148                 break;
1149         }
1150 }
1151
1152 #ifdef INVARIANT_SUPPORT
1153 #ifndef INVARIANTS
1154 #undef  _sx_assert
1155 #endif
1156
1157 /*
1158  * In the non-WITNESS case, sx_assert() can only detect that at least
1159  * *some* thread owns an slock, but it cannot guarantee that *this*
1160  * thread owns an slock.
1161  */
1162 void
1163 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1164 {
1165 #ifndef WITNESS
1166         int slocked = 0;
1167 #endif
1168
1169         if (panicstr != NULL)
1170                 return;
1171         switch (what) {
1172         case SA_SLOCKED:
1173         case SA_SLOCKED | SA_NOTRECURSED:
1174         case SA_SLOCKED | SA_RECURSED:
1175 #ifndef WITNESS
1176                 slocked = 1;
1177                 /* FALLTHROUGH */
1178 #endif
1179         case SA_LOCKED:
1180         case SA_LOCKED | SA_NOTRECURSED:
1181         case SA_LOCKED | SA_RECURSED:
1182 #ifdef WITNESS
1183                 witness_assert(&sx->lock_object, what, file, line);
1184 #else
1185                 /*
1186                  * If some other thread has an exclusive lock or we
1187                  * have one and are asserting a shared lock, fail.
1188                  * Also, if no one has a lock at all, fail.
1189                  */
1190                 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1191                     (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1192                     sx_xholder(sx) != curthread)))
1193                         panic("Lock %s not %slocked @ %s:%d\n",
1194                             sx->lock_object.lo_name, slocked ? "share " : "",
1195                             file, line);
1196
1197                 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1198                         if (sx_recursed(sx)) {
1199                                 if (what & SA_NOTRECURSED)
1200                                         panic("Lock %s recursed @ %s:%d\n",
1201                                             sx->lock_object.lo_name, file,
1202                                             line);
1203                         } else if (what & SA_RECURSED)
1204                                 panic("Lock %s not recursed @ %s:%d\n",
1205                                     sx->lock_object.lo_name, file, line);
1206                 }
1207 #endif
1208                 break;
1209         case SA_XLOCKED:
1210         case SA_XLOCKED | SA_NOTRECURSED:
1211         case SA_XLOCKED | SA_RECURSED:
1212                 if (sx_xholder(sx) != curthread)
1213                         panic("Lock %s not exclusively locked @ %s:%d\n",
1214                             sx->lock_object.lo_name, file, line);
1215                 if (sx_recursed(sx)) {
1216                         if (what & SA_NOTRECURSED)
1217                                 panic("Lock %s recursed @ %s:%d\n",
1218                                     sx->lock_object.lo_name, file, line);
1219                 } else if (what & SA_RECURSED)
1220                         panic("Lock %s not recursed @ %s:%d\n",
1221                             sx->lock_object.lo_name, file, line);
1222                 break;
1223         case SA_UNLOCKED:
1224 #ifdef WITNESS
1225                 witness_assert(&sx->lock_object, what, file, line);
1226 #else
1227                 /*
1228                  * If we hold an exclusve lock fail.  We can't
1229                  * reliably check to see if we hold a shared lock or
1230                  * not.
1231                  */
1232                 if (sx_xholder(sx) == curthread)
1233                         panic("Lock %s exclusively locked @ %s:%d\n",
1234                             sx->lock_object.lo_name, file, line);
1235 #endif
1236                 break;
1237         default:
1238                 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1239                     line);
1240         }
1241 }
1242 #endif  /* INVARIANT_SUPPORT */
1243
1244 #ifdef DDB
1245 static void
1246 db_show_sx(const struct lock_object *lock)
1247 {
1248         struct thread *td;
1249         const struct sx *sx;
1250
1251         sx = (const struct sx *)lock;
1252
1253         db_printf(" state: ");
1254         if (sx->sx_lock == SX_LOCK_UNLOCKED)
1255                 db_printf("UNLOCKED\n");
1256         else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1257                 db_printf("DESTROYED\n");
1258                 return;
1259         } else if (sx->sx_lock & SX_LOCK_SHARED)
1260                 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1261         else {
1262                 td = sx_xholder(sx);
1263                 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1264                     td->td_tid, td->td_proc->p_pid, td->td_name);
1265                 if (sx_recursed(sx))
1266                         db_printf(" recursed: %d\n", sx->sx_recurse);
1267         }
1268
1269         db_printf(" waiters: ");
1270         switch(sx->sx_lock &
1271             (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1272         case SX_LOCK_SHARED_WAITERS:
1273                 db_printf("shared\n");
1274                 break;
1275         case SX_LOCK_EXCLUSIVE_WAITERS:
1276                 db_printf("exclusive\n");
1277                 break;
1278         case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1279                 db_printf("exclusive and shared\n");
1280                 break;
1281         default:
1282                 db_printf("none\n");
1283         }
1284 }
1285
1286 /*
1287  * Check to see if a thread that is blocked on a sleep queue is actually
1288  * blocked on an sx lock.  If so, output some details and return true.
1289  * If the lock has an exclusive owner, return that in *ownerp.
1290  */
1291 int
1292 sx_chain(struct thread *td, struct thread **ownerp)
1293 {
1294         struct sx *sx;
1295
1296         /*
1297          * Check to see if this thread is blocked on an sx lock.
1298          * First, we check the lock class.  If that is ok, then we
1299          * compare the lock name against the wait message.
1300          */
1301         sx = td->td_wchan;
1302         if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1303             sx->lock_object.lo_name != td->td_wmesg)
1304                 return (0);
1305
1306         /* We think we have an sx lock, so output some details. */
1307         db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1308         *ownerp = sx_xholder(sx);
1309         if (sx->sx_lock & SX_LOCK_SHARED)
1310                 db_printf("SLOCK (count %ju)\n",
1311                     (uintmax_t)SX_SHARERS(sx->sx_lock));
1312         else
1313                 db_printf("XLOCK\n");
1314         return (1);
1315 }
1316 #endif