]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_mutex.c
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305145, and update
[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 static void     assert_mtx(const struct lock_object *lock, int what);
98 #ifdef DDB
99 static void     db_show_mtx(const struct lock_object *lock);
100 #endif
101 static void     lock_mtx(struct lock_object *lock, uintptr_t how);
102 static void     lock_spin(struct lock_object *lock, uintptr_t how);
103 #ifdef KDTRACE_HOOKS
104 static int      owner_mtx(const struct lock_object *lock,
105                     struct thread **owner);
106 #endif
107 static uintptr_t unlock_mtx(struct lock_object *lock);
108 static uintptr_t unlock_spin(struct lock_object *lock);
109
110 /*
111  * Lock classes for sleep and spin mutexes.
112  */
113 struct lock_class lock_class_mtx_sleep = {
114         .lc_name = "sleep mutex",
115         .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
116         .lc_assert = assert_mtx,
117 #ifdef DDB
118         .lc_ddb_show = db_show_mtx,
119 #endif
120         .lc_lock = lock_mtx,
121         .lc_unlock = unlock_mtx,
122 #ifdef KDTRACE_HOOKS
123         .lc_owner = owner_mtx,
124 #endif
125 };
126 struct lock_class lock_class_mtx_spin = {
127         .lc_name = "spin mutex",
128         .lc_flags = LC_SPINLOCK | LC_RECURSABLE,
129         .lc_assert = assert_mtx,
130 #ifdef DDB
131         .lc_ddb_show = db_show_mtx,
132 #endif
133         .lc_lock = lock_spin,
134         .lc_unlock = unlock_spin,
135 #ifdef KDTRACE_HOOKS
136         .lc_owner = owner_mtx,
137 #endif
138 };
139
140 #ifdef ADAPTIVE_MUTEXES
141 static SYSCTL_NODE(_debug, OID_AUTO, mtx, CTLFLAG_RD, NULL, "mtx debugging");
142
143 static struct lock_delay_config __read_mostly mtx_delay;
144
145 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_base, CTLFLAG_RW, &mtx_delay.base,
146     0, "");
147 SYSCTL_INT(_debug_mtx, OID_AUTO, delay_max, CTLFLAG_RW, &mtx_delay.max,
148     0, "");
149
150 LOCK_DELAY_SYSINIT_DEFAULT(mtx_delay);
151 #endif
152
153 static SYSCTL_NODE(_debug, OID_AUTO, mtx_spin, CTLFLAG_RD, NULL,
154     "mtx spin debugging");
155
156 static struct lock_delay_config __read_mostly mtx_spin_delay;
157
158 SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_base, CTLFLAG_RW,
159     &mtx_spin_delay.base, 0, "");
160 SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_max, CTLFLAG_RW,
161     &mtx_spin_delay.max, 0, "");
162
163 LOCK_DELAY_SYSINIT_DEFAULT(mtx_spin_delay);
164
165 /*
166  * System-wide mutexes
167  */
168 struct mtx blocked_lock;
169 struct mtx Giant;
170
171 void
172 assert_mtx(const struct lock_object *lock, int what)
173 {
174
175         mtx_assert((const struct mtx *)lock, what);
176 }
177
178 void
179 lock_mtx(struct lock_object *lock, uintptr_t how)
180 {
181
182         mtx_lock((struct mtx *)lock);
183 }
184
185 void
186 lock_spin(struct lock_object *lock, uintptr_t how)
187 {
188
189         panic("spin locks can only use msleep_spin");
190 }
191
192 uintptr_t
193 unlock_mtx(struct lock_object *lock)
194 {
195         struct mtx *m;
196
197         m = (struct mtx *)lock;
198         mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
199         mtx_unlock(m);
200         return (0);
201 }
202
203 uintptr_t
204 unlock_spin(struct lock_object *lock)
205 {
206
207         panic("spin locks can only use msleep_spin");
208 }
209
210 #ifdef KDTRACE_HOOKS
211 int
212 owner_mtx(const struct lock_object *lock, struct thread **owner)
213 {
214         const struct mtx *m;
215         uintptr_t x;
216
217         m = (const struct mtx *)lock;
218         x = m->mtx_lock;
219         *owner = (struct thread *)(x & ~MTX_FLAGMASK);
220         return (x != MTX_UNOWNED);
221 }
222 #endif
223
224 /*
225  * Function versions of the inlined __mtx_* macros.  These are used by
226  * modules and can also be called from assembly language if needed.
227  */
228 void
229 __mtx_lock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
230 {
231         struct mtx *m;
232         uintptr_t tid, v;
233
234         m = mtxlock2mtx(c);
235
236         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
237             ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
238             curthread, m->lock_object.lo_name, file, line));
239         KASSERT(m->mtx_lock != MTX_DESTROYED,
240             ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
241         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
242             ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
243             file, line));
244         WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
245             LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
246
247         tid = (uintptr_t)curthread;
248         v = MTX_UNOWNED;
249         if (!_mtx_obtain_lock_fetch(m, &v, tid))
250                 _mtx_lock_sleep(m, v, tid, opts, file, line);
251         else
252                 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
253                     m, 0, 0, file, line);
254         LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
255             line);
256         WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
257             file, line);
258         TD_LOCKS_INC(curthread);
259 }
260
261 void
262 __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
263 {
264         struct mtx *m;
265
266         m = mtxlock2mtx(c);
267
268         KASSERT(m->mtx_lock != MTX_DESTROYED,
269             ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
270         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
271             ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
272             file, line));
273         WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
274         LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
275             line);
276         mtx_assert(m, MA_OWNED);
277
278 #ifdef LOCK_PROFILING
279         __mtx_unlock_sleep(c, opts, file, line);
280 #else
281         __mtx_unlock(m, curthread, opts, file, line);
282 #endif
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         struct thread *td;
378         uintptr_t tid, v;
379 #ifdef LOCK_PROFILING
380         uint64_t waittime = 0;
381         int contested = 0;
382 #endif
383         int rval;
384         bool recursed;
385
386         td = curthread;
387         tid = (uintptr_t)td;
388         if (SCHEDULER_STOPPED_TD(td))
389                 return (1);
390
391         m = mtxlock2mtx(c);
392
393         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
394             ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
395             curthread, m->lock_object.lo_name, file, line));
396         KASSERT(m->mtx_lock != MTX_DESTROYED,
397             ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
398         KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
399             ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
400             file, line));
401
402         rval = 1;
403         recursed = false;
404         v = MTX_UNOWNED;
405         for (;;) {
406                 if (_mtx_obtain_lock_fetch(m, &v, tid))
407                         break;
408                 if (v == MTX_UNOWNED)
409                         continue;
410                 if (v == tid &&
411                     ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
412                     (opts & MTX_RECURSE) != 0)) {
413                         m->mtx_recurse++;
414                         atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
415                         recursed = true;
416                         break;
417                 }
418                 rval = 0;
419                 break;
420         }
421
422         opts &= ~MTX_RECURSE;
423
424         LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
425         if (rval) {
426                 WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
427                     file, line);
428                 TD_LOCKS_INC(curthread);
429                 if (!recursed)
430                         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
431                             m, contested, waittime, file, line);
432         }
433
434         return (rval);
435 }
436
437 /*
438  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
439  *
440  * We call this if the lock is either contested (i.e. we need to go to
441  * sleep waiting for it), or if we need to recurse on it.
442  */
443 #if LOCK_DEBUG > 0
444 void
445 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, uintptr_t tid, int opts,
446     const char *file, int line)
447 #else
448 void
449 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, uintptr_t tid)
450 #endif
451 {
452         struct mtx *m;
453         struct turnstile *ts;
454 #ifdef ADAPTIVE_MUTEXES
455         volatile struct thread *owner;
456 #endif
457 #ifdef KTR
458         int cont_logged = 0;
459 #endif
460 #ifdef LOCK_PROFILING
461         int contested = 0;
462         uint64_t waittime = 0;
463 #endif
464 #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
465         struct lock_delay_arg lda;
466 #endif
467 #ifdef KDTRACE_HOOKS
468         u_int sleep_cnt = 0;
469         int64_t sleep_time = 0;
470         int64_t all_time = 0;
471 #endif
472 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
473         int doing_lockprof;
474 #endif
475
476         if (SCHEDULER_STOPPED())
477                 return;
478
479 #if defined(ADAPTIVE_MUTEXES)
480         lock_delay_arg_init(&lda, &mtx_delay);
481 #elif defined(KDTRACE_HOOKS)
482         lock_delay_arg_init(&lda, NULL);
483 #endif
484         m = mtxlock2mtx(c);
485         if (__predict_false(v == MTX_UNOWNED))
486                 v = MTX_READ_VALUE(m);
487
488         if (__predict_false(lv_mtx_owner(v) == (struct thread *)tid)) {
489                 KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
490                     (opts & MTX_RECURSE) != 0,
491             ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
492                     m->lock_object.lo_name, file, line));
493 #if LOCK_DEBUG > 0
494                 opts &= ~MTX_RECURSE;
495 #endif
496                 m->mtx_recurse++;
497                 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
498                 if (LOCK_LOG_TEST(&m->lock_object, opts))
499                         CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
500                 return;
501         }
502 #if LOCK_DEBUG > 0
503         opts &= ~MTX_RECURSE;
504 #endif
505
506 #ifdef HWPMC_HOOKS
507         PMC_SOFT_CALL( , , lock, failed);
508 #endif
509         lock_profile_obtain_lock_failed(&m->lock_object,
510                     &contested, &waittime);
511         if (LOCK_LOG_TEST(&m->lock_object, opts))
512                 CTR4(KTR_LOCK,
513                     "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
514                     m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
515 #ifdef LOCK_PROFILING
516         doing_lockprof = 1;
517 #elif defined(KDTRACE_HOOKS)
518         doing_lockprof = lockstat_enabled;
519         if (__predict_false(doing_lockprof))
520                 all_time -= lockstat_nsecs(&m->lock_object);
521 #endif
522
523         for (;;) {
524                 if (v == MTX_UNOWNED) {
525                         if (_mtx_obtain_lock_fetch(m, &v, tid))
526                                 break;
527                         continue;
528                 }
529 #ifdef KDTRACE_HOOKS
530                 lda.spin_cnt++;
531 #endif
532 #ifdef ADAPTIVE_MUTEXES
533                 /*
534                  * If the owner is running on another CPU, spin until the
535                  * owner stops running or the state of the lock changes.
536                  */
537                 owner = lv_mtx_owner(v);
538                 if (TD_IS_RUNNING(owner)) {
539                         if (LOCK_LOG_TEST(&m->lock_object, 0))
540                                 CTR3(KTR_LOCK,
541                                     "%s: spinning on %p held by %p",
542                                     __func__, m, owner);
543                         KTR_STATE1(KTR_SCHED, "thread",
544                             sched_tdname((struct thread *)tid),
545                             "spinning", "lockname:\"%s\"",
546                             m->lock_object.lo_name);
547                         do {
548                                 lock_delay(&lda);
549                                 v = MTX_READ_VALUE(m);
550                                 owner = lv_mtx_owner(v);
551                         } while (v != MTX_UNOWNED && TD_IS_RUNNING(owner));
552                         KTR_STATE0(KTR_SCHED, "thread",
553                             sched_tdname((struct thread *)tid),
554                             "running");
555                         continue;
556                 }
557 #endif
558
559                 ts = turnstile_trywait(&m->lock_object);
560                 v = MTX_READ_VALUE(m);
561
562                 /*
563                  * Check if the lock has been released while spinning for
564                  * the turnstile chain lock.
565                  */
566                 if (v == MTX_UNOWNED) {
567                         turnstile_cancel(ts);
568                         continue;
569                 }
570
571 #ifdef ADAPTIVE_MUTEXES
572                 /*
573                  * The current lock owner might have started executing
574                  * on another CPU (or the lock could have changed
575                  * owners) while we were waiting on the turnstile
576                  * chain lock.  If so, drop the turnstile lock and try
577                  * again.
578                  */
579                 owner = lv_mtx_owner(v);
580                 if (TD_IS_RUNNING(owner)) {
581                         turnstile_cancel(ts);
582                         continue;
583                 }
584 #endif
585
586                 /*
587                  * If the mutex isn't already contested and a failure occurs
588                  * setting the contested bit, the mutex was either released
589                  * or the state of the MTX_RECURSED bit changed.
590                  */
591                 if ((v & MTX_CONTESTED) == 0 &&
592                     !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
593                         turnstile_cancel(ts);
594                         v = MTX_READ_VALUE(m);
595                         continue;
596                 }
597
598                 /*
599                  * We definitely must sleep for this lock.
600                  */
601                 mtx_assert(m, MA_NOTOWNED);
602
603 #ifdef KTR
604                 if (!cont_logged) {
605                         CTR6(KTR_CONTENTION,
606                             "contention: %p at %s:%d wants %s, taken by %s:%d",
607                             (void *)tid, file, line, m->lock_object.lo_name,
608                             WITNESS_FILE(&m->lock_object),
609                             WITNESS_LINE(&m->lock_object));
610                         cont_logged = 1;
611                 }
612 #endif
613
614                 /*
615                  * Block on the turnstile.
616                  */
617 #ifdef KDTRACE_HOOKS
618                 sleep_time -= lockstat_nsecs(&m->lock_object);
619 #endif
620                 turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
621 #ifdef KDTRACE_HOOKS
622                 sleep_time += lockstat_nsecs(&m->lock_object);
623                 sleep_cnt++;
624 #endif
625                 v = MTX_READ_VALUE(m);
626         }
627 #ifdef KTR
628         if (cont_logged) {
629                 CTR4(KTR_CONTENTION,
630                     "contention end: %s acquired by %p at %s:%d",
631                     m->lock_object.lo_name, (void *)tid, file, line);
632         }
633 #endif
634 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
635         if (__predict_true(!doing_lockprof))
636                 return;
637 #endif
638 #ifdef KDTRACE_HOOKS
639         all_time += lockstat_nsecs(&m->lock_object);
640 #endif
641         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
642             waittime, file, line);
643 #ifdef KDTRACE_HOOKS
644         if (sleep_time)
645                 LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
646
647         /*
648          * Only record the loops spinning and not sleeping.
649          */
650         if (lda.spin_cnt > sleep_cnt)
651                 LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
652 #endif
653 }
654
655 static void
656 _mtx_lock_spin_failed(struct mtx *m)
657 {
658         struct thread *td;
659
660         td = mtx_owner(m);
661
662         /* If the mutex is unlocked, try again. */
663         if (td == NULL)
664                 return;
665
666         printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
667             m, m->lock_object.lo_name, td, td->td_tid);
668 #ifdef WITNESS
669         witness_display_spinlock(&m->lock_object, td, printf);
670 #endif
671         panic("spin lock held too long");
672 }
673
674 #ifdef SMP
675 /*
676  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
677  *
678  * This is only called if we need to actually spin for the lock. Recursion
679  * is handled inline.
680  */
681 void
682 _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
683     int opts, const char *file, int line)
684 {
685         struct mtx *m;
686         struct lock_delay_arg lda;
687 #ifdef LOCK_PROFILING
688         int contested = 0;
689         uint64_t waittime = 0;
690 #endif
691 #ifdef KDTRACE_HOOKS
692         int64_t spin_time = 0;
693 #endif
694 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
695         int doing_lockprof;
696 #endif
697
698         if (SCHEDULER_STOPPED())
699                 return;
700
701         lock_delay_arg_init(&lda, &mtx_spin_delay);
702         m = mtxlock2mtx(c);
703
704         if (__predict_false(v == MTX_UNOWNED))
705                 v = MTX_READ_VALUE(m);
706
707         if (__predict_false(v == tid)) {
708                 m->mtx_recurse++;
709                 return;
710         }
711
712         if (LOCK_LOG_TEST(&m->lock_object, opts))
713                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
714         KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
715             "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
716
717 #ifdef HWPMC_HOOKS
718         PMC_SOFT_CALL( , , lock, failed);
719 #endif
720         lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
721 #ifdef LOCK_PROFILING
722         doing_lockprof = 1;
723 #elif defined(KDTRACE_HOOKS)
724         doing_lockprof = lockstat_enabled;
725         if (__predict_false(doing_lockprof))
726                 spin_time -= lockstat_nsecs(&m->lock_object);
727 #endif
728         for (;;) {
729                 if (v == MTX_UNOWNED) {
730                         if (_mtx_obtain_lock_fetch(m, &v, tid))
731                                 break;
732                         continue;
733                 }
734                 /* Give interrupts a chance while we spin. */
735                 spinlock_exit();
736                 do {
737                         if (lda.spin_cnt < 10000000) {
738                                 lock_delay(&lda);
739                         } else {
740                                 lda.spin_cnt++;
741                                 if (lda.spin_cnt < 60000000 || kdb_active ||
742                                     panicstr != NULL)
743                                         DELAY(1);
744                                 else
745                                         _mtx_lock_spin_failed(m);
746                                 cpu_spinwait();
747                         }
748                         v = MTX_READ_VALUE(m);
749                 } while (v != MTX_UNOWNED);
750                 spinlock_enter();
751         }
752
753         if (LOCK_LOG_TEST(&m->lock_object, opts))
754                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
755         KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
756             "running");
757
758 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
759         if (__predict_true(!doing_lockprof))
760                 return;
761 #endif
762 #ifdef KDTRACE_HOOKS
763         spin_time += lockstat_nsecs(&m->lock_object);
764 #endif
765         LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
766             contested, waittime, file, line);
767 #ifdef KDTRACE_HOOKS
768         if (spin_time != 0)
769                 LOCKSTAT_RECORD1(spin__spin, m, spin_time);
770 #endif
771 }
772 #endif /* SMP */
773
774 void
775 thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
776 {
777         struct mtx *m;
778         uintptr_t tid, v;
779         struct lock_delay_arg lda;
780 #ifdef LOCK_PROFILING
781         int contested = 0;
782         uint64_t waittime = 0;
783 #endif
784 #ifdef KDTRACE_HOOKS
785         int64_t spin_time = 0;
786 #endif
787 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
788         int doing_lockprof = 1;
789 #endif
790
791         tid = (uintptr_t)curthread;
792
793         if (SCHEDULER_STOPPED()) {
794                 /*
795                  * Ensure that spinlock sections are balanced even when the
796                  * scheduler is stopped, since we may otherwise inadvertently
797                  * re-enable interrupts while dumping core.
798                  */
799                 spinlock_enter();
800                 return;
801         }
802
803         lock_delay_arg_init(&lda, &mtx_spin_delay);
804
805 #ifdef LOCK_PROFILING
806         doing_lockprof = 1;
807 #elif defined(KDTRACE_HOOKS)
808         doing_lockprof = lockstat_enabled;
809         if (__predict_false(doing_lockprof))
810                 spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
811 #endif
812         for (;;) {
813 retry:
814                 v = MTX_UNOWNED;
815                 spinlock_enter();
816                 m = td->td_lock;
817                 KASSERT(m->mtx_lock != MTX_DESTROYED,
818                     ("thread_lock() of destroyed mutex @ %s:%d", file, line));
819                 KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
820                     ("thread_lock() of sleep mutex %s @ %s:%d",
821                     m->lock_object.lo_name, file, line));
822                 if (mtx_owned(m))
823                         KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
824             ("thread_lock: recursed on non-recursive mutex %s @ %s:%d\n",
825                             m->lock_object.lo_name, file, line));
826                 WITNESS_CHECKORDER(&m->lock_object,
827                     opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
828                 for (;;) {
829                         if (_mtx_obtain_lock_fetch(m, &v, tid))
830                                 break;
831                         if (v == MTX_UNOWNED)
832                                 continue;
833                         if (v == tid) {
834                                 m->mtx_recurse++;
835                                 break;
836                         }
837 #ifdef HWPMC_HOOKS
838                         PMC_SOFT_CALL( , , lock, failed);
839 #endif
840                         lock_profile_obtain_lock_failed(&m->lock_object,
841                             &contested, &waittime);
842                         /* Give interrupts a chance while we spin. */
843                         spinlock_exit();
844                         do {
845                                 if (lda.spin_cnt < 10000000) {
846                                         lock_delay(&lda);
847                                 } else {
848                                         lda.spin_cnt++;
849                                         if (lda.spin_cnt < 60000000 ||
850                                             kdb_active || panicstr != NULL)
851                                                 DELAY(1);
852                                         else
853                                                 _mtx_lock_spin_failed(m);
854                                         cpu_spinwait();
855                                 }
856                                 if (m != td->td_lock)
857                                         goto retry;
858                                 v = MTX_READ_VALUE(m);
859                         } while (v != MTX_UNOWNED);
860                         spinlock_enter();
861                 }
862                 if (m == td->td_lock)
863                         break;
864                 __mtx_unlock_spin(m);   /* does spinlock_exit() */
865         }
866         LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
867             line);
868         WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
869
870 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
871         if (__predict_true(!doing_lockprof))
872                 return;
873 #endif
874 #ifdef KDTRACE_HOOKS
875         spin_time += lockstat_nsecs(&m->lock_object);
876 #endif
877         if (m->mtx_recurse == 0)
878                 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
879                     contested, waittime, file, line);
880 #ifdef KDTRACE_HOOKS
881         if (spin_time != 0)
882                 LOCKSTAT_RECORD1(thread__spin, m, spin_time);
883 #endif
884 }
885
886 struct mtx *
887 thread_lock_block(struct thread *td)
888 {
889         struct mtx *lock;
890
891         THREAD_LOCK_ASSERT(td, MA_OWNED);
892         lock = td->td_lock;
893         td->td_lock = &blocked_lock;
894         mtx_unlock_spin(lock);
895
896         return (lock);
897 }
898
899 void
900 thread_lock_unblock(struct thread *td, struct mtx *new)
901 {
902         mtx_assert(new, MA_OWNED);
903         MPASS(td->td_lock == &blocked_lock);
904         atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
905 }
906
907 void
908 thread_lock_set(struct thread *td, struct mtx *new)
909 {
910         struct mtx *lock;
911
912         mtx_assert(new, MA_OWNED);
913         THREAD_LOCK_ASSERT(td, MA_OWNED);
914         lock = td->td_lock;
915         td->td_lock = new;
916         mtx_unlock_spin(lock);
917 }
918
919 /*
920  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
921  *
922  * We are only called here if the lock is recursed, contested (i.e. we
923  * need to wake up a blocked thread) or lockstat probe is active.
924  */
925 #if LOCK_DEBUG > 0
926 void
927 __mtx_unlock_sleep(volatile uintptr_t *c, int opts, const char *file, int line)
928 #else
929 void
930 __mtx_unlock_sleep(volatile uintptr_t *c)
931 #endif
932 {
933         struct mtx *m;
934         struct turnstile *ts;
935         uintptr_t tid, v;
936
937         if (SCHEDULER_STOPPED())
938                 return;
939
940         tid = (uintptr_t)curthread;
941         m = mtxlock2mtx(c);
942         v = MTX_READ_VALUE(m);
943
944         if (v & MTX_RECURSED) {
945                 if (--(m->mtx_recurse) == 0)
946                         atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
947                 if (LOCK_LOG_TEST(&m->lock_object, opts))
948                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
949                 return;
950         }
951
952         LOCKSTAT_PROFILE_RELEASE_LOCK(adaptive__release, m);
953         if (v == tid && _mtx_release_lock(m, tid))
954                 return;
955
956         /*
957          * We have to lock the chain before the turnstile so this turnstile
958          * can be removed from the hash list if it is empty.
959          */
960         turnstile_chain_lock(&m->lock_object);
961         ts = turnstile_lookup(&m->lock_object);
962         if (LOCK_LOG_TEST(&m->lock_object, opts))
963                 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
964         MPASS(ts != NULL);
965         turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
966         _mtx_release_lock_quick(m);
967
968         /*
969          * This turnstile is now no longer associated with the mutex.  We can
970          * unlock the chain lock so a new turnstile may take it's place.
971          */
972         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
973         turnstile_chain_unlock(&m->lock_object);
974 }
975
976 /*
977  * All the unlocking of MTX_SPIN locks is done inline.
978  * See the __mtx_unlock_spin() macro for the details.
979  */
980
981 /*
982  * The backing function for the INVARIANTS-enabled mtx_assert()
983  */
984 #ifdef INVARIANT_SUPPORT
985 void
986 __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
987 {
988         const struct mtx *m;
989
990         if (panicstr != NULL || dumping || SCHEDULER_STOPPED())
991                 return;
992
993         m = mtxlock2mtx(c);
994
995         switch (what) {
996         case MA_OWNED:
997         case MA_OWNED | MA_RECURSED:
998         case MA_OWNED | MA_NOTRECURSED:
999                 if (!mtx_owned(m))
1000                         panic("mutex %s not owned at %s:%d",
1001                             m->lock_object.lo_name, file, line);
1002                 if (mtx_recursed(m)) {
1003                         if ((what & MA_NOTRECURSED) != 0)
1004                                 panic("mutex %s recursed at %s:%d",
1005                                     m->lock_object.lo_name, file, line);
1006                 } else if ((what & MA_RECURSED) != 0) {
1007                         panic("mutex %s unrecursed at %s:%d",
1008                             m->lock_object.lo_name, file, line);
1009                 }
1010                 break;
1011         case MA_NOTOWNED:
1012                 if (mtx_owned(m))
1013                         panic("mutex %s owned at %s:%d",
1014                             m->lock_object.lo_name, file, line);
1015                 break;
1016         default:
1017                 panic("unknown mtx_assert at %s:%d", file, line);
1018         }
1019 }
1020 #endif
1021
1022 /*
1023  * General init routine used by the MTX_SYSINIT() macro.
1024  */
1025 void
1026 mtx_sysinit(void *arg)
1027 {
1028         struct mtx_args *margs = arg;
1029
1030         mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
1031             margs->ma_opts);
1032 }
1033
1034 /*
1035  * Mutex initialization routine; initialize lock `m' of type contained in
1036  * `opts' with options contained in `opts' and name `name.'  The optional
1037  * lock type `type' is used as a general lock category name for use with
1038  * witness.
1039  */
1040 void
1041 _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
1042 {
1043         struct mtx *m;
1044         struct lock_class *class;
1045         int flags;
1046
1047         m = mtxlock2mtx(c);
1048
1049         MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
1050             MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
1051         ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
1052             ("%s: mtx_lock not aligned for %s: %p", __func__, name,
1053             &m->mtx_lock));
1054
1055         /* Determine lock class and lock flags. */
1056         if (opts & MTX_SPIN)
1057                 class = &lock_class_mtx_spin;
1058         else
1059                 class = &lock_class_mtx_sleep;
1060         flags = 0;
1061         if (opts & MTX_QUIET)
1062                 flags |= LO_QUIET;
1063         if (opts & MTX_RECURSE)
1064                 flags |= LO_RECURSABLE;
1065         if ((opts & MTX_NOWITNESS) == 0)
1066                 flags |= LO_WITNESS;
1067         if (opts & MTX_DUPOK)
1068                 flags |= LO_DUPOK;
1069         if (opts & MTX_NOPROFILE)
1070                 flags |= LO_NOPROFILE;
1071         if (opts & MTX_NEW)
1072                 flags |= LO_NEW;
1073
1074         /* Initialize mutex. */
1075         lock_init(&m->lock_object, class, name, type, flags);
1076
1077         m->mtx_lock = MTX_UNOWNED;
1078         m->mtx_recurse = 0;
1079 }
1080
1081 /*
1082  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
1083  * passed in as a flag here because if the corresponding mtx_init() was
1084  * called with MTX_QUIET set, then it will already be set in the mutex's
1085  * flags.
1086  */
1087 void
1088 _mtx_destroy(volatile uintptr_t *c)
1089 {
1090         struct mtx *m;
1091
1092         m = mtxlock2mtx(c);
1093
1094         if (!mtx_owned(m))
1095                 MPASS(mtx_unowned(m));
1096         else {
1097                 MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
1098
1099                 /* Perform the non-mtx related part of mtx_unlock_spin(). */
1100                 if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
1101                         spinlock_exit();
1102                 else
1103                         TD_LOCKS_DEC(curthread);
1104
1105                 lock_profile_release_lock(&m->lock_object);
1106                 /* Tell witness this isn't locked to make it happy. */
1107                 WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1108                     __LINE__);
1109         }
1110
1111         m->mtx_lock = MTX_DESTROYED;
1112         lock_destroy(&m->lock_object);
1113 }
1114
1115 /*
1116  * Intialize the mutex code and system mutexes.  This is called from the MD
1117  * startup code prior to mi_startup().  The per-CPU data space needs to be
1118  * setup before this is called.
1119  */
1120 void
1121 mutex_init(void)
1122 {
1123
1124         /* Setup turnstiles so that sleep mutexes work. */
1125         init_turnstiles();
1126
1127         /*
1128          * Initialize mutexes.
1129          */
1130         mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
1131         mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
1132         blocked_lock.mtx_lock = 0xdeadc0de;     /* Always blocked. */
1133         mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
1134         mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
1135         mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
1136         mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
1137         mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
1138         mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1139         mtx_lock(&Giant);
1140 }
1141
1142 #ifdef DDB
1143 void
1144 db_show_mtx(const struct lock_object *lock)
1145 {
1146         struct thread *td;
1147         const struct mtx *m;
1148
1149         m = (const struct mtx *)lock;
1150
1151         db_printf(" flags: {");
1152         if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1153                 db_printf("SPIN");
1154         else
1155                 db_printf("DEF");
1156         if (m->lock_object.lo_flags & LO_RECURSABLE)
1157                 db_printf(", RECURSE");
1158         if (m->lock_object.lo_flags & LO_DUPOK)
1159                 db_printf(", DUPOK");
1160         db_printf("}\n");
1161         db_printf(" state: {");
1162         if (mtx_unowned(m))
1163                 db_printf("UNOWNED");
1164         else if (mtx_destroyed(m))
1165                 db_printf("DESTROYED");
1166         else {
1167                 db_printf("OWNED");
1168                 if (m->mtx_lock & MTX_CONTESTED)
1169                         db_printf(", CONTESTED");
1170                 if (m->mtx_lock & MTX_RECURSED)
1171                         db_printf(", RECURSED");
1172         }
1173         db_printf("}\n");
1174         if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1175                 td = mtx_owner(m);
1176                 db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1177                     td->td_tid, td->td_proc->p_pid, td->td_name);
1178                 if (mtx_recursed(m))
1179                         db_printf(" recursed: %d\n", m->mtx_recurse);
1180         }
1181 }
1182 #endif