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