kern_mutex.c revision 97113
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 * $FreeBSD: head/sys/kern/kern_mutex.c 97113 2002-05-22 13:19:22Z jhb $
31 */
32
33/*
34 * Machine independent bits of mutex implementation.
35 */
36
37#include "opt_adaptive_mutexes.h"
38#include "opt_ddb.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/bus.h>
43#include <sys/kernel.h>
44#include <sys/ktr.h>
45#include <sys/lock.h>
46#include <sys/malloc.h>
47#include <sys/mutex.h>
48#include <sys/proc.h>
49#include <sys/resourcevar.h>
50#include <sys/sbuf.h>
51#include <sys/sysctl.h>
52#include <sys/vmmeter.h>
53
54#include <machine/atomic.h>
55#include <machine/bus.h>
56#include <machine/clock.h>
57#include <machine/cpu.h>
58
59#include <ddb/ddb.h>
60
61#include <vm/vm.h>
62#include <vm/vm_extern.h>
63
64/*
65 * Internal utility macros.
66 */
67#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
68
69#define mtx_owner(m)	(mtx_unowned((m)) ? NULL \
70	: (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
71
72/*
73 * Lock classes for sleep and spin mutexes.
74 */
75struct lock_class lock_class_mtx_sleep = {
76	"sleep mutex",
77	LC_SLEEPLOCK | LC_RECURSABLE
78};
79struct lock_class lock_class_mtx_spin = {
80	"spin mutex",
81	LC_SPINLOCK | LC_RECURSABLE
82};
83
84/*
85 * System-wide mutexes
86 */
87struct mtx sched_lock;
88struct mtx Giant;
89
90/*
91 * Prototypes for non-exported routines.
92 */
93static void	propagate_priority(struct thread *);
94
95static void
96propagate_priority(struct thread *td)
97{
98	int pri = td->td_priority;
99	struct mtx *m = td->td_blocked;
100
101	mtx_assert(&sched_lock, MA_OWNED);
102	for (;;) {
103		struct thread *td1;
104
105		td = mtx_owner(m);
106
107		if (td == NULL) {
108			/*
109			 * This really isn't quite right. Really
110			 * ought to bump priority of thread that
111			 * next acquires the mutex.
112			 */
113			MPASS(m->mtx_lock == MTX_CONTESTED);
114			return;
115		}
116
117		MPASS(td->td_proc->p_magic == P_MAGIC);
118		KASSERT(td->td_proc->p_stat != SSLEEP, ("sleeping thread owns a mutex"));
119		if (td->td_priority <= pri) /* lower is higher priority */
120			return;
121
122		/*
123		 * Bump this thread's priority.
124		 */
125		td->td_priority = pri;
126
127		/*
128		 * If lock holder is actually running, just bump priority.
129		 */
130		 /* XXXKSE this test is not sufficient */
131		if (td->td_kse && (td->td_kse->ke_oncpu != NOCPU)) {
132			MPASS(td->td_proc->p_stat == SRUN
133			|| td->td_proc->p_stat == SZOMB
134			|| td->td_proc->p_stat == SSTOP);
135			return;
136		}
137
138#ifndef SMP
139		/*
140		 * For UP, we check to see if td is curthread (this shouldn't
141		 * ever happen however as it would mean we are in a deadlock.)
142		 */
143		KASSERT(td != curthread, ("Deadlock detected"));
144#endif
145
146		/*
147		 * If on run queue move to new run queue, and quit.
148		 * XXXKSE this gets a lot more complicated under threads
149		 * but try anyhow.
150		 */
151		if (td->td_proc->p_stat == SRUN) {
152			MPASS(td->td_blocked == NULL);
153			remrunqueue(td);
154			setrunqueue(td);
155			return;
156		}
157
158		/*
159		 * If we aren't blocked on a mutex, we should be.
160		 */
161		KASSERT(td->td_proc->p_stat == SMTX, (
162		    "process %d(%s):%d holds %s but isn't blocked on a mutex\n",
163		    td->td_proc->p_pid, td->td_proc->p_comm, td->td_proc->p_stat,
164		    m->mtx_object.lo_name));
165
166		/*
167		 * Pick up the mutex that td is blocked on.
168		 */
169		m = td->td_blocked;
170		MPASS(m != NULL);
171
172		/*
173		 * Check if the thread needs to be moved up on
174		 * the blocked chain
175		 */
176		if (td == TAILQ_FIRST(&m->mtx_blocked)) {
177			continue;
178		}
179
180		td1 = TAILQ_PREV(td, threadqueue, td_blkq);
181		if (td1->td_priority <= pri) {
182			continue;
183		}
184
185		/*
186		 * Remove thread from blocked chain and determine where
187		 * it should be moved up to.  Since we know that td1 has
188		 * a lower priority than td, we know that at least one
189		 * thread in the chain has a lower priority and that
190		 * td1 will thus not be NULL after the loop.
191		 */
192		TAILQ_REMOVE(&m->mtx_blocked, td, td_blkq);
193		TAILQ_FOREACH(td1, &m->mtx_blocked, td_blkq) {
194			MPASS(td1->td_proc->p_magic == P_MAGIC);
195			if (td1->td_priority > pri)
196				break;
197		}
198
199		MPASS(td1 != NULL);
200		TAILQ_INSERT_BEFORE(td1, td, td_blkq);
201		CTR4(KTR_LOCK,
202		    "propagate_priority: p %p moved before %p on [%p] %s",
203		    td, td1, m, m->mtx_object.lo_name);
204	}
205}
206
207#ifdef MUTEX_PROFILING
208SYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
209SYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
210static int mutex_prof_enable = 0;
211SYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
212    &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
213
214struct mutex_prof {
215	const char *name;
216	const char *file;
217	int line;
218#define MPROF_MAX 0
219#define MPROF_TOT 1
220#define MPROF_CNT 2
221#define MPROF_AVG 3
222	u_int64_t counter[4];
223	struct mutex_prof *next;
224};
225
226/*
227 * mprof_buf is a static pool of profiling records to avoid possible
228 * reentrance of the memory allocation functions.
229 *
230 * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
231 */
232#define NUM_MPROF_BUFFERS 1000
233static struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
234static int first_free_mprof_buf;
235#define MPROF_HASH_SIZE 1009
236static struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
237
238static int mutex_prof_acquisitions;
239SYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
240    &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
241static int mutex_prof_records;
242SYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
243    &mutex_prof_records, 0, "Number of profiling records");
244static int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
245SYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
246    &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
247static int mutex_prof_rejected;
248SYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
249    &mutex_prof_rejected, 0, "Number of rejected profiling records");
250static int mutex_prof_hashsize = MPROF_HASH_SIZE;
251SYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
252    &mutex_prof_hashsize, 0, "Hash size");
253static int mutex_prof_collisions = 0;
254SYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
255    &mutex_prof_collisions, 0, "Number of hash collisions");
256
257/*
258 * mprof_mtx protects the profiling buffers and the hash.
259 */
260static struct mtx mprof_mtx;
261MTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
262
263static u_int64_t
264nanoseconds(void)
265{
266	struct timespec tv;
267
268	nanotime(&tv);
269	return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
270}
271
272static int
273dump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
274{
275	struct sbuf *sb;
276	int error, i;
277
278	if (first_free_mprof_buf == 0)
279		return SYSCTL_OUT(req, "No locking recorded",
280		    sizeof("No locking recorded"));
281
282	sb = sbuf_new(NULL, NULL, 1024, SBUF_AUTOEXTEND);
283	sbuf_printf(sb, "%12s %12s %12s %12s %s\n",
284	    "max", "total", "count", "average", "name");
285	mtx_lock_spin(&mprof_mtx);
286	for (i = 0; i < first_free_mprof_buf; ++i)
287		sbuf_printf(sb, "%12llu %12llu %12llu %12llu %s:%d (%s)\n",
288		    mprof_buf[i].counter[MPROF_MAX] / 1000,
289		    mprof_buf[i].counter[MPROF_TOT] / 1000,
290		    mprof_buf[i].counter[MPROF_CNT],
291		    mprof_buf[i].counter[MPROF_AVG] / 1000,
292		    mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
293	mtx_unlock_spin(&mprof_mtx);
294	sbuf_finish(sb);
295	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
296	sbuf_delete(sb);
297	return (error);
298}
299SYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING|CTLFLAG_RD,
300    NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
301#endif
302
303/*
304 * Function versions of the inlined __mtx_* macros.  These are used by
305 * modules and can also be called from assembly language if needed.
306 */
307void
308_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
309{
310
311	MPASS(curthread != NULL);
312	_get_sleep_lock(m, curthread, opts, file, line);
313	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
314	    line);
315	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
316#ifdef MUTEX_PROFILING
317	/* don't reset the timer when/if recursing */
318	if (m->acqtime == 0) {
319		m->file = file;
320		m->line = line;
321		m->acqtime = mutex_prof_enable ? nanoseconds() : 0;
322		++mutex_prof_acquisitions;
323	}
324#endif
325}
326
327void
328_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
329{
330
331	MPASS(curthread != NULL);
332	mtx_assert(m, MA_OWNED);
333#ifdef MUTEX_PROFILING
334	if (m->acqtime != 0) {
335		static const char *unknown = "(unknown)";
336		struct mutex_prof *mpp;
337		u_int64_t acqtime, now;
338		const char *p, *q;
339		volatile u_int hash;
340
341		now = nanoseconds();
342		acqtime = m->acqtime;
343		m->acqtime = 0;
344		if (now <= acqtime)
345			goto out;
346		for (p = file; strncmp(p, "../", 3) == 0; p += 3)
347			/* nothing */ ;
348		if (p == NULL || *p == '\0')
349			p = unknown;
350		for (hash = line, q = p; *q != '\0'; ++q)
351			hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
352		mtx_lock_spin(&mprof_mtx);
353		for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
354			if (mpp->line == line && strcmp(mpp->file, p) == 0)
355				break;
356		if (mpp == NULL) {
357			/* Just exit if we cannot get a trace buffer */
358			if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
359				++mutex_prof_rejected;
360				goto unlock;
361			}
362			mpp = &mprof_buf[first_free_mprof_buf++];
363			mpp->name = mtx_name(m);
364			mpp->file = p;
365			mpp->line = line;
366			mpp->next = mprof_hash[hash];
367			if (mprof_hash[hash] != NULL)
368				++mutex_prof_collisions;
369			mprof_hash[hash] = mpp;
370			++mutex_prof_records;
371		}
372		/*
373		 * Record if the mutex has been held longer now than ever
374		 * before
375		 */
376		if ((now - acqtime) > mpp->counter[MPROF_MAX])
377			mpp->counter[MPROF_MAX] = now - acqtime;
378		mpp->counter[MPROF_TOT] += now - acqtime;
379		mpp->counter[MPROF_CNT] += 1;
380		mpp->counter[MPROF_AVG] =
381		    mpp->counter[MPROF_TOT] / mpp->counter[MPROF_CNT];
382unlock:
383		mtx_unlock_spin(&mprof_mtx);
384	}
385out:
386#endif
387 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
388	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
389	    line);
390	_rel_sleep_lock(m, curthread, opts, file, line);
391}
392
393void
394_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
395{
396
397	MPASS(curthread != NULL);
398#if defined(SMP) || LOCK_DEBUG > 0
399	_get_spin_lock(m, curthread, opts, file, line);
400#else
401	critical_enter();
402#endif
403	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
404	    line);
405	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
406}
407
408void
409_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
410{
411
412	MPASS(curthread != NULL);
413	mtx_assert(m, MA_OWNED);
414 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
415	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
416	    line);
417#if defined(SMP) || LOCK_DEBUG > 0
418	_rel_spin_lock(m);
419#else
420	critical_exit();
421#endif
422}
423
424/*
425 * The important part of mtx_trylock{,_flags}()
426 * Tries to acquire lock `m.' We do NOT handle recursion here; we assume that
427 * if we're called, it's because we know we don't already own this lock.
428 */
429int
430_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
431{
432	int rval;
433
434	MPASS(curthread != NULL);
435
436	rval = _obtain_lock(m, curthread);
437
438	LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
439	if (rval) {
440		/*
441		 * We do not handle recursion in _mtx_trylock; see the
442		 * note at the top of the routine.
443		 */
444		KASSERT(!mtx_recursed(m),
445		    ("mtx_trylock() called on a recursed mutex"));
446		WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
447		    file, line);
448	}
449
450	return (rval);
451}
452
453/*
454 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
455 *
456 * We call this if the lock is either contested (i.e. we need to go to
457 * sleep waiting for it), or if we need to recurse on it.
458 */
459void
460_mtx_lock_sleep(struct mtx *m, int opts, const char *file, int line)
461{
462	struct thread *td = curthread;
463#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
464	struct thread *owner;
465#endif
466
467	if ((m->mtx_lock & MTX_FLAGMASK) == (uintptr_t)td) {
468		m->mtx_recurse++;
469		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
470		if (LOCK_LOG_TEST(&m->mtx_object, opts))
471			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
472		return;
473	}
474
475	if (LOCK_LOG_TEST(&m->mtx_object, opts))
476		CTR4(KTR_LOCK,
477		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
478		    m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
479
480	while (!_obtain_lock(m, td)) {
481		uintptr_t v;
482		struct thread *td1;
483
484		mtx_lock_spin(&sched_lock);
485		/*
486		 * Check if the lock has been released while spinning for
487		 * the sched_lock.
488		 */
489		if ((v = m->mtx_lock) == MTX_UNOWNED) {
490			mtx_unlock_spin(&sched_lock);
491#ifdef __i386__
492			pause();
493#endif
494			continue;
495		}
496
497		/*
498		 * The mutex was marked contested on release. This means that
499		 * there are threads blocked on it.
500		 */
501		if (v == MTX_CONTESTED) {
502			td1 = TAILQ_FIRST(&m->mtx_blocked);
503			MPASS(td1 != NULL);
504			m->mtx_lock = (uintptr_t)td | MTX_CONTESTED;
505
506			if (td1->td_priority < td->td_priority)
507				td->td_priority = td1->td_priority;
508			mtx_unlock_spin(&sched_lock);
509			return;
510		}
511
512		/*
513		 * If the mutex isn't already contested and a failure occurs
514		 * setting the contested bit, the mutex was either released
515		 * or the state of the MTX_RECURSED bit changed.
516		 */
517		if ((v & MTX_CONTESTED) == 0 &&
518		    !atomic_cmpset_ptr(&m->mtx_lock, (void *)v,
519			(void *)(v | MTX_CONTESTED))) {
520			mtx_unlock_spin(&sched_lock);
521#ifdef __i386__
522			pause();
523#endif
524			continue;
525		}
526
527#if defined(SMP) && defined(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		if (m != &Giant && owner->td_kse != NULL &&
534		    owner->td_kse->ke_oncpu != NOCPU) {
535			mtx_unlock_spin(&sched_lock);
536#ifdef __i386__
537			pause();
538#endif
539			continue;
540		}
541#endif	/* SMP && ADAPTIVE_MUTEXES */
542
543		/*
544		 * We definitely must sleep for this lock.
545		 */
546		mtx_assert(m, MA_NOTOWNED);
547
548#ifdef notyet
549		/*
550		 * If we're borrowing an interrupted thread's VM context, we
551		 * must clean up before going to sleep.
552		 */
553		if (td->td_ithd != NULL) {
554			struct ithd *it = td->td_ithd;
555
556			if (it->it_interrupted) {
557				if (LOCK_LOG_TEST(&m->mtx_object, opts))
558					CTR2(KTR_LOCK,
559				    "_mtx_lock_sleep: %p interrupted %p",
560					    it, it->it_interrupted);
561				intr_thd_fixup(it);
562			}
563		}
564#endif
565
566		/*
567		 * Put us on the list of threads blocked on this mutex.
568		 */
569		if (TAILQ_EMPTY(&m->mtx_blocked)) {
570			td1 = mtx_owner(m);
571			LIST_INSERT_HEAD(&td1->td_contested, m, mtx_contested);
572			TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_blkq);
573		} else {
574			TAILQ_FOREACH(td1, &m->mtx_blocked, td_blkq)
575				if (td1->td_priority > td->td_priority)
576					break;
577			if (td1)
578				TAILQ_INSERT_BEFORE(td1, td, td_blkq);
579			else
580				TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_blkq);
581		}
582
583		/*
584		 * Save who we're blocked on.
585		 */
586		td->td_blocked = m;
587		td->td_mtxname = m->mtx_object.lo_name;
588		td->td_proc->p_stat = SMTX;
589		propagate_priority(td);
590
591		if (LOCK_LOG_TEST(&m->mtx_object, opts))
592			CTR3(KTR_LOCK,
593			    "_mtx_lock_sleep: p %p blocked on [%p] %s", td, m,
594			    m->mtx_object.lo_name);
595
596		td->td_proc->p_stats->p_ru.ru_nvcsw++;
597		mi_switch();
598
599		if (LOCK_LOG_TEST(&m->mtx_object, opts))
600			CTR3(KTR_LOCK,
601			  "_mtx_lock_sleep: p %p free from blocked on [%p] %s",
602			  td, m, m->mtx_object.lo_name);
603
604		mtx_unlock_spin(&sched_lock);
605	}
606
607	return;
608}
609
610/*
611 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
612 *
613 * This is only called if we need to actually spin for the lock. Recursion
614 * is handled inline.
615 */
616void
617_mtx_lock_spin(struct mtx *m, int opts, const char *file, int line)
618{
619	int i = 0;
620
621	if (LOCK_LOG_TEST(&m->mtx_object, opts))
622		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
623
624	for (;;) {
625		if (_obtain_lock(m, curthread))
626			break;
627
628		/* Give interrupts a chance while we spin. */
629		critical_exit();
630		while (m->mtx_lock != MTX_UNOWNED) {
631			if (i++ < 10000000) {
632#ifdef __i386__
633				pause();
634#endif
635				continue;
636			}
637			if (i < 60000000)
638				DELAY(1);
639#ifdef DDB
640			else if (!db_active)
641#else
642			else
643#endif
644				panic("spin lock %s held by %p for > 5 seconds",
645				    m->mtx_object.lo_name, (void *)m->mtx_lock);
646#ifdef __i386__
647			pause();
648#endif
649		}
650		critical_enter();
651	}
652
653	if (LOCK_LOG_TEST(&m->mtx_object, opts))
654		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
655
656	return;
657}
658
659/*
660 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
661 *
662 * We are only called here if the lock is recursed or contested (i.e. we
663 * need to wake up a blocked thread).
664 */
665void
666_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
667{
668	struct thread *td, *td1;
669	struct mtx *m1;
670	int pri;
671
672	td = curthread;
673
674	if (mtx_recursed(m)) {
675		if (--(m->mtx_recurse) == 0)
676			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
677		if (LOCK_LOG_TEST(&m->mtx_object, opts))
678			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
679		return;
680	}
681
682	mtx_lock_spin(&sched_lock);
683	if (LOCK_LOG_TEST(&m->mtx_object, opts))
684		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
685
686	td1 = TAILQ_FIRST(&m->mtx_blocked);
687#if defined(SMP) && defined(ADAPTIVE_MUTEXES)
688	if (td1 == NULL) {
689		_release_lock_quick(m);
690		if (LOCK_LOG_TEST(&m->mtx_object, opts))
691			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
692		mtx_unlock_spin(&sched_lock);
693		return;
694	}
695#endif
696	MPASS(td->td_proc->p_magic == P_MAGIC);
697	MPASS(td1->td_proc->p_magic == P_MAGIC);
698
699	TAILQ_REMOVE(&m->mtx_blocked, td1, td_blkq);
700
701	if (TAILQ_EMPTY(&m->mtx_blocked)) {
702		LIST_REMOVE(m, mtx_contested);
703		_release_lock_quick(m);
704		if (LOCK_LOG_TEST(&m->mtx_object, opts))
705			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
706	} else
707		atomic_store_rel_ptr(&m->mtx_lock, (void *)MTX_CONTESTED);
708
709	pri = PRI_MAX;
710	LIST_FOREACH(m1, &td->td_contested, mtx_contested) {
711		int cp = TAILQ_FIRST(&m1->mtx_blocked)->td_priority;
712		if (cp < pri)
713			pri = cp;
714	}
715
716	if (pri > td->td_base_pri)
717		pri = td->td_base_pri;
718	td->td_priority = pri;
719
720	if (LOCK_LOG_TEST(&m->mtx_object, opts))
721		CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p contested setrunqueue %p",
722		    m, td1);
723
724	td1->td_blocked = NULL;
725	td1->td_proc->p_stat = SRUN;
726	setrunqueue(td1);
727
728	if (td->td_critnest == 1 && td1->td_priority < pri) {
729#ifdef notyet
730		if (td->td_ithd != NULL) {
731			struct ithd *it = td->td_ithd;
732
733			if (it->it_interrupted) {
734				if (LOCK_LOG_TEST(&m->mtx_object, opts))
735					CTR2(KTR_LOCK,
736				    "_mtx_unlock_sleep: %p interrupted %p",
737					    it, it->it_interrupted);
738				intr_thd_fixup(it);
739			}
740		}
741#endif
742		setrunqueue(td);
743		if (LOCK_LOG_TEST(&m->mtx_object, opts))
744			CTR2(KTR_LOCK,
745			    "_mtx_unlock_sleep: %p switching out lock=%p", m,
746			    (void *)m->mtx_lock);
747
748		td->td_proc->p_stats->p_ru.ru_nivcsw++;
749		mi_switch();
750		if (LOCK_LOG_TEST(&m->mtx_object, opts))
751			CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
752			    m, (void *)m->mtx_lock);
753	}
754
755	mtx_unlock_spin(&sched_lock);
756
757	return;
758}
759
760/*
761 * All the unlocking of MTX_SPIN locks is done inline.
762 * See the _rel_spin_lock() macro for the details.
763 */
764
765/*
766 * The backing function for the INVARIANTS-enabled mtx_assert()
767 */
768#ifdef INVARIANT_SUPPORT
769void
770_mtx_assert(struct mtx *m, int what, const char *file, int line)
771{
772
773	if (panicstr != NULL)
774		return;
775	switch (what) {
776	case MA_OWNED:
777	case MA_OWNED | MA_RECURSED:
778	case MA_OWNED | MA_NOTRECURSED:
779		if (!mtx_owned(m))
780			panic("mutex %s not owned at %s:%d",
781			    m->mtx_object.lo_name, file, line);
782		if (mtx_recursed(m)) {
783			if ((what & MA_NOTRECURSED) != 0)
784				panic("mutex %s recursed at %s:%d",
785				    m->mtx_object.lo_name, file, line);
786		} else if ((what & MA_RECURSED) != 0) {
787			panic("mutex %s unrecursed at %s:%d",
788			    m->mtx_object.lo_name, file, line);
789		}
790		break;
791	case MA_NOTOWNED:
792		if (mtx_owned(m))
793			panic("mutex %s owned at %s:%d",
794			    m->mtx_object.lo_name, file, line);
795		break;
796	default:
797		panic("unknown mtx_assert at %s:%d", file, line);
798	}
799}
800#endif
801
802/*
803 * The MUTEX_DEBUG-enabled mtx_validate()
804 *
805 * Most of these checks have been moved off into the LO_INITIALIZED flag
806 * maintained by the witness code.
807 */
808#ifdef MUTEX_DEBUG
809
810void	mtx_validate(struct mtx *);
811
812void
813mtx_validate(struct mtx *m)
814{
815
816/*
817 * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
818 * we can re-enable the kernacc() checks.
819 */
820#ifndef __alpha__
821	/*
822	 * Can't call kernacc() from early init386(), especially when
823	 * initializing Giant mutex, because some stuff in kernacc()
824	 * requires Giant itself.
825	 */
826	if (!cold)
827		if (!kernacc((caddr_t)m, sizeof(m),
828		    VM_PROT_READ | VM_PROT_WRITE))
829			panic("Can't read and write to mutex %p", m);
830#endif
831}
832#endif
833
834/*
835 * General init routine used by the MTX_SYSINIT() macro.
836 */
837void
838mtx_sysinit(void *arg)
839{
840	struct mtx_args *margs = arg;
841
842	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
843}
844
845/*
846 * Mutex initialization routine; initialize lock `m' of type contained in
847 * `opts' with options contained in `opts' and name `name.'  The optional
848 * lock type `type' is used as a general lock category name for use with
849 * witness.
850 */
851void
852mtx_init(struct mtx *m, const char *name, const char *type, int opts)
853{
854	struct lock_object *lock;
855
856	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
857	    MTX_SLEEPABLE | MTX_NOWITNESS | MTX_DUPOK)) == 0);
858
859#ifdef MUTEX_DEBUG
860	/* Diagnostic and error correction */
861	mtx_validate(m);
862#endif
863
864	lock = &m->mtx_object;
865	KASSERT((lock->lo_flags & LO_INITIALIZED) == 0,
866	    ("mutex %s %p already initialized", name, m));
867	bzero(m, sizeof(*m));
868	if (opts & MTX_SPIN)
869		lock->lo_class = &lock_class_mtx_spin;
870	else
871		lock->lo_class = &lock_class_mtx_sleep;
872	lock->lo_name = name;
873	lock->lo_type = type != NULL ? type : name;
874	if (opts & MTX_QUIET)
875		lock->lo_flags = LO_QUIET;
876	if (opts & MTX_RECURSE)
877		lock->lo_flags |= LO_RECURSABLE;
878	if (opts & MTX_SLEEPABLE)
879		lock->lo_flags |= LO_SLEEPABLE;
880	if ((opts & MTX_NOWITNESS) == 0)
881		lock->lo_flags |= LO_WITNESS;
882	if (opts & MTX_DUPOK)
883		lock->lo_flags |= LO_DUPOK;
884
885	m->mtx_lock = MTX_UNOWNED;
886	TAILQ_INIT(&m->mtx_blocked);
887
888	LOCK_LOG_INIT(lock, opts);
889
890	WITNESS_INIT(lock);
891}
892
893/*
894 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
895 * passed in as a flag here because if the corresponding mtx_init() was
896 * called with MTX_QUIET set, then it will already be set in the mutex's
897 * flags.
898 */
899void
900mtx_destroy(struct mtx *m)
901{
902
903	LOCK_LOG_DESTROY(&m->mtx_object, 0);
904
905	if (!mtx_owned(m))
906		MPASS(mtx_unowned(m));
907	else {
908		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
909
910		/* Tell witness this isn't locked to make it happy. */
911		WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
912		    __LINE__);
913	}
914
915	WITNESS_DESTROY(&m->mtx_object);
916}
917
918/*
919 * Intialize the mutex code and system mutexes.  This is called from the MD
920 * startup code prior to mi_startup().  The per-CPU data space needs to be
921 * setup before this is called.
922 */
923void
924mutex_init(void)
925{
926
927	/* Setup thread0 so that mutexes work. */
928	LIST_INIT(&thread0.td_contested);
929
930	/*
931	 * Initialize mutexes.
932	 */
933	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
934	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
935	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
936	mtx_lock(&Giant);
937}
938
939/*
940 * Encapsulated Giant mutex routines.  These routines provide encapsulation
941 * control for the Giant mutex, allowing sysctls to be used to turn on and
942 * off Giant around certain subsystems.  The default value for the sysctls
943 * are set to what developers believe is stable and working in regards to
944 * the Giant pushdown.  Developers should not turn off Giant via these
945 * sysctls unless they know what they are doing.
946 *
947 * Callers of mtx_lock_giant() are expected to pass the return value to an
948 * accompanying mtx_unlock_giant() later on.  If multiple subsystems are
949 * effected by a Giant wrap, all related sysctl variables must be zero for
950 * the subsystem call to operate without Giant (as determined by the caller).
951 */
952
953SYSCTL_NODE(_kern, OID_AUTO, giant, CTLFLAG_RD, NULL, "Giant mutex manipulation");
954
955static int kern_giant_all = 0;
956SYSCTL_INT(_kern_giant, OID_AUTO, all, CTLFLAG_RW, &kern_giant_all, 0, "");
957
958int kern_giant_proc = 1;	/* Giant around PROC locks */
959int kern_giant_file = 1;	/* Giant around struct file & filedesc */
960int kern_giant_ucred = 1;	/* Giant around ucred */
961SYSCTL_INT(_kern_giant, OID_AUTO, proc, CTLFLAG_RW, &kern_giant_proc, 0, "");
962SYSCTL_INT(_kern_giant, OID_AUTO, file, CTLFLAG_RW, &kern_giant_file, 0, "");
963SYSCTL_INT(_kern_giant, OID_AUTO, ucred, CTLFLAG_RW, &kern_giant_ucred, 0, "");
964
965int
966mtx_lock_giant(int sysctlvar)
967{
968	if (sysctlvar || kern_giant_all) {
969		mtx_lock(&Giant);
970		return(1);
971	}
972	return(0);
973}
974
975void
976mtx_unlock_giant(int s)
977{
978	if (s)
979		mtx_unlock(&Giant);
980}
981
982