]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_mutex.c
Remove unused code.
[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_mprof.h"
42 #include "opt_mutex_wake_all.h"
43 #include "opt_sched.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bus.h>
48 #include <sys/conf.h>
49 #include <sys/kdb.h>
50 #include <sys/kernel.h>
51 #include <sys/ktr.h>
52 #include <sys/lock.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/proc.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
58 #include <sys/sbuf.h>
59 #include <sys/sysctl.h>
60 #include <sys/turnstile.h>
61 #include <sys/vmmeter.h>
62
63 #include <machine/atomic.h>
64 #include <machine/bus.h>
65 #include <machine/clock.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 /* 
76  * Force MUTEX_WAKE_ALL for now.
77  * single thread wakeup needs fixes to avoid race conditions with 
78  * priority inheritance.
79  */
80 #ifndef MUTEX_WAKE_ALL
81 #define MUTEX_WAKE_ALL
82 #endif
83
84 /*
85  * Internal utility macros.
86  */
87 #define mtx_unowned(m)  ((m)->mtx_lock == MTX_UNOWNED)
88
89 #define mtx_owner(m)    (mtx_unowned((m)) ? NULL \
90         : (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
91
92 #ifdef DDB
93 static void     db_show_mtx(struct lock_object *lock);
94 #endif
95
96 /*
97  * Lock classes for sleep and spin mutexes.
98  */
99 struct lock_class lock_class_mtx_sleep = {
100         "sleep mutex",
101         LC_SLEEPLOCK | LC_RECURSABLE,
102 #ifdef DDB
103         db_show_mtx
104 #endif
105 };
106 struct lock_class lock_class_mtx_spin = {
107         "spin mutex",
108         LC_SPINLOCK | LC_RECURSABLE,
109 #ifdef DDB
110         db_show_mtx
111 #endif
112 };
113
114 /*
115  * System-wide mutexes
116  */
117 struct mtx sched_lock;
118 struct mtx Giant;
119
120 #ifdef MUTEX_PROFILING
121 SYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
122 SYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
123 static int mutex_prof_enable = 0;
124 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
125     &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
126
127 struct mutex_prof {
128         const char      *name;
129         const char      *file;
130         int             line;
131         uintmax_t       cnt_max;
132         uintmax_t       cnt_tot;
133         uintmax_t       cnt_cur;
134         uintmax_t       cnt_contest_holding;
135         uintmax_t       cnt_contest_locking;
136         struct mutex_prof *next;
137 };
138
139 /*
140  * mprof_buf is a static pool of profiling records to avoid possible
141  * reentrance of the memory allocation functions.
142  *
143  * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
144  */
145 #ifdef MPROF_BUFFERS
146 #define NUM_MPROF_BUFFERS       MPROF_BUFFERS
147 #else
148 #define NUM_MPROF_BUFFERS       1000
149 #endif
150 static struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
151 static int first_free_mprof_buf;
152 #ifndef MPROF_HASH_SIZE
153 #define MPROF_HASH_SIZE         1009
154 #endif
155 #if NUM_MPROF_BUFFERS >= MPROF_HASH_SIZE
156 #error MPROF_BUFFERS must be larger than MPROF_HASH_SIZE
157 #endif
158 static struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
159 /* SWAG: sbuf size = avg stat. line size * number of locks */
160 #define MPROF_SBUF_SIZE         256 * 400
161
162 static int mutex_prof_acquisitions;
163 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
164     &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
165 static int mutex_prof_records;
166 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
167     &mutex_prof_records, 0, "Number of profiling records");
168 static int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
169 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
170     &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
171 static int mutex_prof_rejected;
172 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
173     &mutex_prof_rejected, 0, "Number of rejected profiling records");
174 static int mutex_prof_hashsize = MPROF_HASH_SIZE;
175 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
176     &mutex_prof_hashsize, 0, "Hash size");
177 static int mutex_prof_collisions = 0;
178 SYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
179     &mutex_prof_collisions, 0, "Number of hash collisions");
180
181 /*
182  * mprof_mtx protects the profiling buffers and the hash.
183  */
184 static struct mtx mprof_mtx;
185 MTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
186
187 static u_int64_t
188 nanoseconds(void)
189 {
190         struct timespec tv;
191
192         nanotime(&tv);
193         return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
194 }
195
196 static int
197 dump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
198 {
199         struct sbuf *sb;
200         int error, i;
201         static int multiplier = 1;
202
203         if (first_free_mprof_buf == 0)
204                 return (SYSCTL_OUT(req, "No locking recorded",
205                     sizeof("No locking recorded")));
206
207 retry_sbufops:
208         sb = sbuf_new(NULL, NULL, MPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
209         sbuf_printf(sb, "\n%6s %12s %11s %5s %12s %12s %s\n",
210             "max", "total", "count", "avg", "cnt_hold", "cnt_lock", "name");
211         /*
212          * XXX this spinlock seems to be by far the largest perpetrator
213          * of spinlock latency (1.6 msec on an Athlon1600 was recorded
214          * even before I pessimized it further by moving the average
215          * computation here).
216          */
217         mtx_lock_spin(&mprof_mtx);
218         for (i = 0; i < first_free_mprof_buf; ++i) {
219                 sbuf_printf(sb, "%6ju %12ju %11ju %5ju %12ju %12ju %s:%d (%s)\n",
220                     mprof_buf[i].cnt_max / 1000,
221                     mprof_buf[i].cnt_tot / 1000,
222                     mprof_buf[i].cnt_cur,
223                     mprof_buf[i].cnt_cur == 0 ? (uintmax_t)0 :
224                         mprof_buf[i].cnt_tot / (mprof_buf[i].cnt_cur * 1000),
225                     mprof_buf[i].cnt_contest_holding,
226                     mprof_buf[i].cnt_contest_locking,
227                     mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
228                 if (sbuf_overflowed(sb)) {
229                         mtx_unlock_spin(&mprof_mtx);
230                         sbuf_delete(sb);
231                         multiplier++;
232                         goto retry_sbufops;
233                 }
234         }
235         mtx_unlock_spin(&mprof_mtx);
236         sbuf_finish(sb);
237         error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
238         sbuf_delete(sb);
239         return (error);
240 }
241 SYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
242     NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
243
244 static int
245 reset_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
246 {
247         int error, v;
248
249         if (first_free_mprof_buf == 0)
250                 return (0);
251
252         v = 0;
253         error = sysctl_handle_int(oidp, &v, 0, req);
254         if (error)
255                 return (error);
256         if (req->newptr == NULL)
257                 return (error);
258         if (v == 0)
259                 return (0);
260
261         mtx_lock_spin(&mprof_mtx);
262         bzero(mprof_buf, sizeof(*mprof_buf) * first_free_mprof_buf);
263         bzero(mprof_hash, sizeof(struct mtx *) * MPROF_HASH_SIZE);
264         first_free_mprof_buf = 0;
265         mtx_unlock_spin(&mprof_mtx);
266         return (0);
267 }
268 SYSCTL_PROC(_debug_mutex_prof, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
269     NULL, 0, reset_mutex_prof_stats, "I", "Reset mutex profiling statistics");
270 #endif
271
272 /*
273  * Function versions of the inlined __mtx_* macros.  These are used by
274  * modules and can also be called from assembly language if needed.
275  */
276 void
277 _mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
278 {
279
280         MPASS(curthread != NULL);
281         KASSERT(LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_sleep,
282             ("mtx_lock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
283             file, line));
284         WITNESS_CHECKORDER(&m->mtx_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
285             file, line);
286         _get_sleep_lock(m, curthread, opts, file, line);
287         LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
288             line);
289         WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
290 #ifdef MUTEX_PROFILING
291         /* don't reset the timer when/if recursing */
292         if (m->mtx_acqtime == 0) {
293                 m->mtx_filename = file;
294                 m->mtx_lineno = line;
295                 m->mtx_acqtime = mutex_prof_enable ? nanoseconds() : 0;
296                 ++mutex_prof_acquisitions;
297         }
298 #endif
299 }
300
301 void
302 _mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
303 {
304
305         MPASS(curthread != NULL);
306         KASSERT(LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_sleep,
307             ("mtx_unlock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
308             file, line));
309         WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
310         LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
311             line);
312         mtx_assert(m, MA_OWNED);
313 #ifdef MUTEX_PROFILING
314         if (m->mtx_acqtime != 0) {
315                 static const char *unknown = "(unknown)";
316                 struct mutex_prof *mpp;
317                 u_int64_t acqtime, now;
318                 const char *p, *q;
319                 volatile u_int hash;
320
321                 now = nanoseconds();
322                 acqtime = m->mtx_acqtime;
323                 m->mtx_acqtime = 0;
324                 if (now <= acqtime)
325                         goto out;
326                 for (p = m->mtx_filename;
327                     p != NULL && strncmp(p, "../", 3) == 0; p += 3)
328                         /* nothing */ ;
329                 if (p == NULL || *p == '\0')
330                         p = unknown;
331                 for (hash = m->mtx_lineno, q = p; *q != '\0'; ++q)
332                         hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
333                 mtx_lock_spin(&mprof_mtx);
334                 for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
335                         if (mpp->line == m->mtx_lineno &&
336                             strcmp(mpp->file, p) == 0)
337                                 break;
338                 if (mpp == NULL) {
339                         /* Just exit if we cannot get a trace buffer */
340                         if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
341                                 ++mutex_prof_rejected;
342                                 goto unlock;
343                         }
344                         mpp = &mprof_buf[first_free_mprof_buf++];
345                         mpp->name = mtx_name(m);
346                         mpp->file = p;
347                         mpp->line = m->mtx_lineno;
348                         mpp->next = mprof_hash[hash];
349                         if (mprof_hash[hash] != NULL)
350                                 ++mutex_prof_collisions;
351                         mprof_hash[hash] = mpp;
352                         ++mutex_prof_records;
353                 }
354                 /*
355                  * Record if the mutex has been held longer now than ever
356                  * before.
357                  */
358                 if (now - acqtime > mpp->cnt_max)
359                         mpp->cnt_max = now - acqtime;
360                 mpp->cnt_tot += now - acqtime;
361                 mpp->cnt_cur++;
362                 /*
363                  * There's a small race, really we should cmpxchg
364                  * 0 with the current value, but that would bill
365                  * the contention to the wrong lock instance if
366                  * it followed this also.
367                  */
368                 mpp->cnt_contest_holding += m->mtx_contest_holding;
369                 m->mtx_contest_holding = 0;
370                 mpp->cnt_contest_locking += m->mtx_contest_locking;
371                 m->mtx_contest_locking = 0;
372 unlock:
373                 mtx_unlock_spin(&mprof_mtx);
374         }
375 out:
376 #endif
377         _rel_sleep_lock(m, curthread, opts, file, line);
378 }
379
380 void
381 _mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
382 {
383
384         MPASS(curthread != NULL);
385         KASSERT(LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_spin,
386             ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
387             m->mtx_object.lo_name, file, line));
388         WITNESS_CHECKORDER(&m->mtx_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
389             file, line);
390         _get_spin_lock(m, curthread, opts, file, line);
391         LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
392             line);
393         WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
394 }
395
396 void
397 _mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
398 {
399
400         MPASS(curthread != NULL);
401         KASSERT(LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_spin,
402             ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
403             m->mtx_object.lo_name, file, line));
404         WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
405         LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
406             line);
407         mtx_assert(m, MA_OWNED);
408         _rel_spin_lock(m);
409 }
410
411 /*
412  * The important part of mtx_trylock{,_flags}()
413  * Tries to acquire lock `m.'  If this function is called on a mutex that
414  * is already owned, it will recursively acquire the lock.
415  */
416 int
417 _mtx_trylock(struct mtx *m, int opts, const char *file, int line)
418 {
419         int rval;
420
421         MPASS(curthread != NULL);
422         KASSERT(LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_sleep,
423             ("mtx_trylock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
424             file, line));
425
426         if (mtx_owned(m) && (m->mtx_object.lo_flags & LO_RECURSABLE) != 0) {
427                 m->mtx_recurse++;
428                 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
429                 rval = 1;
430         } else
431                 rval = _obtain_lock(m, (uintptr_t)curthread);
432
433         LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
434         if (rval)
435                 WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
436                     file, line);
437
438         return (rval);
439 }
440
441 /*
442  * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
443  *
444  * We call this if the lock is either contested (i.e. we need to go to
445  * sleep waiting for it), or if we need to recurse on it.
446  */
447 void
448 _mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
449     int line)
450 {
451 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
452         struct thread *owner;
453 #endif
454         uintptr_t v;
455 #ifdef KTR
456         int cont_logged = 0;
457 #endif
458 #ifdef MUTEX_PROFILING
459         int contested;
460 #endif
461
462         if (mtx_owned(m)) {
463                 KASSERT((m->mtx_object.lo_flags & LO_RECURSABLE) != 0,
464             ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
465                     m->mtx_object.lo_name, file, line));
466                 m->mtx_recurse++;
467                 atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
468                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
469                         CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
470                 return;
471         }
472
473         if (LOCK_LOG_TEST(&m->mtx_object, opts))
474                 CTR4(KTR_LOCK,
475                     "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
476                     m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
477
478 #ifdef MUTEX_PROFILING
479         contested = 0;
480 #endif
481         while (!_obtain_lock(m, tid)) {
482 #ifdef MUTEX_PROFILING
483                 contested = 1;
484                 atomic_add_int(&m->mtx_contest_holding, 1);
485 #endif
486                 turnstile_lock(&m->mtx_object);
487                 v = m->mtx_lock;
488
489                 /*
490                  * Check if the lock has been released while spinning for
491                  * the turnstile chain lock.
492                  */
493                 if (v == MTX_UNOWNED) {
494                         turnstile_release(&m->mtx_object);
495                         cpu_spinwait();
496                         continue;
497                 }
498
499 #ifdef MUTEX_WAKE_ALL
500                 MPASS(v != MTX_CONTESTED);
501 #else
502                 /*
503                  * The mutex was marked contested on release. This means that
504                  * there are other threads blocked on it.  Grab ownership of
505                  * it and propagate its priority to the current thread if
506                  * necessary.
507                  */
508                 if (v == MTX_CONTESTED) {
509                         m->mtx_lock = tid | MTX_CONTESTED;
510                         turnstile_claim(&m->mtx_object);
511                         break;
512                 }
513 #endif
514
515                 /*
516                  * If the mutex isn't already contested and a failure occurs
517                  * setting the contested bit, the mutex was either released
518                  * or the state of the MTX_RECURSED bit changed.
519                  */
520                 if ((v & MTX_CONTESTED) == 0 &&
521                     !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
522                         turnstile_release(&m->mtx_object);
523                         cpu_spinwait();
524                         continue;
525                 }
526
527 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
528                 /*
529                  * If the current owner of the lock is executing on another
530                  * CPU, spin instead of blocking.
531                  */
532                 owner = (struct thread *)(v & MTX_FLAGMASK);
533 #ifdef ADAPTIVE_GIANT
534                 if (TD_IS_RUNNING(owner)) {
535 #else
536                 if (m != &Giant && TD_IS_RUNNING(owner)) {
537 #endif
538                         turnstile_release(&m->mtx_object);
539                         while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
540                                 cpu_spinwait();
541                         }
542                         continue;
543                 }
544 #endif  /* SMP && !NO_ADAPTIVE_MUTEXES */
545
546                 /*
547                  * We definitely must sleep for this lock.
548                  */
549                 mtx_assert(m, MA_NOTOWNED);
550
551 #ifdef KTR
552                 if (!cont_logged) {
553                         CTR6(KTR_CONTENTION,
554                             "contention: %p at %s:%d wants %s, taken by %s:%d",
555                             (void *)tid, file, line, m->mtx_object.lo_name,
556                             WITNESS_FILE(&m->mtx_object),
557                             WITNESS_LINE(&m->mtx_object));
558                         cont_logged = 1;
559                 }
560 #endif
561
562                 /*
563                  * Block on the turnstile.
564                  */
565                 turnstile_wait(&m->mtx_object, mtx_owner(m),
566                     TS_EXCLUSIVE_QUEUE);
567         }
568
569 #ifdef KTR
570         if (cont_logged) {
571                 CTR4(KTR_CONTENTION,
572                     "contention end: %s acquired by %p at %s:%d",
573                     m->mtx_object.lo_name, (void *)tid, file, line);
574         }
575 #endif
576 #ifdef MUTEX_PROFILING
577         if (contested)
578                 m->mtx_contest_locking++;
579         m->mtx_contest_holding = 0;
580 #endif
581         return;
582 }
583
584 #ifdef SMP
585 /*
586  * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
587  *
588  * This is only called if we need to actually spin for the lock. Recursion
589  * is handled inline.
590  */
591 void
592 _mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
593     int line)
594 {
595         int i = 0;
596
597         if (LOCK_LOG_TEST(&m->mtx_object, opts))
598                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
599
600         for (;;) {
601                 if (_obtain_lock(m, tid))
602                         break;
603
604                 /* Give interrupts a chance while we spin. */
605                 spinlock_exit();
606                 while (m->mtx_lock != MTX_UNOWNED) {
607                         if (i++ < 10000000) {
608                                 cpu_spinwait();
609                                 continue;
610                         }
611                         if (i < 60000000)
612                                 DELAY(1);
613                         else if (!kdb_active && !panicstr) {
614                                 printf("spin lock %s held by %p for > 5 seconds\n",
615                                     m->mtx_object.lo_name, (void *)m->mtx_lock);
616 #ifdef WITNESS
617                                 witness_display_spinlock(&m->mtx_object,
618                                     mtx_owner(m));
619 #endif
620                                 panic("spin lock held too long");
621                         }
622                         cpu_spinwait();
623                 }
624                 spinlock_enter();
625         }
626
627         if (LOCK_LOG_TEST(&m->mtx_object, opts))
628                 CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
629
630         return;
631 }
632 #endif /* SMP */
633
634 /*
635  * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
636  *
637  * We are only called here if the lock is recursed or contested (i.e. we
638  * need to wake up a blocked thread).
639  */
640 void
641 _mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
642 {
643         struct turnstile *ts;
644 #ifndef PREEMPTION
645         struct thread *td, *td1;
646 #endif
647
648         if (mtx_recursed(m)) {
649                 if (--(m->mtx_recurse) == 0)
650                         atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
651                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
652                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
653                 return;
654         }
655
656         turnstile_lock(&m->mtx_object);
657         ts = turnstile_lookup(&m->mtx_object);
658         if (LOCK_LOG_TEST(&m->mtx_object, opts))
659                 CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
660
661 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
662         if (ts == NULL) {
663                 _release_lock_quick(m);
664                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
665                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
666                 turnstile_release(&m->mtx_object);
667                 return;
668         }
669 #else
670         MPASS(ts != NULL);
671 #endif
672 #ifndef PREEMPTION
673         /* XXX */
674         td1 = turnstile_head(ts, TS_EXCLUSIVE_QUEUE);
675 #endif
676 #ifdef MUTEX_WAKE_ALL
677         turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
678         _release_lock_quick(m);
679 #else
680         if (turnstile_signal(ts, TS_EXCLUSIVE_QUEUE)) {
681                 _release_lock_quick(m);
682                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
683                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
684         } else {
685                 m->mtx_lock = MTX_CONTESTED;
686                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
687                         CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p still contested",
688                             m);
689         }
690 #endif
691         turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
692
693 #ifndef PREEMPTION
694         /*
695          * XXX: This is just a hack until preemption is done.  However,
696          * once preemption is done we need to either wrap the
697          * turnstile_signal() and release of the actual lock in an
698          * extra critical section or change the preemption code to
699          * always just set a flag and never do instant-preempts.
700          */
701         td = curthread;
702         if (td->td_critnest > 0 || td1->td_priority >= td->td_priority)
703                 return;
704         mtx_lock_spin(&sched_lock);
705         if (!TD_IS_RUNNING(td1)) {
706 #ifdef notyet
707                 if (td->td_ithd != NULL) {
708                         struct ithd *it = td->td_ithd;
709
710                         if (it->it_interrupted) {
711                                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
712                                         CTR2(KTR_LOCK,
713                                     "_mtx_unlock_sleep: %p interrupted %p",
714                                             it, it->it_interrupted);
715                                 intr_thd_fixup(it);
716                         }
717                 }
718 #endif
719                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
720                         CTR2(KTR_LOCK,
721                             "_mtx_unlock_sleep: %p switching out lock=%p", m,
722                             (void *)m->mtx_lock);
723
724                 mi_switch(SW_INVOL, NULL);
725                 if (LOCK_LOG_TEST(&m->mtx_object, opts))
726                         CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
727                             m, (void *)m->mtx_lock);
728         }
729         mtx_unlock_spin(&sched_lock);
730 #endif
731
732         return;
733 }
734
735 /*
736  * All the unlocking of MTX_SPIN locks is done inline.
737  * See the _rel_spin_lock() macro for the details.
738  */
739
740 /*
741  * The backing function for the INVARIANTS-enabled mtx_assert()
742  */
743 #ifdef INVARIANT_SUPPORT
744 void
745 _mtx_assert(struct mtx *m, int what, const char *file, int line)
746 {
747
748         if (panicstr != NULL || dumping)
749                 return;
750         switch (what) {
751         case MA_OWNED:
752         case MA_OWNED | MA_RECURSED:
753         case MA_OWNED | MA_NOTRECURSED:
754                 if (!mtx_owned(m))
755                         panic("mutex %s not owned at %s:%d",
756                             m->mtx_object.lo_name, file, line);
757                 if (mtx_recursed(m)) {
758                         if ((what & MA_NOTRECURSED) != 0)
759                                 panic("mutex %s recursed at %s:%d",
760                                     m->mtx_object.lo_name, file, line);
761                 } else if ((what & MA_RECURSED) != 0) {
762                         panic("mutex %s unrecursed at %s:%d",
763                             m->mtx_object.lo_name, file, line);
764                 }
765                 break;
766         case MA_NOTOWNED:
767                 if (mtx_owned(m))
768                         panic("mutex %s owned at %s:%d",
769                             m->mtx_object.lo_name, file, line);
770                 break;
771         default:
772                 panic("unknown mtx_assert at %s:%d", file, line);
773         }
774 }
775 #endif
776
777 /*
778  * The MUTEX_DEBUG-enabled mtx_validate()
779  *
780  * Most of these checks have been moved off into the LO_INITIALIZED flag
781  * maintained by the witness code.
782  */
783 #ifdef MUTEX_DEBUG
784
785 void    mtx_validate(struct mtx *);
786
787 void
788 mtx_validate(struct mtx *m)
789 {
790
791 /*
792  * XXX: When kernacc() does not require Giant we can reenable this check
793  */
794 #ifdef notyet
795 /*
796  * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
797  * we can re-enable the kernacc() checks.
798  */
799 #ifndef __alpha__
800         /*
801          * Can't call kernacc() from early init386(), especially when
802          * initializing Giant mutex, because some stuff in kernacc()
803          * requires Giant itself.
804          */
805         if (!cold)
806                 if (!kernacc((caddr_t)m, sizeof(m),
807                     VM_PROT_READ | VM_PROT_WRITE))
808                         panic("Can't read and write to mutex %p", m);
809 #endif
810 #endif
811 }
812 #endif
813
814 /*
815  * General init routine used by the MTX_SYSINIT() macro.
816  */
817 void
818 mtx_sysinit(void *arg)
819 {
820         struct mtx_args *margs = arg;
821
822         mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
823 }
824
825 /*
826  * Mutex initialization routine; initialize lock `m' of type contained in
827  * `opts' with options contained in `opts' and name `name.'  The optional
828  * lock type `type' is used as a general lock category name for use with
829  * witness.
830  */
831 void
832 mtx_init(struct mtx *m, const char *name, const char *type, int opts)
833 {
834         struct lock_class *class;
835         int flags;
836
837         MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
838             MTX_NOWITNESS | MTX_DUPOK)) == 0);
839
840 #ifdef MUTEX_DEBUG
841         /* Diagnostic and error correction */
842         mtx_validate(m);
843 #endif
844
845         /* Determine lock class and lock flags. */
846         if (opts & MTX_SPIN)
847                 class = &lock_class_mtx_spin;
848         else
849                 class = &lock_class_mtx_sleep;
850         flags = 0;
851         if (opts & MTX_QUIET)
852                 flags |= LO_QUIET;
853         if (opts & MTX_RECURSE)
854                 flags |= LO_RECURSABLE;
855         if ((opts & MTX_NOWITNESS) == 0)
856                 flags |= LO_WITNESS;
857         if (opts & MTX_DUPOK)
858                 flags |= LO_DUPOK;
859
860         /* Initialize mutex. */
861         m->mtx_lock = MTX_UNOWNED;
862         m->mtx_recurse = 0;
863 #ifdef MUTEX_PROFILING
864         m->mtx_acqtime = 0;
865         m->mtx_filename = NULL;
866         m->mtx_lineno = 0;
867         m->mtx_contest_holding = 0;
868         m->mtx_contest_locking = 0;
869 #endif
870
871         lock_init(&m->mtx_object, class, name, type, flags);
872 }
873
874 /*
875  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
876  * passed in as a flag here because if the corresponding mtx_init() was
877  * called with MTX_QUIET set, then it will already be set in the mutex's
878  * flags.
879  */
880 void
881 mtx_destroy(struct mtx *m)
882 {
883
884         if (!mtx_owned(m))
885                 MPASS(mtx_unowned(m));
886         else {
887                 MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
888
889                 /* Perform the non-mtx related part of mtx_unlock_spin(). */
890                 if (LOCK_CLASS(&m->mtx_object) == &lock_class_mtx_spin)
891                         spinlock_exit();
892
893                 /* Tell witness this isn't locked to make it happy. */
894                 WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
895                     __LINE__);
896         }
897
898         lock_destroy(&m->mtx_object);
899 }
900
901 /*
902  * Intialize the mutex code and system mutexes.  This is called from the MD
903  * startup code prior to mi_startup().  The per-CPU data space needs to be
904  * setup before this is called.
905  */
906 void
907 mutex_init(void)
908 {
909
910         /* Setup turnstiles so that sleep mutexes work. */
911         init_turnstiles();
912
913         /*
914          * Initialize mutexes.
915          */
916         mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
917         mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
918         mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
919         mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
920         mtx_lock(&Giant);
921 }
922
923 #ifdef DDB
924 void
925 db_show_mtx(struct lock_object *lock)
926 {
927         struct thread *td;
928         struct mtx *m;
929
930         m = (struct mtx *)lock;
931
932         db_printf(" flags: {");
933         if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
934                 db_printf("SPIN");
935         else
936                 db_printf("DEF");
937         if (m->mtx_object.lo_flags & LO_RECURSABLE)
938                 db_printf(", RECURSE");
939         if (m->mtx_object.lo_flags & LO_DUPOK)
940                 db_printf(", DUPOK");
941         db_printf("}\n");
942         db_printf(" state: {");
943         if (mtx_unowned(m))
944                 db_printf("UNOWNED");
945         else {
946                 db_printf("OWNED");
947                 if (m->mtx_lock & MTX_CONTESTED)
948                         db_printf(", CONTESTED");
949                 if (m->mtx_lock & MTX_RECURSED)
950                         db_printf(", RECURSED");
951         }
952         db_printf("}\n");
953         if (!mtx_unowned(m)) {
954                 td = mtx_owner(m);
955                 db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
956                     td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
957                 if (mtx_recursed(m))
958                         db_printf(" recursed: %d\n", m->mtx_recurse);
959         }
960 }
961 #endif