]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_rwlock.c
Merge ^/head r325999 through r326131.
[FreeBSD/FreeBSD.git] / sys / kern / kern_rwlock.c
1 /*-
2  * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /*
28  * Machine independent bits of reader/writer lock implementation.
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include "opt_ddb.h"
35 #include "opt_hwpmc_hooks.h"
36 #include "opt_no_adaptive_rwlocks.h"
37
38 #include <sys/param.h>
39 #include <sys/kdb.h>
40 #include <sys/ktr.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/proc.h>
45 #include <sys/rwlock.h>
46 #include <sys/sched.h>
47 #include <sys/smp.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
50 #include <sys/turnstile.h>
51
52 #include <machine/cpu.h>
53
54 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
55 #define ADAPTIVE_RWLOCKS
56 #endif
57
58 #ifdef HWPMC_HOOKS
59 #include <sys/pmckern.h>
60 PMC_SOFT_DECLARE( , , lock, failed);
61 #endif
62
63 /*
64  * Return the rwlock address when the lock cookie address is provided.
65  * This functionality assumes that struct rwlock* have a member named rw_lock.
66  */
67 #define rwlock2rw(c)    (__containerof(c, struct rwlock, rw_lock))
68
69 #ifdef DDB
70 #include <ddb/ddb.h>
71
72 static void     db_show_rwlock(const struct lock_object *lock);
73 #endif
74 static void     assert_rw(const struct lock_object *lock, int what);
75 static void     lock_rw(struct lock_object *lock, uintptr_t how);
76 #ifdef KDTRACE_HOOKS
77 static int      owner_rw(const struct lock_object *lock, struct thread **owner);
78 #endif
79 static uintptr_t unlock_rw(struct lock_object *lock);
80
81 struct lock_class lock_class_rw = {
82         .lc_name = "rw",
83         .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
84         .lc_assert = assert_rw,
85 #ifdef DDB
86         .lc_ddb_show = db_show_rwlock,
87 #endif
88         .lc_lock = lock_rw,
89         .lc_unlock = unlock_rw,
90 #ifdef KDTRACE_HOOKS
91         .lc_owner = owner_rw,
92 #endif
93 };
94
95 #ifdef ADAPTIVE_RWLOCKS
96 static int __read_frequently rowner_retries = 10;
97 static int __read_frequently rowner_loops = 10000;
98 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
99     "rwlock debugging");
100 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
101 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
102
103 static struct lock_delay_config __read_frequently rw_delay;
104
105 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
106     0, "");
107 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
108     0, "");
109
110 LOCK_DELAY_SYSINIT_DEFAULT(rw_delay);
111 #endif
112
113 /*
114  * Return a pointer to the owning thread if the lock is write-locked or
115  * NULL if the lock is unlocked or read-locked.
116  */
117
118 #define lv_rw_wowner(v)                                                 \
119         ((v) & RW_LOCK_READ ? NULL :                                    \
120          (struct thread *)RW_OWNER((v)))
121
122 #define rw_wowner(rw)   lv_rw_wowner(RW_READ_VALUE(rw))
123
124 /*
125  * Returns if a write owner is recursed.  Write ownership is not assured
126  * here and should be previously checked.
127  */
128 #define rw_recursed(rw)         ((rw)->rw_recurse != 0)
129
130 /*
131  * Return true if curthread helds the lock.
132  */
133 #define rw_wlocked(rw)          (rw_wowner((rw)) == curthread)
134
135 /*
136  * Return a pointer to the owning thread for this lock who should receive
137  * any priority lent by threads that block on this lock.  Currently this
138  * is identical to rw_wowner().
139  */
140 #define rw_owner(rw)            rw_wowner(rw)
141
142 #ifndef INVARIANTS
143 #define __rw_assert(c, what, file, line)
144 #endif
145
146 void
147 assert_rw(const struct lock_object *lock, int what)
148 {
149
150         rw_assert((const struct rwlock *)lock, what);
151 }
152
153 void
154 lock_rw(struct lock_object *lock, uintptr_t how)
155 {
156         struct rwlock *rw;
157
158         rw = (struct rwlock *)lock;
159         if (how)
160                 rw_rlock(rw);
161         else
162                 rw_wlock(rw);
163 }
164
165 uintptr_t
166 unlock_rw(struct lock_object *lock)
167 {
168         struct rwlock *rw;
169
170         rw = (struct rwlock *)lock;
171         rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
172         if (rw->rw_lock & RW_LOCK_READ) {
173                 rw_runlock(rw);
174                 return (1);
175         } else {
176                 rw_wunlock(rw);
177                 return (0);
178         }
179 }
180
181 #ifdef KDTRACE_HOOKS
182 int
183 owner_rw(const struct lock_object *lock, struct thread **owner)
184 {
185         const struct rwlock *rw = (const struct rwlock *)lock;
186         uintptr_t x = rw->rw_lock;
187
188         *owner = rw_wowner(rw);
189         return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
190             (*owner != NULL));
191 }
192 #endif
193
194 void
195 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
196 {
197         struct rwlock *rw;
198         int flags;
199
200         rw = rwlock2rw(c);
201
202         MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
203             RW_RECURSE | RW_NEW)) == 0);
204         ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
205             ("%s: rw_lock not aligned for %s: %p", __func__, name,
206             &rw->rw_lock));
207
208         flags = LO_UPGRADABLE;
209         if (opts & RW_DUPOK)
210                 flags |= LO_DUPOK;
211         if (opts & RW_NOPROFILE)
212                 flags |= LO_NOPROFILE;
213         if (!(opts & RW_NOWITNESS))
214                 flags |= LO_WITNESS;
215         if (opts & RW_RECURSE)
216                 flags |= LO_RECURSABLE;
217         if (opts & RW_QUIET)
218                 flags |= LO_QUIET;
219         if (opts & RW_NEW)
220                 flags |= LO_NEW;
221
222         lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
223         rw->rw_lock = RW_UNLOCKED;
224         rw->rw_recurse = 0;
225 }
226
227 void
228 _rw_destroy(volatile uintptr_t *c)
229 {
230         struct rwlock *rw;
231
232         rw = rwlock2rw(c);
233
234         KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
235         KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
236         rw->rw_lock = RW_DESTROYED;
237         lock_destroy(&rw->lock_object);
238 }
239
240 void
241 rw_sysinit(void *arg)
242 {
243         struct rw_args *args;
244
245         args = arg;
246         rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
247             args->ra_flags);
248 }
249
250 int
251 _rw_wowned(const volatile uintptr_t *c)
252 {
253
254         return (rw_wowner(rwlock2rw(c)) == curthread);
255 }
256
257 void
258 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
259 {
260         struct rwlock *rw;
261         uintptr_t tid, v;
262
263         rw = rwlock2rw(c);
264
265         KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
266             !TD_IS_IDLETHREAD(curthread),
267             ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
268             curthread, rw->lock_object.lo_name, file, line));
269         KASSERT(rw->rw_lock != RW_DESTROYED,
270             ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
271         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
272             line, NULL);
273         tid = (uintptr_t)curthread;
274         v = RW_UNLOCKED;
275         if (!_rw_write_lock_fetch(rw, &v, tid))
276                 _rw_wlock_hard(rw, v, file, line);
277         else
278                 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
279                     0, 0, file, line, LOCKSTAT_WRITER);
280
281         LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
282         WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
283         TD_LOCKS_INC(curthread);
284 }
285
286 int
287 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
288 {
289         struct rwlock *rw;
290         struct thread *td;
291         uintptr_t tid, v;
292         int rval;
293         bool recursed;
294
295         td = curthread;
296         tid = (uintptr_t)td;
297         if (SCHEDULER_STOPPED_TD(td))
298                 return (1);
299
300         rw = rwlock2rw(c);
301
302         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
303             ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
304             curthread, rw->lock_object.lo_name, file, line));
305         KASSERT(rw->rw_lock != RW_DESTROYED,
306             ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
307
308         rval = 1;
309         recursed = false;
310         v = RW_UNLOCKED;
311         for (;;) {
312                 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
313                         break;
314                 if (v == RW_UNLOCKED)
315                         continue;
316                 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
317                         rw->rw_recurse++;
318                         atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
319                         break;
320                 }
321                 rval = 0;
322                 break;
323         }
324
325         LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
326         if (rval) {
327                 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
328                     file, line);
329                 if (!recursed)
330                         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
331                             rw, 0, 0, file, line, LOCKSTAT_WRITER);
332                 TD_LOCKS_INC(curthread);
333         }
334         return (rval);
335 }
336
337 void
338 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
339 {
340         struct rwlock *rw;
341
342         rw = rwlock2rw(c);
343
344         KASSERT(rw->rw_lock != RW_DESTROYED,
345             ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
346         __rw_assert(c, RA_WLOCKED, file, line);
347         WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
348         LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
349             line);
350
351 #ifdef LOCK_PROFILING
352         _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
353 #else
354         __rw_wunlock(rw, curthread, file, line);
355 #endif
356
357         TD_LOCKS_DEC(curthread);
358 }
359
360 /*
361  * Determines whether a new reader can acquire a lock.  Succeeds if the
362  * reader already owns a read lock and the lock is locked for read to
363  * prevent deadlock from reader recursion.  Also succeeds if the lock
364  * is unlocked and has no writer waiters or spinners.  Failing otherwise
365  * prioritizes writers before readers.
366  */
367 static bool __always_inline
368 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
369 {
370
371         if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
372             == RW_LOCK_READ)
373                 return (true);
374         if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
375                 return (true);
376         return (false);
377 }
378
379 static bool __always_inline
380 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
381     LOCK_FILE_LINE_ARG_DEF)
382 {
383
384         /*
385          * Handle the easy case.  If no other thread has a write
386          * lock, then try to bump up the count of read locks.  Note
387          * that we have to preserve the current state of the
388          * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
389          * read lock, then rw_lock must have changed, so restart
390          * the loop.  Note that this handles the case of a
391          * completely unlocked rwlock since such a lock is encoded
392          * as a read lock with no waiters.
393          */
394         while (__rw_can_read(td, *vp, fp)) {
395                 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
396                         *vp + RW_ONE_READER)) {
397                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
398                                 CTR4(KTR_LOCK,
399                                     "%s: %p succeed %p -> %p", __func__,
400                                     rw, (void *)*vp,
401                                     (void *)(*vp + RW_ONE_READER));
402                         td->td_rw_rlocks++;
403                         return (true);
404                 }
405         }
406         return (false);
407 }
408
409 static void __noinline
410 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
411     LOCK_FILE_LINE_ARG_DEF)
412 {
413         struct turnstile *ts;
414 #ifdef ADAPTIVE_RWLOCKS
415         volatile struct thread *owner;
416         int spintries = 0;
417         int i, n;
418 #endif
419 #ifdef LOCK_PROFILING
420         uint64_t waittime = 0;
421         int contested = 0;
422 #endif
423 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
424         struct lock_delay_arg lda;
425 #endif
426 #ifdef KDTRACE_HOOKS
427         u_int sleep_cnt = 0;
428         int64_t sleep_time = 0;
429         int64_t all_time = 0;
430 #endif
431 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
432         uintptr_t state;
433         int doing_lockprof;
434 #endif
435
436         if (SCHEDULER_STOPPED())
437                 return;
438
439 #if defined(ADAPTIVE_RWLOCKS)
440         lock_delay_arg_init(&lda, &rw_delay);
441 #elif defined(KDTRACE_HOOKS)
442         lock_delay_arg_init(&lda, NULL);
443 #endif
444
445 #ifdef HWPMC_HOOKS
446         PMC_SOFT_CALL( , , lock, failed);
447 #endif
448         lock_profile_obtain_lock_failed(&rw->lock_object,
449             &contested, &waittime);
450
451 #ifdef LOCK_PROFILING
452         doing_lockprof = 1;
453         state = v;
454 #elif defined(KDTRACE_HOOKS)
455         doing_lockprof = lockstat_enabled;
456         if (__predict_false(doing_lockprof)) {
457                 all_time -= lockstat_nsecs(&rw->lock_object);
458                 state = v;
459         }
460 #endif
461
462         for (;;) {
463                 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
464                         break;
465 #ifdef KDTRACE_HOOKS
466                 lda.spin_cnt++;
467 #endif
468
469 #ifdef ADAPTIVE_RWLOCKS
470                 /*
471                  * If the owner is running on another CPU, spin until
472                  * the owner stops running or the state of the lock
473                  * changes.
474                  */
475                 if ((v & RW_LOCK_READ) == 0) {
476                         owner = (struct thread *)RW_OWNER(v);
477                         if (TD_IS_RUNNING(owner)) {
478                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
479                                         CTR3(KTR_LOCK,
480                                             "%s: spinning on %p held by %p",
481                                             __func__, rw, owner);
482                                 KTR_STATE1(KTR_SCHED, "thread",
483                                     sched_tdname(curthread), "spinning",
484                                     "lockname:\"%s\"", rw->lock_object.lo_name);
485                                 do {
486                                         lock_delay(&lda);
487                                         v = RW_READ_VALUE(rw);
488                                         owner = lv_rw_wowner(v);
489                                 } while (owner != NULL && TD_IS_RUNNING(owner));
490                                 KTR_STATE0(KTR_SCHED, "thread",
491                                     sched_tdname(curthread), "running");
492                                 continue;
493                         }
494                 } else if (spintries < rowner_retries) {
495                         spintries++;
496                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
497                             "spinning", "lockname:\"%s\"",
498                             rw->lock_object.lo_name);
499                         for (i = 0; i < rowner_loops; i += n) {
500                                 n = RW_READERS(v);
501                                 lock_delay_spin(n);
502                                 v = RW_READ_VALUE(rw);
503                                 if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
504                                         break;
505                         }
506 #ifdef KDTRACE_HOOKS
507                         lda.spin_cnt += rowner_loops - i;
508 #endif
509                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
510                             "running");
511                         if (i != rowner_loops)
512                                 continue;
513                 }
514 #endif
515
516                 /*
517                  * Okay, now it's the hard case.  Some other thread already
518                  * has a write lock or there are write waiters present,
519                  * acquire the turnstile lock so we can begin the process
520                  * of blocking.
521                  */
522                 ts = turnstile_trywait(&rw->lock_object);
523
524                 /*
525                  * The lock might have been released while we spun, so
526                  * recheck its state and restart the loop if needed.
527                  */
528                 v = RW_READ_VALUE(rw);
529                 if (__rw_can_read(td, v, false)) {
530                         turnstile_cancel(ts);
531                         continue;
532                 }
533
534 #ifdef ADAPTIVE_RWLOCKS
535                 /*
536                  * The current lock owner might have started executing
537                  * on another CPU (or the lock could have changed
538                  * owners) while we were waiting on the turnstile
539                  * chain lock.  If so, drop the turnstile lock and try
540                  * again.
541                  */
542                 if ((v & RW_LOCK_READ) == 0) {
543                         owner = (struct thread *)RW_OWNER(v);
544                         if (TD_IS_RUNNING(owner)) {
545                                 turnstile_cancel(ts);
546                                 continue;
547                         }
548                 }
549 #endif
550
551                 /*
552                  * The lock is held in write mode or it already has waiters.
553                  */
554                 MPASS(!__rw_can_read(td, v, false));
555
556                 /*
557                  * If the RW_LOCK_READ_WAITERS flag is already set, then
558                  * we can go ahead and block.  If it is not set then try
559                  * to set it.  If we fail to set it drop the turnstile
560                  * lock and restart the loop.
561                  */
562                 if (!(v & RW_LOCK_READ_WAITERS)) {
563                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
564                             v | RW_LOCK_READ_WAITERS)) {
565                                 turnstile_cancel(ts);
566                                 v = RW_READ_VALUE(rw);
567                                 continue;
568                         }
569                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
570                                 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
571                                     __func__, rw);
572                 }
573
574                 /*
575                  * We were unable to acquire the lock and the read waiters
576                  * flag is set, so we must block on the turnstile.
577                  */
578                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
579                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
580                             rw);
581 #ifdef KDTRACE_HOOKS
582                 sleep_time -= lockstat_nsecs(&rw->lock_object);
583 #endif
584                 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
585 #ifdef KDTRACE_HOOKS
586                 sleep_time += lockstat_nsecs(&rw->lock_object);
587                 sleep_cnt++;
588 #endif
589                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
590                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
591                             __func__, rw);
592                 v = RW_READ_VALUE(rw);
593         }
594 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
595         if (__predict_true(!doing_lockprof))
596                 return;
597 #endif
598 #ifdef KDTRACE_HOOKS
599         all_time += lockstat_nsecs(&rw->lock_object);
600         if (sleep_time)
601                 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
602                     LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
603                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
604
605         /* Record only the loops spinning and not sleeping. */
606         if (lda.spin_cnt > sleep_cnt)
607                 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
608                     LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
609                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
610 #endif
611         /*
612          * TODO: acquire "owner of record" here.  Here be turnstile dragons
613          * however.  turnstiles don't like owners changing between calls to
614          * turnstile_wait() currently.
615          */
616         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
617             waittime, file, line, LOCKSTAT_READER);
618 }
619
620 void
621 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
622 {
623         struct thread *td;
624         uintptr_t v;
625
626         td = curthread;
627
628         KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
629             !TD_IS_IDLETHREAD(td),
630             ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
631             td, rw->lock_object.lo_name, file, line));
632         KASSERT(rw->rw_lock != RW_DESTROYED,
633             ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
634         KASSERT(rw_wowner(rw) != td,
635             ("rw_rlock: wlock already held for %s @ %s:%d",
636             rw->lock_object.lo_name, file, line));
637         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
638
639         v = RW_READ_VALUE(rw);
640         if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
641             !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
642                 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
643
644         LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
645         WITNESS_LOCK(&rw->lock_object, 0, file, line);
646         TD_LOCKS_INC(curthread);
647 }
648
649 void
650 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
651 {
652         struct rwlock *rw;
653
654         rw = rwlock2rw(c);
655         __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
656 }
657
658 int
659 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
660 {
661         struct rwlock *rw;
662         uintptr_t x;
663
664         if (SCHEDULER_STOPPED())
665                 return (1);
666
667         rw = rwlock2rw(c);
668
669         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
670             ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
671             curthread, rw->lock_object.lo_name, file, line));
672
673         x = rw->rw_lock;
674         for (;;) {
675                 KASSERT(rw->rw_lock != RW_DESTROYED,
676                     ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
677                 if (!(x & RW_LOCK_READ))
678                         break;
679                 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
680                         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
681                             line);
682                         WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
683                         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
684                             rw, 0, 0, file, line, LOCKSTAT_READER);
685                         TD_LOCKS_INC(curthread);
686                         curthread->td_rw_rlocks++;
687                         return (1);
688                 }
689         }
690
691         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
692         return (0);
693 }
694
695 static bool __always_inline
696 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
697 {
698
699         for (;;) {
700                 /*
701                  * See if there is more than one read lock held.  If so,
702                  * just drop one and return.
703                  */
704                 if (RW_READERS(*vp) > 1) {
705                         if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
706                             *vp - RW_ONE_READER)) {
707                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
708                                         CTR4(KTR_LOCK,
709                                             "%s: %p succeeded %p -> %p",
710                                             __func__, rw, (void *)*vp,
711                                             (void *)(*vp - RW_ONE_READER));
712                                 td->td_rw_rlocks--;
713                                 return (true);
714                         }
715                         continue;
716                 }
717                 /*
718                  * If there aren't any waiters for a write lock, then try
719                  * to drop it quickly.
720                  */
721                 if (!(*vp & RW_LOCK_WAITERS)) {
722                         MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
723                             RW_READERS_LOCK(1));
724                         if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
725                             RW_UNLOCKED)) {
726                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
727                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
728                                             __func__, rw);
729                                 td->td_rw_rlocks--;
730                                 return (true);
731                         }
732                         continue;
733                 }
734                 break;
735         }
736         return (false);
737 }
738
739 static void __noinline
740 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
741     LOCK_FILE_LINE_ARG_DEF)
742 {
743         struct turnstile *ts;
744         uintptr_t x, queue;
745
746         if (SCHEDULER_STOPPED())
747                 return;
748
749         for (;;) {
750                 if (__rw_runlock_try(rw, td, &v))
751                         break;
752
753                 /*
754                  * Ok, we know we have waiters and we think we are the
755                  * last reader, so grab the turnstile lock.
756                  */
757                 turnstile_chain_lock(&rw->lock_object);
758                 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
759                 MPASS(v & RW_LOCK_WAITERS);
760
761                 /*
762                  * Try to drop our lock leaving the lock in a unlocked
763                  * state.
764                  *
765                  * If you wanted to do explicit lock handoff you'd have to
766                  * do it here.  You'd also want to use turnstile_signal()
767                  * and you'd have to handle the race where a higher
768                  * priority thread blocks on the write lock before the
769                  * thread you wakeup actually runs and have the new thread
770                  * "steal" the lock.  For now it's a lot simpler to just
771                  * wakeup all of the waiters.
772                  *
773                  * As above, if we fail, then another thread might have
774                  * acquired a read lock, so drop the turnstile lock and
775                  * restart.
776                  */
777                 x = RW_UNLOCKED;
778                 if (v & RW_LOCK_WRITE_WAITERS) {
779                         queue = TS_EXCLUSIVE_QUEUE;
780                         x |= (v & RW_LOCK_READ_WAITERS);
781                 } else
782                         queue = TS_SHARED_QUEUE;
783                 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
784                     x)) {
785                         turnstile_chain_unlock(&rw->lock_object);
786                         v = RW_READ_VALUE(rw);
787                         continue;
788                 }
789                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
790                         CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
791                             __func__, rw);
792
793                 /*
794                  * Ok.  The lock is released and all that's left is to
795                  * wake up the waiters.  Note that the lock might not be
796                  * free anymore, but in that case the writers will just
797                  * block again if they run before the new lock holder(s)
798                  * release the lock.
799                  */
800                 ts = turnstile_lookup(&rw->lock_object);
801                 MPASS(ts != NULL);
802                 turnstile_broadcast(ts, queue);
803                 turnstile_unpend(ts, TS_SHARED_LOCK);
804                 turnstile_chain_unlock(&rw->lock_object);
805                 td->td_rw_rlocks--;
806                 break;
807         }
808         LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
809 }
810
811 void
812 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
813 {
814         struct thread *td;
815         uintptr_t v;
816
817         KASSERT(rw->rw_lock != RW_DESTROYED,
818             ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
819         __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
820         WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
821         LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
822
823         td = curthread;
824         v = RW_READ_VALUE(rw);
825
826         if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
827             !__rw_runlock_try(rw, td, &v)))
828                 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
829
830         TD_LOCKS_DEC(curthread);
831 }
832
833 void
834 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
835 {
836         struct rwlock *rw;
837
838         rw = rwlock2rw(c);
839         _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
840 }
841
842 /*
843  * This function is called when we are unable to obtain a write lock on the
844  * first try.  This means that at least one other thread holds either a
845  * read or write lock.
846  */
847 void
848 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
849 {
850         uintptr_t tid;
851         struct rwlock *rw;
852         struct turnstile *ts;
853 #ifdef ADAPTIVE_RWLOCKS
854         volatile struct thread *owner;
855         int spintries = 0;
856         int i, n;
857 #endif
858         uintptr_t x;
859 #ifdef LOCK_PROFILING
860         uint64_t waittime = 0;
861         int contested = 0;
862 #endif
863 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
864         struct lock_delay_arg lda;
865 #endif
866 #ifdef KDTRACE_HOOKS
867         u_int sleep_cnt = 0;
868         int64_t sleep_time = 0;
869         int64_t all_time = 0;
870 #endif
871 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
872         uintptr_t state;
873         int doing_lockprof;
874 #endif
875
876         tid = (uintptr_t)curthread;
877         if (SCHEDULER_STOPPED())
878                 return;
879
880 #if defined(ADAPTIVE_RWLOCKS)
881         lock_delay_arg_init(&lda, &rw_delay);
882 #elif defined(KDTRACE_HOOKS)
883         lock_delay_arg_init(&lda, NULL);
884 #endif
885         rw = rwlock2rw(c);
886         if (__predict_false(v == RW_UNLOCKED))
887                 v = RW_READ_VALUE(rw);
888
889         if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
890                 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
891                     ("%s: recursing but non-recursive rw %s @ %s:%d\n",
892                     __func__, rw->lock_object.lo_name, file, line));
893                 rw->rw_recurse++;
894                 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
895                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
896                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
897                 return;
898         }
899
900         if (LOCK_LOG_TEST(&rw->lock_object, 0))
901                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
902                     rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
903
904 #ifdef HWPMC_HOOKS
905         PMC_SOFT_CALL( , , lock, failed);
906 #endif
907         lock_profile_obtain_lock_failed(&rw->lock_object,
908             &contested, &waittime);
909
910 #ifdef LOCK_PROFILING
911         doing_lockprof = 1;
912         state = v;
913 #elif defined(KDTRACE_HOOKS)
914         doing_lockprof = lockstat_enabled;
915         if (__predict_false(doing_lockprof)) {
916                 all_time -= lockstat_nsecs(&rw->lock_object);
917                 state = v;
918         }
919 #endif
920
921         for (;;) {
922                 if (v == RW_UNLOCKED) {
923                         if (_rw_write_lock_fetch(rw, &v, tid))
924                                 break;
925                         continue;
926                 }
927 #ifdef KDTRACE_HOOKS
928                 lda.spin_cnt++;
929 #endif
930
931 #ifdef ADAPTIVE_RWLOCKS
932                 /*
933                  * If the lock is write locked and the owner is
934                  * running on another CPU, spin until the owner stops
935                  * running or the state of the lock changes.
936                  */
937                 owner = lv_rw_wowner(v);
938                 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
939                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
940                                 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
941                                     __func__, rw, owner);
942                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
943                             "spinning", "lockname:\"%s\"",
944                             rw->lock_object.lo_name);
945                         do {
946                                 lock_delay(&lda);
947                                 v = RW_READ_VALUE(rw);
948                                 owner = lv_rw_wowner(v);
949                         } while (owner != NULL && TD_IS_RUNNING(owner));
950                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
951                             "running");
952                         continue;
953                 }
954                 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
955                     spintries < rowner_retries) {
956                         if (!(v & RW_LOCK_WRITE_SPINNER)) {
957                                 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
958                                     v | RW_LOCK_WRITE_SPINNER)) {
959                                         continue;
960                                 }
961                         }
962                         spintries++;
963                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
964                             "spinning", "lockname:\"%s\"",
965                             rw->lock_object.lo_name);
966                         for (i = 0; i < rowner_loops; i += n) {
967                                 n = RW_READERS(v);
968                                 lock_delay_spin(n);
969                                 v = RW_READ_VALUE(rw);
970                                 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
971                                         break;
972                         }
973                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
974                             "running");
975 #ifdef KDTRACE_HOOKS
976                         lda.spin_cnt += rowner_loops - i;
977 #endif
978                         if (i != rowner_loops)
979                                 continue;
980                 }
981 #endif
982                 ts = turnstile_trywait(&rw->lock_object);
983                 v = RW_READ_VALUE(rw);
984
985 #ifdef ADAPTIVE_RWLOCKS
986                 /*
987                  * The current lock owner might have started executing
988                  * on another CPU (or the lock could have changed
989                  * owners) while we were waiting on the turnstile
990                  * chain lock.  If so, drop the turnstile lock and try
991                  * again.
992                  */
993                 if (!(v & RW_LOCK_READ)) {
994                         owner = (struct thread *)RW_OWNER(v);
995                         if (TD_IS_RUNNING(owner)) {
996                                 turnstile_cancel(ts);
997                                 continue;
998                         }
999                 }
1000 #endif
1001                 /*
1002                  * Check for the waiters flags about this rwlock.
1003                  * If the lock was released, without maintain any pending
1004                  * waiters queue, simply try to acquire it.
1005                  * If a pending waiters queue is present, claim the lock
1006                  * ownership and maintain the pending queue.
1007                  */
1008                 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1009                 if ((v & ~x) == RW_UNLOCKED) {
1010                         x &= ~RW_LOCK_WRITE_SPINNER;
1011                         if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
1012                                 if (x)
1013                                         turnstile_claim(ts);
1014                                 else
1015                                         turnstile_cancel(ts);
1016                                 break;
1017                         }
1018                         turnstile_cancel(ts);
1019                         v = RW_READ_VALUE(rw);
1020                         continue;
1021                 }
1022                 /*
1023                  * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1024                  * set it.  If we fail to set it, then loop back and try
1025                  * again.
1026                  */
1027                 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1028                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
1029                             v | RW_LOCK_WRITE_WAITERS)) {
1030                                 turnstile_cancel(ts);
1031                                 v = RW_READ_VALUE(rw);
1032                                 continue;
1033                         }
1034                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
1035                                 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1036                                     __func__, rw);
1037                 }
1038                 /*
1039                  * We were unable to acquire the lock and the write waiters
1040                  * flag is set, so we must block on the turnstile.
1041                  */
1042                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1043                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1044                             rw);
1045 #ifdef KDTRACE_HOOKS
1046                 sleep_time -= lockstat_nsecs(&rw->lock_object);
1047 #endif
1048                 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
1049 #ifdef KDTRACE_HOOKS
1050                 sleep_time += lockstat_nsecs(&rw->lock_object);
1051                 sleep_cnt++;
1052 #endif
1053                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1054                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1055                             __func__, rw);
1056 #ifdef ADAPTIVE_RWLOCKS
1057                 spintries = 0;
1058 #endif
1059                 v = RW_READ_VALUE(rw);
1060         }
1061 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1062         if (__predict_true(!doing_lockprof))
1063                 return;
1064 #endif
1065 #ifdef KDTRACE_HOOKS
1066         all_time += lockstat_nsecs(&rw->lock_object);
1067         if (sleep_time)
1068                 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1069                     LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1070                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1071
1072         /* Record only the loops spinning and not sleeping. */
1073         if (lda.spin_cnt > sleep_cnt)
1074                 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1075                     LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1076                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1077 #endif
1078         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1079             waittime, file, line, LOCKSTAT_WRITER);
1080 }
1081
1082 /*
1083  * This function is called if lockstat is active or the first try at releasing
1084  * a write lock failed.  The latter means that the lock is recursed or one of
1085  * the 2 waiter bits must be set indicating that at least one thread is waiting
1086  * on this lock.
1087  */
1088 void
1089 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1090 {
1091         struct rwlock *rw;
1092         struct turnstile *ts;
1093         uintptr_t tid, setv;
1094         int queue;
1095
1096         tid = (uintptr_t)curthread;
1097         if (SCHEDULER_STOPPED())
1098                 return;
1099
1100         rw = rwlock2rw(c);
1101         if (__predict_false(v == tid))
1102                 v = RW_READ_VALUE(rw);
1103
1104         if (v & RW_LOCK_WRITER_RECURSED) {
1105                 if (--(rw->rw_recurse) == 0)
1106                         atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1107                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1108                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1109                 return;
1110         }
1111
1112         LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1113         if (v == tid && _rw_write_unlock(rw, tid))
1114                 return;
1115
1116         KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1117             ("%s: neither of the waiter flags are set", __func__));
1118
1119         if (LOCK_LOG_TEST(&rw->lock_object, 0))
1120                 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1121
1122         turnstile_chain_lock(&rw->lock_object);
1123
1124         /*
1125          * Use the same algo as sx locks for now.  Prefer waking up shared
1126          * waiters if we have any over writers.  This is probably not ideal.
1127          *
1128          * 'v' is the value we are going to write back to rw_lock.  If we
1129          * have waiters on both queues, we need to preserve the state of
1130          * the waiter flag for the queue we don't wake up.  For now this is
1131          * hardcoded for the algorithm mentioned above.
1132          *
1133          * In the case of both readers and writers waiting we wakeup the
1134          * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
1135          * new writer comes in before a reader it will claim the lock up
1136          * above.  There is probably a potential priority inversion in
1137          * there that could be worked around either by waking both queues
1138          * of waiters or doing some complicated lock handoff gymnastics.
1139          */
1140         setv = RW_UNLOCKED;
1141         v = RW_READ_VALUE(rw);
1142         queue = TS_SHARED_QUEUE;
1143         if (v & RW_LOCK_WRITE_WAITERS) {
1144                 queue = TS_EXCLUSIVE_QUEUE;
1145                 setv |= (v & RW_LOCK_READ_WAITERS);
1146         }
1147         atomic_store_rel_ptr(&rw->rw_lock, setv);
1148
1149         /* Wake up all waiters for the specific queue. */
1150         if (LOCK_LOG_TEST(&rw->lock_object, 0))
1151                 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1152                     queue == TS_SHARED_QUEUE ? "read" : "write");
1153
1154         ts = turnstile_lookup(&rw->lock_object);
1155         MPASS(ts != NULL);
1156         turnstile_broadcast(ts, queue);
1157         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1158         turnstile_chain_unlock(&rw->lock_object);
1159 }
1160
1161 /*
1162  * Attempt to do a non-blocking upgrade from a read lock to a write
1163  * lock.  This will only succeed if this thread holds a single read
1164  * lock.  Returns true if the upgrade succeeded and false otherwise.
1165  */
1166 int
1167 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1168 {
1169         uintptr_t v, x, tid;
1170         struct turnstile *ts;
1171         int success;
1172
1173         if (SCHEDULER_STOPPED())
1174                 return (1);
1175
1176         KASSERT(rw->rw_lock != RW_DESTROYED,
1177             ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1178         __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1179
1180         /*
1181          * Attempt to switch from one reader to a writer.  If there
1182          * are any write waiters, then we will have to lock the
1183          * turnstile first to prevent races with another writer
1184          * calling turnstile_wait() before we have claimed this
1185          * turnstile.  So, do the simple case of no waiters first.
1186          */
1187         tid = (uintptr_t)curthread;
1188         success = 0;
1189         for (;;) {
1190                 v = rw->rw_lock;
1191                 if (RW_READERS(v) > 1)
1192                         break;
1193                 if (!(v & RW_LOCK_WAITERS)) {
1194                         success = atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid);
1195                         if (!success)
1196                                 continue;
1197                         break;
1198                 }
1199
1200                 /*
1201                  * Ok, we think we have waiters, so lock the turnstile.
1202                  */
1203                 ts = turnstile_trywait(&rw->lock_object);
1204                 v = rw->rw_lock;
1205                 if (RW_READERS(v) > 1) {
1206                         turnstile_cancel(ts);
1207                         break;
1208                 }
1209                 /*
1210                  * Try to switch from one reader to a writer again.  This time
1211                  * we honor the current state of the waiters flags.
1212                  * If we obtain the lock with the flags set, then claim
1213                  * ownership of the turnstile.
1214                  */
1215                 x = rw->rw_lock & RW_LOCK_WAITERS;
1216                 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1217                 if (success) {
1218                         if (x)
1219                                 turnstile_claim(ts);
1220                         else
1221                                 turnstile_cancel(ts);
1222                         break;
1223                 }
1224                 turnstile_cancel(ts);
1225         }
1226         LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1227         if (success) {
1228                 curthread->td_rw_rlocks--;
1229                 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1230                     file, line);
1231                 LOCKSTAT_RECORD0(rw__upgrade, rw);
1232         }
1233         return (success);
1234 }
1235
1236 int
1237 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1238 {
1239         struct rwlock *rw;
1240
1241         rw = rwlock2rw(c);
1242         return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1243 }
1244
1245 /*
1246  * Downgrade a write lock into a single read lock.
1247  */
1248 void
1249 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1250 {
1251         struct turnstile *ts;
1252         uintptr_t tid, v;
1253         int rwait, wwait;
1254
1255         if (SCHEDULER_STOPPED())
1256                 return;
1257
1258         KASSERT(rw->rw_lock != RW_DESTROYED,
1259             ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1260         __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1261 #ifndef INVARIANTS
1262         if (rw_recursed(rw))
1263                 panic("downgrade of a recursed lock");
1264 #endif
1265
1266         WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1267
1268         /*
1269          * Convert from a writer to a single reader.  First we handle
1270          * the easy case with no waiters.  If there are any waiters, we
1271          * lock the turnstile and "disown" the lock.
1272          */
1273         tid = (uintptr_t)curthread;
1274         if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1275                 goto out;
1276
1277         /*
1278          * Ok, we think we have waiters, so lock the turnstile so we can
1279          * read the waiter flags without any races.
1280          */
1281         turnstile_chain_lock(&rw->lock_object);
1282         v = rw->rw_lock & RW_LOCK_WAITERS;
1283         rwait = v & RW_LOCK_READ_WAITERS;
1284         wwait = v & RW_LOCK_WRITE_WAITERS;
1285         MPASS(rwait | wwait);
1286
1287         /*
1288          * Downgrade from a write lock while preserving waiters flag
1289          * and give up ownership of the turnstile.
1290          */
1291         ts = turnstile_lookup(&rw->lock_object);
1292         MPASS(ts != NULL);
1293         if (!wwait)
1294                 v &= ~RW_LOCK_READ_WAITERS;
1295         atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1296         /*
1297          * Wake other readers if there are no writers pending.  Otherwise they
1298          * won't be able to acquire the lock anyway.
1299          */
1300         if (rwait && !wwait) {
1301                 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1302                 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1303         } else
1304                 turnstile_disown(ts);
1305         turnstile_chain_unlock(&rw->lock_object);
1306 out:
1307         curthread->td_rw_rlocks++;
1308         LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1309         LOCKSTAT_RECORD0(rw__downgrade, rw);
1310 }
1311
1312 void
1313 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1314 {
1315         struct rwlock *rw;
1316
1317         rw = rwlock2rw(c);
1318         __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1319 }
1320
1321 #ifdef INVARIANT_SUPPORT
1322 #ifndef INVARIANTS
1323 #undef __rw_assert
1324 #endif
1325
1326 /*
1327  * In the non-WITNESS case, rw_assert() can only detect that at least
1328  * *some* thread owns an rlock, but it cannot guarantee that *this*
1329  * thread owns an rlock.
1330  */
1331 void
1332 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1333 {
1334         const struct rwlock *rw;
1335
1336         if (panicstr != NULL)
1337                 return;
1338
1339         rw = rwlock2rw(c);
1340
1341         switch (what) {
1342         case RA_LOCKED:
1343         case RA_LOCKED | RA_RECURSED:
1344         case RA_LOCKED | RA_NOTRECURSED:
1345         case RA_RLOCKED:
1346         case RA_RLOCKED | RA_RECURSED:
1347         case RA_RLOCKED | RA_NOTRECURSED:
1348 #ifdef WITNESS
1349                 witness_assert(&rw->lock_object, what, file, line);
1350 #else
1351                 /*
1352                  * If some other thread has a write lock or we have one
1353                  * and are asserting a read lock, fail.  Also, if no one
1354                  * has a lock at all, fail.
1355                  */
1356                 if (rw->rw_lock == RW_UNLOCKED ||
1357                     (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1358                     rw_wowner(rw) != curthread)))
1359                         panic("Lock %s not %slocked @ %s:%d\n",
1360                             rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1361                             "read " : "", file, line);
1362
1363                 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1364                         if (rw_recursed(rw)) {
1365                                 if (what & RA_NOTRECURSED)
1366                                         panic("Lock %s recursed @ %s:%d\n",
1367                                             rw->lock_object.lo_name, file,
1368                                             line);
1369                         } else if (what & RA_RECURSED)
1370                                 panic("Lock %s not recursed @ %s:%d\n",
1371                                     rw->lock_object.lo_name, file, line);
1372                 }
1373 #endif
1374                 break;
1375         case RA_WLOCKED:
1376         case RA_WLOCKED | RA_RECURSED:
1377         case RA_WLOCKED | RA_NOTRECURSED:
1378                 if (rw_wowner(rw) != curthread)
1379                         panic("Lock %s not exclusively locked @ %s:%d\n",
1380                             rw->lock_object.lo_name, file, line);
1381                 if (rw_recursed(rw)) {
1382                         if (what & RA_NOTRECURSED)
1383                                 panic("Lock %s recursed @ %s:%d\n",
1384                                     rw->lock_object.lo_name, file, line);
1385                 } else if (what & RA_RECURSED)
1386                         panic("Lock %s not recursed @ %s:%d\n",
1387                             rw->lock_object.lo_name, file, line);
1388                 break;
1389         case RA_UNLOCKED:
1390 #ifdef WITNESS
1391                 witness_assert(&rw->lock_object, what, file, line);
1392 #else
1393                 /*
1394                  * If we hold a write lock fail.  We can't reliably check
1395                  * to see if we hold a read lock or not.
1396                  */
1397                 if (rw_wowner(rw) == curthread)
1398                         panic("Lock %s exclusively locked @ %s:%d\n",
1399                             rw->lock_object.lo_name, file, line);
1400 #endif
1401                 break;
1402         default:
1403                 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1404                     line);
1405         }
1406 }
1407 #endif /* INVARIANT_SUPPORT */
1408
1409 #ifdef DDB
1410 void
1411 db_show_rwlock(const struct lock_object *lock)
1412 {
1413         const struct rwlock *rw;
1414         struct thread *td;
1415
1416         rw = (const struct rwlock *)lock;
1417
1418         db_printf(" state: ");
1419         if (rw->rw_lock == RW_UNLOCKED)
1420                 db_printf("UNLOCKED\n");
1421         else if (rw->rw_lock == RW_DESTROYED) {
1422                 db_printf("DESTROYED\n");
1423                 return;
1424         } else if (rw->rw_lock & RW_LOCK_READ)
1425                 db_printf("RLOCK: %ju locks\n",
1426                     (uintmax_t)(RW_READERS(rw->rw_lock)));
1427         else {
1428                 td = rw_wowner(rw);
1429                 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1430                     td->td_tid, td->td_proc->p_pid, td->td_name);
1431                 if (rw_recursed(rw))
1432                         db_printf(" recursed: %u\n", rw->rw_recurse);
1433         }
1434         db_printf(" waiters: ");
1435         switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1436         case RW_LOCK_READ_WAITERS:
1437                 db_printf("readers\n");
1438                 break;
1439         case RW_LOCK_WRITE_WAITERS:
1440                 db_printf("writers\n");
1441                 break;
1442         case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1443                 db_printf("readers and writers\n");
1444                 break;
1445         default:
1446                 db_printf("none\n");
1447                 break;
1448         }
1449 }
1450
1451 #endif