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