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