kern_mutex.c revision 154098
1238730Sdelphij/*-
2294286Sdelphij * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
3238730Sdelphij *
4238730Sdelphij * Redistribution and use in source and binary forms, with or without
5238730Sdelphij * modification, are permitted provided that the following conditions
6238730Sdelphij * are met:
7238730Sdelphij * 1. Redistributions of source code must retain the above copyright
8238730Sdelphij *    notice, this list of conditions and the following disclaimer.
960786Sps * 2. Redistributions in binary form must reproduce the above copyright
1060786Sps *    notice, this list of conditions and the following disclaimer in the
1160786Sps *    documentation and/or other materials provided with the distribution.
1260786Sps * 3. Berkeley Software Design Inc's name may not be used to endorse or
1360786Sps *    promote products derived from this software without specific prior
1460786Sps *    written permission.
1560786Sps *
1660786Sps * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
1760786Sps * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1860786Sps * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1960786Sps * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
2060786Sps * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2160786Sps * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2260786Sps * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23161475Sdelphij * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2460786Sps * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2560786Sps * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2660786Sps * SUCH DAMAGE.
2760786Sps *
2860786Sps *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
2960786Sps *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
3060786Sps */
3160786Sps
32172468Sdelphij/*
3360786Sps * Machine independent bits of mutex implementation.
3460786Sps */
3560786Sps
3660786Sps#include <sys/cdefs.h>
3760786Sps__FBSDID("$FreeBSD: head/sys/kern/kern_mutex.c 154098 2006-01-07 14:03:15Z jhb $");
3860786Sps
39191930Sdelphij#include "opt_adaptive_mutexes.h"
40191930Sdelphij#include "opt_ddb.h"
41191930Sdelphij#include "opt_mprof.h"
42191930Sdelphij#include "opt_mutex_wake_all.h"
43191930Sdelphij#include "opt_sched.h"
44191930Sdelphij
4560786Sps#include <sys/param.h>
4660786Sps#include <sys/systm.h>
4760786Sps#include <sys/bus.h>
4860786Sps#include <sys/conf.h>
4960786Sps#include <sys/kdb.h>
50172468Sdelphij#include <sys/kernel.h>
51172468Sdelphij#include <sys/ktr.h>
52172468Sdelphij#include <sys/lock.h>
5360786Sps#include <sys/malloc.h>
5460786Sps#include <sys/mutex.h>
5560786Sps#include <sys/proc.h>
56172468Sdelphij#include <sys/resourcevar.h>
5760786Sps#include <sys/sched.h>
58172468Sdelphij#include <sys/sbuf.h>
59172468Sdelphij#include <sys/sysctl.h>
60172468Sdelphij#include <sys/turnstile.h>
6160786Sps#include <sys/vmmeter.h>
6260786Sps
6360786Sps#include <machine/atomic.h>
64294286Sdelphij#include <machine/bus.h>
65294286Sdelphij#include <machine/clock.h>
66294286Sdelphij#include <machine/cpu.h>
67294286Sdelphij
68294286Sdelphij#include <ddb/ddb.h>
69294286Sdelphij
70294286Sdelphij#include <fs/devfs/devfs_int.h>
71294286Sdelphij
72294286Sdelphij#include <vm/vm.h>
73294286Sdelphij#include <vm/vm_extern.h>
74294286Sdelphij
75294286Sdelphij/*
76294286Sdelphij * Force MUTEX_WAKE_ALL for now.
77294286Sdelphij * single thread wakeup needs fixes to avoid race conditions with
78294286Sdelphij * priority inheritance.
79294286Sdelphij */
80294286Sdelphij#ifndef MUTEX_WAKE_ALL
81294286Sdelphij#define MUTEX_WAKE_ALL
8260786Sps#endif
8360786Sps
8460786Sps/*
85128345Stjr * Internal utility macros.
86128345Stjr */
8760786Sps#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
8860786Sps
8960786Sps#define mtx_owner(m)	(mtx_unowned((m)) ? NULL \
9060786Sps	: (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
9160786Sps
9260786Sps#ifdef DDB
9360786Spsstatic void	db_show_mtx(struct lock_object *lock);
9460786Sps#endif
9560786Sps
9660786Sps/*
97128345Stjr * Lock classes for sleep and spin mutexes.
9860786Sps */
9960786Spsstruct lock_class lock_class_mtx_sleep = {
10060786Sps	"sleep mutex",
10160786Sps	LC_SLEEPLOCK | LC_RECURSABLE,
10260786Sps#ifdef DDB
103128345Stjr	db_show_mtx
10460786Sps#endif
10560786Sps};
10660786Spsstruct lock_class lock_class_mtx_spin = {
10760786Sps	"spin mutex",
10860786Sps	LC_SPINLOCK | LC_RECURSABLE,
109128345Stjr#ifdef DDB
110128345Stjr	db_show_mtx
11160786Sps#endif
11260786Sps};
11360786Sps
11460786Sps/*
11560786Sps * System-wide mutexes
11660786Sps */
11760786Spsstruct mtx sched_lock;
11860786Spsstruct mtx Giant;
11960786Sps
12060786Sps#ifdef MUTEX_PROFILING
12160786SpsSYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
12260786SpsSYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
12360786Spsstatic int mutex_prof_enable = 0;
12460786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
12560786Sps    &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
12660786Sps
12760786Spsstruct mutex_prof {
12860786Sps	const char	*name;
12960786Sps	const char	*file;
13060786Sps	int		line;
13160786Sps	uintmax_t	cnt_max;
13260786Sps	uintmax_t	cnt_tot;
13360786Sps	uintmax_t	cnt_cur;
134170256Sdelphij	uintmax_t	cnt_contest_holding;
13560786Sps	uintmax_t	cnt_contest_locking;
136170256Sdelphij	struct mutex_prof *next;
13760786Sps};
13860786Sps
13960786Sps/*
14060786Sps * mprof_buf is a static pool of profiling records to avoid possible
14160786Sps * reentrance of the memory allocation functions.
14260786Sps *
14360786Sps * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
14460786Sps */
14560786Sps#ifdef MPROF_BUFFERS
14660786Sps#define NUM_MPROF_BUFFERS	MPROF_BUFFERS
14760786Sps#else
14860786Sps#define	NUM_MPROF_BUFFERS	1000
14960786Sps#endif
15060786Spsstatic struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
15160786Spsstatic int first_free_mprof_buf;
15260786Sps#ifndef MPROF_HASH_SIZE
15360786Sps#define	MPROF_HASH_SIZE		1009
154170256Sdelphij#endif
15560786Sps#if NUM_MPROF_BUFFERS >= MPROF_HASH_SIZE
15660786Sps#error MPROF_BUFFERS must be larger than MPROF_HASH_SIZE
15760786Sps#endif
15860786Spsstatic struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
15960786Sps/* SWAG: sbuf size = avg stat. line size * number of locks */
16060786Sps#define MPROF_SBUF_SIZE		256 * 400
16160786Sps
16260786Spsstatic int mutex_prof_acquisitions;
16360786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
16460786Sps    &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
16560786Spsstatic int mutex_prof_records;
16660786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
16760786Sps    &mutex_prof_records, 0, "Number of profiling records");
16860786Spsstatic int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
16960786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
17060786Sps    &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
17160786Spsstatic int mutex_prof_rejected;
17260786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
17360786Sps    &mutex_prof_rejected, 0, "Number of rejected profiling records");
17460786Spsstatic int mutex_prof_hashsize = MPROF_HASH_SIZE;
17560786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
17660786Sps    &mutex_prof_hashsize, 0, "Hash size");
17760786Spsstatic int mutex_prof_collisions = 0;
17860786SpsSYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
17960786Sps    &mutex_prof_collisions, 0, "Number of hash collisions");
18060786Sps
18160786Sps/*
18260786Sps * mprof_mtx protects the profiling buffers and the hash.
18360786Sps */
18460786Spsstatic struct mtx mprof_mtx;
18560786SpsMTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
18660786Sps
18760786Spsstatic u_int64_t
18860786Spsnanoseconds(void)
18960786Sps{
19060786Sps	struct timespec tv;
19160786Sps
19260786Sps	nanotime(&tv);
19360786Sps	return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
19460786Sps}
19560786Sps
19660786Spsstatic int
19760786Spsdump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
19860786Sps{
19960786Sps	struct sbuf *sb;
20060786Sps	int error, i;
20160786Sps	static int multiplier = 1;
20260786Sps
20360786Sps	if (first_free_mprof_buf == 0)
20460786Sps		return (SYSCTL_OUT(req, "No locking recorded",
20560786Sps		    sizeof("No locking recorded")));
20660786Sps
20760786Spsretry_sbufops:
20860786Sps	sb = sbuf_new(NULL, NULL, MPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
20960786Sps	sbuf_printf(sb, "\n%6s %12s %11s %5s %12s %12s %s\n",
21060786Sps	    "max", "total", "count", "avg", "cnt_hold", "cnt_lock", "name");
21160786Sps	/*
21260786Sps	 * XXX this spinlock seems to be by far the largest perpetrator
21360786Sps	 * of spinlock latency (1.6 msec on an Athlon1600 was recorded
21460786Sps	 * even before I pessimized it further by moving the average
21560786Sps	 * computation here).
21660786Sps	 */
21760786Sps	mtx_lock_spin(&mprof_mtx);
21860786Sps	for (i = 0; i < first_free_mprof_buf; ++i) {
219191930Sdelphij		sbuf_printf(sb, "%6ju %12ju %11ju %5ju %12ju %12ju %s:%d (%s)\n",
22060786Sps		    mprof_buf[i].cnt_max / 1000,
22160786Sps		    mprof_buf[i].cnt_tot / 1000,
222191930Sdelphij		    mprof_buf[i].cnt_cur,
22360786Sps		    mprof_buf[i].cnt_cur == 0 ? (uintmax_t)0 :
22460786Sps			mprof_buf[i].cnt_tot / (mprof_buf[i].cnt_cur * 1000),
22560786Sps		    mprof_buf[i].cnt_contest_holding,
22660786Sps		    mprof_buf[i].cnt_contest_locking,
22760786Sps		    mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
22860786Sps		if (sbuf_overflowed(sb)) {
22960786Sps			mtx_unlock_spin(&mprof_mtx);
23060786Sps			sbuf_delete(sb);
23160786Sps			multiplier++;
23260786Sps			goto retry_sbufops;
23360786Sps		}
23460786Sps	}
23560786Sps	mtx_unlock_spin(&mprof_mtx);
23660786Sps	sbuf_finish(sb);
23760786Sps	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
23860786Sps	sbuf_delete(sb);
23960786Sps	return (error);
24060786Sps}
24160786SpsSYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
24260786Sps    NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
24360786Sps
24460786Spsstatic int
24560786Spsreset_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
24660786Sps{
24760786Sps	int error, v;
24860786Sps
24960786Sps	if (first_free_mprof_buf == 0)
25060786Sps		return (0);
25160786Sps
25260786Sps	v = 0;
25360786Sps	error = sysctl_handle_int(oidp, &v, 0, req);
25460786Sps	if (error)
25560786Sps		return (error);
25660786Sps	if (req->newptr == NULL)
25760786Sps		return (error);
25860786Sps	if (v == 0)
25960786Sps		return (0);
260191930Sdelphij
26160786Sps	mtx_lock_spin(&mprof_mtx);
26260786Sps	bzero(mprof_buf, sizeof(*mprof_buf) * first_free_mprof_buf);
263191930Sdelphij	bzero(mprof_hash, sizeof(struct mtx *) * MPROF_HASH_SIZE);
26460786Sps	first_free_mprof_buf = 0;
26560786Sps	mtx_unlock_spin(&mprof_mtx);
26660786Sps	return (0);
26760786Sps}
26860786SpsSYSCTL_PROC(_debug_mutex_prof, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
26960786Sps    NULL, 0, reset_mutex_prof_stats, "I", "Reset mutex profiling statistics");
27060786Sps#endif
27160786Sps
27260786Sps/*
27360786Sps * Function versions of the inlined __mtx_* macros.  These are used by
27460786Sps * modules and can also be called from assembly language if needed.
27560786Sps */
27660786Spsvoid
27760786Sps_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
27860786Sps{
27960786Sps
28060786Sps	MPASS(curthread != NULL);
28160786Sps	KASSERT(LO_CLASSINDEX(&m->mtx_object) == LOCK_CLASS_SLEEP_MUTEX,
28260786Sps	    ("mtx_lock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
28360786Sps	    file, line));
28460786Sps	WITNESS_CHECKORDER(&m->mtx_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
28560786Sps	    file, line);
28660786Sps	_get_sleep_lock(m, curthread, opts, file, line);
28760786Sps	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
28860786Sps	    line);
28960786Sps	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
29060786Sps#ifdef MUTEX_PROFILING
29160786Sps	/* don't reset the timer when/if recursing */
29260786Sps	if (m->mtx_acqtime == 0) {
29360786Sps		m->mtx_filename = file;
29460786Sps		m->mtx_lineno = line;
29560786Sps		m->mtx_acqtime = mutex_prof_enable ? nanoseconds() : 0;
29660786Sps		++mutex_prof_acquisitions;
29760786Sps	}
29860786Sps#endif
29960786Sps}
30060786Sps
30160786Spsvoid
302294286Sdelphij_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
303294286Sdelphij{
304294286Sdelphij
30560786Sps	MPASS(curthread != NULL);
30660786Sps	KASSERT(LO_CLASSINDEX(&m->mtx_object) == LOCK_CLASS_SLEEP_MUTEX,
30760786Sps	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
30860786Sps	    file, line));
30960786Sps	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
31060786Sps	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
31160786Sps	    line);
31260786Sps	mtx_assert(m, MA_OWNED);
313191930Sdelphij#ifdef MUTEX_PROFILING
31460786Sps	if (m->mtx_acqtime != 0) {
31560786Sps		static const char *unknown = "(unknown)";
316191930Sdelphij		struct mutex_prof *mpp;
31760786Sps		u_int64_t acqtime, now;
31860786Sps		const char *p, *q;
31960786Sps		volatile u_int hash;
32060786Sps
321170256Sdelphij		now = nanoseconds();
322161475Sdelphij		acqtime = m->mtx_acqtime;
323161475Sdelphij		m->mtx_acqtime = 0;
324161475Sdelphij		if (now <= acqtime)
32560786Sps			goto out;
32660786Sps		for (p = m->mtx_filename;
32760786Sps		    p != NULL && strncmp(p, "../", 3) == 0; p += 3)
32860786Sps			/* nothing */ ;
32960786Sps		if (p == NULL || *p == '\0')
330			p = unknown;
331		for (hash = m->mtx_lineno, q = p; *q != '\0'; ++q)
332			hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
333		mtx_lock_spin(&mprof_mtx);
334		for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
335			if (mpp->line == m->mtx_lineno &&
336			    strcmp(mpp->file, p) == 0)
337				break;
338		if (mpp == NULL) {
339			/* Just exit if we cannot get a trace buffer */
340			if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
341				++mutex_prof_rejected;
342				goto unlock;
343			}
344			mpp = &mprof_buf[first_free_mprof_buf++];
345			mpp->name = mtx_name(m);
346			mpp->file = p;
347			mpp->line = m->mtx_lineno;
348			mpp->next = mprof_hash[hash];
349			if (mprof_hash[hash] != NULL)
350				++mutex_prof_collisions;
351			mprof_hash[hash] = mpp;
352			++mutex_prof_records;
353		}
354		/*
355		 * Record if the mutex has been held longer now than ever
356		 * before.
357		 */
358		if (now - acqtime > mpp->cnt_max)
359			mpp->cnt_max = now - acqtime;
360		mpp->cnt_tot += now - acqtime;
361		mpp->cnt_cur++;
362		/*
363		 * There's a small race, really we should cmpxchg
364		 * 0 with the current value, but that would bill
365		 * the contention to the wrong lock instance if
366		 * it followed this also.
367		 */
368		mpp->cnt_contest_holding += m->mtx_contest_holding;
369		m->mtx_contest_holding = 0;
370		mpp->cnt_contest_locking += m->mtx_contest_locking;
371		m->mtx_contest_locking = 0;
372unlock:
373		mtx_unlock_spin(&mprof_mtx);
374	}
375out:
376#endif
377	_rel_sleep_lock(m, curthread, opts, file, line);
378}
379
380void
381_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
382{
383
384	MPASS(curthread != NULL);
385	KASSERT(LO_CLASSINDEX(&m->mtx_object) == LOCK_CLASS_SPIN_MUTEX,
386	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
387	    m->mtx_object.lo_name, file, line));
388	WITNESS_CHECKORDER(&m->mtx_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
389	    file, line);
390	_get_spin_lock(m, curthread, opts, file, line);
391	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
392	    line);
393	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
394}
395
396void
397_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
398{
399
400	MPASS(curthread != NULL);
401	KASSERT(LO_CLASSINDEX(&m->mtx_object) == LOCK_CLASS_SPIN_MUTEX,
402	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
403	    m->mtx_object.lo_name, file, line));
404	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
405	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
406	    line);
407	mtx_assert(m, MA_OWNED);
408	_rel_spin_lock(m);
409}
410
411/*
412 * The important part of mtx_trylock{,_flags}()
413 * Tries to acquire lock `m.'  If this function is called on a mutex that
414 * is already owned, it will recursively acquire the lock.
415 */
416int
417_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
418{
419	int rval;
420
421	MPASS(curthread != NULL);
422	KASSERT(LO_CLASSINDEX(&m->mtx_object) == LOCK_CLASS_SLEEP_MUTEX,
423	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
424	    file, line));
425
426	if (mtx_owned(m) && (m->mtx_object.lo_flags & LO_RECURSABLE) != 0) {
427		m->mtx_recurse++;
428		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
429		rval = 1;
430	} else
431		rval = _obtain_lock(m, (uintptr_t)curthread);
432
433	LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
434	if (rval)
435		WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
436		    file, line);
437
438	return (rval);
439}
440
441/*
442 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
443 *
444 * We call this if the lock is either contested (i.e. we need to go to
445 * sleep waiting for it), or if we need to recurse on it.
446 */
447void
448_mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
449    int line)
450{
451#if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
452	struct thread *owner;
453#endif
454	uintptr_t v;
455#ifdef KTR
456	int cont_logged = 0;
457#endif
458#ifdef MUTEX_PROFILING
459	int contested;
460#endif
461
462	if (mtx_owned(m)) {
463		KASSERT((m->mtx_object.lo_flags & LO_RECURSABLE) != 0,
464	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
465		    m->mtx_object.lo_name, file, line));
466		m->mtx_recurse++;
467		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
468		if (LOCK_LOG_TEST(&m->mtx_object, opts))
469			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
470		return;
471	}
472
473	if (LOCK_LOG_TEST(&m->mtx_object, opts))
474		CTR4(KTR_LOCK,
475		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
476		    m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
477
478#ifdef MUTEX_PROFILING
479	contested = 0;
480#endif
481	while (!_obtain_lock(m, tid)) {
482#ifdef MUTEX_PROFILING
483		contested = 1;
484		atomic_add_int(&m->mtx_contest_holding, 1);
485#endif
486		turnstile_lock(&m->mtx_object);
487		v = m->mtx_lock;
488
489		/*
490		 * Check if the lock has been released while spinning for
491		 * the turnstile chain lock.
492		 */
493		if (v == MTX_UNOWNED) {
494			turnstile_release(&m->mtx_object);
495			cpu_spinwait();
496			continue;
497		}
498
499#ifdef MUTEX_WAKE_ALL
500		MPASS(v != MTX_CONTESTED);
501#else
502		/*
503		 * The mutex was marked contested on release. This means that
504		 * there are other threads blocked on it.  Grab ownership of
505		 * it and propagate its priority to the current thread if
506		 * necessary.
507		 */
508		if (v == MTX_CONTESTED) {
509			m->mtx_lock = tid | MTX_CONTESTED;
510			turnstile_claim(&m->mtx_object);
511			break;
512		}
513#endif
514
515		/*
516		 * If the mutex isn't already contested and a failure occurs
517		 * setting the contested bit, the mutex was either released
518		 * or the state of the MTX_RECURSED bit changed.
519		 */
520		if ((v & MTX_CONTESTED) == 0 &&
521		    !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
522			turnstile_release(&m->mtx_object);
523			cpu_spinwait();
524			continue;
525		}
526
527#if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
528		/*
529		 * If the current owner of the lock is executing on another
530		 * CPU, spin instead of blocking.
531		 */
532		owner = (struct thread *)(v & MTX_FLAGMASK);
533#ifdef ADAPTIVE_GIANT
534		if (TD_IS_RUNNING(owner)) {
535#else
536		if (m != &Giant && TD_IS_RUNNING(owner)) {
537#endif
538			turnstile_release(&m->mtx_object);
539			while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
540				cpu_spinwait();
541			}
542			continue;
543		}
544#endif	/* SMP && !NO_ADAPTIVE_MUTEXES */
545
546		/*
547		 * We definitely must sleep for this lock.
548		 */
549		mtx_assert(m, MA_NOTOWNED);
550
551#ifdef KTR
552		if (!cont_logged) {
553			CTR6(KTR_CONTENTION,
554			    "contention: %p at %s:%d wants %s, taken by %s:%d",
555			    (void *)tid, file, line, m->mtx_object.lo_name,
556			    WITNESS_FILE(&m->mtx_object),
557			    WITNESS_LINE(&m->mtx_object));
558			cont_logged = 1;
559		}
560#endif
561
562		/*
563		 * Block on the turnstile.
564		 */
565		turnstile_wait(&m->mtx_object, mtx_owner(m));
566	}
567
568#ifdef KTR
569	if (cont_logged) {
570		CTR4(KTR_CONTENTION,
571		    "contention end: %s acquired by %p at %s:%d",
572		    m->mtx_object.lo_name, (void *)tid, file, line);
573	}
574#endif
575#ifdef MUTEX_PROFILING
576	if (contested)
577		m->mtx_contest_locking++;
578	m->mtx_contest_holding = 0;
579#endif
580	return;
581}
582
583#ifdef SMP
584/*
585 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
586 *
587 * This is only called if we need to actually spin for the lock. Recursion
588 * is handled inline.
589 */
590void
591_mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
592    int line)
593{
594	int i = 0;
595
596	if (LOCK_LOG_TEST(&m->mtx_object, opts))
597		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
598
599	for (;;) {
600		if (_obtain_lock(m, tid))
601			break;
602
603		/* Give interrupts a chance while we spin. */
604		spinlock_exit();
605		while (m->mtx_lock != MTX_UNOWNED) {
606			if (i++ < 10000000) {
607				cpu_spinwait();
608				continue;
609			}
610			if (i < 60000000)
611				DELAY(1);
612			else if (!kdb_active && !panicstr) {
613				printf("spin lock %s held by %p for > 5 seconds\n",
614				    m->mtx_object.lo_name, (void *)m->mtx_lock);
615#ifdef WITNESS
616				witness_display_spinlock(&m->mtx_object,
617				    mtx_owner(m));
618#endif
619				panic("spin lock held too long");
620			}
621			cpu_spinwait();
622		}
623		spinlock_enter();
624	}
625
626	if (LOCK_LOG_TEST(&m->mtx_object, opts))
627		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
628
629	return;
630}
631#endif /* SMP */
632
633/*
634 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
635 *
636 * We are only called here if the lock is recursed or contested (i.e. we
637 * need to wake up a blocked thread).
638 */
639void
640_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
641{
642	struct turnstile *ts;
643#ifndef PREEMPTION
644	struct thread *td, *td1;
645#endif
646
647	if (mtx_recursed(m)) {
648		if (--(m->mtx_recurse) == 0)
649			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
650		if (LOCK_LOG_TEST(&m->mtx_object, opts))
651			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
652		return;
653	}
654
655	turnstile_lock(&m->mtx_object);
656	ts = turnstile_lookup(&m->mtx_object);
657	if (LOCK_LOG_TEST(&m->mtx_object, opts))
658		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
659
660#if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
661	if (ts == NULL) {
662		_release_lock_quick(m);
663		if (LOCK_LOG_TEST(&m->mtx_object, opts))
664			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
665		turnstile_release(&m->mtx_object);
666		return;
667	}
668#else
669	MPASS(ts != NULL);
670#endif
671#ifndef PREEMPTION
672	/* XXX */
673	td1 = turnstile_head(ts);
674#endif
675#ifdef MUTEX_WAKE_ALL
676	turnstile_broadcast(ts);
677	_release_lock_quick(m);
678#else
679	if (turnstile_signal(ts)) {
680		_release_lock_quick(m);
681		if (LOCK_LOG_TEST(&m->mtx_object, opts))
682			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
683	} else {
684		m->mtx_lock = MTX_CONTESTED;
685		if (LOCK_LOG_TEST(&m->mtx_object, opts))
686			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p still contested",
687			    m);
688	}
689#endif
690	turnstile_unpend(ts);
691
692#ifndef PREEMPTION
693	/*
694	 * XXX: This is just a hack until preemption is done.  However,
695	 * once preemption is done we need to either wrap the
696	 * turnstile_signal() and release of the actual lock in an
697	 * extra critical section or change the preemption code to
698	 * always just set a flag and never do instant-preempts.
699	 */
700	td = curthread;
701	if (td->td_critnest > 0 || td1->td_priority >= td->td_priority)
702		return;
703	mtx_lock_spin(&sched_lock);
704	if (!TD_IS_RUNNING(td1)) {
705#ifdef notyet
706		if (td->td_ithd != NULL) {
707			struct ithd *it = td->td_ithd;
708
709			if (it->it_interrupted) {
710				if (LOCK_LOG_TEST(&m->mtx_object, opts))
711					CTR2(KTR_LOCK,
712				    "_mtx_unlock_sleep: %p interrupted %p",
713					    it, it->it_interrupted);
714				intr_thd_fixup(it);
715			}
716		}
717#endif
718		if (LOCK_LOG_TEST(&m->mtx_object, opts))
719			CTR2(KTR_LOCK,
720			    "_mtx_unlock_sleep: %p switching out lock=%p", m,
721			    (void *)m->mtx_lock);
722
723		mi_switch(SW_INVOL, NULL);
724		if (LOCK_LOG_TEST(&m->mtx_object, opts))
725			CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
726			    m, (void *)m->mtx_lock);
727	}
728	mtx_unlock_spin(&sched_lock);
729#endif
730
731	return;
732}
733
734/*
735 * All the unlocking of MTX_SPIN locks is done inline.
736 * See the _rel_spin_lock() macro for the details.
737 */
738
739/*
740 * The backing function for the INVARIANTS-enabled mtx_assert()
741 */
742#ifdef INVARIANT_SUPPORT
743void
744_mtx_assert(struct mtx *m, int what, const char *file, int line)
745{
746
747	if (panicstr != NULL || dumping)
748		return;
749	switch (what) {
750	case MA_OWNED:
751	case MA_OWNED | MA_RECURSED:
752	case MA_OWNED | MA_NOTRECURSED:
753		if (!mtx_owned(m))
754			panic("mutex %s not owned at %s:%d",
755			    m->mtx_object.lo_name, file, line);
756		if (mtx_recursed(m)) {
757			if ((what & MA_NOTRECURSED) != 0)
758				panic("mutex %s recursed at %s:%d",
759				    m->mtx_object.lo_name, file, line);
760		} else if ((what & MA_RECURSED) != 0) {
761			panic("mutex %s unrecursed at %s:%d",
762			    m->mtx_object.lo_name, file, line);
763		}
764		break;
765	case MA_NOTOWNED:
766		if (mtx_owned(m))
767			panic("mutex %s owned at %s:%d",
768			    m->mtx_object.lo_name, file, line);
769		break;
770	default:
771		panic("unknown mtx_assert at %s:%d", file, line);
772	}
773}
774#endif
775
776/*
777 * The MUTEX_DEBUG-enabled mtx_validate()
778 *
779 * Most of these checks have been moved off into the LO_INITIALIZED flag
780 * maintained by the witness code.
781 */
782#ifdef MUTEX_DEBUG
783
784void	mtx_validate(struct mtx *);
785
786void
787mtx_validate(struct mtx *m)
788{
789
790/*
791 * XXX: When kernacc() does not require Giant we can reenable this check
792 */
793#ifdef notyet
794/*
795 * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
796 * we can re-enable the kernacc() checks.
797 */
798#ifndef __alpha__
799	/*
800	 * Can't call kernacc() from early init386(), especially when
801	 * initializing Giant mutex, because some stuff in kernacc()
802	 * requires Giant itself.
803	 */
804	if (!cold)
805		if (!kernacc((caddr_t)m, sizeof(m),
806		    VM_PROT_READ | VM_PROT_WRITE))
807			panic("Can't read and write to mutex %p", m);
808#endif
809#endif
810}
811#endif
812
813/*
814 * General init routine used by the MTX_SYSINIT() macro.
815 */
816void
817mtx_sysinit(void *arg)
818{
819	struct mtx_args *margs = arg;
820
821	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
822}
823
824/*
825 * Mutex initialization routine; initialize lock `m' of type contained in
826 * `opts' with options contained in `opts' and name `name.'  The optional
827 * lock type `type' is used as a general lock category name for use with
828 * witness.
829 */
830void
831mtx_init(struct mtx *m, const char *name, const char *type, int opts)
832{
833	struct lock_object *lock;
834
835	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
836	    MTX_NOWITNESS | MTX_DUPOK)) == 0);
837
838#ifdef MUTEX_DEBUG
839	/* Diagnostic and error correction */
840	mtx_validate(m);
841#endif
842
843	lock = &m->mtx_object;
844	KASSERT((lock->lo_flags & LO_INITIALIZED) == 0,
845	    ("mutex \"%s\" %p already initialized", name, m));
846	bzero(m, sizeof(*m));
847	if (opts & MTX_SPIN)
848		lock->lo_flags = LOCK_CLASS_SPIN_MUTEX << LO_CLASSSHIFT;
849	else
850		lock->lo_flags = LOCK_CLASS_SLEEP_MUTEX << LO_CLASSSHIFT;
851	lock->lo_name = name;
852	lock->lo_type = type != NULL ? type : name;
853	if (opts & MTX_QUIET)
854		lock->lo_flags |= LO_QUIET;
855	if (opts & MTX_RECURSE)
856		lock->lo_flags |= LO_RECURSABLE;
857	if ((opts & MTX_NOWITNESS) == 0)
858		lock->lo_flags |= LO_WITNESS;
859	if (opts & MTX_DUPOK)
860		lock->lo_flags |= LO_DUPOK;
861
862	m->mtx_lock = MTX_UNOWNED;
863
864	LOCK_LOG_INIT(lock, opts);
865
866	WITNESS_INIT(lock);
867}
868
869/*
870 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
871 * passed in as a flag here because if the corresponding mtx_init() was
872 * called with MTX_QUIET set, then it will already be set in the mutex's
873 * flags.
874 */
875void
876mtx_destroy(struct mtx *m)
877{
878
879	LOCK_LOG_DESTROY(&m->mtx_object, 0);
880
881	if (!mtx_owned(m))
882		MPASS(mtx_unowned(m));
883	else {
884		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
885
886		/* Tell witness this isn't locked to make it happy. */
887		WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
888		    __LINE__);
889	}
890
891	WITNESS_DESTROY(&m->mtx_object);
892}
893
894/*
895 * Intialize the mutex code and system mutexes.  This is called from the MD
896 * startup code prior to mi_startup().  The per-CPU data space needs to be
897 * setup before this is called.
898 */
899void
900mutex_init(void)
901{
902
903	/* Setup thread0 so that mutexes work. */
904	LIST_INIT(&thread0.td_contested);
905
906	/* Setup turnstiles so that sleep mutexes work. */
907	init_turnstiles();
908
909	/*
910	 * Initialize mutexes.
911	 */
912	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
913	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
914	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
915	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
916	mtx_lock(&Giant);
917}
918
919#if LOCK_DEBUG > 0 || defined(DDB)
920/* XXX: This is not mutex-specific. */
921struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
922	&lock_class_mtx_spin,
923	&lock_class_mtx_sleep,
924	&lock_class_sx,
925};
926#endif
927
928#ifdef DDB
929/* XXX: This function is not mutex-specific. */
930DB_SHOW_COMMAND(lock, db_show_lock)
931{
932	struct lock_object *lock;
933	struct lock_class *class;
934
935	if (!have_addr)
936		return;
937	lock = (struct lock_object *)addr;
938	if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
939		db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
940		return;
941	}
942	class = LOCK_CLASS(lock);
943	db_printf(" class: %s\n", class->lc_name);
944	db_printf(" name: %s\n", lock->lo_name);
945	if (lock->lo_type && lock->lo_type != lock->lo_name)
946		db_printf(" type: %s\n", lock->lo_type);
947	class->lc_ddb_show(lock);
948}
949
950void
951db_show_mtx(struct lock_object *lock)
952{
953	struct thread *td;
954	struct mtx *m;
955
956	m = (struct mtx *)lock;
957
958	db_printf(" flags: {");
959	if (LO_CLASSINDEX(lock) == LOCK_CLASS_SPIN_MUTEX)
960		db_printf("SPIN");
961	else
962		db_printf("DEF");
963	if (m->mtx_object.lo_flags & LO_RECURSABLE)
964		db_printf(", RECURSE");
965	if (m->mtx_object.lo_flags & LO_DUPOK)
966		db_printf(", DUPOK");
967	db_printf("}\n");
968	db_printf(" state: {");
969	if (mtx_unowned(m))
970		db_printf("UNOWNED");
971	else {
972		db_printf("OWNED");
973		if (m->mtx_lock & MTX_CONTESTED)
974			db_printf(", CONTESTED");
975		if (m->mtx_lock & MTX_RECURSED)
976			db_printf(", RECURSED");
977	}
978	db_printf("}\n");
979	if (!mtx_unowned(m)) {
980		td = mtx_owner(m);
981		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
982		    td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
983		if (mtx_recursed(m))
984			db_printf(" recursed: %d\n", m->mtx_recurse);
985	}
986}
987#endif
988