]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_rwlock.c
Add missed mergeinfo.
[FreeBSD/stable/8.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  * 3. Neither the name of the author nor the names of any co-contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * Machine independent bits of reader/writer lock implementation.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_ddb.h"
38 #include "opt_kdtrace.h"
39 #include "opt_no_adaptive_rwlocks.h"
40
41 #include <sys/param.h>
42 #include <sys/ktr.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/proc.h>
47 #include <sys/rwlock.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 ADAPTIVE_RWLOCKS
59 #define ROWNER_RETRIES  10
60 #define ROWNER_LOOPS    10000
61 #endif
62
63 #ifdef DDB
64 #include <ddb/ddb.h>
65
66 static void     db_show_rwlock(struct lock_object *lock);
67 #endif
68 static void     assert_rw(struct lock_object *lock, int what);
69 static void     lock_rw(struct lock_object *lock, int how);
70 #ifdef KDTRACE_HOOKS
71 static int      owner_rw(struct lock_object *lock, struct thread **owner);
72 #endif
73 static int      unlock_rw(struct lock_object *lock);
74
75 struct lock_class lock_class_rw = {
76         .lc_name = "rw",
77         .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
78         .lc_assert = assert_rw,
79 #ifdef DDB
80         .lc_ddb_show = db_show_rwlock,
81 #endif
82         .lc_lock = lock_rw,
83         .lc_unlock = unlock_rw,
84 #ifdef KDTRACE_HOOKS
85         .lc_owner = owner_rw,
86 #endif
87 };
88
89 /*
90  * Return a pointer to the owning thread if the lock is write-locked or
91  * NULL if the lock is unlocked or read-locked.
92  */
93 #define rw_wowner(rw)                                                   \
94         ((rw)->rw_lock & RW_LOCK_READ ? NULL :                          \
95             (struct thread *)RW_OWNER((rw)->rw_lock))
96
97 /*
98  * Returns if a write owner is recursed.  Write ownership is not assured
99  * here and should be previously checked.
100  */
101 #define rw_recursed(rw)         ((rw)->rw_recurse != 0)
102
103 /*
104  * Return true if curthread helds the lock.
105  */
106 #define rw_wlocked(rw)          (rw_wowner((rw)) == curthread)
107
108 /*
109  * Return a pointer to the owning thread for this lock who should receive
110  * any priority lent by threads that block on this lock.  Currently this
111  * is identical to rw_wowner().
112  */
113 #define rw_owner(rw)            rw_wowner(rw)
114
115 #ifndef INVARIANTS
116 #define _rw_assert(rw, what, file, line)
117 #endif
118
119 void
120 assert_rw(struct lock_object *lock, int what)
121 {
122
123         rw_assert((struct rwlock *)lock, what);
124 }
125
126 void
127 lock_rw(struct lock_object *lock, int how)
128 {
129         struct rwlock *rw;
130
131         rw = (struct rwlock *)lock;
132         if (how)
133                 rw_wlock(rw);
134         else
135                 rw_rlock(rw);
136 }
137
138 int
139 unlock_rw(struct lock_object *lock)
140 {
141         struct rwlock *rw;
142
143         rw = (struct rwlock *)lock;
144         rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
145         if (rw->rw_lock & RW_LOCK_READ) {
146                 rw_runlock(rw);
147                 return (0);
148         } else {
149                 rw_wunlock(rw);
150                 return (1);
151         }
152 }
153
154 #ifdef KDTRACE_HOOKS
155 int
156 owner_rw(struct lock_object *lock, struct thread **owner)
157 {
158         struct rwlock *rw = (struct rwlock *)lock;
159         uintptr_t x = rw->rw_lock;
160
161         *owner = rw_wowner(rw);
162         return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
163             (*owner != NULL));
164 }
165 #endif
166
167 void
168 rw_init_flags(struct rwlock *rw, const char *name, int opts)
169 {
170         int flags;
171
172         MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
173             RW_RECURSE)) == 0);
174         ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
175             ("%s: rw_lock not aligned for %s: %p", __func__, name,
176             &rw->rw_lock));
177
178         flags = LO_UPGRADABLE;
179         if (opts & RW_DUPOK)
180                 flags |= LO_DUPOK;
181         if (opts & RW_NOPROFILE)
182                 flags |= LO_NOPROFILE;
183         if (!(opts & RW_NOWITNESS))
184                 flags |= LO_WITNESS;
185         if (opts & RW_RECURSE)
186                 flags |= LO_RECURSABLE;
187         if (opts & RW_QUIET)
188                 flags |= LO_QUIET;
189
190         rw->rw_lock = RW_UNLOCKED;
191         rw->rw_recurse = 0;
192         lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
193 }
194
195 void
196 rw_destroy(struct rwlock *rw)
197 {
198
199         KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
200         KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
201         rw->rw_lock = RW_DESTROYED;
202         lock_destroy(&rw->lock_object);
203 }
204
205 void
206 rw_sysinit(void *arg)
207 {
208         struct rw_args *args = arg;
209
210         rw_init(args->ra_rw, args->ra_desc);
211 }
212
213 void
214 rw_sysinit_flags(void *arg)
215 {
216         struct rw_args_flags *args = arg;
217
218         rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
219 }
220
221 int
222 rw_wowned(struct rwlock *rw)
223 {
224
225         return (rw_wowner(rw) == curthread);
226 }
227
228 void
229 _rw_wlock(struct rwlock *rw, const char *file, int line)
230 {
231
232         if (SCHEDULER_STOPPED())
233                 return;
234         MPASS(curthread != NULL);
235         KASSERT(rw->rw_lock != RW_DESTROYED,
236             ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
237         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
238             line, NULL);
239         __rw_wlock(rw, curthread, file, line);
240         LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
241         WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
242         curthread->td_locks++;
243 }
244
245 int
246 _rw_try_wlock(struct rwlock *rw, const char *file, int line)
247 {
248         int rval;
249
250         if (SCHEDULER_STOPPED())
251                 return (1);
252
253         KASSERT(rw->rw_lock != RW_DESTROYED,
254             ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
255
256         if (rw_wlocked(rw) &&
257             (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
258                 rw->rw_recurse++;
259                 rval = 1;
260         } else
261                 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
262                     (uintptr_t)curthread);
263
264         LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
265         if (rval) {
266                 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
267                     file, line);
268                 curthread->td_locks++;
269         }
270         return (rval);
271 }
272
273 void
274 _rw_wunlock(struct rwlock *rw, const char *file, int line)
275 {
276
277         if (SCHEDULER_STOPPED())
278                 return;
279         MPASS(curthread != NULL);
280         KASSERT(rw->rw_lock != RW_DESTROYED,
281             ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
282         _rw_assert(rw, RA_WLOCKED, file, line);
283         curthread->td_locks--;
284         WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
285         LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
286             line);
287         if (!rw_recursed(rw))
288                 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
289         __rw_wunlock(rw, curthread, file, line);
290 }
291 /*
292  * Determines whether a new reader can acquire a lock.  Succeeds if the
293  * reader already owns a read lock and the lock is locked for read to
294  * prevent deadlock from reader recursion.  Also succeeds if the lock
295  * is unlocked and has no writer waiters or spinners.  Failing otherwise
296  * prioritizes writers before readers.
297  */
298 #define RW_CAN_READ(_rw)                                                \
299     ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &      \
300     (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==  \
301     RW_LOCK_READ)
302
303 void
304 _rw_rlock(struct rwlock *rw, const char *file, int line)
305 {
306         struct turnstile *ts;
307 #ifdef ADAPTIVE_RWLOCKS
308         volatile struct thread *owner;
309         int spintries = 0;
310         int i;
311 #endif
312 #ifdef LOCK_PROFILING
313         uint64_t waittime = 0;
314         int contested = 0;
315 #endif
316         uintptr_t v;
317 #ifdef KDTRACE_HOOKS
318         uint64_t spin_cnt = 0;
319         uint64_t sleep_cnt = 0;
320         int64_t sleep_time = 0;
321 #endif
322
323         if (SCHEDULER_STOPPED())
324                 return;
325
326         KASSERT(rw->rw_lock != RW_DESTROYED,
327             ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
328         KASSERT(rw_wowner(rw) != curthread,
329             ("rw_rlock: wlock already held for %s @ %s:%d",
330             rw->lock_object.lo_name, file, line));
331         WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
332
333         for (;;) {
334 #ifdef KDTRACE_HOOKS
335                 spin_cnt++;
336 #endif
337                 /*
338                  * Handle the easy case.  If no other thread has a write
339                  * lock, then try to bump up the count of read locks.  Note
340                  * that we have to preserve the current state of the
341                  * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
342                  * read lock, then rw_lock must have changed, so restart
343                  * the loop.  Note that this handles the case of a
344                  * completely unlocked rwlock since such a lock is encoded
345                  * as a read lock with no waiters.
346                  */
347                 v = rw->rw_lock;
348                 if (RW_CAN_READ(v)) {
349                         /*
350                          * The RW_LOCK_READ_WAITERS flag should only be set
351                          * if the lock has been unlocked and write waiters
352                          * were present.
353                          */
354                         if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
355                             v + RW_ONE_READER)) {
356                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
357                                         CTR4(KTR_LOCK,
358                                             "%s: %p succeed %p -> %p", __func__,
359                                             rw, (void *)v,
360                                             (void *)(v + RW_ONE_READER));
361                                 break;
362                         }
363                         continue;
364                 }
365                 lock_profile_obtain_lock_failed(&rw->lock_object,
366                     &contested, &waittime);
367
368 #ifdef ADAPTIVE_RWLOCKS
369                 /*
370                  * If the owner is running on another CPU, spin until
371                  * the owner stops running or the state of the lock
372                  * changes.
373                  */
374                 if ((v & RW_LOCK_READ) == 0) {
375                         owner = (struct thread *)RW_OWNER(v);
376                         if (TD_IS_RUNNING(owner)) {
377                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
378                                         CTR3(KTR_LOCK,
379                                             "%s: spinning on %p held by %p",
380                                             __func__, rw, owner);
381                                 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
382                                     owner && TD_IS_RUNNING(owner)) {
383                                         cpu_spinwait();
384 #ifdef KDTRACE_HOOKS
385                                         spin_cnt++;
386 #endif
387                                 }
388                                 continue;
389                         }
390                 } else if (spintries < ROWNER_RETRIES) {
391                         spintries++;
392                         for (i = 0; i < ROWNER_LOOPS; i++) {
393                                 v = rw->rw_lock;
394                                 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
395                                         break;
396                                 cpu_spinwait();
397                         }
398                         if (i != ROWNER_LOOPS)
399                                 continue;
400                 }
401 #endif
402
403                 /*
404                  * Okay, now it's the hard case.  Some other thread already
405                  * has a write lock or there are write waiters present,
406                  * acquire the turnstile lock so we can begin the process
407                  * of blocking.
408                  */
409                 ts = turnstile_trywait(&rw->lock_object);
410
411                 /*
412                  * The lock might have been released while we spun, so
413                  * recheck its state and restart the loop if needed.
414                  */
415                 v = rw->rw_lock;
416                 if (RW_CAN_READ(v)) {
417                         turnstile_cancel(ts);
418                         continue;
419                 }
420
421 #ifdef ADAPTIVE_RWLOCKS
422                 /*
423                  * The current lock owner might have started executing
424                  * on another CPU (or the lock could have changed
425                  * owners) while we were waiting on the turnstile
426                  * chain lock.  If so, drop the turnstile lock and try
427                  * again.
428                  */
429                 if ((v & RW_LOCK_READ) == 0) {
430                         owner = (struct thread *)RW_OWNER(v);
431                         if (TD_IS_RUNNING(owner)) {
432                                 turnstile_cancel(ts);
433                                 continue;
434                         }
435                 }
436 #endif
437
438                 /*
439                  * The lock is held in write mode or it already has waiters.
440                  */
441                 MPASS(!RW_CAN_READ(v));
442
443                 /*
444                  * If the RW_LOCK_READ_WAITERS flag is already set, then
445                  * we can go ahead and block.  If it is not set then try
446                  * to set it.  If we fail to set it drop the turnstile
447                  * lock and restart the loop.
448                  */
449                 if (!(v & RW_LOCK_READ_WAITERS)) {
450                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
451                             v | RW_LOCK_READ_WAITERS)) {
452                                 turnstile_cancel(ts);
453                                 continue;
454                         }
455                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
456                                 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
457                                     __func__, rw);
458                 }
459
460                 /*
461                  * We were unable to acquire the lock and the read waiters
462                  * flag is set, so we must block on the turnstile.
463                  */
464                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
465                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
466                             rw);
467 #ifdef KDTRACE_HOOKS
468                 sleep_time -= lockstat_nsecs();
469 #endif
470                 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
471 #ifdef KDTRACE_HOOKS
472                 sleep_time += lockstat_nsecs();
473                 sleep_cnt++;
474 #endif
475                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
476                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
477                             __func__, rw);
478         }
479
480         /*
481          * TODO: acquire "owner of record" here.  Here be turnstile dragons
482          * however.  turnstiles don't like owners changing between calls to
483          * turnstile_wait() currently.
484          */
485         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
486             waittime, file, line);
487         LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
488         WITNESS_LOCK(&rw->lock_object, 0, file, line);
489         curthread->td_locks++;
490         curthread->td_rw_rlocks++;
491 #ifdef KDTRACE_HOOKS
492         if (sleep_time)
493                 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
494
495         /*
496          * Record only the loops spinning and not sleeping. 
497          */
498         if (spin_cnt > sleep_cnt)
499                 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
500 #endif
501 }
502
503 int
504 _rw_try_rlock(struct rwlock *rw, const char *file, int line)
505 {
506         uintptr_t x;
507
508         if (SCHEDULER_STOPPED())
509                 return (1);
510
511         for (;;) {
512                 x = rw->rw_lock;
513                 KASSERT(rw->rw_lock != RW_DESTROYED,
514                     ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
515                 if (!(x & RW_LOCK_READ))
516                         break;
517                 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
518                         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
519                             line);
520                         WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
521                         curthread->td_locks++;
522                         curthread->td_rw_rlocks++;
523                         return (1);
524                 }
525         }
526
527         LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
528         return (0);
529 }
530
531 void
532 _rw_runlock(struct rwlock *rw, const char *file, int line)
533 {
534         struct turnstile *ts;
535         uintptr_t x, v, queue;
536
537         if (SCHEDULER_STOPPED())
538                 return;
539
540         KASSERT(rw->rw_lock != RW_DESTROYED,
541             ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
542         _rw_assert(rw, RA_RLOCKED, file, line);
543         curthread->td_locks--;
544         curthread->td_rw_rlocks--;
545         WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
546         LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
547
548         /* TODO: drop "owner of record" here. */
549
550         for (;;) {
551                 /*
552                  * See if there is more than one read lock held.  If so,
553                  * just drop one and return.
554                  */
555                 x = rw->rw_lock;
556                 if (RW_READERS(x) > 1) {
557                         if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
558                             x - RW_ONE_READER)) {
559                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
560                                         CTR4(KTR_LOCK,
561                                             "%s: %p succeeded %p -> %p",
562                                             __func__, rw, (void *)x,
563                                             (void *)(x - RW_ONE_READER));
564                                 break;
565                         }
566                         continue;
567                 }
568                 /*
569                  * If there aren't any waiters for a write lock, then try
570                  * to drop it quickly.
571                  */
572                 if (!(x & RW_LOCK_WAITERS)) {
573                         MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
574                             RW_READERS_LOCK(1));
575                         if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
576                             RW_UNLOCKED)) {
577                                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
578                                         CTR2(KTR_LOCK, "%s: %p last succeeded",
579                                             __func__, rw);
580                                 break;
581                         }
582                         continue;
583                 }
584                 /*
585                  * Ok, we know we have waiters and we think we are the
586                  * last reader, so grab the turnstile lock.
587                  */
588                 turnstile_chain_lock(&rw->lock_object);
589                 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
590                 MPASS(v & RW_LOCK_WAITERS);
591
592                 /*
593                  * Try to drop our lock leaving the lock in a unlocked
594                  * state.
595                  *
596                  * If you wanted to do explicit lock handoff you'd have to
597                  * do it here.  You'd also want to use turnstile_signal()
598                  * and you'd have to handle the race where a higher
599                  * priority thread blocks on the write lock before the
600                  * thread you wakeup actually runs and have the new thread
601                  * "steal" the lock.  For now it's a lot simpler to just
602                  * wakeup all of the waiters.
603                  *
604                  * As above, if we fail, then another thread might have
605                  * acquired a read lock, so drop the turnstile lock and
606                  * restart.
607                  */
608                 x = RW_UNLOCKED;
609                 if (v & RW_LOCK_WRITE_WAITERS) {
610                         queue = TS_EXCLUSIVE_QUEUE;
611                         x |= (v & RW_LOCK_READ_WAITERS);
612                 } else
613                         queue = TS_SHARED_QUEUE;
614                 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
615                     x)) {
616                         turnstile_chain_unlock(&rw->lock_object);
617                         continue;
618                 }
619                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
620                         CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
621                             __func__, rw);
622
623                 /*
624                  * Ok.  The lock is released and all that's left is to
625                  * wake up the waiters.  Note that the lock might not be
626                  * free anymore, but in that case the writers will just
627                  * block again if they run before the new lock holder(s)
628                  * release the lock.
629                  */
630                 ts = turnstile_lookup(&rw->lock_object);
631                 MPASS(ts != NULL);
632                 turnstile_broadcast(ts, queue);
633                 turnstile_unpend(ts, TS_SHARED_LOCK);
634                 turnstile_chain_unlock(&rw->lock_object);
635                 break;
636         }
637         LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
638 }
639
640 /*
641  * This function is called when we are unable to obtain a write lock on the
642  * first try.  This means that at least one other thread holds either a
643  * read or write lock.
644  */
645 void
646 _rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
647 {
648         struct turnstile *ts;
649 #ifdef ADAPTIVE_RWLOCKS
650         volatile struct thread *owner;
651         int spintries = 0;
652         int i;
653 #endif
654         uintptr_t v, x;
655 #ifdef LOCK_PROFILING
656         uint64_t waittime = 0;
657         int contested = 0;
658 #endif
659 #ifdef KDTRACE_HOOKS
660         uint64_t spin_cnt = 0;
661         uint64_t sleep_cnt = 0;
662         int64_t sleep_time = 0;
663 #endif
664
665         if (SCHEDULER_STOPPED())
666                 return;
667
668         if (rw_wlocked(rw)) {
669                 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
670                     ("%s: recursing but non-recursive rw %s @ %s:%d\n",
671                     __func__, rw->lock_object.lo_name, file, line));
672                 rw->rw_recurse++;
673                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
674                         CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
675                 return;
676         }
677
678         if (LOCK_LOG_TEST(&rw->lock_object, 0))
679                 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
680                     rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
681
682         while (!_rw_write_lock(rw, tid)) {
683 #ifdef KDTRACE_HOOKS
684                 spin_cnt++;
685 #endif
686                 lock_profile_obtain_lock_failed(&rw->lock_object,
687                     &contested, &waittime);
688 #ifdef ADAPTIVE_RWLOCKS
689                 /*
690                  * If the lock is write locked and the owner is
691                  * running on another CPU, spin until the owner stops
692                  * running or the state of the lock changes.
693                  */
694                 v = rw->rw_lock;
695                 owner = (struct thread *)RW_OWNER(v);
696                 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
697                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
698                                 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
699                                     __func__, rw, owner);
700                         while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
701                             TD_IS_RUNNING(owner)) {
702                                 cpu_spinwait();
703 #ifdef KDTRACE_HOOKS
704                                 spin_cnt++;
705 #endif
706                         }
707                         continue;
708                 }
709                 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
710                     spintries < ROWNER_RETRIES) {
711                         if (!(v & RW_LOCK_WRITE_SPINNER)) {
712                                 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
713                                     v | RW_LOCK_WRITE_SPINNER)) {
714                                         continue;
715                                 }
716                         }
717                         spintries++;
718                         for (i = 0; i < ROWNER_LOOPS; i++) {
719                                 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
720                                         break;
721                                 cpu_spinwait();
722                         }
723 #ifdef KDTRACE_HOOKS
724                         spin_cnt += ROWNER_LOOPS - i;
725 #endif
726                         if (i != ROWNER_LOOPS)
727                                 continue;
728                 }
729 #endif
730                 ts = turnstile_trywait(&rw->lock_object);
731                 v = rw->rw_lock;
732
733 #ifdef ADAPTIVE_RWLOCKS
734                 /*
735                  * The current lock owner might have started executing
736                  * on another CPU (or the lock could have changed
737                  * owners) while we were waiting on the turnstile
738                  * chain lock.  If so, drop the turnstile lock and try
739                  * again.
740                  */
741                 if (!(v & RW_LOCK_READ)) {
742                         owner = (struct thread *)RW_OWNER(v);
743                         if (TD_IS_RUNNING(owner)) {
744                                 turnstile_cancel(ts);
745                                 continue;
746                         }
747                 }
748 #endif
749                 /*
750                  * Check for the waiters flags about this rwlock.
751                  * If the lock was released, without maintain any pending
752                  * waiters queue, simply try to acquire it.
753                  * If a pending waiters queue is present, claim the lock
754                  * ownership and maintain the pending queue.
755                  */
756                 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
757                 if ((v & ~x) == RW_UNLOCKED) {
758                         x &= ~RW_LOCK_WRITE_SPINNER;
759                         if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
760                                 if (x)
761                                         turnstile_claim(ts);
762                                 else
763                                         turnstile_cancel(ts);
764                                 break;
765                         }
766                         turnstile_cancel(ts);
767                         continue;
768                 }
769                 /*
770                  * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
771                  * set it.  If we fail to set it, then loop back and try
772                  * again.
773                  */
774                 if (!(v & RW_LOCK_WRITE_WAITERS)) {
775                         if (!atomic_cmpset_ptr(&rw->rw_lock, v,
776                             v | RW_LOCK_WRITE_WAITERS)) {
777                                 turnstile_cancel(ts);
778                                 continue;
779                         }
780                         if (LOCK_LOG_TEST(&rw->lock_object, 0))
781                                 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
782                                     __func__, rw);
783                 }
784                 /*
785                  * We were unable to acquire the lock and the write waiters
786                  * flag is set, so we must block on the turnstile.
787                  */
788                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
789                         CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
790                             rw);
791 #ifdef KDTRACE_HOOKS
792                 sleep_time -= lockstat_nsecs();
793 #endif
794                 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
795 #ifdef KDTRACE_HOOKS
796                 sleep_time += lockstat_nsecs();
797                 sleep_cnt++;
798 #endif
799                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
800                         CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
801                             __func__, rw);
802 #ifdef ADAPTIVE_RWLOCKS
803                 spintries = 0;
804 #endif
805         }
806         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
807             waittime, file, line);
808 #ifdef KDTRACE_HOOKS
809         if (sleep_time)
810                 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
811
812         /*
813          * Record only the loops spinning and not sleeping.
814          */ 
815         if (spin_cnt > sleep_cnt)
816                 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
817 #endif
818 }
819
820 /*
821  * This function is called if the first try at releasing a write lock failed.
822  * This means that one of the 2 waiter bits must be set indicating that at
823  * least one thread is waiting on this lock.
824  */
825 void
826 _rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
827 {
828         struct turnstile *ts;
829         uintptr_t v;
830         int queue;
831
832         if (SCHEDULER_STOPPED())
833                 return;
834
835         if (rw_wlocked(rw) && rw_recursed(rw)) {
836                 rw->rw_recurse--;
837                 if (LOCK_LOG_TEST(&rw->lock_object, 0))
838                         CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
839                 return;
840         }
841
842         KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
843             ("%s: neither of the waiter flags are set", __func__));
844
845         if (LOCK_LOG_TEST(&rw->lock_object, 0))
846                 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
847
848         turnstile_chain_lock(&rw->lock_object);
849         ts = turnstile_lookup(&rw->lock_object);
850         MPASS(ts != NULL);
851
852         /*
853          * Use the same algo as sx locks for now.  Prefer waking up shared
854          * waiters if we have any over writers.  This is probably not ideal.
855          *
856          * 'v' is the value we are going to write back to rw_lock.  If we
857          * have waiters on both queues, we need to preserve the state of
858          * the waiter flag for the queue we don't wake up.  For now this is
859          * hardcoded for the algorithm mentioned above.
860          *
861          * In the case of both readers and writers waiting we wakeup the
862          * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
863          * new writer comes in before a reader it will claim the lock up
864          * above.  There is probably a potential priority inversion in
865          * there that could be worked around either by waking both queues
866          * of waiters or doing some complicated lock handoff gymnastics.
867          */
868         v = RW_UNLOCKED;
869         if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
870                 queue = TS_EXCLUSIVE_QUEUE;
871                 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
872         } else
873                 queue = TS_SHARED_QUEUE;
874
875         /* Wake up all waiters for the specific queue. */
876         if (LOCK_LOG_TEST(&rw->lock_object, 0))
877                 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
878                     queue == TS_SHARED_QUEUE ? "read" : "write");
879         turnstile_broadcast(ts, queue);
880         atomic_store_rel_ptr(&rw->rw_lock, v);
881         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
882         turnstile_chain_unlock(&rw->lock_object);
883 }
884
885 /*
886  * Attempt to do a non-blocking upgrade from a read lock to a write
887  * lock.  This will only succeed if this thread holds a single read
888  * lock.  Returns true if the upgrade succeeded and false otherwise.
889  */
890 int
891 _rw_try_upgrade(struct rwlock *rw, const char *file, int line)
892 {
893         uintptr_t v, x, tid;
894         struct turnstile *ts;
895         int success;
896
897         if (SCHEDULER_STOPPED())
898                 return (1);
899
900         KASSERT(rw->rw_lock != RW_DESTROYED,
901             ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
902         _rw_assert(rw, RA_RLOCKED, file, line);
903
904         /*
905          * Attempt to switch from one reader to a writer.  If there
906          * are any write waiters, then we will have to lock the
907          * turnstile first to prevent races with another writer
908          * calling turnstile_wait() before we have claimed this
909          * turnstile.  So, do the simple case of no waiters first.
910          */
911         tid = (uintptr_t)curthread;
912         success = 0;
913         for (;;) {
914                 v = rw->rw_lock;
915                 if (RW_READERS(v) > 1)
916                         break;
917                 if (!(v & RW_LOCK_WAITERS)) {
918                         success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
919                         if (!success)
920                                 continue;
921                         break;
922                 }
923
924                 /*
925                  * Ok, we think we have waiters, so lock the turnstile.
926                  */
927                 ts = turnstile_trywait(&rw->lock_object);
928                 v = rw->rw_lock;
929                 if (RW_READERS(v) > 1) {
930                         turnstile_cancel(ts);
931                         break;
932                 }
933                 /*
934                  * Try to switch from one reader to a writer again.  This time
935                  * we honor the current state of the waiters flags.
936                  * If we obtain the lock with the flags set, then claim
937                  * ownership of the turnstile.
938                  */
939                 x = rw->rw_lock & RW_LOCK_WAITERS;
940                 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
941                 if (success) {
942                         if (x)
943                                 turnstile_claim(ts);
944                         else
945                                 turnstile_cancel(ts);
946                         break;
947                 }
948                 turnstile_cancel(ts);
949         }
950         LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
951         if (success) {
952                 curthread->td_rw_rlocks--;
953                 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
954                     file, line);
955                 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
956         }
957         return (success);
958 }
959
960 /*
961  * Downgrade a write lock into a single read lock.
962  */
963 void
964 _rw_downgrade(struct rwlock *rw, const char *file, int line)
965 {
966         struct turnstile *ts;
967         uintptr_t tid, v;
968         int rwait, wwait;
969
970         if (SCHEDULER_STOPPED())
971                 return;
972
973         KASSERT(rw->rw_lock != RW_DESTROYED,
974             ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
975         _rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
976 #ifndef INVARIANTS
977         if (rw_recursed(rw))
978                 panic("downgrade of a recursed lock");
979 #endif
980
981         WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
982
983         /*
984          * Convert from a writer to a single reader.  First we handle
985          * the easy case with no waiters.  If there are any waiters, we
986          * lock the turnstile and "disown" the lock.
987          */
988         tid = (uintptr_t)curthread;
989         if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
990                 goto out;
991
992         /*
993          * Ok, we think we have waiters, so lock the turnstile so we can
994          * read the waiter flags without any races.
995          */
996         turnstile_chain_lock(&rw->lock_object);
997         v = rw->rw_lock & RW_LOCK_WAITERS;
998         rwait = v & RW_LOCK_READ_WAITERS;
999         wwait = v & RW_LOCK_WRITE_WAITERS;
1000         MPASS(rwait | wwait);
1001
1002         /*
1003          * Downgrade from a write lock while preserving waiters flag
1004          * and give up ownership of the turnstile.
1005          */
1006         ts = turnstile_lookup(&rw->lock_object);
1007         MPASS(ts != NULL);
1008         if (!wwait)
1009                 v &= ~RW_LOCK_READ_WAITERS;
1010         atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1011         /*
1012          * Wake other readers if there are no writers pending.  Otherwise they
1013          * won't be able to acquire the lock anyway.
1014          */
1015         if (rwait && !wwait) {
1016                 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1017                 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1018         } else
1019                 turnstile_disown(ts);
1020         turnstile_chain_unlock(&rw->lock_object);
1021 out:
1022         curthread->td_rw_rlocks++;
1023         LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1024         LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1025 }
1026
1027 #ifdef INVARIANT_SUPPORT
1028 #ifndef INVARIANTS
1029 #undef _rw_assert
1030 #endif
1031
1032 /*
1033  * In the non-WITNESS case, rw_assert() can only detect that at least
1034  * *some* thread owns an rlock, but it cannot guarantee that *this*
1035  * thread owns an rlock.
1036  */
1037 void
1038 _rw_assert(struct rwlock *rw, int what, const char *file, int line)
1039 {
1040
1041         if (panicstr != NULL)
1042                 return;
1043         switch (what) {
1044         case RA_LOCKED:
1045         case RA_LOCKED | RA_RECURSED:
1046         case RA_LOCKED | RA_NOTRECURSED:
1047         case RA_RLOCKED:
1048         case RA_RLOCKED | RA_RECURSED:
1049         case RA_RLOCKED | RA_NOTRECURSED:
1050 #ifdef WITNESS
1051                 witness_assert(&rw->lock_object, what, file, line);
1052 #else
1053                 /*
1054                  * If some other thread has a write lock or we have one
1055                  * and are asserting a read lock, fail.  Also, if no one
1056                  * has a lock at all, fail.
1057                  */
1058                 if (rw->rw_lock == RW_UNLOCKED ||
1059                     (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1060                     rw_wowner(rw) != curthread)))
1061                         panic("Lock %s not %slocked @ %s:%d\n",
1062                             rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1063                             "read " : "", file, line);
1064
1065                 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1066                         if (rw_recursed(rw)) {
1067                                 if (what & RA_NOTRECURSED)
1068                                         panic("Lock %s recursed @ %s:%d\n",
1069                                             rw->lock_object.lo_name, file,
1070                                             line);
1071                         } else if (what & RA_RECURSED)
1072                                 panic("Lock %s not recursed @ %s:%d\n",
1073                                     rw->lock_object.lo_name, file, line);
1074                 }
1075 #endif
1076                 break;
1077         case RA_WLOCKED:
1078         case RA_WLOCKED | RA_RECURSED:
1079         case RA_WLOCKED | RA_NOTRECURSED:
1080                 if (rw_wowner(rw) != curthread)
1081                         panic("Lock %s not exclusively locked @ %s:%d\n",
1082                             rw->lock_object.lo_name, file, line);
1083                 if (rw_recursed(rw)) {
1084                         if (what & RA_NOTRECURSED)
1085                                 panic("Lock %s recursed @ %s:%d\n",
1086                                     rw->lock_object.lo_name, file, line);
1087                 } else if (what & RA_RECURSED)
1088                         panic("Lock %s not recursed @ %s:%d\n",
1089                             rw->lock_object.lo_name, file, line);
1090                 break;
1091         case RA_UNLOCKED:
1092 #ifdef WITNESS
1093                 witness_assert(&rw->lock_object, what, file, line);
1094 #else
1095                 /*
1096                  * If we hold a write lock fail.  We can't reliably check
1097                  * to see if we hold a read lock or not.
1098                  */
1099                 if (rw_wowner(rw) == curthread)
1100                         panic("Lock %s exclusively locked @ %s:%d\n",
1101                             rw->lock_object.lo_name, file, line);
1102 #endif
1103                 break;
1104         default:
1105                 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1106                     line);
1107         }
1108 }
1109 #endif /* INVARIANT_SUPPORT */
1110
1111 #ifdef DDB
1112 void
1113 db_show_rwlock(struct lock_object *lock)
1114 {
1115         struct rwlock *rw;
1116         struct thread *td;
1117
1118         rw = (struct rwlock *)lock;
1119
1120         db_printf(" state: ");
1121         if (rw->rw_lock == RW_UNLOCKED)
1122                 db_printf("UNLOCKED\n");
1123         else if (rw->rw_lock == RW_DESTROYED) {
1124                 db_printf("DESTROYED\n");
1125                 return;
1126         } else if (rw->rw_lock & RW_LOCK_READ)
1127                 db_printf("RLOCK: %ju locks\n",
1128                     (uintmax_t)(RW_READERS(rw->rw_lock)));
1129         else {
1130                 td = rw_wowner(rw);
1131                 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1132                     td->td_tid, td->td_proc->p_pid, td->td_name);
1133                 if (rw_recursed(rw))
1134                         db_printf(" recursed: %u\n", rw->rw_recurse);
1135         }
1136         db_printf(" waiters: ");
1137         switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1138         case RW_LOCK_READ_WAITERS:
1139                 db_printf("readers\n");
1140                 break;
1141         case RW_LOCK_WRITE_WAITERS:
1142                 db_printf("writers\n");
1143                 break;
1144         case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1145                 db_printf("readers and writers\n");
1146                 break;
1147         default:
1148                 db_printf("none\n");
1149                 break;
1150         }
1151 }
1152
1153 #endif