]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_rwlock.c
Merge ^/head r313644 through r313895.
[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 rowner_retries = 10;
97 static int 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_mostly 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 = arg;
244
245         rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
246 }
247
248 void
249 rw_sysinit_flags(void *arg)
250 {
251         struct rw_args_flags *args = arg;
252
253         rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
254             args->ra_flags);
255 }
256
257 int
258 _rw_wowned(const volatile uintptr_t *c)
259 {
260
261         return (rw_wowner(rwlock2rw(c)) == curthread);
262 }
263
264 void
265 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
266 {
267         struct rwlock *rw;
268         uintptr_t tid, v;
269
270         rw = rwlock2rw(c);
271
272         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
273             ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
274             curthread, rw->lock_object.lo_name, file, line));
275         KASSERT(rw->rw_lock != RW_DESTROYED,
276             ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
277         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
278             line, NULL);
279         tid = (uintptr_t)curthread;
280         v = RW_UNLOCKED;
281         if (!_rw_write_lock_fetch(rw, &v, tid))
282                 _rw_wlock_hard(rw, v, tid, file, line);
283         else
284                 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
285                     0, 0, file, line, LOCKSTAT_WRITER);
286
287         LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
288         WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
289         TD_LOCKS_INC(curthread);
290 }
291
292 int
293 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
294 {
295         struct rwlock *rw;
296         int rval;
297
298         if (SCHEDULER_STOPPED())
299                 return (1);
300
301         rw = rwlock2rw(c);
302
303         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
304             ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
305             curthread, rw->lock_object.lo_name, file, line));
306         KASSERT(rw->rw_lock != RW_DESTROYED,
307             ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
308
309         if (rw_wlocked(rw) &&
310             (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
311                 rw->rw_recurse++;
312                 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
313                 rval = 1;
314         } else
315                 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
316                     (uintptr_t)curthread);
317
318         LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
319         if (rval) {
320                 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
321                     file, line);
322                 if (!rw_recursed(rw))
323                         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
324                             rw, 0, 0, file, line, LOCKSTAT_WRITER);
325                 TD_LOCKS_INC(curthread);
326         }
327         return (rval);
328 }
329
330 void
331 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
332 {
333         struct rwlock *rw;
334
335         rw = rwlock2rw(c);
336
337         KASSERT(rw->rw_lock != RW_DESTROYED,
338             ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
339         __rw_assert(c, RA_WLOCKED, file, line);
340         WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
341         LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
342             line);
343
344 #ifdef LOCK_PROFILING
345         _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
346 #else
347         __rw_wunlock(rw, curthread, file, line);
348 #endif
349
350         TD_LOCKS_DEC(curthread);
351 }
352
353 /*
354  * Determines whether a new reader can acquire a lock.  Succeeds if the
355  * reader already owns a read lock and the lock is locked for read to
356  * prevent deadlock from reader recursion.  Also succeeds if the lock
357  * is unlocked and has no writer waiters or spinners.  Failing otherwise
358  * prioritizes writers before readers.
359  */
360 #define RW_CAN_READ(td, _rw)                                            \
361     (((td)->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &   \
362     (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==  \
363     RW_LOCK_READ)
364
365 static bool __always_inline
366 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp,
367     const char *file, int line)
368 {
369
370         /*
371          * Handle the easy case.  If no other thread has a write
372          * lock, then try to bump up the count of read locks.  Note
373          * that we have to preserve the current state of the
374          * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
375          * read lock, then rw_lock must have changed, so restart
376          * the loop.  Note that this handles the case of a
377          * completely unlocked rwlock since such a lock is encoded
378          * as a read lock with no waiters.
379          */
380         while (RW_CAN_READ(td, *vp)) {
381                 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
382                         *vp + RW_ONE_READER)) {
383                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
384                                 CTR4(KTR_LOCK,
385                                     "%s: %p succeed %p -> %p", __func__,
386                                     rw, (void *)*vp,
387                                     (void *)(*vp + RW_ONE_READER));
388                         td->td_rw_rlocks++;
389                         return (true);
390                 }
391         }
392         return (false);
393 }
394
395 static void __noinline
396 __rw_rlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
397     const char *file, int line)
398 {
399         struct rwlock *rw;
400         struct turnstile *ts;
401 #ifdef ADAPTIVE_RWLOCKS
402         volatile struct thread *owner;
403         int spintries = 0;
404         int i;
405 #endif
406 #ifdef LOCK_PROFILING
407         uint64_t waittime = 0;
408         int contested = 0;
409 #endif
410 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
411         struct lock_delay_arg lda;
412 #endif
413 #ifdef KDTRACE_HOOKS
414         uintptr_t state;
415         u_int sleep_cnt = 0;
416         int64_t sleep_time = 0;
417         int64_t all_time = 0;
418 #endif
419
420         if (SCHEDULER_STOPPED())
421                 return;
422
423 #if defined(ADAPTIVE_RWLOCKS)
424         lock_delay_arg_init(&lda, &rw_delay);
425 #elif defined(KDTRACE_HOOKS)
426         lock_delay_arg_init(&lda, NULL);
427 #endif
428         rw = rwlock2rw(c);
429
430 #ifdef KDTRACE_HOOKS
431         all_time -= lockstat_nsecs(&rw->lock_object);
432 #endif
433 #ifdef KDTRACE_HOOKS
434         state = v;
435 #endif
436         for (;;) {
437                 if (__rw_rlock_try(rw, td, &v, file, line))
438                         break;
439 #ifdef KDTRACE_HOOKS
440                 lda.spin_cnt++;
441 #endif
442 #ifdef HWPMC_HOOKS
443                 PMC_SOFT_CALL( , , lock, failed);
444 #endif
445                 lock_profile_obtain_lock_failed(&rw->lock_object,
446                     &contested, &waittime);
447
448 #ifdef ADAPTIVE_RWLOCKS
449                 /*
450                  * If the owner is running on another CPU, spin until
451                  * the owner stops running or the state of the lock
452                  * changes.
453                  */
454                 if ((v & RW_LOCK_READ) == 0) {
455                         owner = (struct thread *)RW_OWNER(v);
456                         if (TD_IS_RUNNING(owner)) {
457                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
458                                         CTR3(KTR_LOCK,
459                                             "%s: spinning on %p held by %p",
460                                             __func__, rw, owner);
461                                 KTR_STATE1(KTR_SCHED, "thread",
462                                     sched_tdname(curthread), "spinning",
463                                     "lockname:\"%s\"", rw->lock_object.lo_name);
464                                 do {
465                                         lock_delay(&lda);
466                                         v = RW_READ_VALUE(rw);
467                                         owner = lv_rw_wowner(v);
468                                 } while (owner != NULL && TD_IS_RUNNING(owner));
469                                 KTR_STATE0(KTR_SCHED, "thread",
470                                     sched_tdname(curthread), "running");
471                                 continue;
472                         }
473                 } else if (spintries < rowner_retries) {
474                         spintries++;
475                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
476                             "spinning", "lockname:\"%s\"",
477                             rw->lock_object.lo_name);
478                         for (i = 0; i < rowner_loops; i++) {
479                                 v = RW_READ_VALUE(rw);
480                                 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(td, v))
481                                         break;
482                                 cpu_spinwait();
483                         }
484                         v = RW_READ_VALUE(rw);
485 #ifdef KDTRACE_HOOKS
486                         lda.spin_cnt += rowner_loops - i;
487 #endif
488                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
489                             "running");
490                         if (i != rowner_loops)
491                                 continue;
492                 }
493 #endif
494
495                 /*
496                  * Okay, now it's the hard case.  Some other thread already
497                  * has a write lock or there are write waiters present,
498                  * acquire the turnstile lock so we can begin the process
499                  * of blocking.
500                  */
501                 ts = turnstile_trywait(&rw->lock_object);
502
503                 /*
504                  * The lock might have been released while we spun, so
505                  * recheck its state and restart the loop if needed.
506                  */
507                 v = RW_READ_VALUE(rw);
508                 if (RW_CAN_READ(td, v)) {
509                         turnstile_cancel(ts);
510                         continue;
511                 }
512
513 #ifdef ADAPTIVE_RWLOCKS
514                 /*
515                  * The current lock owner might have started executing
516                  * on another CPU (or the lock could have changed
517                  * owners) while we were waiting on the turnstile
518                  * chain lock.  If so, drop the turnstile lock and try
519                  * again.
520                  */
521                 if ((v & RW_LOCK_READ) == 0) {
522                         owner = (struct thread *)RW_OWNER(v);
523                         if (TD_IS_RUNNING(owner)) {
524                                 turnstile_cancel(ts);
525                                 continue;
526                         }
527                 }
528 #endif
529
530                 /*
531                  * The lock is held in write mode or it already has waiters.
532                  */
533                 MPASS(!RW_CAN_READ(td, v));
534
535                 /*
536                  * If the RW_LOCK_READ_WAITERS flag is already set, then
537                  * we can go ahead and block.  If it is not set then try
538                  * to set it.  If we fail to set it drop the turnstile
539                  * lock and restart the loop.
540                  */
541                 if (!(v & RW_LOCK_READ_WAITERS)) {
542                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
543                             v | RW_LOCK_READ_WAITERS)) {
544                                 turnstile_cancel(ts);
545                                 v = RW_READ_VALUE(rw);
546                                 continue;
547                         }
548                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
549                                 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
550                                     __func__, rw);
551                 }
552
553                 /*
554                  * We were unable to acquire the lock and the read waiters
555                  * flag is set, so we must block on the turnstile.
556                  */
557                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
558                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
559                             rw);
560 #ifdef KDTRACE_HOOKS
561                 sleep_time -= lockstat_nsecs(&rw->lock_object);
562 #endif
563                 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
564 #ifdef KDTRACE_HOOKS
565                 sleep_time += lockstat_nsecs(&rw->lock_object);
566                 sleep_cnt++;
567 #endif
568                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
569                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
570                             __func__, rw);
571                 v = RW_READ_VALUE(rw);
572         }
573 #ifdef KDTRACE_HOOKS
574         all_time += lockstat_nsecs(&rw->lock_object);
575         if (sleep_time)
576                 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
577                     LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
578                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
579
580         /* Record only the loops spinning and not sleeping. */
581         if (lda.spin_cnt > sleep_cnt)
582                 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
583                     LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
584                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
585 #endif
586         /*
587          * TODO: acquire "owner of record" here.  Here be turnstile dragons
588          * however.  turnstiles don't like owners changing between calls to
589          * turnstile_wait() currently.
590          */
591         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
592             waittime, file, line, LOCKSTAT_READER);
593 }
594
595 void
596 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
597 {
598         struct rwlock *rw;
599         struct thread *td;
600         uintptr_t v;
601
602         td = curthread;
603         rw = rwlock2rw(c);
604
605         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
606             ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
607             td, rw->lock_object.lo_name, file, line));
608         KASSERT(rw->rw_lock != RW_DESTROYED,
609             ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
610         KASSERT(rw_wowner(rw) != td,
611             ("rw_rlock: wlock already held for %s @ %s:%d",
612             rw->lock_object.lo_name, file, line));
613         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
614
615         v = RW_READ_VALUE(rw);
616         if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
617             !__rw_rlock_try(rw, td, &v, file, line)))
618                 __rw_rlock_hard(c, td, v, file, line);
619
620         LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
621         WITNESS_LOCK(&rw->lock_object, 0, file, line);
622         TD_LOCKS_INC(curthread);
623 }
624
625 int
626 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
627 {
628         struct rwlock *rw;
629         uintptr_t x;
630
631         if (SCHEDULER_STOPPED())
632                 return (1);
633
634         rw = rwlock2rw(c);
635
636         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
637             ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
638             curthread, rw->lock_object.lo_name, file, line));
639
640         for (;;) {
641                 x = rw->rw_lock;
642                 KASSERT(rw->rw_lock != RW_DESTROYED,
643                     ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
644                 if (!(x & RW_LOCK_READ))
645                         break;
646                 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
647                         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
648                             line);
649                         WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
650                         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
651                             rw, 0, 0, file, line, LOCKSTAT_READER);
652                         TD_LOCKS_INC(curthread);
653                         curthread->td_rw_rlocks++;
654                         return (1);
655                 }
656         }
657
658         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
659         return (0);
660 }
661
662 static bool __always_inline
663 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
664 {
665
666         for (;;) {
667                 /*
668                  * See if there is more than one read lock held.  If so,
669                  * just drop one and return.
670                  */
671                 if (RW_READERS(*vp) > 1) {
672                         if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
673                             *vp - RW_ONE_READER)) {
674                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
675                                         CTR4(KTR_LOCK,
676                                             "%s: %p succeeded %p -> %p",
677                                             __func__, rw, (void *)*vp,
678                                             (void *)(*vp - RW_ONE_READER));
679                                 td->td_rw_rlocks--;
680                                 return (true);
681                         }
682                         continue;
683                 }
684                 /*
685                  * If there aren't any waiters for a write lock, then try
686                  * to drop it quickly.
687                  */
688                 if (!(*vp & RW_LOCK_WAITERS)) {
689                         MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
690                             RW_READERS_LOCK(1));
691                         if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
692                             RW_UNLOCKED)) {
693                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
694                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
695                                             __func__, rw);
696                                 td->td_rw_rlocks--;
697                                 return (true);
698                         }
699                         continue;
700                 }
701                 break;
702         }
703         return (false);
704 }
705
706 static void __noinline
707 __rw_runlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
708     const char *file, int line)
709 {
710         struct rwlock *rw;
711         struct turnstile *ts;
712         uintptr_t x, queue;
713
714         if (SCHEDULER_STOPPED())
715                 return;
716
717         rw = rwlock2rw(c);
718
719         for (;;) {
720                 if (__rw_runlock_try(rw, td, &v))
721                         break;
722
723                 /*
724                  * Ok, we know we have waiters and we think we are the
725                  * last reader, so grab the turnstile lock.
726                  */
727                 turnstile_chain_lock(&rw->lock_object);
728                 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
729                 MPASS(v & RW_LOCK_WAITERS);
730
731                 /*
732                  * Try to drop our lock leaving the lock in a unlocked
733                  * state.
734                  *
735                  * If you wanted to do explicit lock handoff you'd have to
736                  * do it here.  You'd also want to use turnstile_signal()
737                  * and you'd have to handle the race where a higher
738                  * priority thread blocks on the write lock before the
739                  * thread you wakeup actually runs and have the new thread
740                  * "steal" the lock.  For now it's a lot simpler to just
741                  * wakeup all of the waiters.
742                  *
743                  * As above, if we fail, then another thread might have
744                  * acquired a read lock, so drop the turnstile lock and
745                  * restart.
746                  */
747                 x = RW_UNLOCKED;
748                 if (v & RW_LOCK_WRITE_WAITERS) {
749                         queue = TS_EXCLUSIVE_QUEUE;
750                         x |= (v & RW_LOCK_READ_WAITERS);
751                 } else
752                         queue = TS_SHARED_QUEUE;
753                 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
754                     x)) {
755                         turnstile_chain_unlock(&rw->lock_object);
756                         v = RW_READ_VALUE(rw);
757                         continue;
758                 }
759                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
760                         CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
761                             __func__, rw);
762
763                 /*
764                  * Ok.  The lock is released and all that's left is to
765                  * wake up the waiters.  Note that the lock might not be
766                  * free anymore, but in that case the writers will just
767                  * block again if they run before the new lock holder(s)
768                  * release the lock.
769                  */
770                 ts = turnstile_lookup(&rw->lock_object);
771                 MPASS(ts != NULL);
772                 turnstile_broadcast(ts, queue);
773                 turnstile_unpend(ts, TS_SHARED_LOCK);
774                 turnstile_chain_unlock(&rw->lock_object);
775                 td->td_rw_rlocks--;
776                 break;
777         }
778         LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
779 }
780
781 void
782 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
783 {
784         struct rwlock *rw;
785         struct thread *td;
786         uintptr_t v;
787
788         rw = rwlock2rw(c);
789
790         KASSERT(rw->rw_lock != RW_DESTROYED,
791             ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
792         __rw_assert(c, RA_RLOCKED, file, line);
793         WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
794         LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
795
796         td = curthread;
797         v = RW_READ_VALUE(rw);
798
799         if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
800             !__rw_runlock_try(rw, td, &v)))
801                 __rw_runlock_hard(c, td, v, file, line);
802
803         TD_LOCKS_DEC(curthread);
804 }
805
806
807 /*
808  * This function is called when we are unable to obtain a write lock on the
809  * first try.  This means that at least one other thread holds either a
810  * read or write lock.
811  */
812 void
813 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
814     const char *file, int line)
815 {
816         struct rwlock *rw;
817         struct turnstile *ts;
818 #ifdef ADAPTIVE_RWLOCKS
819         volatile struct thread *owner;
820         int spintries = 0;
821         int i;
822 #endif
823         uintptr_t x;
824 #ifdef LOCK_PROFILING
825         uint64_t waittime = 0;
826         int contested = 0;
827 #endif
828 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
829         struct lock_delay_arg lda;
830 #endif
831 #ifdef KDTRACE_HOOKS
832         uintptr_t state;
833         u_int sleep_cnt = 0;
834         int64_t sleep_time = 0;
835         int64_t all_time = 0;
836 #endif
837
838         if (SCHEDULER_STOPPED())
839                 return;
840
841 #if defined(ADAPTIVE_RWLOCKS)
842         lock_delay_arg_init(&lda, &rw_delay);
843 #elif defined(KDTRACE_HOOKS)
844         lock_delay_arg_init(&lda, NULL);
845 #endif
846         rw = rwlock2rw(c);
847         if (__predict_false(v == RW_UNLOCKED))
848                 v = RW_READ_VALUE(rw);
849
850         if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
851                 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
852                     ("%s: recursing but non-recursive rw %s @ %s:%d\n",
853                     __func__, rw->lock_object.lo_name, file, line));
854                 rw->rw_recurse++;
855                 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
856                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
857                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
858                 return;
859         }
860
861         if (LOCK_LOG_TEST(&rw->lock_object, 0))
862                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
863                     rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
864
865 #ifdef KDTRACE_HOOKS
866         all_time -= lockstat_nsecs(&rw->lock_object);
867         state = v;
868 #endif
869         for (;;) {
870                 if (v == RW_UNLOCKED) {
871                         if (_rw_write_lock_fetch(rw, &v, tid))
872                                 break;
873                         continue;
874                 }
875 #ifdef KDTRACE_HOOKS
876                 lda.spin_cnt++;
877 #endif
878 #ifdef HWPMC_HOOKS
879                 PMC_SOFT_CALL( , , lock, failed);
880 #endif
881                 lock_profile_obtain_lock_failed(&rw->lock_object,
882                     &contested, &waittime);
883 #ifdef ADAPTIVE_RWLOCKS
884                 /*
885                  * If the lock is write locked and the owner is
886                  * running on another CPU, spin until the owner stops
887                  * running or the state of the lock changes.
888                  */
889                 owner = lv_rw_wowner(v);
890                 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
891                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
892                                 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
893                                     __func__, rw, owner);
894                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
895                             "spinning", "lockname:\"%s\"",
896                             rw->lock_object.lo_name);
897                         do {
898                                 lock_delay(&lda);
899                                 v = RW_READ_VALUE(rw);
900                                 owner = lv_rw_wowner(v);
901                         } while (owner != NULL && TD_IS_RUNNING(owner));
902                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
903                             "running");
904                         continue;
905                 }
906                 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
907                     spintries < rowner_retries) {
908                         if (!(v & RW_LOCK_WRITE_SPINNER)) {
909                                 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
910                                     v | RW_LOCK_WRITE_SPINNER)) {
911                                         v = RW_READ_VALUE(rw);
912                                         continue;
913                                 }
914                         }
915                         spintries++;
916                         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
917                             "spinning", "lockname:\"%s\"",
918                             rw->lock_object.lo_name);
919                         for (i = 0; i < rowner_loops; i++) {
920                                 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
921                                         break;
922                                 cpu_spinwait();
923                         }
924                         KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
925                             "running");
926                         v = RW_READ_VALUE(rw);
927 #ifdef KDTRACE_HOOKS
928                         lda.spin_cnt += rowner_loops - i;
929 #endif
930                         if (i != rowner_loops)
931                                 continue;
932                 }
933 #endif
934                 ts = turnstile_trywait(&rw->lock_object);
935                 v = RW_READ_VALUE(rw);
936
937 #ifdef ADAPTIVE_RWLOCKS
938                 /*
939                  * The current lock owner might have started executing
940                  * on another CPU (or the lock could have changed
941                  * owners) while we were waiting on the turnstile
942                  * chain lock.  If so, drop the turnstile lock and try
943                  * again.
944                  */
945                 if (!(v & RW_LOCK_READ)) {
946                         owner = (struct thread *)RW_OWNER(v);
947                         if (TD_IS_RUNNING(owner)) {
948                                 turnstile_cancel(ts);
949                                 continue;
950                         }
951                 }
952 #endif
953                 /*
954                  * Check for the waiters flags about this rwlock.
955                  * If the lock was released, without maintain any pending
956                  * waiters queue, simply try to acquire it.
957                  * If a pending waiters queue is present, claim the lock
958                  * ownership and maintain the pending queue.
959                  */
960                 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
961                 if ((v & ~x) == RW_UNLOCKED) {
962                         x &= ~RW_LOCK_WRITE_SPINNER;
963                         if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
964                                 if (x)
965                                         turnstile_claim(ts);
966                                 else
967                                         turnstile_cancel(ts);
968                                 break;
969                         }
970                         turnstile_cancel(ts);
971                         v = RW_READ_VALUE(rw);
972                         continue;
973                 }
974                 /*
975                  * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
976                  * set it.  If we fail to set it, then loop back and try
977                  * again.
978                  */
979                 if (!(v & RW_LOCK_WRITE_WAITERS)) {
980                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
981                             v | RW_LOCK_WRITE_WAITERS)) {
982                                 turnstile_cancel(ts);
983                                 v = RW_READ_VALUE(rw);
984                                 continue;
985                         }
986                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
987                                 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
988                                     __func__, rw);
989                 }
990                 /*
991                  * We were unable to acquire the lock and the write waiters
992                  * flag is set, so we must block on the turnstile.
993                  */
994                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
995                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
996                             rw);
997 #ifdef KDTRACE_HOOKS
998                 sleep_time -= lockstat_nsecs(&rw->lock_object);
999 #endif
1000                 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
1001 #ifdef KDTRACE_HOOKS
1002                 sleep_time += lockstat_nsecs(&rw->lock_object);
1003                 sleep_cnt++;
1004 #endif
1005                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1006                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1007                             __func__, rw);
1008 #ifdef ADAPTIVE_RWLOCKS
1009                 spintries = 0;
1010 #endif
1011                 v = RW_READ_VALUE(rw);
1012         }
1013 #ifdef KDTRACE_HOOKS
1014         all_time += lockstat_nsecs(&rw->lock_object);
1015         if (sleep_time)
1016                 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1017                     LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1018                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1019
1020         /* Record only the loops spinning and not sleeping. */
1021         if (lda.spin_cnt > sleep_cnt)
1022                 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1023                     LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1024                     (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1025 #endif
1026         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1027             waittime, file, line, LOCKSTAT_WRITER);
1028 }
1029
1030 /*
1031  * This function is called if lockstat is active or the first try at releasing
1032  * a write lock failed.  The latter means that the lock is recursed or one of
1033  * the 2 waiter bits must be set indicating that at least one thread is waiting
1034  * on this lock.
1035  */
1036 void
1037 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
1038     int line)
1039 {
1040         struct rwlock *rw;
1041         struct turnstile *ts;
1042         uintptr_t v;
1043         int queue;
1044
1045         if (SCHEDULER_STOPPED())
1046                 return;
1047
1048         rw = rwlock2rw(c);
1049         v = RW_READ_VALUE(rw);
1050         if (v & RW_LOCK_WRITER_RECURSED) {
1051                 if (--(rw->rw_recurse) == 0)
1052                         atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1053                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1054                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1055                 return;
1056         }
1057
1058         LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1059         if (v == tid && _rw_write_unlock(rw, tid))
1060                 return;
1061
1062         KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1063             ("%s: neither of the waiter flags are set", __func__));
1064
1065         if (LOCK_LOG_TEST(&rw->lock_object, 0))
1066                 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1067
1068         turnstile_chain_lock(&rw->lock_object);
1069         ts = turnstile_lookup(&rw->lock_object);
1070         MPASS(ts != NULL);
1071
1072         /*
1073          * Use the same algo as sx locks for now.  Prefer waking up shared
1074          * waiters if we have any over writers.  This is probably not ideal.
1075          *
1076          * 'v' is the value we are going to write back to rw_lock.  If we
1077          * have waiters on both queues, we need to preserve the state of
1078          * the waiter flag for the queue we don't wake up.  For now this is
1079          * hardcoded for the algorithm mentioned above.
1080          *
1081          * In the case of both readers and writers waiting we wakeup the
1082          * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
1083          * new writer comes in before a reader it will claim the lock up
1084          * above.  There is probably a potential priority inversion in
1085          * there that could be worked around either by waking both queues
1086          * of waiters or doing some complicated lock handoff gymnastics.
1087          */
1088         v = RW_UNLOCKED;
1089         if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
1090                 queue = TS_EXCLUSIVE_QUEUE;
1091                 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
1092         } else
1093                 queue = TS_SHARED_QUEUE;
1094
1095         /* Wake up all waiters for the specific queue. */
1096         if (LOCK_LOG_TEST(&rw->lock_object, 0))
1097                 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1098                     queue == TS_SHARED_QUEUE ? "read" : "write");
1099         turnstile_broadcast(ts, queue);
1100         atomic_store_rel_ptr(&rw->rw_lock, v);
1101         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1102         turnstile_chain_unlock(&rw->lock_object);
1103 }
1104
1105 /*
1106  * Attempt to do a non-blocking upgrade from a read lock to a write
1107  * lock.  This will only succeed if this thread holds a single read
1108  * lock.  Returns true if the upgrade succeeded and false otherwise.
1109  */
1110 int
1111 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1112 {
1113         struct rwlock *rw;
1114         uintptr_t v, x, tid;
1115         struct turnstile *ts;
1116         int success;
1117
1118         if (SCHEDULER_STOPPED())
1119                 return (1);
1120
1121         rw = rwlock2rw(c);
1122
1123         KASSERT(rw->rw_lock != RW_DESTROYED,
1124             ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1125         __rw_assert(c, RA_RLOCKED, file, line);
1126
1127         /*
1128          * Attempt to switch from one reader to a writer.  If there
1129          * are any write waiters, then we will have to lock the
1130          * turnstile first to prevent races with another writer
1131          * calling turnstile_wait() before we have claimed this
1132          * turnstile.  So, do the simple case of no waiters first.
1133          */
1134         tid = (uintptr_t)curthread;
1135         success = 0;
1136         for (;;) {
1137                 v = rw->rw_lock;
1138                 if (RW_READERS(v) > 1)
1139                         break;
1140                 if (!(v & RW_LOCK_WAITERS)) {
1141                         success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1142                         if (!success)
1143                                 continue;
1144                         break;
1145                 }
1146
1147                 /*
1148                  * Ok, we think we have waiters, so lock the turnstile.
1149                  */
1150                 ts = turnstile_trywait(&rw->lock_object);
1151                 v = rw->rw_lock;
1152                 if (RW_READERS(v) > 1) {
1153                         turnstile_cancel(ts);
1154                         break;
1155                 }
1156                 /*
1157                  * Try to switch from one reader to a writer again.  This time
1158                  * we honor the current state of the waiters flags.
1159                  * If we obtain the lock with the flags set, then claim
1160                  * ownership of the turnstile.
1161                  */
1162                 x = rw->rw_lock & RW_LOCK_WAITERS;
1163                 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1164                 if (success) {
1165                         if (x)
1166                                 turnstile_claim(ts);
1167                         else
1168                                 turnstile_cancel(ts);
1169                         break;
1170                 }
1171                 turnstile_cancel(ts);
1172         }
1173         LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1174         if (success) {
1175                 curthread->td_rw_rlocks--;
1176                 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1177                     file, line);
1178                 LOCKSTAT_RECORD0(rw__upgrade, rw);
1179         }
1180         return (success);
1181 }
1182
1183 /*
1184  * Downgrade a write lock into a single read lock.
1185  */
1186 void
1187 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1188 {
1189         struct rwlock *rw;
1190         struct turnstile *ts;
1191         uintptr_t tid, v;
1192         int rwait, wwait;
1193
1194         if (SCHEDULER_STOPPED())
1195                 return;
1196
1197         rw = rwlock2rw(c);
1198
1199         KASSERT(rw->rw_lock != RW_DESTROYED,
1200             ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1201         __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1202 #ifndef INVARIANTS
1203         if (rw_recursed(rw))
1204                 panic("downgrade of a recursed lock");
1205 #endif
1206
1207         WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1208
1209         /*
1210          * Convert from a writer to a single reader.  First we handle
1211          * the easy case with no waiters.  If there are any waiters, we
1212          * lock the turnstile and "disown" the lock.
1213          */
1214         tid = (uintptr_t)curthread;
1215         if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1216                 goto out;
1217
1218         /*
1219          * Ok, we think we have waiters, so lock the turnstile so we can
1220          * read the waiter flags without any races.
1221          */
1222         turnstile_chain_lock(&rw->lock_object);
1223         v = rw->rw_lock & RW_LOCK_WAITERS;
1224         rwait = v & RW_LOCK_READ_WAITERS;
1225         wwait = v & RW_LOCK_WRITE_WAITERS;
1226         MPASS(rwait | wwait);
1227
1228         /*
1229          * Downgrade from a write lock while preserving waiters flag
1230          * and give up ownership of the turnstile.
1231          */
1232         ts = turnstile_lookup(&rw->lock_object);
1233         MPASS(ts != NULL);
1234         if (!wwait)
1235                 v &= ~RW_LOCK_READ_WAITERS;
1236         atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1237         /*
1238          * Wake other readers if there are no writers pending.  Otherwise they
1239          * won't be able to acquire the lock anyway.
1240          */
1241         if (rwait && !wwait) {
1242                 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1243                 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1244         } else
1245                 turnstile_disown(ts);
1246         turnstile_chain_unlock(&rw->lock_object);
1247 out:
1248         curthread->td_rw_rlocks++;
1249         LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1250         LOCKSTAT_RECORD0(rw__downgrade, rw);
1251 }
1252
1253 #ifdef INVARIANT_SUPPORT
1254 #ifndef INVARIANTS
1255 #undef __rw_assert
1256 #endif
1257
1258 /*
1259  * In the non-WITNESS case, rw_assert() can only detect that at least
1260  * *some* thread owns an rlock, but it cannot guarantee that *this*
1261  * thread owns an rlock.
1262  */
1263 void
1264 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1265 {
1266         const struct rwlock *rw;
1267
1268         if (panicstr != NULL)
1269                 return;
1270
1271         rw = rwlock2rw(c);
1272
1273         switch (what) {
1274         case RA_LOCKED:
1275         case RA_LOCKED | RA_RECURSED:
1276         case RA_LOCKED | RA_NOTRECURSED:
1277         case RA_RLOCKED:
1278         case RA_RLOCKED | RA_RECURSED:
1279         case RA_RLOCKED | RA_NOTRECURSED:
1280 #ifdef WITNESS
1281                 witness_assert(&rw->lock_object, what, file, line);
1282 #else
1283                 /*
1284                  * If some other thread has a write lock or we have one
1285                  * and are asserting a read lock, fail.  Also, if no one
1286                  * has a lock at all, fail.
1287                  */
1288                 if (rw->rw_lock == RW_UNLOCKED ||
1289                     (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1290                     rw_wowner(rw) != curthread)))
1291                         panic("Lock %s not %slocked @ %s:%d\n",
1292                             rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1293                             "read " : "", file, line);
1294
1295                 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1296                         if (rw_recursed(rw)) {
1297                                 if (what & RA_NOTRECURSED)
1298                                         panic("Lock %s recursed @ %s:%d\n",
1299                                             rw->lock_object.lo_name, file,
1300                                             line);
1301                         } else if (what & RA_RECURSED)
1302                                 panic("Lock %s not recursed @ %s:%d\n",
1303                                     rw->lock_object.lo_name, file, line);
1304                 }
1305 #endif
1306                 break;
1307         case RA_WLOCKED:
1308         case RA_WLOCKED | RA_RECURSED:
1309         case RA_WLOCKED | RA_NOTRECURSED:
1310                 if (rw_wowner(rw) != curthread)
1311                         panic("Lock %s not exclusively locked @ %s:%d\n",
1312                             rw->lock_object.lo_name, file, line);
1313                 if (rw_recursed(rw)) {
1314                         if (what & RA_NOTRECURSED)
1315                                 panic("Lock %s recursed @ %s:%d\n",
1316                                     rw->lock_object.lo_name, file, line);
1317                 } else if (what & RA_RECURSED)
1318                         panic("Lock %s not recursed @ %s:%d\n",
1319                             rw->lock_object.lo_name, file, line);
1320                 break;
1321         case RA_UNLOCKED:
1322 #ifdef WITNESS
1323                 witness_assert(&rw->lock_object, what, file, line);
1324 #else
1325                 /*
1326                  * If we hold a write lock fail.  We can't reliably check
1327                  * to see if we hold a read lock or not.
1328                  */
1329                 if (rw_wowner(rw) == curthread)
1330                         panic("Lock %s exclusively locked @ %s:%d\n",
1331                             rw->lock_object.lo_name, file, line);
1332 #endif
1333                 break;
1334         default:
1335                 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1336                     line);
1337         }
1338 }
1339 #endif /* INVARIANT_SUPPORT */
1340
1341 #ifdef DDB
1342 void
1343 db_show_rwlock(const struct lock_object *lock)
1344 {
1345         const struct rwlock *rw;
1346         struct thread *td;
1347
1348         rw = (const struct rwlock *)lock;
1349
1350         db_printf(" state: ");
1351         if (rw->rw_lock == RW_UNLOCKED)
1352                 db_printf("UNLOCKED\n");
1353         else if (rw->rw_lock == RW_DESTROYED) {
1354                 db_printf("DESTROYED\n");
1355                 return;
1356         } else if (rw->rw_lock & RW_LOCK_READ)
1357                 db_printf("RLOCK: %ju locks\n",
1358                     (uintmax_t)(RW_READERS(rw->rw_lock)));
1359         else {
1360                 td = rw_wowner(rw);
1361                 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1362                     td->td_tid, td->td_proc->p_pid, td->td_name);
1363                 if (rw_recursed(rw))
1364                         db_printf(" recursed: %u\n", rw->rw_recurse);
1365         }
1366         db_printf(" waiters: ");
1367         switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1368         case RW_LOCK_READ_WAITERS:
1369                 db_printf("readers\n");
1370                 break;
1371         case RW_LOCK_WRITE_WAITERS:
1372                 db_printf("writers\n");
1373                 break;
1374         case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1375                 db_printf("readers and writers\n");
1376                 break;
1377         default:
1378                 db_printf("none\n");
1379                 break;
1380         }
1381 }
1382
1383 #endif