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