2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * This module holds the global variables and functions used to maintain
30 * lock_object structures.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
37 #include "opt_mprof.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
43 #include <sys/limits.h>
45 #include <sys/lock_profile.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
51 #include <sys/sched.h>
53 #include <sys/sysctl.h>
59 #include <machine/cpufunc.h>
62 * Uncomment to validate that spin argument to acquire/release routines matches
63 * the flag in the lock
65 //#define LOCK_PROFILING_DEBUG_SPIN
67 CTASSERT(LOCK_CLASS_MAX == 15);
69 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
71 &lock_class_mtx_sleep,
74 &lock_class_rm_sleepable,
80 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
81 const char *type, int flags)
85 /* Check for double-init and zero object. */
86 KASSERT(flags & LO_NEW || !lock_initialized(lock),
87 ("lock \"%s\" %p already initialized", name, lock));
89 /* Look up lock class to find its index. */
90 for (i = 0; i < LOCK_CLASS_MAX; i++)
91 if (lock_classes[i] == class) {
92 lock->lo_flags = i << LO_CLASSSHIFT;
95 KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
97 /* Initialize the lock object. */
99 lock->lo_flags |= flags | LO_INITIALIZED;
100 LOCK_LOG_INIT(lock, 0);
101 WITNESS_INIT(lock, (type != NULL) ? type : name);
105 lock_destroy(struct lock_object *lock)
108 KASSERT(lock_initialized(lock), ("lock %p is not initialized", lock));
109 WITNESS_DESTROY(lock);
110 LOCK_LOG_DESTROY(lock, 0);
111 lock->lo_flags &= ~LO_INITIALIZED;
114 static SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
116 static SYSCTL_NODE(_debug_lock, OID_AUTO, delay,
117 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
121 lock_delay(struct lock_delay_arg *la)
123 struct lock_delay_config *lc = la->config;
126 for (i = la->delay; i > 0; i--)
128 la->spin_cnt += la->delay;
131 if (__predict_false(la->delay > lc->max))
136 lock_roundup_2(u_int val)
140 for (res = 1; res <= val; res <<= 1)
147 lock_delay_default_init(struct lock_delay_config *lc)
151 lc->max = lock_roundup_2(mp_ncpus) * 256;
156 struct lock_delay_config __read_frequently locks_delay;
157 u_short __read_frequently locks_delay_retries;
158 u_short __read_frequently locks_delay_loops;
160 SYSCTL_U16(_debug_lock, OID_AUTO, delay_base, CTLFLAG_RW, &locks_delay.base,
162 SYSCTL_U16(_debug_lock, OID_AUTO, delay_max, CTLFLAG_RW, &locks_delay.max,
164 SYSCTL_U16(_debug_lock, OID_AUTO, delay_retries, CTLFLAG_RW, &locks_delay_retries,
166 SYSCTL_U16(_debug_lock, OID_AUTO, delay_loops, CTLFLAG_RW, &locks_delay_loops,
170 locks_delay_init(void *arg __unused)
173 lock_delay_default_init(&locks_delay);
174 locks_delay_retries = 10;
175 locks_delay_loops = max(10000, locks_delay.max);
177 LOCK_DELAY_SYSINIT(locks_delay_init);
180 DB_SHOW_COMMAND(lock, db_show_lock)
182 struct lock_object *lock;
183 struct lock_class *class;
187 lock = (struct lock_object *)addr;
188 if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
189 db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
192 class = LOCK_CLASS(lock);
193 db_printf(" class: %s\n", class->lc_name);
194 db_printf(" name: %s\n", lock->lo_name);
195 class->lc_ddb_show(lock);
199 #ifdef LOCK_PROFILING
202 * One object per-thread for each lock the thread owns. Tracks individual
205 struct lock_profile_object {
206 LIST_ENTRY(lock_profile_object) lpo_link;
207 struct lock_object *lpo_obj;
208 const char *lpo_file;
212 uint64_t lpo_acqtime;
213 uint64_t lpo_waittime;
214 u_int lpo_contest_locking;
218 * One lock_prof for each (file, line, lock object) triple.
221 SLIST_ENTRY(lock_prof) link;
222 struct lock_class *class;
227 uintmax_t cnt_wait_max;
232 uintmax_t cnt_contest_locking;
235 SLIST_HEAD(lphead, lock_prof);
237 #define LPROF_HASH_SIZE 4096
238 #define LPROF_HASH_MASK (LPROF_HASH_SIZE - 1)
239 #define LPROF_CACHE_SIZE 4096
242 * Array of objects and profs for each type of object for each cpu. Spinlocks
243 * are handled separately because a thread may be preempted and acquire a
244 * spinlock while in the lock profiling code of a non-spinlock. In this way
245 * we only need a critical section to protect the per-cpu lists.
247 struct lock_prof_type {
248 struct lphead lpt_lpalloc;
249 struct lpohead lpt_lpoalloc;
250 struct lphead lpt_hash[LPROF_HASH_SIZE];
251 struct lock_prof lpt_prof[LPROF_CACHE_SIZE];
252 struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
255 struct lock_prof_cpu {
256 struct lock_prof_type lpc_types[2]; /* One for spin one for other. */
259 DPCPU_DEFINE_STATIC(struct lock_prof_cpu, lp);
260 #define LP_CPU_SELF (DPCPU_PTR(lp))
261 #define LP_CPU(cpu) (DPCPU_ID_PTR((cpu), lp))
263 volatile int __read_mostly lock_prof_enable;
264 int __read_mostly lock_contested_only;
265 static volatile int lock_prof_resetting;
267 #define LPROF_SBUF_SIZE 256
269 static int lock_prof_rejected;
270 static int lock_prof_skipspin;
272 #ifndef USE_CPU_NANOSECONDS
280 /* From bintime2timespec */
281 ns = bt.sec * (uint64_t)1000000000;
282 ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
288 lock_prof_init_type(struct lock_prof_type *type)
292 SLIST_INIT(&type->lpt_lpalloc);
293 LIST_INIT(&type->lpt_lpoalloc);
294 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
295 SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
297 LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
303 lock_prof_init(void *arg)
308 lock_prof_init_type(&LP_CPU(cpu)->lpc_types[0]);
309 lock_prof_init_type(&LP_CPU(cpu)->lpc_types[1]);
312 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
315 lock_prof_reset_wait(void)
319 * Spin relinquishing our cpu so that quiesce_all_cpus may
322 while (lock_prof_resetting)
323 sched_relinquish(curthread);
327 lock_prof_reset(void)
329 struct lock_prof_cpu *lpc;
333 * We not only race with acquiring and releasing locks but also
334 * thread exit. To be certain that threads exit without valid head
335 * pointers they must see resetting set before enabled is cleared.
336 * Otherwise a lock may not be removed from a per-thread list due
337 * to disabled being set but not wait for reset() to remove it below.
339 atomic_store_rel_int(&lock_prof_resetting, 1);
340 enabled = lock_prof_enable;
341 lock_prof_enable = 0;
343 * This both publishes lock_prof_enable as disabled and makes sure
344 * everyone else reads it if they are not far enough. We wait for the
347 cpus_fence_seq_cst();
348 quiesce_all_critical();
350 * Some objects may have migrated between CPUs. Clear all links
351 * before we zero the structures. Some items may still be linked
352 * into per-thread lists as well.
356 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
357 LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
358 LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
363 bzero(lpc, sizeof(*lpc));
364 lock_prof_init_type(&lpc->lpc_types[0]);
365 lock_prof_init_type(&lpc->lpc_types[1]);
368 * Paired with the fence from cpus_fence_seq_cst()
370 atomic_store_rel_int(&lock_prof_resetting, 0);
371 lock_prof_enable = enabled;
375 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
379 for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
381 "%8ju %9ju %11ju %11ju %11ju %6ju %6ju %2ju %6ju %s:%d (%s:%s)\n",
382 lp->cnt_max / 1000, lp->cnt_wait_max / 1000, lp->cnt_tot / 1000,
383 lp->cnt_wait / 1000, lp->cnt_cur,
384 lp->cnt_cur == 0 ? (uintmax_t)0 :
385 lp->cnt_tot / (lp->cnt_cur * 1000),
386 lp->cnt_cur == 0 ? (uintmax_t)0 :
387 lp->cnt_wait / (lp->cnt_cur * 1000),
388 (uintmax_t)0, lp->cnt_contest_locking,
389 p, lp->line, lp->class->lc_name, lp->name);
393 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
396 struct lock_prof_type *type;
400 dst->file = match->file;
401 dst->line = match->line;
402 dst->class = match->class;
403 dst->name = match->name;
406 type = &LP_CPU(cpu)->lpc_types[spin];
407 SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
410 if (l->file != match->file || l->line != match->line ||
411 l->name != match->name)
414 if (l->cnt_max > dst->cnt_max)
415 dst->cnt_max = l->cnt_max;
416 if (l->cnt_wait_max > dst->cnt_wait_max)
417 dst->cnt_wait_max = l->cnt_wait_max;
418 dst->cnt_tot += l->cnt_tot;
419 dst->cnt_wait += l->cnt_wait;
420 dst->cnt_cur += l->cnt_cur;
421 dst->cnt_contest_locking += l->cnt_contest_locking;
427 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
433 for (i = 0; i < LPROF_HASH_SIZE; ++i) {
434 SLIST_FOREACH(l, &type->lpt_hash[i], link) {
435 struct lock_prof lp = {};
439 lock_prof_sum(l, &lp, i, spin, t);
440 lock_prof_output(&lp, sb);
446 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
452 error = sysctl_wire_old_buffer(req, 0);
455 sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
456 sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
457 "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
458 enabled = lock_prof_enable;
459 lock_prof_enable = 0;
461 * See the comment in lock_prof_reset
463 cpus_fence_seq_cst();
464 quiesce_all_critical();
467 lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[0], sb, 0, t);
468 lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[1], sb, 1, t);
470 atomic_thread_fence_rel();
471 lock_prof_enable = enabled;
473 error = sbuf_finish(sb);
474 /* Output a trailing NUL. */
476 error = SYSCTL_OUT(req, "", 1);
482 enable_lock_prof(SYSCTL_HANDLER_ARGS)
486 v = lock_prof_enable;
487 error = sysctl_handle_int(oidp, &v, v, req);
490 if (req->newptr == NULL)
492 if (v == lock_prof_enable)
496 lock_prof_enable = !!v;
502 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
507 error = sysctl_handle_int(oidp, &v, 0, req);
510 if (req->newptr == NULL)
519 static struct lock_prof *
520 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
523 const char *unknown = "(unknown)";
524 struct lock_prof_type *type;
525 struct lock_prof *lp;
531 if (p == NULL || *p == '\0')
533 hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
534 hash &= LPROF_HASH_MASK;
535 type = &LP_CPU_SELF->lpc_types[spin];
536 head = &type->lpt_hash[hash];
537 SLIST_FOREACH(lp, head, link) {
538 if (lp->line == line && lp->file == p &&
539 lp->name == lo->lo_name)
542 lp = SLIST_FIRST(&type->lpt_lpalloc);
544 lock_prof_rejected++;
547 SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
550 lp->class = LOCK_CLASS(lo);
551 lp->name = lo->lo_name;
552 SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
556 static struct lock_profile_object *
557 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
560 struct lock_profile_object *l;
561 struct lock_prof_type *type;
562 struct lpohead *head;
564 head = &curthread->td_lprof[spin];
565 LIST_FOREACH(l, head, lpo_link)
566 if (l->lpo_obj == lo && l->lpo_file == file &&
569 type = &LP_CPU_SELF->lpc_types[spin];
570 l = LIST_FIRST(&type->lpt_lpoalloc);
572 lock_prof_rejected++;
575 LIST_REMOVE(l, lpo_link);
580 LIST_INSERT_HEAD(head, l, lpo_link);
586 lock_profile_obtain_lock_success(struct lock_object *lo, bool spin,
587 int contested, uint64_t waittime, const char *file, int line)
589 struct lock_profile_object *l;
591 #ifdef LOCK_PROFILING_DEBUG_SPIN
592 bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
593 if ((spin && !is_spin) || (!spin && is_spin))
594 printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
595 lo->lo_name, spin, is_spin);
598 /* don't reset the timer when/if recursing */
599 if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
601 if (lock_contested_only && !contested)
603 if (spin && lock_prof_skipspin == 1)
606 if (SCHEDULER_STOPPED())
610 /* Recheck enabled now that we're in a critical section. */
611 if (lock_prof_enable == 0)
613 l = lock_profile_object_lookup(lo, spin, file, line);
617 if (++l->lpo_ref > 1)
619 l->lpo_contest_locking = contested;
620 l->lpo_acqtime = nanoseconds();
621 if (waittime && (l->lpo_acqtime > waittime))
622 l->lpo_waittime = l->lpo_acqtime - waittime;
627 * Paired with cpus_fence_seq_cst().
629 atomic_thread_fence_rel();
634 lock_profile_thread_exit(struct thread *td)
637 struct lock_profile_object *l;
639 MPASS(curthread->td_critnest == 0);
642 * If lock profiling was disabled we have to wait for reset to
643 * clear our pointers before we can exit safely.
645 lock_prof_reset_wait();
647 LIST_FOREACH(l, &td->td_lprof[0], lpo_link)
648 printf("thread still holds lock acquired at %s:%d\n",
649 l->lpo_file, l->lpo_line);
650 LIST_FOREACH(l, &td->td_lprof[1], lpo_link)
651 printf("thread still holds lock acquired at %s:%d\n",
652 l->lpo_file, l->lpo_line);
654 MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
655 MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
659 lock_profile_release_lock(struct lock_object *lo, bool spin)
661 struct lock_profile_object *l;
662 struct lock_prof_type *type;
663 struct lock_prof *lp;
664 uint64_t curtime, holdtime;
665 struct lpohead *head;
667 #ifdef LOCK_PROFILING_DEBUG_SPIN
668 bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
669 if ((spin && !is_spin) || (!spin && is_spin))
670 printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
671 lo->lo_name, spin, is_spin);
674 if (lo->lo_flags & LO_NOPROFILE)
676 head = &curthread->td_lprof[spin];
677 if (LIST_FIRST(head) == NULL)
679 if (SCHEDULER_STOPPED())
682 /* Recheck enabled now that we're in a critical section. */
683 if (lock_prof_enable == 0 && lock_prof_resetting == 1)
686 * If lock profiling is not enabled we still want to remove the
687 * lpo from our queue.
689 LIST_FOREACH(l, head, lpo_link)
690 if (l->lpo_obj == lo)
694 if (--l->lpo_ref > 0)
696 lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
699 curtime = nanoseconds();
700 if (curtime < l->lpo_acqtime)
702 holdtime = curtime - l->lpo_acqtime;
705 * Record if the lock has been held longer now than ever
708 if (holdtime > lp->cnt_max)
709 lp->cnt_max = holdtime;
710 if (l->lpo_waittime > lp->cnt_wait_max)
711 lp->cnt_wait_max = l->lpo_waittime;
712 lp->cnt_tot += holdtime;
713 lp->cnt_wait += l->lpo_waittime;
714 lp->cnt_contest_locking += l->lpo_contest_locking;
715 lp->cnt_cur += l->lpo_cnt;
717 LIST_REMOVE(l, lpo_link);
718 type = &LP_CPU_SELF->lpc_types[spin];
719 LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
722 * Paired with cpus_fence_seq_cst().
724 atomic_thread_fence_rel();
728 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof,
729 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
731 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
732 &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
733 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
734 &lock_prof_rejected, 0, "Number of rejected profiling records");
735 SYSCTL_INT(_debug_lock_prof, OID_AUTO, contested_only, CTLFLAG_RW,
736 &lock_contested_only, 0, "Only profile contested acquires");
737 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats,
738 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
739 dump_lock_prof_stats, "A",
740 "Lock profiling statistics");
741 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset,
742 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
743 reset_lock_prof_stats, "I",
744 "Reset lock profiling statistics");
745 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable,
746 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
747 enable_lock_prof, "I",
748 "Enable lock profiling");