kern_mutex.c revision 124944
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 124944 2004-01-25 03:54:52Z jeff $");
38
39#include "opt_adaptive_mutexes.h"
40#include "opt_ddb.h"
41
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/bus.h>
45#include <sys/kernel.h>
46#include <sys/ktr.h>
47#include <sys/lock.h>
48#include <sys/malloc.h>
49#include <sys/mutex.h>
50#include <sys/proc.h>
51#include <sys/resourcevar.h>
52#include <sys/sched.h>
53#include <sys/sbuf.h>
54#include <sys/sysctl.h>
55#include <sys/turnstile.h>
56#include <sys/vmmeter.h>
57
58#include <machine/atomic.h>
59#include <machine/bus.h>
60#include <machine/clock.h>
61#include <machine/cpu.h>
62
63#include <ddb/ddb.h>
64
65#include <vm/vm.h>
66#include <vm/vm_extern.h>
67
68/*
69 * Internal utility macros.
70 */
71#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
72
73#define mtx_owner(m)	(mtx_unowned((m)) ? NULL \
74	: (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
75
76/*
77 * Lock classes for sleep and spin mutexes.
78 */
79struct lock_class lock_class_mtx_sleep = {
80	"sleep mutex",
81	LC_SLEEPLOCK | LC_RECURSABLE
82};
83struct lock_class lock_class_mtx_spin = {
84	"spin mutex",
85	LC_SPINLOCK | LC_RECURSABLE
86};
87
88/*
89 * System-wide mutexes
90 */
91struct mtx sched_lock;
92struct mtx Giant;
93
94#ifdef MUTEX_PROFILING
95SYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
96SYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
97static int mutex_prof_enable = 0;
98SYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
99    &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
100
101struct mutex_prof {
102	const char	*name;
103	const char	*file;
104	int		line;
105	uintmax_t	cnt_max;
106	uintmax_t	cnt_tot;
107	uintmax_t	cnt_cur;
108	uintmax_t	cnt_contest_holding;
109	uintmax_t	cnt_contest_locking;
110	struct mutex_prof *next;
111};
112
113/*
114 * mprof_buf is a static pool of profiling records to avoid possible
115 * reentrance of the memory allocation functions.
116 *
117 * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
118 */
119#define	NUM_MPROF_BUFFERS	1000
120static struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
121static int first_free_mprof_buf;
122#define	MPROF_HASH_SIZE		1009
123static struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
124/* SWAG: sbuf size = avg stat. line size * number of locks */
125#define MPROF_SBUF_SIZE		256 * 400
126
127static int mutex_prof_acquisitions;
128SYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
129    &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
130static int mutex_prof_records;
131SYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
132    &mutex_prof_records, 0, "Number of profiling records");
133static int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
134SYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
135    &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
136static int mutex_prof_rejected;
137SYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
138    &mutex_prof_rejected, 0, "Number of rejected profiling records");
139static int mutex_prof_hashsize = MPROF_HASH_SIZE;
140SYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
141    &mutex_prof_hashsize, 0, "Hash size");
142static int mutex_prof_collisions = 0;
143SYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
144    &mutex_prof_collisions, 0, "Number of hash collisions");
145
146/*
147 * mprof_mtx protects the profiling buffers and the hash.
148 */
149static struct mtx mprof_mtx;
150MTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
151
152static u_int64_t
153nanoseconds(void)
154{
155	struct timespec tv;
156
157	nanotime(&tv);
158	return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
159}
160
161static int
162dump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
163{
164	struct sbuf *sb;
165	int error, i;
166	static int multiplier = 1;
167
168	if (first_free_mprof_buf == 0)
169		return (SYSCTL_OUT(req, "No locking recorded",
170		    sizeof("No locking recorded")));
171
172retry_sbufops:
173	sb = sbuf_new(NULL, NULL, MPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
174	sbuf_printf(sb, "%6s %12s %11s %5s %12s %12s %s\n",
175	    "max", "total", "count", "avg", "cnt_hold", "cnt_lock", "name");
176	/*
177	 * XXX this spinlock seems to be by far the largest perpetrator
178	 * of spinlock latency (1.6 msec on an Athlon1600 was recorded
179	 * even before I pessimized it further by moving the average
180	 * computation here).
181	 */
182	mtx_lock_spin(&mprof_mtx);
183	for (i = 0; i < first_free_mprof_buf; ++i) {
184		sbuf_printf(sb, "%6ju %12ju %11ju %5ju %12ju %12ju %s:%d (%s)\n",
185		    mprof_buf[i].cnt_max / 1000,
186		    mprof_buf[i].cnt_tot / 1000,
187		    mprof_buf[i].cnt_cur,
188		    mprof_buf[i].cnt_cur == 0 ? (uintmax_t)0 :
189			mprof_buf[i].cnt_tot / (mprof_buf[i].cnt_cur * 1000),
190		    mprof_buf[i].cnt_contest_holding,
191		    mprof_buf[i].cnt_contest_locking,
192		    mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
193		if (sbuf_overflowed(sb)) {
194			mtx_unlock_spin(&mprof_mtx);
195			sbuf_delete(sb);
196			multiplier++;
197			goto retry_sbufops;
198		}
199	}
200	mtx_unlock_spin(&mprof_mtx);
201	sbuf_finish(sb);
202	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
203	sbuf_delete(sb);
204	return (error);
205}
206SYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
207    NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
208#endif
209
210/*
211 * Function versions of the inlined __mtx_* macros.  These are used by
212 * modules and can also be called from assembly language if needed.
213 */
214void
215_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
216{
217
218	MPASS(curthread != NULL);
219	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
220	    ("mtx_lock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
221	    file, line));
222	_get_sleep_lock(m, curthread, opts, file, line);
223	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
224	    line);
225	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
226#ifdef MUTEX_PROFILING
227	/* don't reset the timer when/if recursing */
228	if (m->mtx_acqtime == 0) {
229		m->mtx_filename = file;
230		m->mtx_lineno = line;
231		m->mtx_acqtime = mutex_prof_enable ? nanoseconds() : 0;
232		++mutex_prof_acquisitions;
233	}
234#endif
235}
236
237void
238_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
239{
240
241	MPASS(curthread != NULL);
242	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
243	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
244	    file, line));
245	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
246	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
247	    line);
248	mtx_assert(m, MA_OWNED);
249#ifdef MUTEX_PROFILING
250	if (m->mtx_acqtime != 0) {
251		static const char *unknown = "(unknown)";
252		struct mutex_prof *mpp;
253		u_int64_t acqtime, now;
254		const char *p, *q;
255		volatile u_int hash;
256
257		now = nanoseconds();
258		acqtime = m->mtx_acqtime;
259		m->mtx_acqtime = 0;
260		if (now <= acqtime)
261			goto out;
262		for (p = m->mtx_filename;
263		    p != NULL && strncmp(p, "../", 3) == 0; p += 3)
264			/* nothing */ ;
265		if (p == NULL || *p == '\0')
266			p = unknown;
267		for (hash = m->mtx_lineno, q = p; *q != '\0'; ++q)
268			hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
269		mtx_lock_spin(&mprof_mtx);
270		for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
271			if (mpp->line == m->mtx_lineno &&
272			    strcmp(mpp->file, p) == 0)
273				break;
274		if (mpp == NULL) {
275			/* Just exit if we cannot get a trace buffer */
276			if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
277				++mutex_prof_rejected;
278				goto unlock;
279			}
280			mpp = &mprof_buf[first_free_mprof_buf++];
281			mpp->name = mtx_name(m);
282			mpp->file = p;
283			mpp->line = m->mtx_lineno;
284			mpp->next = mprof_hash[hash];
285			if (mprof_hash[hash] != NULL)
286				++mutex_prof_collisions;
287			mprof_hash[hash] = mpp;
288			++mutex_prof_records;
289		}
290		/*
291		 * Record if the mutex has been held longer now than ever
292		 * before.
293		 */
294		if (now - acqtime > mpp->cnt_max)
295			mpp->cnt_max = now - acqtime;
296		mpp->cnt_tot += now - acqtime;
297		mpp->cnt_cur++;
298		/*
299		 * There's a small race, really we should cmpxchg
300		 * 0 with the current value, but that would bill
301		 * the contention to the wrong lock instance if
302		 * it followed this also.
303		 */
304		mpp->cnt_contest_holding += m->mtx_contest_holding;
305		m->mtx_contest_holding = 0;
306		mpp->cnt_contest_locking += m->mtx_contest_locking;
307		m->mtx_contest_locking = 0;
308unlock:
309		mtx_unlock_spin(&mprof_mtx);
310	}
311out:
312#endif
313	_rel_sleep_lock(m, curthread, opts, file, line);
314}
315
316void
317_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
318{
319
320	MPASS(curthread != NULL);
321	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
322	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
323	    m->mtx_object.lo_name, file, line));
324#if defined(SMP) || LOCK_DEBUG > 0 || 1
325	_get_spin_lock(m, curthread, opts, file, line);
326#else
327	critical_enter();
328#endif
329	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
330	    line);
331	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
332}
333
334void
335_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
336{
337
338	MPASS(curthread != NULL);
339	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
340	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
341	    m->mtx_object.lo_name, file, line));
342	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
343	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
344	    line);
345	mtx_assert(m, MA_OWNED);
346#if defined(SMP) || LOCK_DEBUG > 0 || 1
347	_rel_spin_lock(m);
348#else
349	critical_exit();
350#endif
351}
352
353/*
354 * The important part of mtx_trylock{,_flags}()
355 * Tries to acquire lock `m.'  If this function is called on a mutex that
356 * is already owned, it will recursively acquire the lock.
357 */
358int
359_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
360{
361	int rval;
362
363	MPASS(curthread != NULL);
364
365	if (mtx_owned(m) && (m->mtx_object.lo_flags & LO_RECURSABLE) != 0) {
366		m->mtx_recurse++;
367		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
368		rval = 1;
369	} else
370		rval = _obtain_lock(m, curthread);
371
372	LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
373	if (rval)
374		WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
375		    file, line);
376
377	return (rval);
378}
379
380/*
381 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
382 *
383 * We call this if the lock is either contested (i.e. we need to go to
384 * sleep waiting for it), or if we need to recurse on it.
385 */
386void
387_mtx_lock_sleep(struct mtx *m, int opts, const char *file, int line)
388{
389	struct turnstile *ts;
390	struct thread *td = curthread;
391#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
392	struct thread *owner;
393#endif
394	uintptr_t v;
395#ifdef KTR
396	int cont_logged = 0;
397#endif
398#ifdef MUTEX_PROFILING
399	int contested;
400#endif
401
402	if (mtx_owned(m)) {
403		KASSERT((m->mtx_object.lo_flags & LO_RECURSABLE) != 0,
404	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
405		    m->mtx_object.lo_name, file, line));
406		m->mtx_recurse++;
407		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
408		if (LOCK_LOG_TEST(&m->mtx_object, opts))
409			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
410		return;
411	}
412
413	if (LOCK_LOG_TEST(&m->mtx_object, opts))
414		CTR4(KTR_LOCK,
415		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
416		    m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
417
418#ifdef MUTEX_PROFILING
419	contested = 0;
420#endif
421	while (!_obtain_lock(m, td)) {
422#ifdef MUTEX_PROFILING
423		contested = 1;
424		atomic_add_int(&m->mtx_contest_holding, 1);
425#endif
426		ts = turnstile_lookup(&m->mtx_object);
427		v = m->mtx_lock;
428
429		/*
430		 * Check if the lock has been released while spinning for
431		 * the turnstile chain lock.
432		 */
433		if (v == MTX_UNOWNED) {
434			turnstile_release(&m->mtx_object);
435#ifdef __i386__
436			ia32_pause();
437#endif
438			continue;
439		}
440
441		/*
442		 * The mutex was marked contested on release. This means that
443		 * there are other threads blocked on it.  Grab ownership of
444		 * it and propagate its priority to the current thread if
445		 * necessary.
446		 */
447		if (v == MTX_CONTESTED) {
448			MPASS(ts != NULL);
449			m->mtx_lock = (uintptr_t)td | MTX_CONTESTED;
450			turnstile_claim(ts);
451			break;
452		}
453
454		/*
455		 * If the mutex isn't already contested and a failure occurs
456		 * setting the contested bit, the mutex was either released
457		 * or the state of the MTX_RECURSED bit changed.
458		 */
459		if ((v & MTX_CONTESTED) == 0 &&
460		    !atomic_cmpset_ptr(&m->mtx_lock, (void *)v,
461			(void *)(v | MTX_CONTESTED))) {
462			turnstile_release(&m->mtx_object);
463#ifdef __i386__
464			ia32_pause();
465#endif
466			continue;
467		}
468
469#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
470		/*
471		 * If the current owner of the lock is executing on another
472		 * CPU, spin instead of blocking.
473		 */
474		owner = (struct thread *)(v & MTX_FLAGMASK);
475		if (m != &Giant && TD_IS_RUNNING(owner)) {
476			turnstile_release(&m->mtx_object);
477			while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
478#ifdef __i386__
479				ia32_pause();
480#endif
481			}
482			continue;
483		}
484#endif	/* SMP && ADAPTIVE_MUTEXES */
485
486		/*
487		 * We definitely must sleep for this lock.
488		 */
489		mtx_assert(m, MA_NOTOWNED);
490
491#ifdef KTR
492		if (!cont_logged) {
493			CTR6(KTR_CONTENTION,
494			    "contention: %p at %s:%d wants %s, taken by %s:%d",
495			    td, file, line, m->mtx_object.lo_name,
496			    WITNESS_FILE(&m->mtx_object),
497			    WITNESS_LINE(&m->mtx_object));
498			cont_logged = 1;
499		}
500#endif
501
502		/*
503		 * Block on the turnstile.
504		 */
505		turnstile_wait(ts, &m->mtx_object, mtx_owner(m));
506	}
507
508#ifdef KTR
509	if (cont_logged) {
510		CTR4(KTR_CONTENTION,
511		    "contention end: %s acquired by %p at %s:%d",
512		    m->mtx_object.lo_name, td, file, line);
513	}
514#endif
515#ifdef MUTEX_PROFILING
516	if (contested)
517		m->mtx_contest_locking++;
518	m->mtx_contest_holding = 0;
519#endif
520	return;
521}
522
523/*
524 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
525 *
526 * This is only called if we need to actually spin for the lock. Recursion
527 * is handled inline.
528 */
529void
530_mtx_lock_spin(struct mtx *m, int opts, const char *file, int line)
531{
532	int i = 0;
533
534	if (LOCK_LOG_TEST(&m->mtx_object, opts))
535		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
536
537	for (;;) {
538		if (_obtain_lock(m, curthread))
539			break;
540
541		/* Give interrupts a chance while we spin. */
542		critical_exit();
543		while (m->mtx_lock != MTX_UNOWNED) {
544			if (i++ < 10000000) {
545#ifdef __i386__
546				ia32_pause();
547#endif
548				continue;
549			}
550			if (i < 60000000)
551				DELAY(1);
552#ifdef DDB
553			else if (!db_active) {
554#else
555			else {
556#endif
557				printf("spin lock %s held by %p for > 5 seconds\n",
558				    m->mtx_object.lo_name, (void *)m->mtx_lock);
559#ifdef WITNESS
560				witness_display_spinlock(&m->mtx_object,
561				    mtx_owner(m));
562#endif
563				panic("spin lock held too long");
564			}
565#ifdef __i386__
566			ia32_pause();
567#endif
568		}
569		critical_enter();
570	}
571
572	if (LOCK_LOG_TEST(&m->mtx_object, opts))
573		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
574
575	return;
576}
577
578/*
579 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
580 *
581 * We are only called here if the lock is recursed or contested (i.e. we
582 * need to wake up a blocked thread).
583 */
584void
585_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
586{
587	struct turnstile *ts;
588	struct thread *td, *td1;
589
590	if (mtx_recursed(m)) {
591		if (--(m->mtx_recurse) == 0)
592			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
593		if (LOCK_LOG_TEST(&m->mtx_object, opts))
594			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
595		return;
596	}
597
598	ts = turnstile_lookup(&m->mtx_object);
599	if (LOCK_LOG_TEST(&m->mtx_object, opts))
600		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
601
602#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
603	if (ts == NULL) {
604		_release_lock_quick(m);
605		if (LOCK_LOG_TEST(&m->mtx_object, opts))
606			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
607		turnstile_release(&m->mtx_object);
608		return;
609	}
610#else
611	MPASS(ts != NULL);
612#endif
613	/* XXX */
614	td1 = turnstile_head(ts);
615	if (turnstile_signal(ts)) {
616		_release_lock_quick(m);
617		if (LOCK_LOG_TEST(&m->mtx_object, opts))
618			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
619	} else {
620		m->mtx_lock = MTX_CONTESTED;
621		if (LOCK_LOG_TEST(&m->mtx_object, opts))
622			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p still contested",
623			    m);
624	}
625	turnstile_unpend(ts);
626
627	/*
628	 * XXX: This is just a hack until preemption is done.  However,
629	 * once preemption is done we need to either wrap the
630	 * turnstile_signal() and release of the actual lock in an
631	 * extra critical section or change the preemption code to
632	 * always just set a flag and never do instant-preempts.
633	 */
634	td = curthread;
635	if (td->td_critnest > 0 || td1->td_priority >= td->td_priority)
636		return;
637	mtx_lock_spin(&sched_lock);
638	if (!TD_IS_RUNNING(td1)) {
639#ifdef notyet
640		if (td->td_ithd != NULL) {
641			struct ithd *it = td->td_ithd;
642
643			if (it->it_interrupted) {
644				if (LOCK_LOG_TEST(&m->mtx_object, opts))
645					CTR2(KTR_LOCK,
646				    "_mtx_unlock_sleep: %p interrupted %p",
647					    it, it->it_interrupted);
648				intr_thd_fixup(it);
649			}
650		}
651#endif
652		if (LOCK_LOG_TEST(&m->mtx_object, opts))
653			CTR2(KTR_LOCK,
654			    "_mtx_unlock_sleep: %p switching out lock=%p", m,
655			    (void *)m->mtx_lock);
656
657		mi_switch(SW_INVOL);
658		if (LOCK_LOG_TEST(&m->mtx_object, opts))
659			CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
660			    m, (void *)m->mtx_lock);
661	}
662	mtx_unlock_spin(&sched_lock);
663
664	return;
665}
666
667/*
668 * All the unlocking of MTX_SPIN locks is done inline.
669 * See the _rel_spin_lock() macro for the details.
670 */
671
672/*
673 * The backing function for the INVARIANTS-enabled mtx_assert()
674 */
675#ifdef INVARIANT_SUPPORT
676void
677_mtx_assert(struct mtx *m, int what, const char *file, int line)
678{
679
680	if (panicstr != NULL)
681		return;
682	switch (what) {
683	case MA_OWNED:
684	case MA_OWNED | MA_RECURSED:
685	case MA_OWNED | MA_NOTRECURSED:
686		if (!mtx_owned(m))
687			panic("mutex %s not owned at %s:%d",
688			    m->mtx_object.lo_name, file, line);
689		if (mtx_recursed(m)) {
690			if ((what & MA_NOTRECURSED) != 0)
691				panic("mutex %s recursed at %s:%d",
692				    m->mtx_object.lo_name, file, line);
693		} else if ((what & MA_RECURSED) != 0) {
694			panic("mutex %s unrecursed at %s:%d",
695			    m->mtx_object.lo_name, file, line);
696		}
697		break;
698	case MA_NOTOWNED:
699		if (mtx_owned(m))
700			panic("mutex %s owned at %s:%d",
701			    m->mtx_object.lo_name, file, line);
702		break;
703	default:
704		panic("unknown mtx_assert at %s:%d", file, line);
705	}
706}
707#endif
708
709/*
710 * The MUTEX_DEBUG-enabled mtx_validate()
711 *
712 * Most of these checks have been moved off into the LO_INITIALIZED flag
713 * maintained by the witness code.
714 */
715#ifdef MUTEX_DEBUG
716
717void	mtx_validate(struct mtx *);
718
719void
720mtx_validate(struct mtx *m)
721{
722
723/*
724 * XXX: When kernacc() does not require Giant we can reenable this check
725 */
726#ifdef notyet
727/*
728 * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
729 * we can re-enable the kernacc() checks.
730 */
731#ifndef __alpha__
732	/*
733	 * Can't call kernacc() from early init386(), especially when
734	 * initializing Giant mutex, because some stuff in kernacc()
735	 * requires Giant itself.
736	 */
737	if (!cold)
738		if (!kernacc((caddr_t)m, sizeof(m),
739		    VM_PROT_READ | VM_PROT_WRITE))
740			panic("Can't read and write to mutex %p", m);
741#endif
742#endif
743}
744#endif
745
746/*
747 * General init routine used by the MTX_SYSINIT() macro.
748 */
749void
750mtx_sysinit(void *arg)
751{
752	struct mtx_args *margs = arg;
753
754	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
755}
756
757/*
758 * Mutex initialization routine; initialize lock `m' of type contained in
759 * `opts' with options contained in `opts' and name `name.'  The optional
760 * lock type `type' is used as a general lock category name for use with
761 * witness.
762 */
763void
764mtx_init(struct mtx *m, const char *name, const char *type, int opts)
765{
766	struct lock_object *lock;
767
768	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
769	    MTX_NOWITNESS | MTX_DUPOK)) == 0);
770
771#ifdef MUTEX_DEBUG
772	/* Diagnostic and error correction */
773	mtx_validate(m);
774#endif
775
776	lock = &m->mtx_object;
777	KASSERT((lock->lo_flags & LO_INITIALIZED) == 0,
778	    ("mutex \"%s\" %p already initialized", name, m));
779	bzero(m, sizeof(*m));
780	if (opts & MTX_SPIN)
781		lock->lo_class = &lock_class_mtx_spin;
782	else
783		lock->lo_class = &lock_class_mtx_sleep;
784	lock->lo_name = name;
785	lock->lo_type = type != NULL ? type : name;
786	if (opts & MTX_QUIET)
787		lock->lo_flags = LO_QUIET;
788	if (opts & MTX_RECURSE)
789		lock->lo_flags |= LO_RECURSABLE;
790	if ((opts & MTX_NOWITNESS) == 0)
791		lock->lo_flags |= LO_WITNESS;
792	if (opts & MTX_DUPOK)
793		lock->lo_flags |= LO_DUPOK;
794
795	m->mtx_lock = MTX_UNOWNED;
796
797	LOCK_LOG_INIT(lock, opts);
798
799	WITNESS_INIT(lock);
800}
801
802/*
803 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
804 * passed in as a flag here because if the corresponding mtx_init() was
805 * called with MTX_QUIET set, then it will already be set in the mutex's
806 * flags.
807 */
808void
809mtx_destroy(struct mtx *m)
810{
811
812	LOCK_LOG_DESTROY(&m->mtx_object, 0);
813
814	if (!mtx_owned(m))
815		MPASS(mtx_unowned(m));
816	else {
817		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
818
819		/* Tell witness this isn't locked to make it happy. */
820		WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
821		    __LINE__);
822	}
823
824	WITNESS_DESTROY(&m->mtx_object);
825}
826
827/*
828 * Intialize the mutex code and system mutexes.  This is called from the MD
829 * startup code prior to mi_startup().  The per-CPU data space needs to be
830 * setup before this is called.
831 */
832void
833mutex_init(void)
834{
835
836	/* Setup thread0 so that mutexes work. */
837	LIST_INIT(&thread0.td_contested);
838
839	/* Setup turnstiles so that sleep mutexes work. */
840	init_turnstiles();
841
842	/*
843	 * Initialize mutexes.
844	 */
845	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
846	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
847	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
848	mtx_lock(&Giant);
849}
850