kern_mutex.c revision 227588
1/*-
2 * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
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
14 *    written permission.
15 *
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
26 * SUCH DAMAGE.
27 *
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 $
30 */
31
32/*
33 * Machine independent bits of mutex implementation.
34 */
35
36#include <sys/cdefs.h>
37__FBSDID("$FreeBSD: head/sys/kern/kern_mutex.c 227588 2011-11-16 21:51:17Z pjd $");
38
39#include "opt_adaptive_mutexes.h"
40#include "opt_ddb.h"
41#include "opt_global.h"
42#include "opt_kdtrace.h"
43#include "opt_sched.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/bus.h>
48#include <sys/conf.h>
49#include <sys/kdb.h>
50#include <sys/kernel.h>
51#include <sys/ktr.h>
52#include <sys/lock.h>
53#include <sys/malloc.h>
54#include <sys/mutex.h>
55#include <sys/proc.h>
56#include <sys/resourcevar.h>
57#include <sys/sched.h>
58#include <sys/sbuf.h>
59#include <sys/sysctl.h>
60#include <sys/turnstile.h>
61#include <sys/vmmeter.h>
62#include <sys/lock_profile.h>
63
64#include <machine/atomic.h>
65#include <machine/bus.h>
66#include <machine/cpu.h>
67
68#include <ddb/ddb.h>
69
70#include <fs/devfs/devfs_int.h>
71
72#include <vm/vm.h>
73#include <vm/vm_extern.h>
74
75#if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
76#define	ADAPTIVE_MUTEXES
77#endif
78
79/*
80 * Internal utility macros.
81 */
82#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
83
84#define	mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
85
86#define	mtx_owner(m)	((struct thread *)((m)->mtx_lock & ~MTX_FLAGMASK))
87
88static void	assert_mtx(const struct lock_object *lock, int what);
89#ifdef DDB
90static void	db_show_mtx(const struct lock_object *lock);
91#endif
92static void	lock_mtx(struct lock_object *lock, int how);
93static void	lock_spin(struct lock_object *lock, int how);
94#ifdef KDTRACE_HOOKS
95static int	owner_mtx(const struct lock_object *lock,
96		    struct thread **owner);
97#endif
98static int	unlock_mtx(struct lock_object *lock);
99static int	unlock_spin(struct lock_object *lock);
100
101/*
102 * Lock classes for sleep and spin mutexes.
103 */
104struct lock_class lock_class_mtx_sleep = {
105	.lc_name = "sleep mutex",
106	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
107	.lc_assert = assert_mtx,
108#ifdef DDB
109	.lc_ddb_show = db_show_mtx,
110#endif
111	.lc_lock = lock_mtx,
112	.lc_unlock = unlock_mtx,
113#ifdef KDTRACE_HOOKS
114	.lc_owner = owner_mtx,
115#endif
116};
117struct lock_class lock_class_mtx_spin = {
118	.lc_name = "spin mutex",
119	.lc_flags = LC_SPINLOCK | LC_RECURSABLE,
120	.lc_assert = assert_mtx,
121#ifdef DDB
122	.lc_ddb_show = db_show_mtx,
123#endif
124	.lc_lock = lock_spin,
125	.lc_unlock = unlock_spin,
126#ifdef KDTRACE_HOOKS
127	.lc_owner = owner_mtx,
128#endif
129};
130
131/*
132 * System-wide mutexes
133 */
134struct mtx blocked_lock;
135struct mtx Giant;
136
137void
138assert_mtx(const struct lock_object *lock, int what)
139{
140
141	mtx_assert((const struct mtx *)lock, what);
142}
143
144void
145lock_mtx(struct lock_object *lock, int how)
146{
147
148	mtx_lock((struct mtx *)lock);
149}
150
151void
152lock_spin(struct lock_object *lock, int how)
153{
154
155	panic("spin locks can only use msleep_spin");
156}
157
158int
159unlock_mtx(struct lock_object *lock)
160{
161	struct mtx *m;
162
163	m = (struct mtx *)lock;
164	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
165	mtx_unlock(m);
166	return (0);
167}
168
169int
170unlock_spin(struct lock_object *lock)
171{
172
173	panic("spin locks can only use msleep_spin");
174}
175
176#ifdef KDTRACE_HOOKS
177int
178owner_mtx(const struct lock_object *lock, struct thread **owner)
179{
180	const struct mtx *m = (const struct mtx *)lock;
181
182	*owner = mtx_owner(m);
183	return (mtx_unowned(m) == 0);
184}
185#endif
186
187/*
188 * Function versions of the inlined __mtx_* macros.  These are used by
189 * modules and can also be called from assembly language if needed.
190 */
191void
192_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
193{
194
195	MPASS(curthread != NULL);
196	KASSERT(m->mtx_lock != MTX_DESTROYED,
197	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
198	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
199	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
200	    file, line));
201	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
202	    file, line, NULL);
203
204	__mtx_lock(m, curthread, opts, file, line);
205	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
206	    line);
207	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
208	curthread->td_locks++;
209}
210
211void
212_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
213{
214	MPASS(curthread != NULL);
215	KASSERT(m->mtx_lock != MTX_DESTROYED,
216	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
217	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
218	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
219	    file, line));
220	curthread->td_locks--;
221	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
222	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
223	    line);
224	mtx_assert(m, MA_OWNED);
225
226	if (m->mtx_recurse == 0)
227		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_MTX_UNLOCK_RELEASE, m);
228	__mtx_unlock(m, curthread, opts, file, line);
229}
230
231void
232_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
233{
234
235	MPASS(curthread != NULL);
236	KASSERT(m->mtx_lock != MTX_DESTROYED,
237	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
238	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
239	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
240	    m->lock_object.lo_name, file, line));
241	if (mtx_owned(m))
242		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
243	    ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
244		    m->lock_object.lo_name, file, line));
245	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
246	    file, line, NULL);
247	__mtx_lock_spin(m, curthread, opts, file, line);
248	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
249	    line);
250	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
251}
252
253void
254_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
255{
256
257	MPASS(curthread != NULL);
258	KASSERT(m->mtx_lock != MTX_DESTROYED,
259	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
260	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
261	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
262	    m->lock_object.lo_name, file, line));
263	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
264	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
265	    line);
266	mtx_assert(m, MA_OWNED);
267
268	__mtx_unlock_spin(m);
269}
270
271/*
272 * The important part of mtx_trylock{,_flags}()
273 * Tries to acquire lock `m.'  If this function is called on a mutex that
274 * is already owned, it will recursively acquire the lock.
275 */
276int
277_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
278{
279#ifdef LOCK_PROFILING
280	uint64_t waittime = 0;
281	int contested = 0;
282#endif
283	int rval;
284
285	MPASS(curthread != NULL);
286	KASSERT(m->mtx_lock != MTX_DESTROYED,
287	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
288	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
289	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
290	    file, line));
291
292	if (mtx_owned(m) && (m->lock_object.lo_flags & LO_RECURSABLE) != 0) {
293		m->mtx_recurse++;
294		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
295		rval = 1;
296	} else
297		rval = _mtx_obtain_lock(m, (uintptr_t)curthread);
298
299	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
300	if (rval) {
301		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
302		    file, line);
303		curthread->td_locks++;
304		if (m->mtx_recurse == 0)
305			LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_LOCK_ACQUIRE,
306			    m, contested, waittime, file, line);
307
308	}
309
310	return (rval);
311}
312
313/*
314 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
315 *
316 * We call this if the lock is either contested (i.e. we need to go to
317 * sleep waiting for it), or if we need to recurse on it.
318 */
319void
320_mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
321    int line)
322{
323	struct turnstile *ts;
324	uintptr_t v;
325#ifdef ADAPTIVE_MUTEXES
326	volatile struct thread *owner;
327#endif
328#ifdef KTR
329	int cont_logged = 0;
330#endif
331#ifdef LOCK_PROFILING
332	int contested = 0;
333	uint64_t waittime = 0;
334#endif
335#ifdef KDTRACE_HOOKS
336	uint64_t spin_cnt = 0;
337	uint64_t sleep_cnt = 0;
338	int64_t sleep_time = 0;
339#endif
340
341	if (mtx_owned(m)) {
342		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
343	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
344		    m->lock_object.lo_name, file, line));
345		m->mtx_recurse++;
346		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
347		if (LOCK_LOG_TEST(&m->lock_object, opts))
348			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
349		return;
350	}
351
352	lock_profile_obtain_lock_failed(&m->lock_object,
353		    &contested, &waittime);
354	if (LOCK_LOG_TEST(&m->lock_object, opts))
355		CTR4(KTR_LOCK,
356		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
357		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
358
359	while (!_mtx_obtain_lock(m, tid)) {
360#ifdef KDTRACE_HOOKS
361		spin_cnt++;
362#endif
363#ifdef ADAPTIVE_MUTEXES
364		/*
365		 * If the owner is running on another CPU, spin until the
366		 * owner stops running or the state of the lock changes.
367		 */
368		v = m->mtx_lock;
369		if (v != MTX_UNOWNED) {
370			owner = (struct thread *)(v & ~MTX_FLAGMASK);
371			if (TD_IS_RUNNING(owner)) {
372				if (LOCK_LOG_TEST(&m->lock_object, 0))
373					CTR3(KTR_LOCK,
374					    "%s: spinning on %p held by %p",
375					    __func__, m, owner);
376				while (mtx_owner(m) == owner &&
377				    TD_IS_RUNNING(owner)) {
378					cpu_spinwait();
379#ifdef KDTRACE_HOOKS
380					spin_cnt++;
381#endif
382				}
383				continue;
384			}
385		}
386#endif
387
388		ts = turnstile_trywait(&m->lock_object);
389		v = m->mtx_lock;
390
391		/*
392		 * Check if the lock has been released while spinning for
393		 * the turnstile chain lock.
394		 */
395		if (v == MTX_UNOWNED) {
396			turnstile_cancel(ts);
397			continue;
398		}
399
400#ifdef ADAPTIVE_MUTEXES
401		/*
402		 * The current lock owner might have started executing
403		 * on another CPU (or the lock could have changed
404		 * owners) while we were waiting on the turnstile
405		 * chain lock.  If so, drop the turnstile lock and try
406		 * again.
407		 */
408		owner = (struct thread *)(v & ~MTX_FLAGMASK);
409		if (TD_IS_RUNNING(owner)) {
410			turnstile_cancel(ts);
411			continue;
412		}
413#endif
414
415		/*
416		 * If the mutex isn't already contested and a failure occurs
417		 * setting the contested bit, the mutex was either released
418		 * or the state of the MTX_RECURSED bit changed.
419		 */
420		if ((v & MTX_CONTESTED) == 0 &&
421		    !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
422			turnstile_cancel(ts);
423			continue;
424		}
425
426		/*
427		 * We definitely must sleep for this lock.
428		 */
429		mtx_assert(m, MA_NOTOWNED);
430
431#ifdef KTR
432		if (!cont_logged) {
433			CTR6(KTR_CONTENTION,
434			    "contention: %p at %s:%d wants %s, taken by %s:%d",
435			    (void *)tid, file, line, m->lock_object.lo_name,
436			    WITNESS_FILE(&m->lock_object),
437			    WITNESS_LINE(&m->lock_object));
438			cont_logged = 1;
439		}
440#endif
441
442		/*
443		 * Block on the turnstile.
444		 */
445#ifdef KDTRACE_HOOKS
446		sleep_time -= lockstat_nsecs();
447#endif
448		turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
449#ifdef KDTRACE_HOOKS
450		sleep_time += lockstat_nsecs();
451		sleep_cnt++;
452#endif
453	}
454#ifdef KTR
455	if (cont_logged) {
456		CTR4(KTR_CONTENTION,
457		    "contention end: %s acquired by %p at %s:%d",
458		    m->lock_object.lo_name, (void *)tid, file, line);
459	}
460#endif
461	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_LOCK_ACQUIRE, m, contested,
462	    waittime, file, line);
463#ifdef KDTRACE_HOOKS
464	if (sleep_time)
465		LOCKSTAT_RECORD1(LS_MTX_LOCK_BLOCK, m, sleep_time);
466
467	/*
468	 * Only record the loops spinning and not sleeping.
469	 */
470	if (spin_cnt > sleep_cnt)
471		LOCKSTAT_RECORD1(LS_MTX_LOCK_SPIN, m, (spin_cnt - sleep_cnt));
472#endif
473}
474
475static void
476_mtx_lock_spin_failed(struct mtx *m)
477{
478	struct thread *td;
479
480	td = mtx_owner(m);
481
482	/* If the mutex is unlocked, try again. */
483	if (td == NULL)
484		return;
485
486	printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
487	    m, m->lock_object.lo_name, td, td->td_tid);
488#ifdef WITNESS
489	witness_display_spinlock(&m->lock_object, td, printf);
490#endif
491	panic("spin lock held too long");
492}
493
494#ifdef SMP
495/*
496 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
497 *
498 * This is only called if we need to actually spin for the lock. Recursion
499 * is handled inline.
500 */
501void
502_mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
503    int line)
504{
505	int i = 0;
506#ifdef LOCK_PROFILING
507	int contested = 0;
508	uint64_t waittime = 0;
509#endif
510
511	if (LOCK_LOG_TEST(&m->lock_object, opts))
512		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
513
514	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
515	while (!_mtx_obtain_lock(m, tid)) {
516
517		/* Give interrupts a chance while we spin. */
518		spinlock_exit();
519		while (m->mtx_lock != MTX_UNOWNED) {
520			if (i++ < 10000000) {
521				cpu_spinwait();
522				continue;
523			}
524			if (i < 60000000 || kdb_active || panicstr != NULL)
525				DELAY(1);
526			else
527				_mtx_lock_spin_failed(m);
528			cpu_spinwait();
529		}
530		spinlock_enter();
531	}
532
533	if (LOCK_LOG_TEST(&m->lock_object, opts))
534		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
535
536	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_SPIN_LOCK_ACQUIRE, m,
537	    contested, waittime, (file), (line));
538	LOCKSTAT_RECORD1(LS_MTX_SPIN_LOCK_SPIN, m, i);
539}
540#endif /* SMP */
541
542void
543_thread_lock_flags(struct thread *td, int opts, const char *file, int line)
544{
545	struct mtx *m;
546	uintptr_t tid;
547	int i;
548#ifdef LOCK_PROFILING
549	int contested = 0;
550	uint64_t waittime = 0;
551#endif
552#ifdef KDTRACE_HOOKS
553	uint64_t spin_cnt = 0;
554#endif
555
556	i = 0;
557	tid = (uintptr_t)curthread;
558	for (;;) {
559retry:
560		spinlock_enter();
561		m = td->td_lock;
562		KASSERT(m->mtx_lock != MTX_DESTROYED,
563		    ("thread_lock() of destroyed mutex @ %s:%d", file, line));
564		KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
565		    ("thread_lock() of sleep mutex %s @ %s:%d",
566		    m->lock_object.lo_name, file, line));
567		if (mtx_owned(m))
568			KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
569	    ("thread_lock: recursed on non-recursive mutex %s @ %s:%d\n",
570			    m->lock_object.lo_name, file, line));
571		WITNESS_CHECKORDER(&m->lock_object,
572		    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
573		while (!_mtx_obtain_lock(m, tid)) {
574#ifdef KDTRACE_HOOKS
575			spin_cnt++;
576#endif
577			if (m->mtx_lock == tid) {
578				m->mtx_recurse++;
579				break;
580			}
581			lock_profile_obtain_lock_failed(&m->lock_object,
582			    &contested, &waittime);
583			/* Give interrupts a chance while we spin. */
584			spinlock_exit();
585			while (m->mtx_lock != MTX_UNOWNED) {
586				if (i++ < 10000000)
587					cpu_spinwait();
588				else if (i < 60000000 ||
589				    kdb_active || panicstr != NULL)
590					DELAY(1);
591				else
592					_mtx_lock_spin_failed(m);
593				cpu_spinwait();
594				if (m != td->td_lock)
595					goto retry;
596			}
597			spinlock_enter();
598		}
599		if (m == td->td_lock)
600			break;
601		__mtx_unlock_spin(m);	/* does spinlock_exit() */
602#ifdef KDTRACE_HOOKS
603		spin_cnt++;
604#endif
605	}
606	if (m->mtx_recurse == 0)
607		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_SPIN_LOCK_ACQUIRE,
608		    m, contested, waittime, (file), (line));
609	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
610	    line);
611	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
612	LOCKSTAT_RECORD1(LS_THREAD_LOCK_SPIN, m, spin_cnt);
613}
614
615struct mtx *
616thread_lock_block(struct thread *td)
617{
618	struct mtx *lock;
619
620	THREAD_LOCK_ASSERT(td, MA_OWNED);
621	lock = td->td_lock;
622	td->td_lock = &blocked_lock;
623	mtx_unlock_spin(lock);
624
625	return (lock);
626}
627
628void
629thread_lock_unblock(struct thread *td, struct mtx *new)
630{
631	mtx_assert(new, MA_OWNED);
632	MPASS(td->td_lock == &blocked_lock);
633	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
634}
635
636void
637thread_lock_set(struct thread *td, struct mtx *new)
638{
639	struct mtx *lock;
640
641	mtx_assert(new, MA_OWNED);
642	THREAD_LOCK_ASSERT(td, MA_OWNED);
643	lock = td->td_lock;
644	td->td_lock = new;
645	mtx_unlock_spin(lock);
646}
647
648/*
649 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
650 *
651 * We are only called here if the lock is recursed or contested (i.e. we
652 * need to wake up a blocked thread).
653 */
654void
655_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
656{
657	struct turnstile *ts;
658
659	if (mtx_recursed(m)) {
660		if (--(m->mtx_recurse) == 0)
661			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
662		if (LOCK_LOG_TEST(&m->lock_object, opts))
663			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
664		return;
665	}
666
667	/*
668	 * We have to lock the chain before the turnstile so this turnstile
669	 * can be removed from the hash list if it is empty.
670	 */
671	turnstile_chain_lock(&m->lock_object);
672	ts = turnstile_lookup(&m->lock_object);
673	if (LOCK_LOG_TEST(&m->lock_object, opts))
674		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
675	MPASS(ts != NULL);
676	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
677	_mtx_release_lock_quick(m);
678
679	/*
680	 * This turnstile is now no longer associated with the mutex.  We can
681	 * unlock the chain lock so a new turnstile may take it's place.
682	 */
683	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
684	turnstile_chain_unlock(&m->lock_object);
685}
686
687/*
688 * All the unlocking of MTX_SPIN locks is done inline.
689 * See the __mtx_unlock_spin() macro for the details.
690 */
691
692/*
693 * The backing function for the INVARIANTS-enabled mtx_assert()
694 */
695#ifdef INVARIANT_SUPPORT
696void
697_mtx_assert(const struct mtx *m, int what, const char *file, int line)
698{
699
700	if (panicstr != NULL || dumping)
701		return;
702	switch (what) {
703	case MA_OWNED:
704	case MA_OWNED | MA_RECURSED:
705	case MA_OWNED | MA_NOTRECURSED:
706		if (!mtx_owned(m))
707			panic("mutex %s not owned at %s:%d",
708			    m->lock_object.lo_name, file, line);
709		if (mtx_recursed(m)) {
710			if ((what & MA_NOTRECURSED) != 0)
711				panic("mutex %s recursed at %s:%d",
712				    m->lock_object.lo_name, file, line);
713		} else if ((what & MA_RECURSED) != 0) {
714			panic("mutex %s unrecursed at %s:%d",
715			    m->lock_object.lo_name, file, line);
716		}
717		break;
718	case MA_NOTOWNED:
719		if (mtx_owned(m))
720			panic("mutex %s owned at %s:%d",
721			    m->lock_object.lo_name, file, line);
722		break;
723	default:
724		panic("unknown mtx_assert at %s:%d", file, line);
725	}
726}
727#endif
728
729/*
730 * The MUTEX_DEBUG-enabled mtx_validate()
731 *
732 * Most of these checks have been moved off into the LO_INITIALIZED flag
733 * maintained by the witness code.
734 */
735#ifdef MUTEX_DEBUG
736
737void	mtx_validate(struct mtx *);
738
739void
740mtx_validate(struct mtx *m)
741{
742
743/*
744 * XXX: When kernacc() does not require Giant we can reenable this check
745 */
746#ifdef notyet
747	/*
748	 * Can't call kernacc() from early init386(), especially when
749	 * initializing Giant mutex, because some stuff in kernacc()
750	 * requires Giant itself.
751	 */
752	if (!cold)
753		if (!kernacc((caddr_t)m, sizeof(m),
754		    VM_PROT_READ | VM_PROT_WRITE))
755			panic("Can't read and write to mutex %p", m);
756#endif
757}
758#endif
759
760/*
761 * General init routine used by the MTX_SYSINIT() macro.
762 */
763void
764mtx_sysinit(void *arg)
765{
766	struct mtx_args *margs = arg;
767
768	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
769}
770
771/*
772 * Mutex initialization routine; initialize lock `m' of type contained in
773 * `opts' with options contained in `opts' and name `name.'  The optional
774 * lock type `type' is used as a general lock category name for use with
775 * witness.
776 */
777void
778mtx_init(struct mtx *m, const char *name, const char *type, int opts)
779{
780	struct lock_class *class;
781	int flags;
782
783	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
784		MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE)) == 0);
785	ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
786	    ("%s: mtx_lock not aligned for %s: %p", __func__, name,
787	    &m->mtx_lock));
788
789#ifdef MUTEX_DEBUG
790	/* Diagnostic and error correction */
791	mtx_validate(m);
792#endif
793
794	/* Determine lock class and lock flags. */
795	if (opts & MTX_SPIN)
796		class = &lock_class_mtx_spin;
797	else
798		class = &lock_class_mtx_sleep;
799	flags = 0;
800	if (opts & MTX_QUIET)
801		flags |= LO_QUIET;
802	if (opts & MTX_RECURSE)
803		flags |= LO_RECURSABLE;
804	if ((opts & MTX_NOWITNESS) == 0)
805		flags |= LO_WITNESS;
806	if (opts & MTX_DUPOK)
807		flags |= LO_DUPOK;
808	if (opts & MTX_NOPROFILE)
809		flags |= LO_NOPROFILE;
810
811	/* Initialize mutex. */
812	m->mtx_lock = MTX_UNOWNED;
813	m->mtx_recurse = 0;
814
815	lock_init(&m->lock_object, class, name, type, flags);
816}
817
818/*
819 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
820 * passed in as a flag here because if the corresponding mtx_init() was
821 * called with MTX_QUIET set, then it will already be set in the mutex's
822 * flags.
823 */
824void
825mtx_destroy(struct mtx *m)
826{
827
828	if (!mtx_owned(m))
829		MPASS(mtx_unowned(m));
830	else {
831		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
832
833		/* Perform the non-mtx related part of mtx_unlock_spin(). */
834		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
835			spinlock_exit();
836		else
837			curthread->td_locks--;
838
839		lock_profile_release_lock(&m->lock_object);
840		/* Tell witness this isn't locked to make it happy. */
841		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
842		    __LINE__);
843	}
844
845	m->mtx_lock = MTX_DESTROYED;
846	lock_destroy(&m->lock_object);
847}
848
849/*
850 * Intialize the mutex code and system mutexes.  This is called from the MD
851 * startup code prior to mi_startup().  The per-CPU data space needs to be
852 * setup before this is called.
853 */
854void
855mutex_init(void)
856{
857
858	/* Setup turnstiles so that sleep mutexes work. */
859	init_turnstiles();
860
861	/*
862	 * Initialize mutexes.
863	 */
864	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
865	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
866	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
867	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
868	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
869	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
870	mtx_lock(&Giant);
871}
872
873#ifdef DDB
874void
875db_show_mtx(const struct lock_object *lock)
876{
877	struct thread *td;
878	const struct mtx *m;
879
880	m = (const struct mtx *)lock;
881
882	db_printf(" flags: {");
883	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
884		db_printf("SPIN");
885	else
886		db_printf("DEF");
887	if (m->lock_object.lo_flags & LO_RECURSABLE)
888		db_printf(", RECURSE");
889	if (m->lock_object.lo_flags & LO_DUPOK)
890		db_printf(", DUPOK");
891	db_printf("}\n");
892	db_printf(" state: {");
893	if (mtx_unowned(m))
894		db_printf("UNOWNED");
895	else if (mtx_destroyed(m))
896		db_printf("DESTROYED");
897	else {
898		db_printf("OWNED");
899		if (m->mtx_lock & MTX_CONTESTED)
900			db_printf(", CONTESTED");
901		if (m->mtx_lock & MTX_RECURSED)
902			db_printf(", RECURSED");
903	}
904	db_printf("}\n");
905	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
906		td = mtx_owner(m);
907		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
908		    td->td_tid, td->td_proc->p_pid, td->td_name);
909		if (mtx_recursed(m))
910			db_printf(" recursed: %d\n", m->mtx_recurse);
911	}
912}
913#endif
914