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