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