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