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