2 * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. Berkeley Software Design Inc's name may not be used to endorse or
13 * promote products derived from this software without specific prior
16 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
29 * and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
33 * Machine independent bits of mutex implementation.
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include "opt_adaptive_mutexes.h"
41 #include "opt_global.h"
42 #include "opt_mutex_wake_all.h"
43 #include "opt_sched.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
50 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
59 #include <sys/sysctl.h>
60 #include <sys/turnstile.h>
61 #include <sys/vmmeter.h>
62 #include <sys/lock_profile.h>
64 #include <machine/atomic.h>
65 #include <machine/bus.h>
66 #include <machine/cpu.h>
70 #include <fs/devfs/devfs_int.h>
73 #include <vm/vm_extern.h>
76 * Force MUTEX_WAKE_ALL for now.
77 * single thread wakeup needs fixes to avoid race conditions with
78 * priority inheritance.
80 #ifndef MUTEX_WAKE_ALL
81 #define MUTEX_WAKE_ALL
84 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
85 #define ADAPTIVE_MUTEXES
89 * Internal utility macros.
91 #define mtx_unowned(m) ((m)->mtx_lock == MTX_UNOWNED)
93 #define mtx_owner(m) ((struct thread *)((m)->mtx_lock & ~MTX_FLAGMASK))
96 static void db_show_mtx(struct lock_object *lock);
98 static void lock_mtx(struct lock_object *lock, int how);
99 static void lock_spin(struct lock_object *lock, int how);
100 static int unlock_mtx(struct lock_object *lock);
101 static int unlock_spin(struct lock_object *lock);
104 * Lock classes for sleep and spin mutexes.
106 struct lock_class lock_class_mtx_sleep = {
107 .lc_name = "sleep mutex",
108 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
110 .lc_ddb_show = db_show_mtx,
113 .lc_unlock = unlock_mtx,
115 struct lock_class lock_class_mtx_spin = {
116 .lc_name = "spin mutex",
117 .lc_flags = LC_SPINLOCK | LC_RECURSABLE,
119 .lc_ddb_show = db_show_mtx,
121 .lc_lock = lock_spin,
122 .lc_unlock = unlock_spin,
126 * System-wide mutexes
128 struct mtx sched_lock;
131 #ifdef LOCK_PROFILING
132 static inline void lock_profile_init(void)
135 /* Initialize the mutex profiling locks */
136 for (i = 0; i < LPROF_LOCK_SIZE; i++) {
137 mtx_init(&lprof_locks[i], "mprof lock",
138 NULL, MTX_SPIN|MTX_QUIET|MTX_NOPROFILE);
142 static inline void lock_profile_init(void) {;}
146 lock_mtx(struct lock_object *lock, int how)
149 mtx_lock((struct mtx *)lock);
153 lock_spin(struct lock_object *lock, int how)
156 panic("spin locks can only use msleep_spin");
160 unlock_mtx(struct lock_object *lock)
164 m = (struct mtx *)lock;
165 mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
171 unlock_spin(struct lock_object *lock)
174 panic("spin locks can only use msleep_spin");
178 * Function versions of the inlined __mtx_* macros. These are used by
179 * modules and can also be called from assembly language if needed.
182 _mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
185 MPASS(curthread != NULL);
186 KASSERT(m->mtx_lock != MTX_DESTROYED,
187 ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
188 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
189 ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
191 WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
194 _get_sleep_lock(m, curthread, opts, file, line);
195 LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
197 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
198 curthread->td_locks++;
202 _mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
204 MPASS(curthread != NULL);
205 KASSERT(m->mtx_lock != MTX_DESTROYED,
206 ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
207 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
208 ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
210 curthread->td_locks--;
211 WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
212 LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
214 mtx_assert(m, MA_OWNED);
216 lock_profile_release_lock(&m->lock_object);
217 _rel_sleep_lock(m, curthread, opts, file, line);
221 _mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
224 MPASS(curthread != NULL);
225 KASSERT(m->mtx_lock != MTX_DESTROYED,
226 ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
227 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
228 ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
229 m->lock_object.lo_name, file, line));
230 WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
232 _get_spin_lock(m, curthread, opts, file, line);
233 LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
235 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
239 _mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
242 MPASS(curthread != NULL);
243 KASSERT(m->mtx_lock != MTX_DESTROYED,
244 ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
245 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
246 ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
247 m->lock_object.lo_name, file, line));
248 WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
249 LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
251 mtx_assert(m, MA_OWNED);
253 lock_profile_release_lock(&m->lock_object);
258 * The important part of mtx_trylock{,_flags}()
259 * Tries to acquire lock `m.' If this function is called on a mutex that
260 * is already owned, it will recursively acquire the lock.
263 _mtx_trylock(struct mtx *m, int opts, const char *file, int line)
265 int rval, contested = 0;
266 uint64_t waittime = 0;
268 MPASS(curthread != NULL);
269 KASSERT(m->mtx_lock != MTX_DESTROYED,
270 ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
271 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
272 ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
275 if (mtx_owned(m) && (m->lock_object.lo_flags & LO_RECURSABLE) != 0) {
277 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
280 rval = _obtain_lock(m, (uintptr_t)curthread);
282 LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
284 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
286 curthread->td_locks++;
287 if (m->mtx_recurse == 0)
288 lock_profile_obtain_lock_success(&m->lock_object, contested,
289 waittime, file, line);
297 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
299 * We call this if the lock is either contested (i.e. we need to go to
300 * sleep waiting for it), or if we need to recurse on it.
303 _mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
306 #ifdef ADAPTIVE_MUTEXES
307 volatile struct thread *owner;
315 KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
316 ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
317 m->lock_object.lo_name, file, line));
319 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
320 if (LOCK_LOG_TEST(&m->lock_object, opts))
321 CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
325 if (LOCK_LOG_TEST(&m->lock_object, opts))
327 "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
328 m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
330 while (!_obtain_lock(m, tid)) {
331 turnstile_lock(&m->lock_object);
335 * Check if the lock has been released while spinning for
336 * the turnstile chain lock.
338 if (v == MTX_UNOWNED) {
339 turnstile_release(&m->lock_object);
344 #ifdef MUTEX_WAKE_ALL
345 MPASS(v != MTX_CONTESTED);
348 * The mutex was marked contested on release. This means that
349 * there are other threads blocked on it. Grab ownership of
350 * it and propagate its priority to the current thread if
353 if (v == MTX_CONTESTED) {
354 m->mtx_lock = tid | MTX_CONTESTED;
355 turnstile_claim(&m->lock_object);
361 * If the mutex isn't already contested and a failure occurs
362 * setting the contested bit, the mutex was either released
363 * or the state of the MTX_RECURSED bit changed.
365 if ((v & MTX_CONTESTED) == 0 &&
366 !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
367 turnstile_release(&m->lock_object);
372 #ifdef ADAPTIVE_MUTEXES
374 * If the current owner of the lock is executing on another
375 * CPU, spin instead of blocking.
377 owner = (struct thread *)(v & ~MTX_FLAGMASK);
378 #ifdef ADAPTIVE_GIANT
379 if (TD_IS_RUNNING(owner))
381 if (m != &Giant && TD_IS_RUNNING(owner))
384 turnstile_release(&m->lock_object);
385 while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
390 #endif /* ADAPTIVE_MUTEXES */
393 * We definitely must sleep for this lock.
395 mtx_assert(m, MA_NOTOWNED);
400 "contention: %p at %s:%d wants %s, taken by %s:%d",
401 (void *)tid, file, line, m->lock_object.lo_name,
402 WITNESS_FILE(&m->lock_object),
403 WITNESS_LINE(&m->lock_object));
409 * Block on the turnstile.
411 turnstile_wait(&m->lock_object, mtx_owner(m),
417 "contention end: %s acquired by %p at %s:%d",
418 m->lock_object.lo_name, (void *)tid, file, line);
426 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
428 * This is only called if we need to actually spin for the lock. Recursion
432 _mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
438 if (LOCK_LOG_TEST(&m->lock_object, opts))
439 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
441 while (!_obtain_lock(m, tid)) {
443 /* Give interrupts a chance while we spin. */
445 while (m->mtx_lock != MTX_UNOWNED) {
446 if (i++ < 10000000) {
450 if (i < 60000000 || kdb_active || panicstr != NULL)
455 /* If the mutex is unlocked, try again. */
459 "spin lock %p (%s) held by %p (tid %d) too long\n",
460 m, m->lock_object.lo_name, td, td->td_tid);
462 witness_display_spinlock(&m->lock_object, td);
464 panic("spin lock held too long");
471 if (LOCK_LOG_TEST(&m->lock_object, opts))
472 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
479 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
481 * We are only called here if the lock is recursed or contested (i.e. we
482 * need to wake up a blocked thread).
485 _mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
487 struct turnstile *ts;
489 struct thread *td, *td1;
492 if (mtx_recursed(m)) {
493 if (--(m->mtx_recurse) == 0)
494 atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
495 if (LOCK_LOG_TEST(&m->lock_object, opts))
496 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
500 turnstile_lock(&m->lock_object);
501 ts = turnstile_lookup(&m->lock_object);
502 if (LOCK_LOG_TEST(&m->lock_object, opts))
503 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
505 #ifdef ADAPTIVE_MUTEXES
507 _release_lock_quick(m);
508 if (LOCK_LOG_TEST(&m->lock_object, opts))
509 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
510 turnstile_release(&m->lock_object);
518 td1 = turnstile_head(ts, TS_EXCLUSIVE_QUEUE);
520 #ifdef MUTEX_WAKE_ALL
521 turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
522 _release_lock_quick(m);
524 if (turnstile_signal(ts, TS_EXCLUSIVE_QUEUE)) {
525 _release_lock_quick(m);
526 if (LOCK_LOG_TEST(&m->lock_object, opts))
527 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
529 m->mtx_lock = MTX_CONTESTED;
530 if (LOCK_LOG_TEST(&m->lock_object, opts))
531 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p still contested",
535 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
539 * XXX: This is just a hack until preemption is done. However,
540 * once preemption is done we need to either wrap the
541 * turnstile_signal() and release of the actual lock in an
542 * extra critical section or change the preemption code to
543 * always just set a flag and never do instant-preempts.
546 if (td->td_critnest > 0 || td1->td_priority >= td->td_priority)
548 mtx_lock_spin(&sched_lock);
549 if (!TD_IS_RUNNING(td1)) {
551 if (td->td_ithd != NULL) {
552 struct ithd *it = td->td_ithd;
554 if (it->it_interrupted) {
555 if (LOCK_LOG_TEST(&m->lock_object, opts))
557 "_mtx_unlock_sleep: %p interrupted %p",
558 it, it->it_interrupted);
563 if (LOCK_LOG_TEST(&m->lock_object, opts))
565 "_mtx_unlock_sleep: %p switching out lock=%p", m,
566 (void *)m->mtx_lock);
568 mi_switch(SW_INVOL, NULL);
569 if (LOCK_LOG_TEST(&m->lock_object, opts))
570 CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
571 m, (void *)m->mtx_lock);
573 mtx_unlock_spin(&sched_lock);
580 * All the unlocking of MTX_SPIN locks is done inline.
581 * See the _rel_spin_lock() macro for the details.
585 * The backing function for the INVARIANTS-enabled mtx_assert()
587 #ifdef INVARIANT_SUPPORT
589 _mtx_assert(struct mtx *m, int what, const char *file, int line)
592 if (panicstr != NULL || dumping)
596 case MA_OWNED | MA_RECURSED:
597 case MA_OWNED | MA_NOTRECURSED:
599 panic("mutex %s not owned at %s:%d",
600 m->lock_object.lo_name, file, line);
601 if (mtx_recursed(m)) {
602 if ((what & MA_NOTRECURSED) != 0)
603 panic("mutex %s recursed at %s:%d",
604 m->lock_object.lo_name, file, line);
605 } else if ((what & MA_RECURSED) != 0) {
606 panic("mutex %s unrecursed at %s:%d",
607 m->lock_object.lo_name, file, line);
612 panic("mutex %s owned at %s:%d",
613 m->lock_object.lo_name, file, line);
616 panic("unknown mtx_assert at %s:%d", file, line);
622 * The MUTEX_DEBUG-enabled mtx_validate()
624 * Most of these checks have been moved off into the LO_INITIALIZED flag
625 * maintained by the witness code.
629 void mtx_validate(struct mtx *);
632 mtx_validate(struct mtx *m)
636 * XXX: When kernacc() does not require Giant we can reenable this check
640 * Can't call kernacc() from early init386(), especially when
641 * initializing Giant mutex, because some stuff in kernacc()
642 * requires Giant itself.
645 if (!kernacc((caddr_t)m, sizeof(m),
646 VM_PROT_READ | VM_PROT_WRITE))
647 panic("Can't read and write to mutex %p", m);
653 * General init routine used by the MTX_SYSINIT() macro.
656 mtx_sysinit(void *arg)
658 struct mtx_args *margs = arg;
660 mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
664 * Mutex initialization routine; initialize lock `m' of type contained in
665 * `opts' with options contained in `opts' and name `name.' The optional
666 * lock type `type' is used as a general lock category name for use with
670 mtx_init(struct mtx *m, const char *name, const char *type, int opts)
672 struct lock_class *class;
675 MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
676 MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE)) == 0);
679 /* Diagnostic and error correction */
683 /* Determine lock class and lock flags. */
685 class = &lock_class_mtx_spin;
687 class = &lock_class_mtx_sleep;
689 if (opts & MTX_QUIET)
691 if (opts & MTX_RECURSE)
692 flags |= LO_RECURSABLE;
693 if ((opts & MTX_NOWITNESS) == 0)
695 if (opts & MTX_DUPOK)
697 if (opts & MTX_NOPROFILE)
698 flags |= LO_NOPROFILE;
700 /* Initialize mutex. */
701 m->mtx_lock = MTX_UNOWNED;
704 lock_profile_object_init(&m->lock_object, class, name);
705 lock_init(&m->lock_object, class, name, type, flags);
709 * Remove lock `m' from all_mtx queue. We don't allow MTX_QUIET to be
710 * passed in as a flag here because if the corresponding mtx_init() was
711 * called with MTX_QUIET set, then it will already be set in the mutex's
715 mtx_destroy(struct mtx *m)
719 MPASS(mtx_unowned(m));
721 MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
723 /* Perform the non-mtx related part of mtx_unlock_spin(). */
724 if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
727 curthread->td_locks--;
729 /* Tell witness this isn't locked to make it happy. */
730 WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
734 m->mtx_lock = MTX_DESTROYED;
735 lock_profile_object_destroy(&m->lock_object);
736 lock_destroy(&m->lock_object);
740 * Intialize the mutex code and system mutexes. This is called from the MD
741 * startup code prior to mi_startup(). The per-CPU data space needs to be
742 * setup before this is called.
748 /* Setup turnstiles so that sleep mutexes work. */
752 * Initialize mutexes.
754 mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
755 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
756 mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
757 mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
765 db_show_mtx(struct lock_object *lock)
770 m = (struct mtx *)lock;
772 db_printf(" flags: {");
773 if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
777 if (m->lock_object.lo_flags & LO_RECURSABLE)
778 db_printf(", RECURSE");
779 if (m->lock_object.lo_flags & LO_DUPOK)
780 db_printf(", DUPOK");
782 db_printf(" state: {");
784 db_printf("UNOWNED");
787 if (m->mtx_lock & MTX_CONTESTED)
788 db_printf(", CONTESTED");
789 if (m->mtx_lock & MTX_RECURSED)
790 db_printf(", RECURSED");
793 if (!mtx_unowned(m)) {
795 db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
796 td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
798 db_printf(" recursed: %d\n", m->mtx_recurse);