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