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