]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_sx.c
This commit was generated by cvs2svn to compensate for changes in r170764,
[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_adaptive_sx.h"
40 #include "opt_ddb.h"
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 #include <sys/param.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/proc.h>
50 #include <sys/sleepqueue.h>
51 #include <sys/sx.h>
52 #include <sys/systm.h>
53
54 #ifdef ADAPTIVE_SX
55 #include <machine/cpu.h>
56 #endif
57
58 #ifdef DDB
59 #include <ddb/ddb.h>
60 #endif
61
62 #if !defined(SMP) && defined(ADAPTIVE_SX)
63 #error "You must have SMP to enable the ADAPTIVE_SX option"
64 #endif
65
66 /* Handy macros for sleep queues. */
67 #define SQ_EXCLUSIVE_QUEUE      0
68 #define SQ_SHARED_QUEUE         1
69
70 /*
71  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
72  * drop Giant anytime we have to sleep or if we adaptively spin.
73  */
74 #define GIANT_DECLARE                                                   \
75         int _giantcnt = 0;                                              \
76         WITNESS_SAVE_DECL(Giant)                                        \
77
78 #define GIANT_SAVE() do {                                               \
79         if (mtx_owned(&Giant)) {                                        \
80                 WITNESS_SAVE(&Giant.lock_object, Giant);                \
81                 while (mtx_owned(&Giant)) {                             \
82                         _giantcnt++;                                    \
83                         mtx_unlock(&Giant);                             \
84                 }                                                       \
85         }                                                               \
86 } while (0)
87
88 #define GIANT_RESTORE() do {                                            \
89         if (_giantcnt > 0) {                                            \
90                 mtx_assert(&Giant, MA_NOTOWNED);                        \
91                 while (_giantcnt--)                                     \
92                         mtx_lock(&Giant);                               \
93                 WITNESS_RESTORE(&Giant.lock_object, Giant);             \
94         }                                                               \
95 } while (0)
96
97 /*
98  * Returns true if an exclusive lock is recursed.  It assumes
99  * curthread currently has an exclusive lock.
100  */
101 #define sx_recursed(sx)         ((sx)->sx_recurse != 0)
102
103 #ifdef DDB
104 static void     db_show_sx(struct lock_object *lock);
105 #endif
106 static void     lock_sx(struct lock_object *lock, int how);
107 static int      unlock_sx(struct lock_object *lock);
108
109 struct lock_class lock_class_sx = {
110         .lc_name = "sx",
111         .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
112 #ifdef DDB
113         .lc_ddb_show = db_show_sx,
114 #endif
115         .lc_lock = lock_sx,
116         .lc_unlock = unlock_sx,
117 };
118
119 #ifndef INVARIANTS
120 #define _sx_assert(sx, what, file, line)
121 #endif
122
123 void
124 lock_sx(struct lock_object *lock, int how)
125 {
126         struct sx *sx;
127
128         sx = (struct sx *)lock;
129         if (how)
130                 sx_xlock(sx);
131         else
132                 sx_slock(sx);
133 }
134
135 int
136 unlock_sx(struct lock_object *lock)
137 {
138         struct sx *sx;
139
140         sx = (struct sx *)lock;
141         sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
142         if (sx_xlocked(sx)) {
143                 sx_xunlock(sx);
144                 return (1);
145         } else {
146                 sx_sunlock(sx);
147                 return (0);
148         }
149 }
150
151 void
152 sx_sysinit(void *arg)
153 {
154         struct sx_args *sargs = arg;
155
156         sx_init(sargs->sa_sx, sargs->sa_desc);
157 }
158
159 void
160 sx_init_flags(struct sx *sx, const char *description, int opts)
161 {
162         int flags;
163
164         MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
165             SX_NOPROFILE | SX_ADAPTIVESPIN)) == 0);
166
167         flags = LO_RECURSABLE | LO_SLEEPABLE | LO_UPGRADABLE;
168         if (opts & SX_DUPOK)
169                 flags |= LO_DUPOK;
170         if (opts & SX_NOPROFILE)
171                 flags |= LO_NOPROFILE;
172         if (!(opts & SX_NOWITNESS))
173                 flags |= LO_WITNESS;
174         if (opts & SX_QUIET)
175                 flags |= LO_QUIET;
176
177         flags |= opts & (SX_ADAPTIVESPIN | SX_RECURSE);
178         sx->sx_lock = SX_LOCK_UNLOCKED;
179         sx->sx_recurse = 0;
180         lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
181 }
182
183 void
184 sx_destroy(struct sx *sx)
185 {
186
187         KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
188         KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
189         sx->sx_lock = SX_LOCK_DESTROYED;
190         lock_destroy(&sx->lock_object);
191 }
192
193 int
194 _sx_slock(struct sx *sx, int opts, const char *file, int line)
195 {
196         int error = 0;
197
198         MPASS(curthread != NULL);
199         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
200             ("sx_slock() of destroyed sx @ %s:%d", file, line));
201         WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line);
202         error = __sx_slock(sx, opts, file, line);
203         if (!error) {
204                 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
205                 WITNESS_LOCK(&sx->lock_object, 0, file, line);
206                 curthread->td_locks++;
207         }
208
209         return (error);
210 }
211
212 int
213 _sx_try_slock(struct sx *sx, const char *file, int line)
214 {
215         uintptr_t x;
216
217         x = sx->sx_lock;
218         KASSERT(x != SX_LOCK_DESTROYED,
219             ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
220         if ((x & SX_LOCK_SHARED) && atomic_cmpset_acq_ptr(&sx->sx_lock, x,
221             x + SX_ONE_SHARER)) {
222                 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
223                 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
224                 curthread->td_locks++;
225                 return (1);
226         }
227
228         LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
229         return (0);
230 }
231
232 int
233 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
234 {
235         int error = 0;
236
237         MPASS(curthread != NULL);
238         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
239             ("sx_xlock() of destroyed sx @ %s:%d", file, line));
240         WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
241             line);
242         error = __sx_xlock(sx, curthread, opts, file, line);
243         if (!error) {
244                 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
245                     file, line);
246                 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
247                 curthread->td_locks++;
248         }
249
250         return (error);
251 }
252
253 int
254 _sx_try_xlock(struct sx *sx, const char *file, int line)
255 {
256         int rval;
257
258         MPASS(curthread != NULL);
259         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
260             ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
261
262         if (sx_xlocked(sx) && (sx->lock_object.lo_flags & SX_RECURSE) != 0) {
263                 sx->sx_recurse++;
264                 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
265                 rval = 1;
266         } else
267                 rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
268                     (uintptr_t)curthread);
269         LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
270         if (rval) {
271                 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
272                     file, line);
273                 curthread->td_locks++;
274         }
275
276         return (rval);
277 }
278
279 void
280 _sx_sunlock(struct sx *sx, const char *file, int line)
281 {
282
283         MPASS(curthread != NULL);
284         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
285             ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
286         _sx_assert(sx, SA_SLOCKED, file, line);
287         curthread->td_locks--;
288         WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
289         LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
290         if (SX_SHARERS(sx->sx_lock) == 1)
291                 lock_profile_release_lock(&sx->lock_object);
292         __sx_sunlock(sx, file, line);
293 }
294
295 void
296 _sx_xunlock(struct sx *sx, const char *file, int line)
297 {
298
299         MPASS(curthread != NULL);
300         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
301             ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
302         _sx_assert(sx, SA_XLOCKED, file, line);
303         curthread->td_locks--;
304         WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
305         LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
306             line);
307         if (!sx_recursed(sx))
308                 lock_profile_release_lock(&sx->lock_object);
309         __sx_xunlock(sx, curthread, file, line);
310 }
311
312 /*
313  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
314  * This will only succeed if this thread holds a single shared lock.
315  * Return 1 if if the upgrade succeed, 0 otherwise.
316  */
317 int
318 _sx_try_upgrade(struct sx *sx, const char *file, int line)
319 {
320         uintptr_t x;
321         int success;
322
323         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
324             ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
325         _sx_assert(sx, SA_SLOCKED, file, line);
326
327         /*
328          * Try to switch from one shared lock to an exclusive lock.  We need
329          * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
330          * we will wake up the exclusive waiters when we drop the lock.
331          */
332         x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
333         success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
334             (uintptr_t)curthread | x);
335         LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
336         if (success)
337                 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
338                     file, line);
339         return (success);
340 }
341
342 /*
343  * Downgrade an unrecursed exclusive lock into a single shared lock.
344  */
345 void
346 _sx_downgrade(struct sx *sx, const char *file, int line)
347 {
348         uintptr_t x;
349
350         KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
351             ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
352         _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
353 #ifndef INVARIANTS
354         if (sx_recursed(sx))
355                 panic("downgrade of a recursed lock");
356 #endif
357
358         WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
359
360         /*
361          * Try to switch from an exclusive lock with no shared waiters
362          * to one sharer with no shared waiters.  If there are
363          * exclusive waiters, we don't need to lock the sleep queue so
364          * long as we preserve the flag.  We do one quick try and if
365          * that fails we grab the sleepq lock to keep the flags from
366          * changing and do it the slow way.
367          *
368          * We have to lock the sleep queue if there are shared waiters
369          * so we can wake them up.
370          */
371         x = sx->sx_lock;
372         if (!(x & SX_LOCK_SHARED_WAITERS) &&
373             atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
374             (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
375                 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
376                 return;
377         }
378
379         /*
380          * Lock the sleep queue so we can read the waiters bits
381          * without any races and wakeup any shared waiters.
382          */
383         sleepq_lock(&sx->lock_object);
384
385         /*
386          * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
387          * shared lock.  If there are any shared waiters, wake them up.
388          */
389         x = sx->sx_lock;
390         atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
391             (x & SX_LOCK_EXCLUSIVE_WAITERS));
392         if (x & SX_LOCK_SHARED_WAITERS)
393                 sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, -1,
394                     SQ_SHARED_QUEUE);
395         else
396                 sleepq_release(&sx->lock_object);
397
398         LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
399 }
400
401 /*
402  * This function represents the so-called 'hard case' for sx_xlock
403  * operation.  All 'easy case' failures are redirected to this.  Note
404  * that ideally this would be a static function, but it needs to be
405  * accessible from at least sx.h.
406  */
407 int
408 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
409     int line)
410 {
411         GIANT_DECLARE;
412 #ifdef ADAPTIVE_SX
413         volatile struct thread *owner;
414 #endif
415         uintptr_t x;
416         int contested = 0, error = 0;
417         uint64_t waitstart = 0;
418
419         /* If we already hold an exclusive lock, then recurse. */
420         if (sx_xlocked(sx)) {
421                 KASSERT((sx->lock_object.lo_flags & SX_RECURSE) != 0,
422             ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
423                     sx->lock_object.lo_name, file, line));              
424                 sx->sx_recurse++;
425                 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
426                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
427                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
428                 return (0);
429         }
430         lock_profile_obtain_lock_failed(&(sx)->lock_object,
431             &contested, &waitstart);
432
433         if (LOCK_LOG_TEST(&sx->lock_object, 0))
434                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
435                     sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
436
437         while (!atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid)) {
438 #ifdef ADAPTIVE_SX
439                 /*
440                  * If the lock is write locked and the owner is
441                  * running on another CPU, spin until the owner stops
442                  * running or the state of the lock changes.
443                  */
444                 x = sx->sx_lock;
445                 if (!(x & SX_LOCK_SHARED) &&
446                     (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
447                         x = SX_OWNER(x);
448                         owner = (struct thread *)x;
449                         if (TD_IS_RUNNING(owner)) {
450                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
451                                         CTR3(KTR_LOCK,
452                                             "%s: spinning on %p held by %p",
453                                             __func__, sx, owner);
454                                 GIANT_SAVE();
455                                 while (SX_OWNER(sx->sx_lock) == x &&
456                                     TD_IS_RUNNING(owner))
457                                         cpu_spinwait();
458                                 continue;
459                         }
460                 }
461 #endif
462
463                 sleepq_lock(&sx->lock_object);
464                 x = sx->sx_lock;
465
466                 /*
467                  * If the lock was released while spinning on the
468                  * sleep queue chain lock, try again.
469                  */
470                 if (x == SX_LOCK_UNLOCKED) {
471                         sleepq_release(&sx->lock_object);
472                         continue;
473                 }
474
475 #ifdef ADAPTIVE_SX
476                 /*
477                  * The current lock owner might have started executing
478                  * on another CPU (or the lock could have changed
479                  * owners) while we were waiting on the sleep queue
480                  * chain lock.  If so, drop the sleep queue lock and try
481                  * again.
482                  */
483                 if (!(x & SX_LOCK_SHARED) &&
484                     (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
485                         owner = (struct thread *)SX_OWNER(x);
486                         if (TD_IS_RUNNING(owner)) {
487                                 sleepq_release(&sx->lock_object);
488                                 continue;
489                         }
490                 }
491 #endif
492
493                 /*
494                  * If an exclusive lock was released with both shared
495                  * and exclusive waiters and a shared waiter hasn't
496                  * woken up and acquired the lock yet, sx_lock will be
497                  * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
498                  * If we see that value, try to acquire it once.  Note
499                  * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
500                  * as there are other exclusive waiters still.  If we
501                  * fail, restart the loop.
502                  */
503                 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
504                         if (atomic_cmpset_acq_ptr(&sx->sx_lock,
505                             SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
506                             tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
507                                 sleepq_release(&sx->lock_object);
508                                 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
509                                     __func__, sx);
510                                 break;
511                         }
512                         sleepq_release(&sx->lock_object);
513                         continue;
514                 }
515
516                 /*
517                  * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
518                  * than loop back and retry.
519                  */
520                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
521                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
522                             x | SX_LOCK_EXCLUSIVE_WAITERS)) {
523                                 sleepq_release(&sx->lock_object);
524                                 continue;
525                         }
526                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
527                                 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
528                                     __func__, sx);
529                 }
530
531                 /*
532                  * Since we have been unable to acquire the exclusive
533                  * lock and the exclusive waiters flag is set, we have
534                  * to sleep.
535                  */
536                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
537                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
538                             __func__, sx);
539
540                 GIANT_SAVE();
541                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
542                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
543                     SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
544                 if (!(opts & SX_INTERRUPTIBLE))
545                         sleepq_wait(&sx->lock_object);
546                 else
547                         error = sleepq_wait_sig(&sx->lock_object);
548
549                 if (error) {
550                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
551                                 CTR2(KTR_LOCK,
552                         "%s: interruptible sleep by %p suspended by signal",
553                                     __func__, sx);
554                         break;
555                 }
556                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
557                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
558                             __func__, sx);
559         }
560
561         GIANT_RESTORE();
562         if (!error)
563                 lock_profile_obtain_lock_success(&(sx)->lock_object, contested,
564                     waitstart, file, line);
565         return (error);
566 }
567
568 /*
569  * This function represents the so-called 'hard case' for sx_xunlock
570  * operation.  All 'easy case' failures are redirected to this.  Note
571  * that ideally this would be a static function, but it needs to be
572  * accessible from at least sx.h.
573  */
574 void
575 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
576 {
577         uintptr_t x;
578         int queue;
579
580         MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
581
582         /* If the lock is recursed, then unrecurse one level. */
583         if (sx_xlocked(sx) && sx_recursed(sx)) {
584                 if ((--sx->sx_recurse) == 0)
585                         atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
586                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
587                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
588                 return;
589         }
590         MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
591             SX_LOCK_EXCLUSIVE_WAITERS));
592         if (LOCK_LOG_TEST(&sx->lock_object, 0))
593                 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
594
595         sleepq_lock(&sx->lock_object);
596         x = SX_LOCK_UNLOCKED;
597
598         /*
599          * The wake up algorithm here is quite simple and probably not
600          * ideal.  It gives precedence to shared waiters if they are
601          * present.  For this condition, we have to preserve the
602          * state of the exclusive waiters flag.
603          */
604         if (sx->sx_lock & SX_LOCK_SHARED_WAITERS) {
605                 queue = SQ_SHARED_QUEUE;
606                 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
607         } else
608                 queue = SQ_EXCLUSIVE_QUEUE;
609
610         /* Wake up all the waiters for the specific queue. */
611         if (LOCK_LOG_TEST(&sx->lock_object, 0))
612                 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
613                     __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
614                     "exclusive");
615         atomic_store_rel_ptr(&sx->sx_lock, x);
616         sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, -1, queue);
617 }
618
619 /*
620  * This function represents the so-called 'hard case' for sx_slock
621  * operation.  All 'easy case' failures are redirected to this.  Note
622  * that ideally this would be a static function, but it needs to be
623  * accessible from at least sx.h.
624  */
625 int
626 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
627 {
628         GIANT_DECLARE;
629 #ifdef ADAPTIVE_SX
630         volatile struct thread *owner;
631 #endif
632         uintptr_t x;
633         uint64_t waitstart = 0;
634         int contested = 0, error = 0;
635         /*
636          * As with rwlocks, we don't make any attempt to try to block
637          * shared locks once there is an exclusive waiter.
638          */
639         
640         for (;;) {
641                 x = sx->sx_lock;
642
643                 /*
644                  * If no other thread has an exclusive lock then try to bump up
645                  * the count of sharers.  Since we have to preserve the state
646                  * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
647                  * shared lock loop back and retry.
648                  */
649                 if (x & SX_LOCK_SHARED) {
650                         MPASS(!(x & SX_LOCK_SHARED_WAITERS));
651                         if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
652                             x + SX_ONE_SHARER)) {
653                                 if (SX_SHARERS(x) == 0)
654                                         lock_profile_obtain_lock_success(
655                                             &sx->lock_object, contested,
656                                             waitstart, file, line);
657                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
658                                         CTR4(KTR_LOCK,
659                                             "%s: %p succeed %p -> %p", __func__,
660                                             sx, (void *)x,
661                                             (void *)(x + SX_ONE_SHARER));
662                                 break;
663                         }
664                         lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
665                             &waitstart);
666
667                         continue;
668                 }
669
670 #ifdef ADAPTIVE_SX
671                 /*
672                  * If the owner is running on another CPU, spin until
673                  * the owner stops running or the state of the lock
674                  * changes.
675                  */
676                 else if (sx->lock_object.lo_flags & SX_ADAPTIVESPIN) {
677                         x = SX_OWNER(x);
678                         owner = (struct thread *)x;
679                         if (TD_IS_RUNNING(owner)) {
680                                 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
681                                     &waitstart);
682                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
683                                         CTR3(KTR_LOCK,
684                                             "%s: spinning on %p held by %p",
685                                             __func__, sx, owner);
686                                 GIANT_SAVE();
687                                 while (SX_OWNER(sx->sx_lock) == x &&
688                                     TD_IS_RUNNING(owner))
689                                         cpu_spinwait();
690                                 continue;
691                         }
692                 } 
693 #endif
694                 else
695                         lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
696                             &waitstart);
697
698                 /*
699                  * Some other thread already has an exclusive lock, so
700                  * start the process of blocking.
701                  */
702                 sleepq_lock(&sx->lock_object);
703                 x = sx->sx_lock;
704
705                 /*
706                  * The lock could have been released while we spun.
707                  * In this case loop back and retry.
708                  */
709                 if (x & SX_LOCK_SHARED) {
710                         sleepq_release(&sx->lock_object);
711                         continue;
712                 }
713
714 #ifdef ADAPTIVE_SX
715                 /*
716                  * If the owner is running on another CPU, spin until
717                  * the owner stops running or the state of the lock
718                  * changes.
719                  */
720                 if (!(x & SX_LOCK_SHARED) &&
721                     (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
722                         owner = (struct thread *)SX_OWNER(x);
723                         if (TD_IS_RUNNING(owner)) {
724                                 sleepq_release(&sx->lock_object);
725                                 continue;
726                         }
727                 }
728 #endif
729
730                 /*
731                  * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
732                  * fail to set it drop the sleep queue lock and loop
733                  * back.
734                  */
735                 if (!(x & SX_LOCK_SHARED_WAITERS)) {
736                         if (!atomic_cmpset_ptr(&sx->sx_lock, x,
737                             x | SX_LOCK_SHARED_WAITERS)) {
738                                 sleepq_release(&sx->lock_object);
739                                 continue;
740                         }
741                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
742                                 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
743                                     __func__, sx);
744                 }
745
746                 /*
747                  * Since we have been unable to acquire the shared lock,
748                  * we have to sleep.
749                  */
750                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
751                         CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
752                             __func__, sx);
753                 
754                 GIANT_SAVE();
755                 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
756                     SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
757                     SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
758                 if (!(opts & SX_INTERRUPTIBLE))
759                         sleepq_wait(&sx->lock_object);
760                 else
761                         error = sleepq_wait_sig(&sx->lock_object);
762
763                 if (error) {
764                         if (LOCK_LOG_TEST(&sx->lock_object, 0))
765                                 CTR2(KTR_LOCK,
766                         "%s: interruptible sleep by %p suspended by signal",
767                                     __func__, sx);
768                         break;
769                 }
770                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
771                         CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
772                             __func__, sx);
773         }
774
775         GIANT_RESTORE();
776         return (error);
777 }
778
779 /*
780  * This function represents the so-called 'hard case' for sx_sunlock
781  * operation.  All 'easy case' failures are redirected to this.  Note
782  * that ideally this would be a static function, but it needs to be
783  * accessible from at least sx.h.
784  */
785 void
786 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
787 {
788         uintptr_t x;
789
790         for (;;) {
791                 x = sx->sx_lock;
792
793                 /*
794                  * We should never have sharers while at least one thread
795                  * holds a shared lock.
796                  */
797                 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
798                     ("%s: waiting sharers", __func__));
799
800                 /*
801                  * See if there is more than one shared lock held.  If
802                  * so, just drop one and return.
803                  */
804                 if (SX_SHARERS(x) > 1) {
805                         if (atomic_cmpset_ptr(&sx->sx_lock, x,
806                             x - SX_ONE_SHARER)) {
807                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
808                                         CTR4(KTR_LOCK,
809                                             "%s: %p succeeded %p -> %p",
810                                             __func__, sx, (void *)x,
811                                             (void *)(x - SX_ONE_SHARER));
812                                 break;
813                         }
814                         continue;
815                 }
816
817                 /*
818                  * If there aren't any waiters for an exclusive lock,
819                  * then try to drop it quickly.
820                  */
821                 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
822                         MPASS(x == SX_SHARERS_LOCK(1));
823                         if (atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1),
824                             SX_LOCK_UNLOCKED)) {
825                                 lock_profile_release_lock(&sx->lock_object);
826                                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
827                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
828                                             __func__, sx);
829                                 break;
830                         }
831                         continue;
832                 }
833
834                 /*
835                  * At this point, there should just be one sharer with
836                  * exclusive waiters.
837                  */
838                 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
839
840                 lock_profile_release_lock(&sx->lock_object);
841                 sleepq_lock(&sx->lock_object);
842
843                 /*
844                  * Wake up semantic here is quite simple:
845                  * Just wake up all the exclusive waiters.
846                  * Note that the state of the lock could have changed,
847                  * so if it fails loop back and retry.
848                  */
849                 if (!atomic_cmpset_ptr(&sx->sx_lock,
850                     SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
851                     SX_LOCK_UNLOCKED)) {
852                         sleepq_release(&sx->lock_object);
853                         continue;
854                 }
855                 if (LOCK_LOG_TEST(&sx->lock_object, 0))
856                         CTR2(KTR_LOCK, "%s: %p waking up all thread on"
857                             "exclusive queue", __func__, sx);
858                 sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, -1,
859                     SQ_EXCLUSIVE_QUEUE);
860                 break;
861         }
862 }
863
864 #ifdef INVARIANT_SUPPORT
865 #ifndef INVARIANTS
866 #undef  _sx_assert
867 #endif
868
869 /*
870  * In the non-WITNESS case, sx_assert() can only detect that at least
871  * *some* thread owns an slock, but it cannot guarantee that *this*
872  * thread owns an slock.
873  */
874 void
875 _sx_assert(struct sx *sx, int what, const char *file, int line)
876 {
877 #ifndef WITNESS
878         int slocked = 0;
879 #endif
880
881         if (panicstr != NULL)
882                 return;
883         switch (what) {
884         case SA_SLOCKED:
885         case SA_SLOCKED | SA_NOTRECURSED:
886         case SA_SLOCKED | SA_RECURSED:
887 #ifndef WITNESS
888                 slocked = 1;
889                 /* FALLTHROUGH */
890 #endif
891         case SA_LOCKED:
892         case SA_LOCKED | SA_NOTRECURSED:
893         case SA_LOCKED | SA_RECURSED:
894 #ifdef WITNESS
895                 witness_assert(&sx->lock_object, what, file, line);
896 #else
897                 /*
898                  * If some other thread has an exclusive lock or we
899                  * have one and are asserting a shared lock, fail.
900                  * Also, if no one has a lock at all, fail.
901                  */
902                 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
903                     (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
904                     sx_xholder(sx) != curthread)))
905                         panic("Lock %s not %slocked @ %s:%d\n",
906                             sx->lock_object.lo_name, slocked ? "share " : "",
907                             file, line);
908
909                 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
910                         if (sx_recursed(sx)) {
911                                 if (what & SA_NOTRECURSED)
912                                         panic("Lock %s recursed @ %s:%d\n",
913                                             sx->lock_object.lo_name, file,
914                                             line);
915                         } else if (what & SA_RECURSED)
916                                 panic("Lock %s not recursed @ %s:%d\n",
917                                     sx->lock_object.lo_name, file, line);
918                 }
919 #endif
920                 break;
921         case SA_XLOCKED:
922         case SA_XLOCKED | SA_NOTRECURSED:
923         case SA_XLOCKED | SA_RECURSED:
924                 if (sx_xholder(sx) != curthread)
925                         panic("Lock %s not exclusively locked @ %s:%d\n",
926                             sx->lock_object.lo_name, file, line);
927                 if (sx_recursed(sx)) {
928                         if (what & SA_NOTRECURSED)
929                                 panic("Lock %s recursed @ %s:%d\n",
930                                     sx->lock_object.lo_name, file, line);
931                 } else if (what & SA_RECURSED)
932                         panic("Lock %s not recursed @ %s:%d\n",
933                             sx->lock_object.lo_name, file, line);
934                 break;
935         case SA_UNLOCKED:
936 #ifdef WITNESS
937                 witness_assert(&sx->lock_object, what, file, line);
938 #else
939                 /*
940                  * If we hold an exclusve lock fail.  We can't
941                  * reliably check to see if we hold a shared lock or
942                  * not.
943                  */
944                 if (sx_xholder(sx) == curthread)
945                         panic("Lock %s exclusively locked @ %s:%d\n",
946                             sx->lock_object.lo_name, file, line);
947 #endif
948                 break;
949         default:
950                 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
951                     line);
952         }
953 }
954 #endif  /* INVARIANT_SUPPORT */
955
956 #ifdef DDB
957 static void
958 db_show_sx(struct lock_object *lock)
959 {
960         struct thread *td;
961         struct sx *sx;
962
963         sx = (struct sx *)lock;
964
965         db_printf(" state: ");
966         if (sx->sx_lock == SX_LOCK_UNLOCKED)
967                 db_printf("UNLOCKED\n");
968         else if (sx->sx_lock == SX_LOCK_DESTROYED) {
969                 db_printf("DESTROYED\n");
970                 return;
971         } else if (sx->sx_lock & SX_LOCK_SHARED)
972                 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
973         else {
974                 td = sx_xholder(sx);
975                 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
976                     td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
977                 if (sx_recursed(sx))
978                         db_printf(" recursed: %d\n", sx->sx_recurse);
979         }
980
981         db_printf(" waiters: ");
982         switch(sx->sx_lock &
983             (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
984         case SX_LOCK_SHARED_WAITERS:
985                 db_printf("shared\n");
986                 break;
987         case SX_LOCK_EXCLUSIVE_WAITERS:
988                 db_printf("exclusive\n");
989                 break;
990         case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
991                 db_printf("exclusive and shared\n");
992                 break;
993         default:
994                 db_printf("none\n");
995         }
996 }
997
998 /*
999  * Check to see if a thread that is blocked on a sleep queue is actually
1000  * blocked on an sx lock.  If so, output some details and return true.
1001  * If the lock has an exclusive owner, return that in *ownerp.
1002  */
1003 int
1004 sx_chain(struct thread *td, struct thread **ownerp)
1005 {
1006         struct sx *sx;
1007
1008         /*
1009          * Check to see if this thread is blocked on an sx lock.
1010          * First, we check the lock class.  If that is ok, then we
1011          * compare the lock name against the wait message.
1012          */
1013         sx = td->td_wchan;
1014         if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1015             sx->lock_object.lo_name != td->td_wmesg)
1016                 return (0);
1017
1018         /* We think we have an sx lock, so output some details. */
1019         db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1020         *ownerp = sx_xholder(sx);
1021         if (sx->sx_lock & SX_LOCK_SHARED)
1022                 db_printf("SLOCK (count %ju)\n",
1023                     (uintmax_t)SX_SHARERS(sx->sx_lock));
1024         else
1025                 db_printf("XLOCK\n");
1026         return (1);
1027 }
1028 #endif