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