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