kern_mutex.c revision 105644
11558Srgrimes/*-
21558Srgrimes * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
31558Srgrimes *
41558Srgrimes * Redistribution and use in source and binary forms, with or without
51558Srgrimes * modification, are permitted provided that the following conditions
61558Srgrimes * are met:
71558Srgrimes * 1. Redistributions of source code must retain the above copyright
81558Srgrimes *    notice, this list of conditions and the following disclaimer.
91558Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
101558Srgrimes *    notice, this list of conditions and the following disclaimer in the
111558Srgrimes *    documentation and/or other materials provided with the distribution.
121558Srgrimes * 3. Berkeley Software Design Inc's name may not be used to endorse or
131558Srgrimes *    promote products derived from this software without specific prior
141558Srgrimes *    written permission.
151558Srgrimes *
161558Srgrimes * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
171558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
181558Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
191558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
201558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
211558Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
221558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
231558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
241558Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
251558Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
261558Srgrimes * SUCH DAMAGE.
271558Srgrimes *
281558Srgrimes *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
291558Srgrimes *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
301558Srgrimes * $FreeBSD: head/sys/kern/kern_mutex.c 105644 2002-10-21 18:48:28Z des $
311558Srgrimes */
321558Srgrimes
331558Srgrimes/*
34114589Sobrien * Machine independent bits of mutex implementation.
351558Srgrimes */
3638040Scharnier
371558Srgrimes#include "opt_adaptive_mutexes.h"
381558Srgrimes#include "opt_ddb.h"
391558Srgrimes
401558Srgrimes#include <sys/param.h>
411558Srgrimes#include <sys/systm.h>
421558Srgrimes#include <sys/bus.h>
43114589Sobrien#include <sys/kernel.h>
4438040Scharnier#include <sys/ktr.h>
45114589Sobrien#include <sys/lock.h>
46114589Sobrien#include <sys/malloc.h>
471558Srgrimes#include <sys/mutex.h>
481558Srgrimes#include <sys/proc.h>
49102231Strhodes#include <sys/resourcevar.h>
501558Srgrimes#include <sys/sched.h>
511558Srgrimes#include <sys/sbuf.h>
5242873Sluoqi#include <sys/stdint.h>
5396478Sphk#include <sys/sysctl.h>
541558Srgrimes#include <sys/vmmeter.h>
551558Srgrimes
5698542Smckusick#include <machine/atomic.h>
5798542Smckusick#include <machine/bus.h>
581558Srgrimes#include <machine/clock.h>
591558Srgrimes#include <machine/cpu.h>
60110174Sgordon
611558Srgrimes#include <ddb/ddb.h>
621558Srgrimes
631558Srgrimes#include <vm/vm.h>
64109597Sjmallett#include <vm/vm_extern.h>
6538040Scharnier
661558Srgrimes/*
671558Srgrimes * Internal utility macros.
6858047Ssheldonh */
691558Srgrimes#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
701558Srgrimes
711558Srgrimes#define mtx_owner(m)	(mtx_unowned((m)) ? NULL \
721558Srgrimes	: (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
731558Srgrimes
74109597Sjmallett/* XXXKSE This test will change. */
75109597Sjmallett#define	thread_running(td)						\
761558Srgrimes	((td)->td_kse != NULL && (td)->td_kse->ke_oncpu != NOCPU)
7792883Simp
7892883Simp/*
791558Srgrimes * Lock classes for sleep and spin mutexes.
801558Srgrimes */
81109597Sjmallettstruct lock_class lock_class_mtx_sleep = {
821558Srgrimes	"sleep mutex",
83109963Sjmallett	LC_SLEEPLOCK | LC_RECURSABLE
8479750Sdd};
85110174Sgordonstruct lock_class lock_class_mtx_spin = {
86105120Srwatson	"spin mutex",
8775377Smckusick	LC_SPINLOCK | LC_RECURSABLE
88103005Sphk};
8975377Smckusick
90127441Sbde/*
91110174Sgordon * System-wide mutexes
9279750Sdd */
9342873Sluoqistruct mtx sched_lock;
9442873Sluoqistruct mtx Giant;
951558Srgrimes
96127441Sbde/*
97127441Sbde * Prototypes for non-exported routines.
98127441Sbde */
99111287Srustatic void	propagate_priority(struct thread *);
100127441Sbde
101127441Sbdestatic void
102127441Sbdepropagate_priority(struct thread *td)
103127441Sbde{
104127441Sbde	int pri = td->td_priority;
105127441Sbde	struct mtx *m = td->td_blocked;
106127441Sbde
107127441Sbde	mtx_assert(&sched_lock, MA_OWNED);
108127441Sbde	for (;;) {
109127441Sbde		struct thread *td1;
110127441Sbde
111127441Sbde		td = mtx_owner(m);
112127441Sbde
113127441Sbde		if (td == NULL) {
114127441Sbde			/*
115127441Sbde			 * This really isn't quite right. Really
116127441Sbde			 * ought to bump priority of thread that
117127441Sbde			 * next acquires the mutex.
118127441Sbde			 */
119127441Sbde			MPASS(m->mtx_lock == MTX_CONTESTED);
120127441Sbde			return;
121127441Sbde		}
122127441Sbde
123127441Sbde		MPASS(td->td_proc != NULL);
124127441Sbde		MPASS(td->td_proc->p_magic == P_MAGIC);
125127441Sbde		KASSERT(!TD_IS_SLEEPING(td), ("sleeping thread owns a mutex"));
126127441Sbde		if (td->td_priority <= pri) /* lower is higher priority */
127127441Sbde			return;
128127441Sbde
129127441Sbde
130127441Sbde		/*
131127441Sbde		 * If lock holder is actually running, just bump priority.
132127441Sbde		 */
133127441Sbde		if (TD_IS_RUNNING(td)) {
134127441Sbde			td->td_priority = pri;
135127441Sbde			return;
136127441Sbde		}
137127441Sbde
138127441Sbde#ifndef SMP
139127441Sbde		/*
140127441Sbde		 * For UP, we check to see if td is curthread (this shouldn't
141127441Sbde		 * ever happen however as it would mean we are in a deadlock.)
142127441Sbde		 */
143127441Sbde		KASSERT(td != curthread, ("Deadlock detected"));
144127441Sbde#endif
145127441Sbde
146127441Sbde		/*
147127441Sbde		 * If on run queue move to new run queue, and quit.
148127441Sbde		 * XXXKSE this gets a lot more complicated under threads
149127441Sbde		 * but try anyhow.
150127441Sbde		 */
151127441Sbde		if (TD_ON_RUNQ(td)) {
152127441Sbde			MPASS(td->td_blocked == NULL);
153127441Sbde			sched_prio(td, pri);
154127441Sbde			return;
155127441Sbde		}
156127441Sbde		/*
157127441Sbde		 * Adjust for any other cases.
158127441Sbde		 */
159127441Sbde		td->td_priority = pri;
160127441Sbde
161127441Sbde		/*
162127441Sbde		 * If we aren't blocked on a mutex, we should be.
163127441Sbde		 */
164127441Sbde		KASSERT(TD_ON_LOCK(td), (
165127441Sbde		    "process %d(%s):%d holds %s but isn't blocked on a mutex\n",
166127441Sbde		    td->td_proc->p_pid, td->td_proc->p_comm, td->td_state,
167127441Sbde		    m->mtx_object.lo_name));
168127441Sbde
169127441Sbde		/*
170127441Sbde		 * Pick up the mutex that td is blocked on.
171127441Sbde		 */
172127441Sbde		m = td->td_blocked;
173127441Sbde		MPASS(m != NULL);
174127441Sbde
175127441Sbde		/*
176127441Sbde		 * Check if the thread needs to be moved up on
177127441Sbde		 * the blocked chain
178127441Sbde		 */
179127441Sbde		if (td == TAILQ_FIRST(&m->mtx_blocked)) {
180127441Sbde			continue;
181127441Sbde		}
182127441Sbde
183127441Sbde		td1 = TAILQ_PREV(td, threadqueue, td_lockq);
184127441Sbde		if (td1->td_priority <= pri) {
185127441Sbde			continue;
186127441Sbde		}
187127441Sbde
188127441Sbde		/*
189127441Sbde		 * Remove thread from blocked chain and determine where
190127441Sbde		 * it should be moved up to.  Since we know that td1 has
191127441Sbde		 * a lower priority than td, we know that at least one
192127441Sbde		 * thread in the chain has a lower priority and that
193127441Sbde		 * td1 will thus not be NULL after the loop.
194127441Sbde		 */
195127441Sbde		TAILQ_REMOVE(&m->mtx_blocked, td, td_lockq);
196127441Sbde		TAILQ_FOREACH(td1, &m->mtx_blocked, td_lockq) {
197127441Sbde			MPASS(td1->td_proc->p_magic == P_MAGIC);
198127441Sbde			if (td1->td_priority > pri)
199127441Sbde				break;
200127441Sbde		}
201127441Sbde
202127441Sbde		MPASS(td1 != NULL);
203127441Sbde		TAILQ_INSERT_BEFORE(td1, td, td_lockq);
204127441Sbde		CTR4(KTR_LOCK,
205127441Sbde		    "propagate_priority: p %p moved before %p on [%p] %s",
206127441Sbde		    td, td1, m, m->mtx_object.lo_name);
207127441Sbde	}
208127441Sbde}
209127441Sbde
210127441Sbde#ifdef MUTEX_PROFILING
211127441SbdeSYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
212127441SbdeSYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
213127441Sbdestatic int mutex_prof_enable = 0;
214127441SbdeSYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
215127441Sbde    &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
216127441Sbde
217127441Sbdestruct mutex_prof {
218127441Sbde	const char	*name;
219127441Sbde	const char	*file;
220127441Sbde	int		line;
221127441Sbde	/*
222127441Sbde	 * XXX should use specialized struct members instead of an array
223105120Srwatson	 * and these silly #defines.
22469314Scharnier	 */
22569314Scharnier#define MPROF_MAX 0
22669314Scharnier#define MPROF_TOT 1
227127441Sbde#define MPROF_CNT 2
22869314Scharnier	uintmax_t	counter[3];
229109963Sjmallett	struct mutex_prof *next;
230109963Sjmallett};
231109963Sjmallett
232109963Sjmallett/*
233109963Sjmallett * mprof_buf is a static pool of profiling records to avoid possible
23469829Scharnier * reentrance of the memory allocation functions.
235109963Sjmallett *
23669829Scharnier * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
23769829Scharnier */
23869829Scharnier#define	NUM_MPROF_BUFFERS	1000
23969829Scharnierstatic struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
24069829Scharnierstatic int first_free_mprof_buf;
24169829Scharnier#define	MPROF_HASH_SIZE		1009
24269829Scharnierstatic struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
243110174Sgordon
244110174Sgordonstatic int mutex_prof_acquisitions;
245110174SgordonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
246110174Sgordon    &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
247105120Srwatsonstatic int mutex_prof_records;
248105120SrwatsonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
249105120Srwatson    &mutex_prof_records, 0, "Number of profiling records");
250105120Srwatsonstatic int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
251105120SrwatsonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
252105120Srwatson    &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
253105120Srwatsonstatic int mutex_prof_rejected;
254105120SrwatsonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
255105120Srwatson    &mutex_prof_rejected, 0, "Number of rejected profiling records");
256105120Srwatsonstatic int mutex_prof_hashsize = MPROF_HASH_SIZE;
257105120SrwatsonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
258105120Srwatson    &mutex_prof_hashsize, 0, "Hash size");
259105120Srwatsonstatic int mutex_prof_collisions = 0;
260105120SrwatsonSYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
261105120Srwatson    &mutex_prof_collisions, 0, "Number of hash collisions");
262105120Srwatson
263105206Srwatson/*
264105120Srwatson * mprof_mtx protects the profiling buffers and the hash.
265105120Srwatson */
266105120Srwatsonstatic struct mtx mprof_mtx;
26769829ScharnierMTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
26869829Scharnier
26969829Scharnierstatic u_int64_t
27069829Scharniernanoseconds(void)
27169829Scharnier{
27269829Scharnier	struct timespec tv;
27369829Scharnier
27469829Scharnier	nanotime(&tv);
27569829Scharnier	return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
27669829Scharnier}
27769829Scharnier
27875377Smckusickstatic int
27975377Smckusickdump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
28075377Smckusick{
28175377Smckusick	struct sbuf *sb;
28275377Smckusick	int error, i;
28375377Smckusick
28475377Smckusick	if (first_free_mprof_buf == 0)
28575377Smckusick		return (SYSCTL_OUT(req, "No locking recorded",
28675377Smckusick		    sizeof("No locking recorded")));
28775377Smckusick
28875377Smckusick	sb = sbuf_new(NULL, NULL, 1024, SBUF_AUTOEXTEND);
289105120Srwatson	sbuf_printf(sb, "%6s %12s %11s %5s %s\n",
290105120Srwatson	    "max", "total", "count", "avg", "name");
291105120Srwatson	/*
292105120Srwatson	 * XXX this spinlock seems to be by far the largest perpetrator
293105120Srwatson	 * of spinlock latency (1.6 msec on an Athlon1600 was recorded
294105120Srwatson	 * even before I pessimized it further by moving the average
295105120Srwatson	 * computation here).
296105120Srwatson	 */
297105120Srwatson	mtx_lock_spin(&mprof_mtx);
298105120Srwatson	for (i = 0; i < first_free_mprof_buf; ++i)
299105120Srwatson		sbuf_printf(sb, "%6ju %12ju %11ju %5ju %s:%d (%s)\n",
300105120Srwatson		    mprof_buf[i].counter[MPROF_MAX] / 1000,
301105120Srwatson		    mprof_buf[i].counter[MPROF_TOT] / 1000,
302105120Srwatson		    mprof_buf[i].counter[MPROF_CNT],
303105120Srwatson		    mprof_buf[i].counter[MPROF_CNT] == 0 ? (uintmax_t)0 :
304105120Srwatson			mprof_buf[i].counter[MPROF_TOT] /
305105206Srwatson			(mprof_buf[i].counter[MPROF_CNT] * 1000),
306105120Srwatson		    mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
307105120Srwatson	mtx_unlock_spin(&mprof_mtx);
308105120Srwatson	sbuf_finish(sb);
30969829Scharnier	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
31069829Scharnier	sbuf_delete(sb);
31169829Scharnier	return (error);
31269829Scharnier}
31369829ScharnierSYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
31469829Scharnier    NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
31569829Scharnier#endif
31669829Scharnier
31769829Scharnier/*
31869829Scharnier * Function versions of the inlined __mtx_* macros.  These are used by
31969829Scharnier * modules and can also be called from assembly language if needed.
32069829Scharnier */
32169829Scharniervoid
32269829Scharnier_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
32369829Scharnier{
32469829Scharnier
32569829Scharnier	MPASS(curthread != NULL);
32669829Scharnier	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
32775498Smckusick	    ("mtx_lock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
32869829Scharnier	    file, line));
32975498Smckusick	_get_sleep_lock(m, curthread, opts, file, line);
33075498Smckusick	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
33175498Smckusick	    line);
33269829Scharnier	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
33369829Scharnier#ifdef MUTEX_PROFILING
33469829Scharnier	/* don't reset the timer when/if recursing */
33569829Scharnier	if (m->mtx_acqtime == 0) {
33669829Scharnier		m->mtx_filename = file;
33769829Scharnier		m->mtx_lineno = line;
33869829Scharnier		m->mtx_acqtime = mutex_prof_enable ? nanoseconds() : 0;
33969829Scharnier		++mutex_prof_acquisitions;
34069829Scharnier	}
34169829Scharnier#endif
34269829Scharnier}
34369829Scharnier
34469829Scharniervoid
34569829Scharnier_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
34669829Scharnier{
34769829Scharnier
34869829Scharnier	MPASS(curthread != NULL);
34969829Scharnier	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
35069829Scharnier	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
35169829Scharnier	    file, line));
35269829Scharnier 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
35369829Scharnier	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
35469829Scharnier	    line);
35569829Scharnier	mtx_assert(m, MA_OWNED);
35669829Scharnier#ifdef MUTEX_PROFILING
35769829Scharnier	if (m->mtx_acqtime != 0) {
35869829Scharnier		static const char *unknown = "(unknown)";
35969829Scharnier		struct mutex_prof *mpp;
36069829Scharnier		u_int64_t acqtime, now;
36169829Scharnier		const char *p, *q;
36269829Scharnier		volatile u_int hash;
36369829Scharnier
36475377Smckusick		now = nanoseconds();
36575377Smckusick		acqtime = m->mtx_acqtime;
36675377Smckusick		m->mtx_acqtime = 0;
36775377Smckusick		if (now <= acqtime)
36875377Smckusick			goto out;
36975377Smckusick		for (p = m->mtx_filename; strncmp(p, "../", 3) == 0; p += 3)
37075377Smckusick			/* nothing */ ;
37175377Smckusick		if (p == NULL || *p == '\0')
37275377Smckusick			p = unknown;
37375377Smckusick		for (hash = m->mtx_lineno, q = p; *q != '\0'; ++q)
37475377Smckusick			hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
37569829Scharnier		mtx_lock_spin(&mprof_mtx);
376109963Sjmallett		for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
377109963Sjmallett			if (mpp->line == m->mtx_lineno &&
378109963Sjmallett			    strcmp(mpp->file, p) == 0)
37942873Sluoqi				break;
38042873Sluoqi		if (mpp == NULL) {
381109963Sjmallett			/* Just exit if we cannot get a trace buffer */
38242873Sluoqi			if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
38342873Sluoqi				++mutex_prof_rejected;
384102231Strhodes				goto unlock;
38542873Sluoqi			}
3861558Srgrimes			mpp = &mprof_buf[first_free_mprof_buf++];
387109963Sjmallett			mpp->name = mtx_name(m);
388109963Sjmallett			mpp->file = p;
389109963Sjmallett			mpp->line = m->mtx_lineno;
390109963Sjmallett			mpp->next = mprof_hash[hash];
391109963Sjmallett			if (mprof_hash[hash] != NULL)
3921558Srgrimes				++mutex_prof_collisions;
3931558Srgrimes			mprof_hash[hash] = mpp;
3941558Srgrimes			++mutex_prof_records;
395109597Sjmallett		}
3961558Srgrimes		/*
397110174Sgordon		 * Record if the mutex has been held longer now than ever
398111287Sru		 * before.
399111287Sru		 */
400110174Sgordon		if (now - acqtime > mpp->counter[MPROF_MAX])
401110174Sgordon			mpp->counter[MPROF_MAX] = now - acqtime;
4021558Srgrimes		mpp->counter[MPROF_TOT] += now - acqtime;
4031558Srgrimes		mpp->counter[MPROF_CNT]++;
4041558Srgrimesunlock:
4051558Srgrimes		mtx_unlock_spin(&mprof_mtx);
406109597Sjmallett	}
4071558Srgrimesout:
408105162Srwatson#endif
409105162Srwatson	_rel_sleep_lock(m, curthread, opts, file, line);
410105162Srwatson}
411105162Srwatson
412109468Sjmallettvoid
41334266Sjulian_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
4149315Sjoerg{
4159315Sjoerg
41675377Smckusick	MPASS(curthread != NULL);
41775377Smckusick	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
41875377Smckusick	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
41975377Smckusick	    m->mtx_object.lo_name, file, line));
4209315Sjoerg#if defined(SMP) || LOCK_DEBUG > 0 || 1
4219315Sjoerg	_get_spin_lock(m, curthread, opts, file, line);
4229315Sjoerg#else
4239315Sjoerg	critical_enter();
4249315Sjoerg#endif
4259315Sjoerg	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
4269315Sjoerg	    line);
4279315Sjoerg	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
4289315Sjoerg}
4299315Sjoerg
430110174Sgordonvoid
431110174Sgordon_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
4329315Sjoerg{
433
434	MPASS(curthread != NULL);
435	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
436	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
437	    m->mtx_object.lo_name, file, line));
438 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
439	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
440	    line);
441	mtx_assert(m, MA_OWNED);
442#if defined(SMP) || LOCK_DEBUG > 0 || 1
443	_rel_spin_lock(m);
444#else
445	critical_exit();
446#endif
447}
448
449/*
450 * The important part of mtx_trylock{,_flags}()
451 * Tries to acquire lock `m.' We do NOT handle recursion here; we assume that
452 * if we're called, it's because we know we don't already own this lock.
453 */
454int
455_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
456{
457	int rval;
458
459	MPASS(curthread != NULL);
460
461	rval = _obtain_lock(m, curthread);
462
463	LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
464	if (rval) {
465		/*
466		 * We do not handle recursion in _mtx_trylock; see the
467		 * note at the top of the routine.
468		 */
469		KASSERT(!mtx_recursed(m),
470		    ("mtx_trylock() called on a recursed mutex"));
471		WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
472		    file, line);
473	}
474
475	return (rval);
476}
477
478/*
479 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
480 *
481 * We call this if the lock is either contested (i.e. we need to go to
482 * sleep waiting for it), or if we need to recurse on it.
483 */
484void
485_mtx_lock_sleep(struct mtx *m, int opts, const char *file, int line)
486{
487	struct thread *td = curthread;
488#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
489	struct thread *owner;
490#endif
491#ifdef KTR
492	int cont_logged = 0;
493#endif
494
495	if ((m->mtx_lock & MTX_FLAGMASK) == (uintptr_t)td) {
496		m->mtx_recurse++;
497		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
498		if (LOCK_LOG_TEST(&m->mtx_object, opts))
499			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
500		return;
501	}
502
503	if (LOCK_LOG_TEST(&m->mtx_object, opts))
504		CTR4(KTR_LOCK,
505		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
506		    m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
507
508	while (!_obtain_lock(m, td)) {
509		uintptr_t v;
510		struct thread *td1;
511
512		mtx_lock_spin(&sched_lock);
513		/*
514		 * Check if the lock has been released while spinning for
515		 * the sched_lock.
516		 */
517		if ((v = m->mtx_lock) == MTX_UNOWNED) {
518			mtx_unlock_spin(&sched_lock);
519#ifdef __i386__
520			ia32_pause();
521#endif
522			continue;
523		}
524
525		/*
526		 * The mutex was marked contested on release. This means that
527		 * there are threads blocked on it.
528		 */
529		if (v == MTX_CONTESTED) {
530			td1 = TAILQ_FIRST(&m->mtx_blocked);
531			MPASS(td1 != NULL);
532			m->mtx_lock = (uintptr_t)td | MTX_CONTESTED;
533
534			if (td1->td_priority < td->td_priority)
535				td->td_priority = td1->td_priority;
536			mtx_unlock_spin(&sched_lock);
537			return;
538		}
539
540		/*
541		 * If the mutex isn't already contested and a failure occurs
542		 * setting the contested bit, the mutex was either released
543		 * or the state of the MTX_RECURSED bit changed.
544		 */
545		if ((v & MTX_CONTESTED) == 0 &&
546		    !atomic_cmpset_ptr(&m->mtx_lock, (void *)v,
547			(void *)(v | MTX_CONTESTED))) {
548			mtx_unlock_spin(&sched_lock);
549#ifdef __i386__
550			ia32_pause();
551#endif
552			continue;
553		}
554
555#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
556		/*
557		 * If the current owner of the lock is executing on another
558		 * CPU, spin instead of blocking.
559		 */
560		owner = (struct thread *)(v & MTX_FLAGMASK);
561		if (m != &Giant && thread_running(owner)) {
562			mtx_unlock_spin(&sched_lock);
563			while (mtx_owner(m) == owner && thread_running(owner)) {
564#ifdef __i386__
565				ia32_pause();
566#endif
567			}
568			continue;
569		}
570#endif	/* SMP && ADAPTIVE_MUTEXES */
571
572		/*
573		 * We definitely must sleep for this lock.
574		 */
575		mtx_assert(m, MA_NOTOWNED);
576
577#ifdef notyet
578		/*
579		 * If we're borrowing an interrupted thread's VM context, we
580		 * must clean up before going to sleep.
581		 */
582		if (td->td_ithd != NULL) {
583			struct ithd *it = td->td_ithd;
584
585			if (it->it_interrupted) {
586				if (LOCK_LOG_TEST(&m->mtx_object, opts))
587					CTR2(KTR_LOCK,
588				    "_mtx_lock_sleep: %p interrupted %p",
589					    it, it->it_interrupted);
590				intr_thd_fixup(it);
591			}
592		}
593#endif
594
595		/*
596		 * Put us on the list of threads blocked on this mutex.
597		 */
598		if (TAILQ_EMPTY(&m->mtx_blocked)) {
599			td1 = mtx_owner(m);
600			LIST_INSERT_HEAD(&td1->td_contested, m, mtx_contested);
601			TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_lockq);
602		} else {
603			TAILQ_FOREACH(td1, &m->mtx_blocked, td_lockq)
604				if (td1->td_priority > td->td_priority)
605					break;
606			if (td1)
607				TAILQ_INSERT_BEFORE(td1, td, td_lockq);
608			else
609				TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_lockq);
610		}
611#ifdef KTR
612		if (!cont_logged) {
613			CTR6(KTR_CONTENTION,
614			    "contention: %p at %s:%d wants %s, taken by %s:%d",
615			    td, file, line, m->mtx_object.lo_name,
616			    WITNESS_FILE(&m->mtx_object),
617			    WITNESS_LINE(&m->mtx_object));
618			cont_logged = 1;
619		}
620#endif
621
622		/*
623		 * Save who we're blocked on.
624		 */
625		td->td_blocked = m;
626		td->td_lockname = m->mtx_object.lo_name;
627		TD_SET_LOCK(td);
628		propagate_priority(td);
629
630		if (LOCK_LOG_TEST(&m->mtx_object, opts))
631			CTR3(KTR_LOCK,
632			    "_mtx_lock_sleep: p %p blocked on [%p] %s", td, m,
633			    m->mtx_object.lo_name);
634
635		td->td_proc->p_stats->p_ru.ru_nvcsw++;
636		mi_switch();
637
638		if (LOCK_LOG_TEST(&m->mtx_object, opts))
639			CTR3(KTR_LOCK,
640			  "_mtx_lock_sleep: p %p free from blocked on [%p] %s",
641			  td, m, m->mtx_object.lo_name);
642
643		mtx_unlock_spin(&sched_lock);
644	}
645
646#ifdef KTR
647	if (cont_logged) {
648		CTR4(KTR_CONTENTION,
649		    "contention end: %s acquired by %p at %s:%d",
650		    m->mtx_object.lo_name, td, file, line);
651	}
652#endif
653	return;
654}
655
656/*
657 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
658 *
659 * This is only called if we need to actually spin for the lock. Recursion
660 * is handled inline.
661 */
662void
663_mtx_lock_spin(struct mtx *m, int opts, const char *file, int line)
664{
665	int i = 0;
666
667	if (LOCK_LOG_TEST(&m->mtx_object, opts))
668		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
669
670	for (;;) {
671		if (_obtain_lock(m, curthread))
672			break;
673
674		/* Give interrupts a chance while we spin. */
675		critical_exit();
676		while (m->mtx_lock != MTX_UNOWNED) {
677			if (i++ < 10000000) {
678#ifdef __i386__
679				ia32_pause();
680#endif
681				continue;
682			}
683			if (i < 60000000)
684				DELAY(1);
685#ifdef DDB
686			else if (!db_active)
687#else
688			else
689#endif
690				panic("spin lock %s held by %p for > 5 seconds",
691				    m->mtx_object.lo_name, (void *)m->mtx_lock);
692#ifdef __i386__
693			ia32_pause();
694#endif
695		}
696		critical_enter();
697	}
698
699	if (LOCK_LOG_TEST(&m->mtx_object, opts))
700		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
701
702	return;
703}
704
705/*
706 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
707 *
708 * We are only called here if the lock is recursed or contested (i.e. we
709 * need to wake up a blocked thread).
710 */
711void
712_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
713{
714	struct thread *td, *td1;
715	struct mtx *m1;
716	int pri;
717
718	td = curthread;
719
720	if (mtx_recursed(m)) {
721		if (--(m->mtx_recurse) == 0)
722			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
723		if (LOCK_LOG_TEST(&m->mtx_object, opts))
724			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
725		return;
726	}
727
728	mtx_lock_spin(&sched_lock);
729	if (LOCK_LOG_TEST(&m->mtx_object, opts))
730		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
731
732	td1 = TAILQ_FIRST(&m->mtx_blocked);
733#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
734	if (td1 == NULL) {
735		_release_lock_quick(m);
736		if (LOCK_LOG_TEST(&m->mtx_object, opts))
737			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
738		mtx_unlock_spin(&sched_lock);
739		return;
740	}
741#endif
742	MPASS(td->td_proc->p_magic == P_MAGIC);
743	MPASS(td1->td_proc->p_magic == P_MAGIC);
744
745	TAILQ_REMOVE(&m->mtx_blocked, td1, td_lockq);
746
747	if (TAILQ_EMPTY(&m->mtx_blocked)) {
748		LIST_REMOVE(m, mtx_contested);
749		_release_lock_quick(m);
750		if (LOCK_LOG_TEST(&m->mtx_object, opts))
751			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
752	} else
753		atomic_store_rel_ptr(&m->mtx_lock, (void *)MTX_CONTESTED);
754
755	pri = PRI_MAX;
756	LIST_FOREACH(m1, &td->td_contested, mtx_contested) {
757		int cp = TAILQ_FIRST(&m1->mtx_blocked)->td_priority;
758		if (cp < pri)
759			pri = cp;
760	}
761
762	if (pri > td->td_base_pri)
763		pri = td->td_base_pri;
764	td->td_priority = pri;
765
766	if (LOCK_LOG_TEST(&m->mtx_object, opts))
767		CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p contested setrunqueue %p",
768		    m, td1);
769
770	td1->td_blocked = NULL;
771	TD_CLR_LOCK(td1);
772	if (!TD_CAN_RUN(td1)) {
773		mtx_unlock_spin(&sched_lock);
774		return;
775	}
776	setrunqueue(td1);
777
778	if (td->td_critnest == 1 && td1->td_priority < pri) {
779#ifdef notyet
780		if (td->td_ithd != NULL) {
781			struct ithd *it = td->td_ithd;
782
783			if (it->it_interrupted) {
784				if (LOCK_LOG_TEST(&m->mtx_object, opts))
785					CTR2(KTR_LOCK,
786				    "_mtx_unlock_sleep: %p interrupted %p",
787					    it, it->it_interrupted);
788				intr_thd_fixup(it);
789			}
790		}
791#endif
792		if (LOCK_LOG_TEST(&m->mtx_object, opts))
793			CTR2(KTR_LOCK,
794			    "_mtx_unlock_sleep: %p switching out lock=%p", m,
795			    (void *)m->mtx_lock);
796
797		td->td_proc->p_stats->p_ru.ru_nivcsw++;
798		mi_switch();
799		if (LOCK_LOG_TEST(&m->mtx_object, opts))
800			CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
801			    m, (void *)m->mtx_lock);
802	}
803
804	mtx_unlock_spin(&sched_lock);
805
806	return;
807}
808
809/*
810 * All the unlocking of MTX_SPIN locks is done inline.
811 * See the _rel_spin_lock() macro for the details.
812 */
813
814/*
815 * The backing function for the INVARIANTS-enabled mtx_assert()
816 */
817#ifdef INVARIANT_SUPPORT
818void
819_mtx_assert(struct mtx *m, int what, const char *file, int line)
820{
821
822	if (panicstr != NULL)
823		return;
824	switch (what) {
825	case MA_OWNED:
826	case MA_OWNED | MA_RECURSED:
827	case MA_OWNED | MA_NOTRECURSED:
828		if (!mtx_owned(m))
829			panic("mutex %s not owned at %s:%d",
830			    m->mtx_object.lo_name, file, line);
831		if (mtx_recursed(m)) {
832			if ((what & MA_NOTRECURSED) != 0)
833				panic("mutex %s recursed at %s:%d",
834				    m->mtx_object.lo_name, file, line);
835		} else if ((what & MA_RECURSED) != 0) {
836			panic("mutex %s unrecursed at %s:%d",
837			    m->mtx_object.lo_name, file, line);
838		}
839		break;
840	case MA_NOTOWNED:
841		if (mtx_owned(m))
842			panic("mutex %s owned at %s:%d",
843			    m->mtx_object.lo_name, file, line);
844		break;
845	default:
846		panic("unknown mtx_assert at %s:%d", file, line);
847	}
848}
849#endif
850
851/*
852 * The MUTEX_DEBUG-enabled mtx_validate()
853 *
854 * Most of these checks have been moved off into the LO_INITIALIZED flag
855 * maintained by the witness code.
856 */
857#ifdef MUTEX_DEBUG
858
859void	mtx_validate(struct mtx *);
860
861void
862mtx_validate(struct mtx *m)
863{
864
865/*
866 * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
867 * we can re-enable the kernacc() checks.
868 */
869#ifndef __alpha__
870	/*
871	 * Can't call kernacc() from early init386(), especially when
872	 * initializing Giant mutex, because some stuff in kernacc()
873	 * requires Giant itself.
874	 */
875	if (!cold)
876		if (!kernacc((caddr_t)m, sizeof(m),
877		    VM_PROT_READ | VM_PROT_WRITE))
878			panic("Can't read and write to mutex %p", m);
879#endif
880}
881#endif
882
883/*
884 * General init routine used by the MTX_SYSINIT() macro.
885 */
886void
887mtx_sysinit(void *arg)
888{
889	struct mtx_args *margs = arg;
890
891	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
892}
893
894/*
895 * Mutex initialization routine; initialize lock `m' of type contained in
896 * `opts' with options contained in `opts' and name `name.'  The optional
897 * lock type `type' is used as a general lock category name for use with
898 * witness.
899 */
900void
901mtx_init(struct mtx *m, const char *name, const char *type, int opts)
902{
903	struct lock_object *lock;
904
905	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
906	    MTX_SLEEPABLE | MTX_NOWITNESS | MTX_DUPOK)) == 0);
907
908#ifdef MUTEX_DEBUG
909	/* Diagnostic and error correction */
910	mtx_validate(m);
911#endif
912
913	lock = &m->mtx_object;
914	KASSERT((lock->lo_flags & LO_INITIALIZED) == 0,
915	    ("mutex %s %p already initialized", name, m));
916	bzero(m, sizeof(*m));
917	if (opts & MTX_SPIN)
918		lock->lo_class = &lock_class_mtx_spin;
919	else
920		lock->lo_class = &lock_class_mtx_sleep;
921	lock->lo_name = name;
922	lock->lo_type = type != NULL ? type : name;
923	if (opts & MTX_QUIET)
924		lock->lo_flags = LO_QUIET;
925	if (opts & MTX_RECURSE)
926		lock->lo_flags |= LO_RECURSABLE;
927	if (opts & MTX_SLEEPABLE)
928		lock->lo_flags |= LO_SLEEPABLE;
929	if ((opts & MTX_NOWITNESS) == 0)
930		lock->lo_flags |= LO_WITNESS;
931	if (opts & MTX_DUPOK)
932		lock->lo_flags |= LO_DUPOK;
933
934	m->mtx_lock = MTX_UNOWNED;
935	TAILQ_INIT(&m->mtx_blocked);
936
937	LOCK_LOG_INIT(lock, opts);
938
939	WITNESS_INIT(lock);
940}
941
942/*
943 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
944 * passed in as a flag here because if the corresponding mtx_init() was
945 * called with MTX_QUIET set, then it will already be set in the mutex's
946 * flags.
947 */
948void
949mtx_destroy(struct mtx *m)
950{
951
952	LOCK_LOG_DESTROY(&m->mtx_object, 0);
953
954	if (!mtx_owned(m))
955		MPASS(mtx_unowned(m));
956	else {
957		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
958
959		/* Tell witness this isn't locked to make it happy. */
960		WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
961		    __LINE__);
962	}
963
964	WITNESS_DESTROY(&m->mtx_object);
965}
966
967/*
968 * Intialize the mutex code and system mutexes.  This is called from the MD
969 * startup code prior to mi_startup().  The per-CPU data space needs to be
970 * setup before this is called.
971 */
972void
973mutex_init(void)
974{
975
976	/* Setup thread0 so that mutexes work. */
977	LIST_INIT(&thread0.td_contested);
978
979	/*
980	 * Initialize mutexes.
981	 */
982	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
983	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
984	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
985	mtx_lock(&Giant);
986}
987
988/*
989 * Encapsulated Giant mutex routines.  These routines provide encapsulation
990 * control for the Giant mutex, allowing sysctls to be used to turn on and
991 * off Giant around certain subsystems.  The default value for the sysctls
992 * are set to what developers believe is stable and working in regards to
993 * the Giant pushdown.  Developers should not turn off Giant via these
994 * sysctls unless they know what they are doing.
995 *
996 * Callers of mtx_lock_giant() are expected to pass the return value to an
997 * accompanying mtx_unlock_giant() later on.  If multiple subsystems are
998 * effected by a Giant wrap, all related sysctl variables must be zero for
999 * the subsystem call to operate without Giant (as determined by the caller).
1000 */
1001
1002SYSCTL_NODE(_kern, OID_AUTO, giant, CTLFLAG_RD, NULL, "Giant mutex manipulation");
1003
1004static int kern_giant_all = 0;
1005SYSCTL_INT(_kern_giant, OID_AUTO, all, CTLFLAG_RW, &kern_giant_all, 0, "");
1006
1007int kern_giant_proc = 1;	/* Giant around PROC locks */
1008int kern_giant_file = 1;	/* Giant around struct file & filedesc */
1009int kern_giant_ucred = 1;	/* Giant around ucred */
1010SYSCTL_INT(_kern_giant, OID_AUTO, proc, CTLFLAG_RW, &kern_giant_proc, 0, "");
1011SYSCTL_INT(_kern_giant, OID_AUTO, file, CTLFLAG_RW, &kern_giant_file, 0, "");
1012SYSCTL_INT(_kern_giant, OID_AUTO, ucred, CTLFLAG_RW, &kern_giant_ucred, 0, "");
1013
1014int
1015mtx_lock_giant(int sysctlvar)
1016{
1017	if (sysctlvar || kern_giant_all) {
1018		mtx_lock(&Giant);
1019		return(1);
1020	}
1021	return(0);
1022}
1023
1024void
1025mtx_unlock_giant(int s)
1026{
1027	if (s)
1028		mtx_unlock(&Giant);
1029}
1030
1031