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