]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_mutex.c
Implement trivial backoff for locking primitives.
[FreeBSD/FreeBSD.git] / sys / kern / kern_mutex.c
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 #include "opt_hwpmc_hooks.h"
42 #include "opt_sched.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bus.h>
47 #include <sys/conf.h>
48 #include <sys/kdb.h>
49 #include <sys/kernel.h>
50 #include <sys/ktr.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sched.h>
57 #include <sys/sbuf.h>
58 #include <sys/smp.h>
59 #include <sys/sysctl.h>
60 #include <sys/turnstile.h>
61 #include <sys/vmmeter.h>
62 #include <sys/lock_profile.h>
63
64 #include <machine/atomic.h>
65 #include <machine/bus.h>
66 #include <machine/cpu.h>
67
68 #include <ddb/ddb.h>
69
70 #include <fs/devfs/devfs_int.h>
71
72 #include <vm/vm.h>
73 #include <vm/vm_extern.h>
74
75 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
76 #define ADAPTIVE_MUTEXES
77 #endif
78
79 #ifdef HWPMC_HOOKS
80 #include <sys/pmckern.h>
81 PMC_SOFT_DEFINE( , , lock, failed);
82 #endif
83
84 /*
85  * Return the mutex address when the lock cookie address is provided.
86  * This functionality assumes that struct mtx* have a member named mtx_lock.
87  */
88 #define mtxlock2mtx(c)  (__containerof(c, struct mtx, mtx_lock))
89
90 /*
91  * Internal utility macros.
92  */
93 #define mtx_unowned(m)  ((m)->mtx_lock == MTX_UNOWNED)
94
95 #define mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
96
97 #define mtx_owner(m)    ((struct thread *)((m)->mtx_lock & ~MTX_FLAGMASK))
98
99 static void     assert_mtx(const struct lock_object *lock, int what);
100 #ifdef DDB
101 static void     db_show_mtx(const struct lock_object *lock);
102 #endif
103 static void     lock_mtx(struct lock_object *lock, uintptr_t how);
104 static void     lock_spin(struct lock_object *lock, uintptr_t how);
105 #ifdef KDTRACE_HOOKS
106 static int      owner_mtx(const struct lock_object *lock,
107                     struct thread **owner);
108 #endif
109 static uintptr_t unlock_mtx(struct lock_object *lock);
110 static uintptr_t unlock_spin(struct lock_object *lock);
111
112 /*
113  * Lock classes for sleep and spin mutexes.
114  */
115 struct lock_class lock_class_mtx_sleep = {
116         .lc_name = "sleep mutex",
117         .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
118         .lc_assert = assert_mtx,
119 #ifdef DDB
120         .lc_ddb_show = db_show_mtx,
121 #endif
122         .lc_lock = lock_mtx,
123         .lc_unlock = unlock_mtx,
124 #ifdef KDTRACE_HOOKS
125         .lc_owner = owner_mtx,
126 #endif
127 };
128 struct lock_class lock_class_mtx_spin = {
129         .lc_name = "spin mutex",
130         .lc_flags = LC_SPINLOCK | LC_RECURSABLE,
131         .lc_assert = assert_mtx,
132 #ifdef DDB
133         .lc_ddb_show = db_show_mtx,
134 #endif
135         .lc_lock = lock_spin,
136         .lc_unlock = unlock_spin,
137 #ifdef KDTRACE_HOOKS
138         .lc_owner = owner_mtx,
139 #endif
140 };
141
142 #ifdef ADAPTIVE_MUTEXES
143 static SYSCTL_NODE(_debug, OID_AUTO, mtx, CTLFLAG_RD, NULL, "mtx debugging");
144
145 static struct lock_delay_config mtx_delay = {
146         .initial        = 1000,
147         .step           = 500,
148         .min            = 100,
149         .max            = 5000,
150 };
151
152 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_initial, CTLFLAG_RW, &mtx_delay.initial,
153     0, "");
154 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_step, CTLFLAG_RW, &mtx_delay.step,
155     0, "");
156 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_min, CTLFLAG_RW, &mtx_delay.min,
157     0, "");
158 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_max, CTLFLAG_RW, &mtx_delay.max,
159     0, "");
160
161 static void
162 mtx_delay_sysinit(void *dummy)
163 {
164
165         mtx_delay.initial = mp_ncpus * 25;
166         mtx_delay.step = (mp_ncpus * 25) / 2;
167         mtx_delay.min = mp_ncpus * 5;
168         mtx_delay.max = mp_ncpus * 25 * 10;
169 }
170 LOCK_DELAY_SYSINIT(mtx_delay_sysinit);
171 #endif
172
173 /*
174  * System-wide mutexes
175  */
176 struct mtx blocked_lock;
177 struct mtx Giant;
178
179 void
180 assert_mtx(const struct lock_object *lock, int what)
181 {
182
183         mtx_assert((const struct mtx *)lock, what);
184 }
185
186 void
187 lock_mtx(struct lock_object *lock, uintptr_t how)
188 {
189
190         mtx_lock((struct mtx *)lock);
191 }
192
193 void
194 lock_spin(struct lock_object *lock, uintptr_t how)
195 {
196
197         panic("spin locks can only use msleep_spin");
198 }
199
200 uintptr_t
201 unlock_mtx(struct lock_object *lock)
202 {
203         struct mtx *m;
204
205         m = (struct mtx *)lock;
206         mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
207         mtx_unlock(m);
208         return (0);
209 }
210
211 uintptr_t
212 unlock_spin(struct lock_object *lock)
213 {
214
215         panic("spin locks can only use msleep_spin");
216 }
217
218 #ifdef KDTRACE_HOOKS
219 int
220 owner_mtx(const struct lock_object *lock, struct thread **owner)
221 {
222         const struct mtx *m = (const struct mtx *)lock;
223
224         *owner = mtx_owner(m);
225         return (mtx_unowned(m) == 0);
226 }
227 #endif
228
229 /*
230  * Function versions of the inlined __mtx_* macros.  These are used by
231  * modules and can also be called from assembly language if needed.
232  */
233 void
234 __mtx_lock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
235 {
236         struct mtx *m;
237
238         if (SCHEDULER_STOPPED())
239                 return;
240
241         m = mtxlock2mtx(c);
242
243         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
244             ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
245             curthread, m->lock_object.lo_name, file, line));
246         KASSERT(m->mtx_lock != MTX_DESTROYED,
247             ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
248         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
249             ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
250             file, line));
251         WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
252             LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
253
254         __mtx_lock(m, curthread, opts, file, line);
255         LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
256             line);
257         WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
258             file, line);
259         TD_LOCKS_INC(curthread);
260 }
261
262 void
263 __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
264 {
265         struct mtx *m;
266
267         if (SCHEDULER_STOPPED())
268                 return;
269
270         m = mtxlock2mtx(c);
271
272         KASSERT(m->mtx_lock != MTX_DESTROYED,
273             ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
274         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
275             ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
276             file, line));
277         WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
278         LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
279             line);
280         mtx_assert(m, MA_OWNED);
281
282         __mtx_unlock(m, curthread, opts, file, line);
283         TD_LOCKS_DEC(curthread);
284 }
285
286 void
287 __mtx_lock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
288     int line)
289 {
290         struct mtx *m;
291
292         if (SCHEDULER_STOPPED())
293                 return;
294
295         m = mtxlock2mtx(c);
296
297         KASSERT(m->mtx_lock != MTX_DESTROYED,
298             ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
299         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
300             ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
301             m->lock_object.lo_name, file, line));
302         if (mtx_owned(m))
303                 KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
304                     (opts & MTX_RECURSE) != 0,
305             ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
306                     m->lock_object.lo_name, file, line));
307         opts &= ~MTX_RECURSE;
308         WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
309             file, line, NULL);
310         __mtx_lock_spin(m, curthread, opts, file, line);
311         LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
312             line);
313         WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
314 }
315
316 int
317 __mtx_trylock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
318     int line)
319 {
320         struct mtx *m;
321
322         if (SCHEDULER_STOPPED())
323                 return (1);
324
325         m = mtxlock2mtx(c);
326
327         KASSERT(m->mtx_lock != MTX_DESTROYED,
328             ("mtx_trylock_spin() of destroyed mutex @ %s:%d", file, line));
329         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
330             ("mtx_trylock_spin() of sleep mutex %s @ %s:%d",
331             m->lock_object.lo_name, file, line));
332         KASSERT((opts & MTX_RECURSE) == 0,
333             ("mtx_trylock_spin: unsupp. opt MTX_RECURSE on mutex %s @ %s:%d\n",
334             m->lock_object.lo_name, file, line));
335         if (__mtx_trylock_spin(m, curthread, opts, file, line)) {
336                 LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 1, file, line);
337                 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
338                 return (1);
339         }
340         LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 0, file, line);
341         return (0);
342 }
343
344 void
345 __mtx_unlock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
346     int line)
347 {
348         struct mtx *m;
349
350         if (SCHEDULER_STOPPED())
351                 return;
352
353         m = mtxlock2mtx(c);
354
355         KASSERT(m->mtx_lock != MTX_DESTROYED,
356             ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
357         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
358             ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
359             m->lock_object.lo_name, file, line));
360         WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
361         LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
362             line);
363         mtx_assert(m, MA_OWNED);
364
365         __mtx_unlock_spin(m);
366 }
367
368 /*
369  * The important part of mtx_trylock{,_flags}()
370  * Tries to acquire lock `m.'  If this function is called on a mutex that
371  * is already owned, it will recursively acquire the lock.
372  */
373 int
374 _mtx_trylock_flags_(volatile uintptr_t *c, int opts, const char *file, int line)
375 {
376         struct mtx *m;
377 #ifdef LOCK_PROFILING
378         uint64_t waittime = 0;
379         int contested = 0;
380 #endif
381         int rval;
382
383         if (SCHEDULER_STOPPED())
384                 return (1);
385
386         m = mtxlock2mtx(c);
387
388         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
389             ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
390             curthread, m->lock_object.lo_name, file, line));
391         KASSERT(m->mtx_lock != MTX_DESTROYED,
392             ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
393         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
394             ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
395             file, line));
396
397         if (mtx_owned(m) && ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
398             (opts & MTX_RECURSE) != 0)) {
399                 m->mtx_recurse++;
400                 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
401                 rval = 1;
402         } else
403                 rval = _mtx_obtain_lock(m, (uintptr_t)curthread);
404         opts &= ~MTX_RECURSE;
405
406         LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
407         if (rval) {
408                 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
409                     file, line);
410                 TD_LOCKS_INC(curthread);
411                 if (m->mtx_recurse == 0)
412                         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
413                             m, contested, waittime, file, line);
414
415         }
416
417         return (rval);
418 }
419
420 /*
421  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
422  *
423  * We call this if the lock is either contested (i.e. we need to go to
424  * sleep waiting for it), or if we need to recurse on it.
425  */
426 void
427 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t tid, int opts,
428     const char *file, int line)
429 {
430         struct mtx *m;
431         struct turnstile *ts;
432         uintptr_t v;
433 #ifdef ADAPTIVE_MUTEXES
434         volatile struct thread *owner;
435 #endif
436 #ifdef KTR
437         int cont_logged = 0;
438 #endif
439 #ifdef LOCK_PROFILING
440         int contested = 0;
441         uint64_t waittime = 0;
442 #endif
443 #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
444         struct lock_delay_arg lda;
445 #endif
446 #ifdef KDTRACE_HOOKS
447         u_int sleep_cnt = 0;
448         int64_t sleep_time = 0;
449         int64_t all_time = 0;
450 #endif
451
452         if (SCHEDULER_STOPPED())
453                 return;
454
455 #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
456         lock_delay_arg_init(&lda, &mtx_delay);
457 #endif
458         m = mtxlock2mtx(c);
459
460         if (mtx_owned(m)) {
461                 KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
462                     (opts & MTX_RECURSE) != 0,
463             ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
464                     m->lock_object.lo_name, file, line));
465                 opts &= ~MTX_RECURSE;
466                 m->mtx_recurse++;
467                 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
468                 if (LOCK_LOG_TEST(&m->lock_object, opts))
469                         CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
470                 return;
471         }
472         opts &= ~MTX_RECURSE;
473
474 #ifdef HWPMC_HOOKS
475         PMC_SOFT_CALL( , , lock, failed);
476 #endif
477         lock_profile_obtain_lock_failed(&m->lock_object,
478                     &contested, &waittime);
479         if (LOCK_LOG_TEST(&m->lock_object, opts))
480                 CTR4(KTR_LOCK,
481                     "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
482                     m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
483 #ifdef KDTRACE_HOOKS
484         all_time -= lockstat_nsecs(&m->lock_object);
485 #endif
486
487         for (;;) {
488                 if (m->mtx_lock == MTX_UNOWNED && _mtx_obtain_lock(m, tid))
489                         break;
490 #ifdef KDTRACE_HOOKS
491                 lda.spin_cnt++;
492 #endif
493 #ifdef ADAPTIVE_MUTEXES
494                 /*
495                  * If the owner is running on another CPU, spin until the
496                  * owner stops running or the state of the lock changes.
497                  */
498                 v = m->mtx_lock;
499                 if (v != MTX_UNOWNED) {
500                         owner = (struct thread *)(v & ~MTX_FLAGMASK);
501                         if (TD_IS_RUNNING(owner)) {
502                                 if (LOCK_LOG_TEST(&m->lock_object, 0))
503                                         CTR3(KTR_LOCK,
504                                             "%s: spinning on %p held by %p",
505                                             __func__, m, owner);
506                                 KTR_STATE1(KTR_SCHED, "thread",
507                                     sched_tdname((struct thread *)tid),
508                                     "spinning", "lockname:\"%s\"",
509                                     m->lock_object.lo_name);
510                                 while (mtx_owner(m) == owner &&
511                                     TD_IS_RUNNING(owner))
512                                         lock_delay(&lda);
513                                 KTR_STATE0(KTR_SCHED, "thread",
514                                     sched_tdname((struct thread *)tid),
515                                     "running");
516                                 continue;
517                         }
518                 }
519 #endif
520
521                 ts = turnstile_trywait(&m->lock_object);
522                 v = m->mtx_lock;
523
524                 /*
525                  * Check if the lock has been released while spinning for
526                  * the turnstile chain lock.
527                  */
528                 if (v == MTX_UNOWNED) {
529                         turnstile_cancel(ts);
530                         continue;
531                 }
532
533 #ifdef ADAPTIVE_MUTEXES
534                 /*
535                  * The current lock owner might have started executing
536                  * on another CPU (or the lock could have changed
537                  * owners) while we were waiting on the turnstile
538                  * chain lock.  If so, drop the turnstile lock and try
539                  * again.
540                  */
541                 owner = (struct thread *)(v & ~MTX_FLAGMASK);
542                 if (TD_IS_RUNNING(owner)) {
543                         turnstile_cancel(ts);
544                         continue;
545                 }
546 #endif
547
548                 /*
549                  * If the mutex isn't already contested and a failure occurs
550                  * setting the contested bit, the mutex was either released
551                  * or the state of the MTX_RECURSED bit changed.
552                  */
553                 if ((v & MTX_CONTESTED) == 0 &&
554                     !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
555                         turnstile_cancel(ts);
556                         continue;
557                 }
558
559                 /*
560                  * We definitely must sleep for this lock.
561                  */
562                 mtx_assert(m, MA_NOTOWNED);
563
564 #ifdef KTR
565                 if (!cont_logged) {
566                         CTR6(KTR_CONTENTION,
567                             "contention: %p at %s:%d wants %s, taken by %s:%d",
568                             (void *)tid, file, line, m->lock_object.lo_name,
569                             WITNESS_FILE(&m->lock_object),
570                             WITNESS_LINE(&m->lock_object));
571                         cont_logged = 1;
572                 }
573 #endif
574
575                 /*
576                  * Block on the turnstile.
577                  */
578 #ifdef KDTRACE_HOOKS
579                 sleep_time -= lockstat_nsecs(&m->lock_object);
580 #endif
581                 turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
582 #ifdef KDTRACE_HOOKS
583                 sleep_time += lockstat_nsecs(&m->lock_object);
584                 sleep_cnt++;
585 #endif
586         }
587 #ifdef KDTRACE_HOOKS
588         all_time += lockstat_nsecs(&m->lock_object);
589 #endif
590 #ifdef KTR
591         if (cont_logged) {
592                 CTR4(KTR_CONTENTION,
593                     "contention end: %s acquired by %p at %s:%d",
594                     m->lock_object.lo_name, (void *)tid, file, line);
595         }
596 #endif
597         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
598             waittime, file, line);
599 #ifdef KDTRACE_HOOKS
600         if (sleep_time)
601                 LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
602
603         /*
604          * Only record the loops spinning and not sleeping. 
605          */
606         if (lda.spin_cnt > sleep_cnt)
607                 LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
608 #endif
609 }
610
611 static void
612 _mtx_lock_spin_failed(struct mtx *m)
613 {
614         struct thread *td;
615
616         td = mtx_owner(m);
617
618         /* If the mutex is unlocked, try again. */
619         if (td == NULL)
620                 return;
621
622         printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
623             m, m->lock_object.lo_name, td, td->td_tid);
624 #ifdef WITNESS
625         witness_display_spinlock(&m->lock_object, td, printf);
626 #endif
627         panic("spin lock held too long");
628 }
629
630 #ifdef SMP
631 /*
632  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
633  *
634  * This is only called if we need to actually spin for the lock. Recursion
635  * is handled inline.
636  */
637 void
638 _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t tid, int opts,
639     const char *file, int line)
640 {
641         struct mtx *m;
642         int i = 0;
643 #ifdef LOCK_PROFILING
644         int contested = 0;
645         uint64_t waittime = 0;
646 #endif
647 #ifdef KDTRACE_HOOKS
648         int64_t spin_time = 0;
649 #endif
650
651         if (SCHEDULER_STOPPED())
652                 return;
653
654         m = mtxlock2mtx(c);
655
656         if (LOCK_LOG_TEST(&m->lock_object, opts))
657                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
658         KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
659             "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
660
661 #ifdef HWPMC_HOOKS
662         PMC_SOFT_CALL( , , lock, failed);
663 #endif
664         lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
665 #ifdef KDTRACE_HOOKS
666         spin_time -= lockstat_nsecs(&m->lock_object);
667 #endif
668         for (;;) {
669                 if (m->mtx_lock == MTX_UNOWNED && _mtx_obtain_lock(m, tid))
670                         break;
671                 /* Give interrupts a chance while we spin. */
672                 spinlock_exit();
673                 while (m->mtx_lock != MTX_UNOWNED) {
674                         if (i++ < 10000000) {
675                                 cpu_spinwait();
676                                 continue;
677                         }
678                         if (i < 60000000 || kdb_active || panicstr != NULL)
679                                 DELAY(1);
680                         else
681                                 _mtx_lock_spin_failed(m);
682                         cpu_spinwait();
683                 }
684                 spinlock_enter();
685         }
686 #ifdef KDTRACE_HOOKS
687         spin_time += lockstat_nsecs(&m->lock_object);
688 #endif
689
690         if (LOCK_LOG_TEST(&m->lock_object, opts))
691                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
692         KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
693             "running");
694
695 #ifdef KDTRACE_HOOKS
696         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
697             contested, waittime, file, line);
698         if (spin_time != 0)
699                 LOCKSTAT_RECORD1(spin__spin, m, spin_time);
700 #endif
701 }
702 #endif /* SMP */
703
704 void
705 thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
706 {
707         struct mtx *m;
708         uintptr_t tid;
709         int i;
710 #ifdef LOCK_PROFILING
711         int contested = 0;
712         uint64_t waittime = 0;
713 #endif
714 #ifdef KDTRACE_HOOKS
715         int64_t spin_time = 0;
716 #endif
717
718         i = 0;
719         tid = (uintptr_t)curthread;
720
721         if (SCHEDULER_STOPPED()) {
722                 /*
723                  * Ensure that spinlock sections are balanced even when the
724                  * scheduler is stopped, since we may otherwise inadvertently
725                  * re-enable interrupts while dumping core.
726                  */
727                 spinlock_enter();
728                 return;
729         }
730
731 #ifdef KDTRACE_HOOKS
732         spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
733 #endif
734         for (;;) {
735 retry:
736                 spinlock_enter();
737                 m = td->td_lock;
738                 KASSERT(m->mtx_lock != MTX_DESTROYED,
739                     ("thread_lock() of destroyed mutex @ %s:%d", file, line));
740                 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
741                     ("thread_lock() of sleep mutex %s @ %s:%d",
742                     m->lock_object.lo_name, file, line));
743                 if (mtx_owned(m))
744                         KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
745             ("thread_lock: recursed on non-recursive mutex %s @ %s:%d\n",
746                             m->lock_object.lo_name, file, line));
747                 WITNESS_CHECKORDER(&m->lock_object,
748                     opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
749                 for (;;) {
750                         if (m->mtx_lock == MTX_UNOWNED && _mtx_obtain_lock(m, tid))
751                                 break;
752                         if (m->mtx_lock == tid) {
753                                 m->mtx_recurse++;
754                                 break;
755                         }
756 #ifdef HWPMC_HOOKS
757                         PMC_SOFT_CALL( , , lock, failed);
758 #endif
759                         lock_profile_obtain_lock_failed(&m->lock_object,
760                             &contested, &waittime);
761                         /* Give interrupts a chance while we spin. */
762                         spinlock_exit();
763                         while (m->mtx_lock != MTX_UNOWNED) {
764                                 if (i++ < 10000000)
765                                         cpu_spinwait();
766                                 else if (i < 60000000 ||
767                                     kdb_active || panicstr != NULL)
768                                         DELAY(1);
769                                 else
770                                         _mtx_lock_spin_failed(m);
771                                 cpu_spinwait();
772                                 if (m != td->td_lock)
773                                         goto retry;
774                         }
775                         spinlock_enter();
776                 }
777                 if (m == td->td_lock)
778                         break;
779                 __mtx_unlock_spin(m);   /* does spinlock_exit() */
780         }
781 #ifdef KDTRACE_HOOKS
782         spin_time += lockstat_nsecs(&m->lock_object);
783 #endif
784         if (m->mtx_recurse == 0)
785                 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
786                     contested, waittime, file, line);
787         LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
788             line);
789         WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
790 #ifdef KDTRACE_HOOKS
791         if (spin_time != 0)
792                 LOCKSTAT_RECORD1(thread__spin, m, spin_time);
793 #endif
794 }
795
796 struct mtx *
797 thread_lock_block(struct thread *td)
798 {
799         struct mtx *lock;
800
801         THREAD_LOCK_ASSERT(td, MA_OWNED);
802         lock = td->td_lock;
803         td->td_lock = &blocked_lock;
804         mtx_unlock_spin(lock);
805
806         return (lock);
807 }
808
809 void
810 thread_lock_unblock(struct thread *td, struct mtx *new)
811 {
812         mtx_assert(new, MA_OWNED);
813         MPASS(td->td_lock == &blocked_lock);
814         atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
815 }
816
817 void
818 thread_lock_set(struct thread *td, struct mtx *new)
819 {
820         struct mtx *lock;
821
822         mtx_assert(new, MA_OWNED);
823         THREAD_LOCK_ASSERT(td, MA_OWNED);
824         lock = td->td_lock;
825         td->td_lock = new;
826         mtx_unlock_spin(lock);
827 }
828
829 /*
830  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
831  *
832  * We are only called here if the lock is recursed or contested (i.e. we
833  * need to wake up a blocked thread).
834  */
835 void
836 __mtx_unlock_sleep(volatile uintptr_t *c, int opts, const char *file, int line)
837 {
838         struct mtx *m;
839         struct turnstile *ts;
840
841         if (SCHEDULER_STOPPED())
842                 return;
843
844         m = mtxlock2mtx(c);
845
846         if (mtx_recursed(m)) {
847                 if (--(m->mtx_recurse) == 0)
848                         atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
849                 if (LOCK_LOG_TEST(&m->lock_object, opts))
850                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
851                 return;
852         }
853
854         /*
855          * We have to lock the chain before the turnstile so this turnstile
856          * can be removed from the hash list if it is empty.
857          */
858         turnstile_chain_lock(&m->lock_object);
859         ts = turnstile_lookup(&m->lock_object);
860         if (LOCK_LOG_TEST(&m->lock_object, opts))
861                 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
862         MPASS(ts != NULL);
863         turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
864         _mtx_release_lock_quick(m);
865
866         /*
867          * This turnstile is now no longer associated with the mutex.  We can
868          * unlock the chain lock so a new turnstile may take it's place.
869          */
870         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
871         turnstile_chain_unlock(&m->lock_object);
872 }
873
874 /*
875  * All the unlocking of MTX_SPIN locks is done inline.
876  * See the __mtx_unlock_spin() macro for the details.
877  */
878
879 /*
880  * The backing function for the INVARIANTS-enabled mtx_assert()
881  */
882 #ifdef INVARIANT_SUPPORT
883 void
884 __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
885 {
886         const struct mtx *m;
887
888         if (panicstr != NULL || dumping)
889                 return;
890
891         m = mtxlock2mtx(c);
892
893         switch (what) {
894         case MA_OWNED:
895         case MA_OWNED | MA_RECURSED:
896         case MA_OWNED | MA_NOTRECURSED:
897                 if (!mtx_owned(m))
898                         panic("mutex %s not owned at %s:%d",
899                             m->lock_object.lo_name, file, line);
900                 if (mtx_recursed(m)) {
901                         if ((what & MA_NOTRECURSED) != 0)
902                                 panic("mutex %s recursed at %s:%d",
903                                     m->lock_object.lo_name, file, line);
904                 } else if ((what & MA_RECURSED) != 0) {
905                         panic("mutex %s unrecursed at %s:%d",
906                             m->lock_object.lo_name, file, line);
907                 }
908                 break;
909         case MA_NOTOWNED:
910                 if (mtx_owned(m))
911                         panic("mutex %s owned at %s:%d",
912                             m->lock_object.lo_name, file, line);
913                 break;
914         default:
915                 panic("unknown mtx_assert at %s:%d", file, line);
916         }
917 }
918 #endif
919
920 /*
921  * General init routine used by the MTX_SYSINIT() macro.
922  */
923 void
924 mtx_sysinit(void *arg)
925 {
926         struct mtx_args *margs = arg;
927
928         mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
929             margs->ma_opts);
930 }
931
932 /*
933  * Mutex initialization routine; initialize lock `m' of type contained in
934  * `opts' with options contained in `opts' and name `name.'  The optional
935  * lock type `type' is used as a general lock category name for use with
936  * witness.
937  */
938 void
939 _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
940 {
941         struct mtx *m;
942         struct lock_class *class;
943         int flags;
944
945         m = mtxlock2mtx(c);
946
947         MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
948             MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
949         ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
950             ("%s: mtx_lock not aligned for %s: %p", __func__, name,
951             &m->mtx_lock));
952
953         /* Determine lock class and lock flags. */
954         if (opts & MTX_SPIN)
955                 class = &lock_class_mtx_spin;
956         else
957                 class = &lock_class_mtx_sleep;
958         flags = 0;
959         if (opts & MTX_QUIET)
960                 flags |= LO_QUIET;
961         if (opts & MTX_RECURSE)
962                 flags |= LO_RECURSABLE;
963         if ((opts & MTX_NOWITNESS) == 0)
964                 flags |= LO_WITNESS;
965         if (opts & MTX_DUPOK)
966                 flags |= LO_DUPOK;
967         if (opts & MTX_NOPROFILE)
968                 flags |= LO_NOPROFILE;
969         if (opts & MTX_NEW)
970                 flags |= LO_NEW;
971
972         /* Initialize mutex. */
973         lock_init(&m->lock_object, class, name, type, flags);
974
975         m->mtx_lock = MTX_UNOWNED;
976         m->mtx_recurse = 0;
977 }
978
979 /*
980  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
981  * passed in as a flag here because if the corresponding mtx_init() was
982  * called with MTX_QUIET set, then it will already be set in the mutex's
983  * flags.
984  */
985 void
986 _mtx_destroy(volatile uintptr_t *c)
987 {
988         struct mtx *m;
989
990         m = mtxlock2mtx(c);
991
992         if (!mtx_owned(m))
993                 MPASS(mtx_unowned(m));
994         else {
995                 MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
996
997                 /* Perform the non-mtx related part of mtx_unlock_spin(). */
998                 if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
999                         spinlock_exit();
1000                 else
1001                         TD_LOCKS_DEC(curthread);
1002
1003                 lock_profile_release_lock(&m->lock_object);
1004                 /* Tell witness this isn't locked to make it happy. */
1005                 WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1006                     __LINE__);
1007         }
1008
1009         m->mtx_lock = MTX_DESTROYED;
1010         lock_destroy(&m->lock_object);
1011 }
1012
1013 /*
1014  * Intialize the mutex code and system mutexes.  This is called from the MD
1015  * startup code prior to mi_startup().  The per-CPU data space needs to be
1016  * setup before this is called.
1017  */
1018 void
1019 mutex_init(void)
1020 {
1021
1022         /* Setup turnstiles so that sleep mutexes work. */
1023         init_turnstiles();
1024
1025         /*
1026          * Initialize mutexes.
1027          */
1028         mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
1029         mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
1030         blocked_lock.mtx_lock = 0xdeadc0de;     /* Always blocked. */
1031         mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
1032         mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
1033         mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
1034         mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
1035         mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
1036         mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1037         mtx_lock(&Giant);
1038 }
1039
1040 #ifdef DDB
1041 void
1042 db_show_mtx(const struct lock_object *lock)
1043 {
1044         struct thread *td;
1045         const struct mtx *m;
1046
1047         m = (const struct mtx *)lock;
1048
1049         db_printf(" flags: {");
1050         if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1051                 db_printf("SPIN");
1052         else
1053                 db_printf("DEF");
1054         if (m->lock_object.lo_flags & LO_RECURSABLE)
1055                 db_printf(", RECURSE");
1056         if (m->lock_object.lo_flags & LO_DUPOK)
1057                 db_printf(", DUPOK");
1058         db_printf("}\n");
1059         db_printf(" state: {");
1060         if (mtx_unowned(m))
1061                 db_printf("UNOWNED");
1062         else if (mtx_destroyed(m))
1063                 db_printf("DESTROYED");
1064         else {
1065                 db_printf("OWNED");
1066                 if (m->mtx_lock & MTX_CONTESTED)
1067                         db_printf(", CONTESTED");
1068                 if (m->mtx_lock & MTX_RECURSED)
1069                         db_printf(", RECURSED");
1070         }
1071         db_printf("}\n");
1072         if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1073                 td = mtx_owner(m);
1074                 db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1075                     td->td_tid, td->td_proc->p_pid, td->td_name);
1076                 if (mtx_recursed(m))
1077                         db_printf(" recursed: %d\n", m->mtx_recurse);
1078         }
1079 }
1080 #endif