2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2007 Stephan Uphoff <ups@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the author nor the names of any co-contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * Machine independent bits of reader/writer lock implementation.
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
41 #include <sys/param.h>
42 #include <sys/systm.h>
44 #include <sys/kernel.h>
48 #include <sys/mutex.h>
50 #include <sys/rmlock.h>
51 #include <sys/sched.h>
53 #include <sys/turnstile.h>
54 #include <sys/lock_profile.h>
55 #include <machine/cpu.h>
62 * A cookie to mark destroyed rmlocks. This is stored in the head of
65 #define RM_DESTROYED ((void *)0xdead)
67 #define rm_destroyed(rm) \
68 (LIST_FIRST(&(rm)->rm_activeReaders) == RM_DESTROYED)
70 #define RMPF_ONQUEUE 1
74 #define _rm_assert(c, what, file, line)
77 static void assert_rm(const struct lock_object *lock, int what);
79 static void db_show_rm(const struct lock_object *lock);
81 static void lock_rm(struct lock_object *lock, uintptr_t how);
83 static int owner_rm(const struct lock_object *lock, struct thread **owner);
85 static uintptr_t unlock_rm(struct lock_object *lock);
87 struct lock_class lock_class_rm = {
89 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
90 .lc_assert = assert_rm,
92 .lc_ddb_show = db_show_rm,
95 .lc_unlock = unlock_rm,
101 struct lock_class lock_class_rm_sleepable = {
102 .lc_name = "sleepable rm",
103 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE,
104 .lc_assert = assert_rm,
106 .lc_ddb_show = db_show_rm,
109 .lc_unlock = unlock_rm,
111 .lc_owner = owner_rm,
116 assert_rm(const struct lock_object *lock, int what)
119 rm_assert((const struct rmlock *)lock, what);
123 lock_rm(struct lock_object *lock, uintptr_t how)
126 struct rm_priotracker *tracker;
128 rm = (struct rmlock *)lock;
132 tracker = (struct rm_priotracker *)how;
133 rm_rlock(rm, tracker);
138 unlock_rm(struct lock_object *lock)
143 struct rm_queue *queue;
144 struct rm_priotracker *tracker;
147 rm = (struct rmlock *)lock;
150 rm_assert(rm, RA_LOCKED | RA_NOTRECURSED);
155 * Find the right rm_priotracker structure for curthread.
156 * The guarantee about its uniqueness is given by the fact
157 * we already asserted the lock wasn't recursively acquired.
162 for (queue = pc->pc_rm_queue.rmq_next;
163 queue != &pc->pc_rm_queue; queue = queue->rmq_next) {
164 tracker = (struct rm_priotracker *)queue;
165 if ((tracker->rmp_rmlock == rm) &&
166 (tracker->rmp_thread == td)) {
167 how = (uintptr_t)tracker;
171 KASSERT(tracker != NULL,
172 ("rm_priotracker is non-NULL when lock held in read mode"));
174 rm_runlock(rm, tracker);
181 owner_rm(const struct lock_object *lock, struct thread **owner)
183 const struct rmlock *rm;
184 struct lock_class *lc;
186 rm = (const struct rmlock *)lock;
187 lc = LOCK_CLASS(&rm->rm_wlock_object);
188 return (lc->lc_owner(&rm->rm_wlock_object, owner));
192 static struct mtx rm_spinlock;
194 MTX_SYSINIT(rm_spinlock, &rm_spinlock, "rm_spinlock", MTX_SPIN);
197 * Add or remove tracker from per-cpu list.
199 * The per-cpu list can be traversed at any time in forward direction from an
200 * interrupt on the *local* cpu.
203 rm_tracker_add(struct pcpu *pc, struct rm_priotracker *tracker)
205 struct rm_queue *next;
207 /* Initialize all tracker pointers */
208 tracker->rmp_cpuQueue.rmq_prev = &pc->pc_rm_queue;
209 next = pc->pc_rm_queue.rmq_next;
210 tracker->rmp_cpuQueue.rmq_next = next;
212 /* rmq_prev is not used during froward traversal. */
213 next->rmq_prev = &tracker->rmp_cpuQueue;
215 /* Update pointer to first element. */
216 pc->pc_rm_queue.rmq_next = &tracker->rmp_cpuQueue;
220 * Return a count of the number of trackers the thread 'td' already
221 * has on this CPU for the lock 'rm'.
224 rm_trackers_present(const struct pcpu *pc, const struct rmlock *rm,
225 const struct thread *td)
227 struct rm_queue *queue;
228 struct rm_priotracker *tracker;
232 for (queue = pc->pc_rm_queue.rmq_next; queue != &pc->pc_rm_queue;
233 queue = queue->rmq_next) {
234 tracker = (struct rm_priotracker *)queue;
235 if ((tracker->rmp_rmlock == rm) && (tracker->rmp_thread == td))
242 rm_tracker_remove(struct pcpu *pc, struct rm_priotracker *tracker)
244 struct rm_queue *next, *prev;
246 next = tracker->rmp_cpuQueue.rmq_next;
247 prev = tracker->rmp_cpuQueue.rmq_prev;
249 /* Not used during forward traversal. */
250 next->rmq_prev = prev;
252 /* Remove from list. */
253 prev->rmq_next = next;
257 rm_cleanIPI(void *arg)
260 struct rmlock *rm = arg;
261 struct rm_priotracker *tracker;
262 struct rm_queue *queue;
265 for (queue = pc->pc_rm_queue.rmq_next; queue != &pc->pc_rm_queue;
266 queue = queue->rmq_next) {
267 tracker = (struct rm_priotracker *)queue;
268 if (tracker->rmp_rmlock == rm && tracker->rmp_flags == 0) {
269 tracker->rmp_flags = RMPF_ONQUEUE;
270 mtx_lock_spin(&rm_spinlock);
271 LIST_INSERT_HEAD(&rm->rm_activeReaders, tracker,
273 mtx_unlock_spin(&rm_spinlock);
279 rm_init_flags(struct rmlock *rm, const char *name, int opts)
281 struct lock_class *lc;
285 if (!(opts & RM_NOWITNESS))
286 liflags |= LO_WITNESS;
287 if (opts & RM_RECURSE)
288 liflags |= LO_RECURSABLE;
291 rm->rm_writecpus = all_cpus;
292 LIST_INIT(&rm->rm_activeReaders);
293 if (opts & RM_SLEEPABLE) {
294 liflags |= LO_SLEEPABLE;
295 lc = &lock_class_rm_sleepable;
296 xflags = (opts & RM_NEW ? SX_NEW : 0);
297 sx_init_flags(&rm->rm_lock_sx, "rmlock_sx",
298 xflags | SX_NOWITNESS);
301 xflags = (opts & RM_NEW ? MTX_NEW : 0);
302 mtx_init(&rm->rm_lock_mtx, name, "rmlock_mtx",
303 xflags | MTX_NOWITNESS);
305 lock_init(&rm->lock_object, lc, name, NULL, liflags);
309 rm_init(struct rmlock *rm, const char *name)
312 rm_init_flags(rm, name, 0);
316 rm_destroy(struct rmlock *rm)
319 rm_assert(rm, RA_UNLOCKED);
320 LIST_FIRST(&rm->rm_activeReaders) = RM_DESTROYED;
321 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
322 sx_destroy(&rm->rm_lock_sx);
324 mtx_destroy(&rm->rm_lock_mtx);
325 lock_destroy(&rm->lock_object);
329 rm_wowned(const struct rmlock *rm)
332 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
333 return (sx_xlocked(&rm->rm_lock_sx));
335 return (mtx_owned(&rm->rm_lock_mtx));
339 rm_sysinit(void *arg)
341 struct rm_args *args;
344 rm_init_flags(args->ra_rm, args->ra_desc, args->ra_flags);
347 static __noinline int
348 _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
355 /* Check if we just need to do a proper critical_exit. */
356 if (!CPU_ISSET(pc->pc_cpuid, &rm->rm_writecpus)) {
361 /* Remove our tracker from the per-cpu list. */
362 rm_tracker_remove(pc, tracker);
364 /* Check to see if the IPI granted us the lock after all. */
365 if (tracker->rmp_flags) {
366 /* Just add back tracker - we hold the lock. */
367 rm_tracker_add(pc, tracker);
373 * We allow readers to acquire a lock even if a writer is blocked if
374 * the lock is recursive and the reader already holds the lock.
376 if ((rm->lock_object.lo_flags & LO_RECURSABLE) != 0) {
378 * Just grant the lock if this thread already has a tracker
379 * for this lock on the per-cpu queue.
381 if (rm_trackers_present(pc, rm, curthread) != 0) {
382 mtx_lock_spin(&rm_spinlock);
383 LIST_INSERT_HEAD(&rm->rm_activeReaders, tracker,
385 tracker->rmp_flags = RMPF_ONQUEUE;
386 mtx_unlock_spin(&rm_spinlock);
387 rm_tracker_add(pc, tracker);
397 if (rm->lock_object.lo_flags & LO_SLEEPABLE) {
398 if (!sx_try_xlock(&rm->rm_lock_sx))
401 if (!mtx_trylock(&rm->rm_lock_mtx))
405 if (rm->lock_object.lo_flags & LO_SLEEPABLE) {
406 THREAD_SLEEPING_OK();
407 sx_xlock(&rm->rm_lock_sx);
408 THREAD_NO_SLEEPING();
410 mtx_lock(&rm->rm_lock_mtx);
415 CPU_CLR(pc->pc_cpuid, &rm->rm_writecpus);
416 rm_tracker_add(pc, tracker);
420 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
421 sx_xunlock(&rm->rm_lock_sx);
423 mtx_unlock(&rm->rm_lock_mtx);
429 _rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
431 struct thread *td = curthread;
434 if (SCHEDULER_STOPPED())
437 tracker->rmp_flags = 0;
438 tracker->rmp_thread = td;
439 tracker->rmp_rmlock = rm;
441 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
442 THREAD_NO_SLEEPING();
444 td->td_critnest++; /* critical_enter(); */
448 pc = cpuid_to_pcpu[td->td_oncpu]; /* pcpu_find(td->td_oncpu); */
450 rm_tracker_add(pc, tracker);
459 * Fast path to combine two common conditions into a single
462 if (__predict_true(0 == (td->td_owepreempt |
463 CPU_ISSET(pc->pc_cpuid, &rm->rm_writecpus))))
466 /* We do not have a read token and need to acquire one. */
467 return _rm_rlock_hard(rm, tracker, trylock);
470 static __noinline void
471 _rm_unlock_hard(struct thread *td,struct rm_priotracker *tracker)
474 if (td->td_owepreempt) {
479 if (!tracker->rmp_flags)
482 mtx_lock_spin(&rm_spinlock);
483 LIST_REMOVE(tracker, rmp_qentry);
485 if (tracker->rmp_flags & RMPF_SIGNAL) {
487 struct turnstile *ts;
489 rm = tracker->rmp_rmlock;
491 turnstile_chain_lock(&rm->lock_object);
492 mtx_unlock_spin(&rm_spinlock);
494 ts = turnstile_lookup(&rm->lock_object);
496 turnstile_signal(ts, TS_EXCLUSIVE_QUEUE);
497 turnstile_unpend(ts);
498 turnstile_chain_unlock(&rm->lock_object);
500 mtx_unlock_spin(&rm_spinlock);
504 _rm_runlock(struct rmlock *rm, struct rm_priotracker *tracker)
507 struct thread *td = tracker->rmp_thread;
509 if (SCHEDULER_STOPPED())
512 td->td_critnest++; /* critical_enter(); */
513 pc = cpuid_to_pcpu[td->td_oncpu]; /* pcpu_find(td->td_oncpu); */
514 rm_tracker_remove(pc, tracker);
518 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
519 THREAD_SLEEPING_OK();
521 if (__predict_true(0 == (td->td_owepreempt | tracker->rmp_flags)))
524 _rm_unlock_hard(td, tracker);
528 _rm_wlock(struct rmlock *rm)
530 struct rm_priotracker *prio;
531 struct turnstile *ts;
534 if (SCHEDULER_STOPPED())
537 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
538 sx_xlock(&rm->rm_lock_sx);
540 mtx_lock(&rm->rm_lock_mtx);
542 if (CPU_CMP(&rm->rm_writecpus, &all_cpus)) {
543 /* Get all read tokens back */
545 CPU_NAND(&readcpus, &rm->rm_writecpus);
546 rm->rm_writecpus = all_cpus;
549 * Assumes rm->rm_writecpus update is visible on other CPUs
550 * before rm_cleanIPI is called.
553 smp_rendezvous_cpus(readcpus,
554 smp_no_rendezvous_barrier,
556 smp_no_rendezvous_barrier,
563 mtx_lock_spin(&rm_spinlock);
564 while ((prio = LIST_FIRST(&rm->rm_activeReaders)) != NULL) {
565 ts = turnstile_trywait(&rm->lock_object);
566 prio->rmp_flags = RMPF_ONQUEUE | RMPF_SIGNAL;
567 mtx_unlock_spin(&rm_spinlock);
568 turnstile_wait(ts, prio->rmp_thread,
570 mtx_lock_spin(&rm_spinlock);
572 mtx_unlock_spin(&rm_spinlock);
577 _rm_wunlock(struct rmlock *rm)
580 if (rm->lock_object.lo_flags & LO_SLEEPABLE)
581 sx_xunlock(&rm->rm_lock_sx);
583 mtx_unlock(&rm->rm_lock_mtx);
589 _rm_wlock_debug(struct rmlock *rm, const char *file, int line)
592 if (SCHEDULER_STOPPED())
595 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
596 ("rm_wlock() by idle thread %p on rmlock %s @ %s:%d",
597 curthread, rm->lock_object.lo_name, file, line));
598 KASSERT(!rm_destroyed(rm),
599 ("rm_wlock() of destroyed rmlock @ %s:%d", file, line));
600 _rm_assert(rm, RA_UNLOCKED, file, line);
602 WITNESS_CHECKORDER(&rm->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE,
607 LOCK_LOG_LOCK("RMWLOCK", &rm->lock_object, 0, 0, file, line);
608 WITNESS_LOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
609 TD_LOCKS_INC(curthread);
613 _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
616 if (SCHEDULER_STOPPED())
619 KASSERT(!rm_destroyed(rm),
620 ("rm_wunlock() of destroyed rmlock @ %s:%d", file, line));
621 _rm_assert(rm, RA_WLOCKED, file, line);
622 WITNESS_UNLOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
623 LOCK_LOG_LOCK("RMWUNLOCK", &rm->lock_object, 0, 0, file, line);
625 TD_LOCKS_DEC(curthread);
629 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
630 int trylock, const char *file, int line)
633 if (SCHEDULER_STOPPED())
637 if (!(rm->lock_object.lo_flags & LO_RECURSABLE) && !trylock) {
639 KASSERT(rm_trackers_present(get_pcpu(), rm,
641 ("rm_rlock: recursed on non-recursive rmlock %s @ %s:%d\n",
642 rm->lock_object.lo_name, file, line));
646 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
647 ("rm_rlock() by idle thread %p on rmlock %s @ %s:%d",
648 curthread, rm->lock_object.lo_name, file, line));
649 KASSERT(!rm_destroyed(rm),
650 ("rm_rlock() of destroyed rmlock @ %s:%d", file, line));
652 KASSERT(!rm_wowned(rm),
653 ("rm_rlock: wlock already held for %s @ %s:%d",
654 rm->lock_object.lo_name, file, line));
655 WITNESS_CHECKORDER(&rm->lock_object, LOP_NEWORDER, file, line,
659 if (_rm_rlock(rm, tracker, trylock)) {
661 LOCK_LOG_TRY("RMRLOCK", &rm->lock_object, 0, 1, file,
664 LOCK_LOG_LOCK("RMRLOCK", &rm->lock_object, 0, 0, file,
666 WITNESS_LOCK(&rm->lock_object, 0, file, line);
667 TD_LOCKS_INC(curthread);
670 LOCK_LOG_TRY("RMRLOCK", &rm->lock_object, 0, 0, file, line);
676 _rm_runlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
677 const char *file, int line)
680 if (SCHEDULER_STOPPED())
683 KASSERT(!rm_destroyed(rm),
684 ("rm_runlock() of destroyed rmlock @ %s:%d", file, line));
685 _rm_assert(rm, RA_RLOCKED, file, line);
686 WITNESS_UNLOCK(&rm->lock_object, 0, file, line);
687 LOCK_LOG_LOCK("RMRUNLOCK", &rm->lock_object, 0, 0, file, line);
688 _rm_runlock(rm, tracker);
689 TD_LOCKS_DEC(curthread);
695 * Just strip out file and line arguments if no lock debugging is enabled in
696 * the kernel - we are called from a kernel module.
699 _rm_wlock_debug(struct rmlock *rm, const char *file, int line)
706 _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
713 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
714 int trylock, const char *file, int line)
717 return _rm_rlock(rm, tracker, trylock);
721 _rm_runlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
722 const char *file, int line)
725 _rm_runlock(rm, tracker);
730 #ifdef INVARIANT_SUPPORT
736 * Note that this does not need to use witness_assert() for read lock
737 * assertions since an exact count of read locks held by this thread
741 _rm_assert(const struct rmlock *rm, int what, const char *file, int line)
745 if (panicstr != NULL)
749 case RA_LOCKED | RA_RECURSED:
750 case RA_LOCKED | RA_NOTRECURSED:
752 case RA_RLOCKED | RA_RECURSED:
753 case RA_RLOCKED | RA_NOTRECURSED:
755 * Handle the write-locked case. Unlike other
756 * primitives, writers can never recurse.
759 if (what & RA_RLOCKED)
760 panic("Lock %s exclusively locked @ %s:%d\n",
761 rm->lock_object.lo_name, file, line);
762 if (what & RA_RECURSED)
763 panic("Lock %s not recursed @ %s:%d\n",
764 rm->lock_object.lo_name, file, line);
769 count = rm_trackers_present(get_pcpu(), rm, curthread);
773 panic("Lock %s not %slocked @ %s:%d\n",
774 rm->lock_object.lo_name, (what & RA_RLOCKED) ?
775 "read " : "", file, line);
777 if (what & RA_NOTRECURSED)
778 panic("Lock %s recursed @ %s:%d\n",
779 rm->lock_object.lo_name, file, line);
780 } else if (what & RA_RECURSED)
781 panic("Lock %s not recursed @ %s:%d\n",
782 rm->lock_object.lo_name, file, line);
786 panic("Lock %s not exclusively locked @ %s:%d\n",
787 rm->lock_object.lo_name, file, line);
791 panic("Lock %s exclusively locked @ %s:%d\n",
792 rm->lock_object.lo_name, file, line);
795 count = rm_trackers_present(get_pcpu(), rm, curthread);
799 panic("Lock %s read locked @ %s:%d\n",
800 rm->lock_object.lo_name, file, line);
803 panic("Unknown rm lock assertion: %d @ %s:%d", what, file,
807 #endif /* INVARIANT_SUPPORT */
811 print_tracker(struct rm_priotracker *tr)
816 db_printf(" thread %p (tid %d, pid %d, \"%s\") {", td, td->td_tid,
817 td->td_proc->p_pid, td->td_name);
818 if (tr->rmp_flags & RMPF_ONQUEUE) {
819 db_printf("ONQUEUE");
820 if (tr->rmp_flags & RMPF_SIGNAL)
821 db_printf(",SIGNAL");
828 db_show_rm(const struct lock_object *lock)
830 struct rm_priotracker *tr;
831 struct rm_queue *queue;
832 const struct rmlock *rm;
833 struct lock_class *lc;
836 rm = (const struct rmlock *)lock;
837 db_printf(" writecpus: ");
838 ddb_display_cpuset(__DEQUALIFY(const cpuset_t *, &rm->rm_writecpus));
840 db_printf(" per-CPU readers:\n");
841 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu)
842 for (queue = pc->pc_rm_queue.rmq_next;
843 queue != &pc->pc_rm_queue; queue = queue->rmq_next) {
844 tr = (struct rm_priotracker *)queue;
845 if (tr->rmp_rmlock == rm)
848 db_printf(" active readers:\n");
849 LIST_FOREACH(tr, &rm->rm_activeReaders, rmp_qentry)
851 lc = LOCK_CLASS(&rm->rm_wlock_object);
852 db_printf("Backing write-lock (%s):\n", lc->lc_name);
853 lc->lc_ddb_show(&rm->rm_wlock_object);