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