2 * Copyright (c) 2007 Stephan Uphoff <ups@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
31 * Machine independent bits of reader/writer lock implementation.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 #include "opt_kdtrace.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
43 #include <sys/kernel.h>
47 #include <sys/mutex.h>
49 #include <sys/rmlock.h>
50 #include <sys/sched.h>
52 #include <sys/turnstile.h>
53 #include <sys/lock_profile.h>
54 #include <machine/cpu.h>
61 * A cookie to mark destroyed rmlocks. This is stored in the head of
64 #define RM_DESTROYED ((void *)0xdead)
66 #define rm_destroyed(rm) \
67 (LIST_FIRST(&(rm)->rm_activeReaders) == RM_DESTROYED)
69 #define RMPF_ONQUEUE 1
73 #define _rm_assert(c, what, file, line)
76 static void assert_rm(const struct lock_object *lock, int what);
78 static void db_show_rm(const struct lock_object *lock);
80 static void lock_rm(struct lock_object *lock, uintptr_t how);
82 static int owner_rm(const struct lock_object *lock, struct thread **owner);
84 static uintptr_t unlock_rm(struct lock_object *lock);
86 struct lock_class lock_class_rm = {
88 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
89 .lc_assert = assert_rm,
91 .lc_ddb_show = db_show_rm,
94 .lc_unlock = unlock_rm,
100 struct lock_class lock_class_rm_sleepable = {
101 .lc_name = "sleepable rm",
102 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE,
103 .lc_assert = assert_rm,
105 .lc_ddb_show = db_show_rm,
108 .lc_unlock = unlock_rm,
110 .lc_owner = owner_rm,
115 assert_rm(const struct lock_object *lock, int what)
118 rm_assert((const struct rmlock *)lock, what);
122 lock_rm(struct lock_object *lock, uintptr_t how)
125 struct rm_priotracker *tracker;
127 rm = (struct rmlock *)lock;
131 tracker = (struct rm_priotracker *)how;
132 rm_rlock(rm, tracker);
137 unlock_rm(struct lock_object *lock)
142 struct rm_queue *queue;
143 struct rm_priotracker *tracker;
146 rm = (struct rmlock *)lock;
149 rm_assert(rm, RA_LOCKED | RA_NOTRECURSED);
154 * Find the right rm_priotracker structure for curthread.
155 * The guarantee about its uniqueness is given by the fact
156 * we already asserted the lock wasn't recursively acquired.
160 pc = pcpu_find(curcpu);
161 for (queue = pc->pc_rm_queue.rmq_next;
162 queue != &pc->pc_rm_queue; queue = queue->rmq_next) {
163 tracker = (struct rm_priotracker *)queue;
164 if ((tracker->rmp_rmlock == rm) &&
165 (tracker->rmp_thread == td)) {
166 how = (uintptr_t)tracker;
170 KASSERT(tracker != NULL,
171 ("rm_priotracker is non-NULL when lock held in read mode"));
173 rm_runlock(rm, tracker);
180 owner_rm(const struct lock_object *lock, struct thread **owner)
182 const struct rmlock *rm;
183 struct lock_class *lc;
185 rm = (const struct rmlock *)lock;
186 lc = LOCK_CLASS(&rm->rm_wlock_object);
187 return (lc->lc_owner(&rm->rm_wlock_object, owner));
191 static struct mtx rm_spinlock;
193 MTX_SYSINIT(rm_spinlock, &rm_spinlock, "rm_spinlock", MTX_SPIN);
196 * Add or remove tracker from per-cpu list.
198 * The per-cpu list can be traversed at any time in forward direction from an
199 * interrupt on the *local* cpu.
202 rm_tracker_add(struct pcpu *pc, struct rm_priotracker *tracker)
204 struct rm_queue *next;
206 /* Initialize all tracker pointers */
207 tracker->rmp_cpuQueue.rmq_prev = &pc->pc_rm_queue;
208 next = pc->pc_rm_queue.rmq_next;
209 tracker->rmp_cpuQueue.rmq_next = next;
211 /* rmq_prev is not used during froward traversal. */
212 next->rmq_prev = &tracker->rmp_cpuQueue;
214 /* Update pointer to first element. */
215 pc->pc_rm_queue.rmq_next = &tracker->rmp_cpuQueue;
219 * Return a count of the number of trackers the thread 'td' already
220 * has on this CPU for the lock 'rm'.
223 rm_trackers_present(const struct pcpu *pc, const struct rmlock *rm,
224 const struct thread *td)
226 struct rm_queue *queue;
227 struct rm_priotracker *tracker;
231 for (queue = pc->pc_rm_queue.rmq_next; queue != &pc->pc_rm_queue;
232 queue = queue->rmq_next) {
233 tracker = (struct rm_priotracker *)queue;
234 if ((tracker->rmp_rmlock == rm) && (tracker->rmp_thread == td))
241 rm_tracker_remove(struct pcpu *pc, struct rm_priotracker *tracker)
243 struct rm_queue *next, *prev;
245 next = tracker->rmp_cpuQueue.rmq_next;
246 prev = tracker->rmp_cpuQueue.rmq_prev;
248 /* Not used during forward traversal. */
249 next->rmq_prev = prev;
251 /* Remove from list. */
252 prev->rmq_next = next;
256 rm_cleanIPI(void *arg)
259 struct rmlock *rm = arg;
260 struct rm_priotracker *tracker;
261 struct rm_queue *queue;
262 pc = pcpu_find(curcpu);
264 for (queue = pc->pc_rm_queue.rmq_next; queue != &pc->pc_rm_queue;
265 queue = queue->rmq_next) {
266 tracker = (struct rm_priotracker *)queue;
267 if (tracker->rmp_rmlock == rm && tracker->rmp_flags == 0) {
268 tracker->rmp_flags = RMPF_ONQUEUE;
269 mtx_lock_spin(&rm_spinlock);
270 LIST_INSERT_HEAD(&rm->rm_activeReaders, tracker,
272 mtx_unlock_spin(&rm_spinlock);
278 rm_init_flags(struct rmlock *rm, const char *name, int opts)
280 struct lock_class *lc;
284 if (!(opts & RM_NOWITNESS))
285 liflags |= LO_WITNESS;
286 if (opts & RM_RECURSE)
287 liflags |= LO_RECURSABLE;
290 rm->rm_writecpus = all_cpus;
291 LIST_INIT(&rm->rm_activeReaders);
292 if (opts & RM_SLEEPABLE) {
293 liflags |= LO_SLEEPABLE;
294 lc = &lock_class_rm_sleepable;
295 xflags = (opts & RM_NEW ? SX_NEW : 0);
296 sx_init_flags(&rm->rm_lock_sx, "rmlock_sx",
297 xflags | SX_NOWITNESS);
300 xflags = (opts & RM_NEW ? MTX_NEW : 0);
301 mtx_init(&rm->rm_lock_mtx, name, "rmlock_mtx",
302 xflags | MTX_NOWITNESS);
304 lock_init(&rm->lock_object, lc, name, NULL, liflags);
308 rm_init(struct rmlock *rm, const char *name)
311 rm_init_flags(rm, name, 0);
315 rm_destroy(struct rmlock *rm)
318 rm_assert(rm, RA_UNLOCKED);
319 LIST_FIRST(&rm->rm_activeReaders) = RM_DESTROYED;
320 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
321 sx_destroy(&rm->rm_lock_sx);
323 mtx_destroy(&rm->rm_lock_mtx);
324 lock_destroy(&rm->lock_object);
328 rm_wowned(const struct rmlock *rm)
331 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
332 return (sx_xlocked(&rm->rm_lock_sx));
334 return (mtx_owned(&rm->rm_lock_mtx));
338 rm_sysinit(void *arg)
340 struct rm_args *args = arg;
342 rm_init(args->ra_rm, args->ra_desc);
346 rm_sysinit_flags(void *arg)
348 struct rm_args_flags *args = arg;
350 rm_init_flags(args->ra_rm, args->ra_desc, args->ra_opts);
354 _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
359 pc = pcpu_find(curcpu);
361 /* Check if we just need to do a proper critical_exit. */
362 if (!CPU_ISSET(pc->pc_cpuid, &rm->rm_writecpus)) {
367 /* Remove our tracker from the per-cpu list. */
368 rm_tracker_remove(pc, tracker);
370 /* Check to see if the IPI granted us the lock after all. */
371 if (tracker->rmp_flags) {
372 /* Just add back tracker - we hold the lock. */
373 rm_tracker_add(pc, tracker);
379 * We allow readers to acquire a lock even if a writer is blocked if
380 * the lock is recursive and the reader already holds the lock.
382 if ((rm->lock_object.lo_flags & LO_RECURSABLE) != 0) {
384 * Just grant the lock if this thread already has a tracker
385 * for this lock on the per-cpu queue.
387 if (rm_trackers_present(pc, rm, curthread) != 0) {
388 mtx_lock_spin(&rm_spinlock);
389 LIST_INSERT_HEAD(&rm->rm_activeReaders, tracker,
391 tracker->rmp_flags = RMPF_ONQUEUE;
392 mtx_unlock_spin(&rm_spinlock);
393 rm_tracker_add(pc, tracker);
403 if (rm->lock_object.lo_flags & LO_SLEEPABLE) {
404 if (!sx_try_xlock(&rm->rm_lock_sx))
407 if (!mtx_trylock(&rm->rm_lock_mtx))
411 if (rm->lock_object.lo_flags & LO_SLEEPABLE) {
412 THREAD_SLEEPING_OK();
413 sx_xlock(&rm->rm_lock_sx);
414 THREAD_NO_SLEEPING();
416 mtx_lock(&rm->rm_lock_mtx);
420 pc = pcpu_find(curcpu);
421 CPU_CLR(pc->pc_cpuid, &rm->rm_writecpus);
422 rm_tracker_add(pc, tracker);
426 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
427 sx_xunlock(&rm->rm_lock_sx);
429 mtx_unlock(&rm->rm_lock_mtx);
435 _rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
437 struct thread *td = curthread;
440 if (SCHEDULER_STOPPED())
443 tracker->rmp_flags = 0;
444 tracker->rmp_thread = td;
445 tracker->rmp_rmlock = rm;
447 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
448 THREAD_NO_SLEEPING();
450 td->td_critnest++; /* critical_enter(); */
454 pc = cpuid_to_pcpu[td->td_oncpu]; /* pcpu_find(td->td_oncpu); */
456 rm_tracker_add(pc, tracker);
465 * Fast path to combine two common conditions into a single
468 if (0 == (td->td_owepreempt |
469 CPU_ISSET(pc->pc_cpuid, &rm->rm_writecpus)))
472 /* We do not have a read token and need to acquire one. */
473 return _rm_rlock_hard(rm, tracker, trylock);
477 _rm_unlock_hard(struct thread *td,struct rm_priotracker *tracker)
480 if (td->td_owepreempt) {
485 if (!tracker->rmp_flags)
488 mtx_lock_spin(&rm_spinlock);
489 LIST_REMOVE(tracker, rmp_qentry);
491 if (tracker->rmp_flags & RMPF_SIGNAL) {
493 struct turnstile *ts;
495 rm = tracker->rmp_rmlock;
497 turnstile_chain_lock(&rm->lock_object);
498 mtx_unlock_spin(&rm_spinlock);
500 ts = turnstile_lookup(&rm->lock_object);
502 turnstile_signal(ts, TS_EXCLUSIVE_QUEUE);
503 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
504 turnstile_chain_unlock(&rm->lock_object);
506 mtx_unlock_spin(&rm_spinlock);
510 _rm_runlock(struct rmlock *rm, struct rm_priotracker *tracker)
513 struct thread *td = tracker->rmp_thread;
515 if (SCHEDULER_STOPPED())
518 td->td_critnest++; /* critical_enter(); */
519 pc = cpuid_to_pcpu[td->td_oncpu]; /* pcpu_find(td->td_oncpu); */
520 rm_tracker_remove(pc, tracker);
524 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
525 THREAD_SLEEPING_OK();
527 if (0 == (td->td_owepreempt | tracker->rmp_flags))
530 _rm_unlock_hard(td, tracker);
534 _rm_wlock(struct rmlock *rm)
536 struct rm_priotracker *prio;
537 struct turnstile *ts;
540 if (SCHEDULER_STOPPED())
543 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
544 sx_xlock(&rm->rm_lock_sx);
546 mtx_lock(&rm->rm_lock_mtx);
548 if (CPU_CMP(&rm->rm_writecpus, &all_cpus)) {
549 /* Get all read tokens back */
551 CPU_NAND(&readcpus, &rm->rm_writecpus);
552 rm->rm_writecpus = all_cpus;
555 * Assumes rm->rm_writecpus update is visible on other CPUs
556 * before rm_cleanIPI is called.
559 smp_rendezvous_cpus(readcpus,
560 smp_no_rendevous_barrier,
562 smp_no_rendevous_barrier,
569 mtx_lock_spin(&rm_spinlock);
570 while ((prio = LIST_FIRST(&rm->rm_activeReaders)) != NULL) {
571 ts = turnstile_trywait(&rm->lock_object);
572 prio->rmp_flags = RMPF_ONQUEUE | RMPF_SIGNAL;
573 mtx_unlock_spin(&rm_spinlock);
574 turnstile_wait(ts, prio->rmp_thread,
576 mtx_lock_spin(&rm_spinlock);
578 mtx_unlock_spin(&rm_spinlock);
583 _rm_wunlock(struct rmlock *rm)
586 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
587 sx_xunlock(&rm->rm_lock_sx);
589 mtx_unlock(&rm->rm_lock_mtx);
595 _rm_wlock_debug(struct rmlock *rm, const char *file, int line)
598 if (SCHEDULER_STOPPED())
601 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
602 ("rm_wlock() by idle thread %p on rmlock %s @ %s:%d",
603 curthread, rm->lock_object.lo_name, file, line));
604 KASSERT(!rm_destroyed(rm),
605 ("rm_wlock() of destroyed rmlock @ %s:%d", file, line));
606 _rm_assert(rm, RA_UNLOCKED, file, line);
608 WITNESS_CHECKORDER(&rm->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE,
613 LOCK_LOG_LOCK("RMWLOCK", &rm->lock_object, 0, 0, file, line);
615 WITNESS_LOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
617 curthread->td_locks++;
622 _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
625 if (SCHEDULER_STOPPED())
628 KASSERT(!rm_destroyed(rm),
629 ("rm_wunlock() of destroyed rmlock @ %s:%d", file, line));
630 _rm_assert(rm, RA_WLOCKED, file, line);
631 WITNESS_UNLOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
632 LOCK_LOG_LOCK("RMWUNLOCK", &rm->lock_object, 0, 0, file, line);
634 curthread->td_locks--;
638 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
639 int trylock, const char *file, int line)
642 if (SCHEDULER_STOPPED())
646 if (!(rm->lock_object.lo_flags & LO_RECURSABLE) && !trylock) {
648 KASSERT(rm_trackers_present(pcpu_find(curcpu), rm,
650 ("rm_rlock: recursed on non-recursive rmlock %s @ %s:%d\n",
651 rm->lock_object.lo_name, file, line));
655 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
656 ("rm_rlock() by idle thread %p on rmlock %s @ %s:%d",
657 curthread, rm->lock_object.lo_name, file, line));
658 KASSERT(!rm_destroyed(rm),
659 ("rm_rlock() of destroyed rmlock @ %s:%d", file, line));
661 KASSERT(!rm_wowned(rm),
662 ("rm_rlock: wlock already held for %s @ %s:%d",
663 rm->lock_object.lo_name, file, line));
664 WITNESS_CHECKORDER(&rm->lock_object, LOP_NEWORDER, file, line,
668 if (_rm_rlock(rm, tracker, trylock)) {
670 LOCK_LOG_TRY("RMRLOCK", &rm->lock_object, 0, 1, file,
673 LOCK_LOG_LOCK("RMRLOCK", &rm->lock_object, 0, 0, file,
675 WITNESS_LOCK(&rm->lock_object, 0, file, line);
677 curthread->td_locks++;
681 LOCK_LOG_TRY("RMRLOCK", &rm->lock_object, 0, 0, file, line);
687 _rm_runlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
688 const char *file, int line)
691 if (SCHEDULER_STOPPED())
694 KASSERT(!rm_destroyed(rm),
695 ("rm_runlock() of destroyed rmlock @ %s:%d", file, line));
696 _rm_assert(rm, RA_RLOCKED, file, line);
697 WITNESS_UNLOCK(&rm->lock_object, 0, file, line);
698 LOCK_LOG_LOCK("RMRUNLOCK", &rm->lock_object, 0, 0, file, line);
699 _rm_runlock(rm, tracker);
700 curthread->td_locks--;
706 * Just strip out file and line arguments if no lock debugging is enabled in
707 * the kernel - we are called from a kernel module.
710 _rm_wlock_debug(struct rmlock *rm, const char *file, int line)
717 _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
724 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
725 int trylock, const char *file, int line)
728 return _rm_rlock(rm, tracker, trylock);
732 _rm_runlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
733 const char *file, int line)
736 _rm_runlock(rm, tracker);
741 #ifdef INVARIANT_SUPPORT
747 * Note that this does not need to use witness_assert() for read lock
748 * assertions since an exact count of read locks held by this thread
752 _rm_assert(const struct rmlock *rm, int what, const char *file, int line)
756 if (panicstr != NULL)
760 case RA_LOCKED | RA_RECURSED:
761 case RA_LOCKED | RA_NOTRECURSED:
763 case RA_RLOCKED | RA_RECURSED:
764 case RA_RLOCKED | RA_NOTRECURSED:
766 * Handle the write-locked case. Unlike other
767 * primitives, writers can never recurse.
770 if (what & RA_RLOCKED)
771 panic("Lock %s exclusively locked @ %s:%d\n",
772 rm->lock_object.lo_name, file, line);
773 if (what & RA_RECURSED)
774 panic("Lock %s not recursed @ %s:%d\n",
775 rm->lock_object.lo_name, file, line);
780 count = rm_trackers_present(pcpu_find(curcpu), rm, curthread);
784 panic("Lock %s not %slocked @ %s:%d\n",
785 rm->lock_object.lo_name, (what & RA_RLOCKED) ?
786 "read " : "", file, line);
788 if (what & RA_NOTRECURSED)
789 panic("Lock %s recursed @ %s:%d\n",
790 rm->lock_object.lo_name, file, line);
791 } else if (what & RA_RECURSED)
792 panic("Lock %s not recursed @ %s:%d\n",
793 rm->lock_object.lo_name, file, line);
797 panic("Lock %s not exclusively locked @ %s:%d\n",
798 rm->lock_object.lo_name, file, line);
802 panic("Lock %s exclusively locked @ %s:%d\n",
803 rm->lock_object.lo_name, file, line);
806 count = rm_trackers_present(pcpu_find(curcpu), rm, curthread);
810 panic("Lock %s read locked @ %s:%d\n",
811 rm->lock_object.lo_name, file, line);
814 panic("Unknown rm lock assertion: %d @ %s:%d", what, file,
818 #endif /* INVARIANT_SUPPORT */
822 print_tracker(struct rm_priotracker *tr)
827 db_printf(" thread %p (tid %d, pid %d, \"%s\") {", td, td->td_tid,
828 td->td_proc->p_pid, td->td_name);
829 if (tr->rmp_flags & RMPF_ONQUEUE) {
830 db_printf("ONQUEUE");
831 if (tr->rmp_flags & RMPF_SIGNAL)
832 db_printf(",SIGNAL");
839 db_show_rm(const struct lock_object *lock)
841 struct rm_priotracker *tr;
842 struct rm_queue *queue;
843 const struct rmlock *rm;
844 struct lock_class *lc;
847 rm = (const struct rmlock *)lock;
848 db_printf(" writecpus: ");
849 ddb_display_cpuset(__DEQUALIFY(const cpuset_t *, &rm->rm_writecpus));
851 db_printf(" per-CPU readers:\n");
852 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu)
853 for (queue = pc->pc_rm_queue.rmq_next;
854 queue != &pc->pc_rm_queue; queue = queue->rmq_next) {
855 tr = (struct rm_priotracker *)queue;
856 if (tr->rmp_rmlock == rm)
859 db_printf(" active readers:\n");
860 LIST_FOREACH(tr, &rm->rm_activeReaders, rmp_qentry)
862 lc = LOCK_CLASS(&rm->rm_wlock_object);
863 db_printf("Backing write-lock (%s):\n", lc->lc_name);
864 lc->lc_ddb_show(&rm->rm_wlock_object);