2 * SPDX-License-Identifier: BSD-2-Clause
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>
35 #include "opt_mprof.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
41 #include <sys/limits.h>
43 #include <sys/lock_profile.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
49 #include <sys/sched.h>
51 #include <sys/sysctl.h>
57 #include <machine/cpufunc.h>
60 * Uncomment to validate that spin argument to acquire/release routines matches
61 * the flag in the lock
63 //#define LOCK_PROFILING_DEBUG_SPIN
65 CTASSERT(LOCK_CLASS_MAX == 15);
67 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
69 &lock_class_mtx_sleep,
72 &lock_class_rm_sleepable,
78 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
79 const char *type, int flags)
83 /* Check for double-init and zero object. */
84 KASSERT(flags & LO_NEW || !lock_initialized(lock),
85 ("lock \"%s\" %p already initialized", name, lock));
87 /* Look up lock class to find its index. */
88 for (i = 0; i < LOCK_CLASS_MAX; i++)
89 if (lock_classes[i] == class) {
90 lock->lo_flags = i << LO_CLASSSHIFT;
93 KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
95 /* Initialize the lock object. */
97 lock->lo_flags |= flags | LO_INITIALIZED;
98 LOCK_LOG_INIT(lock, 0);
99 WITNESS_INIT(lock, (type != NULL) ? type : name);
103 lock_destroy(struct lock_object *lock)
106 KASSERT(lock_initialized(lock), ("lock %p is not initialized", lock));
107 WITNESS_DESTROY(lock);
108 LOCK_LOG_DESTROY(lock, 0);
109 lock->lo_flags &= ~LO_INITIALIZED;
112 static SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
114 static SYSCTL_NODE(_debug_lock, OID_AUTO, delay,
115 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
119 lock_delay(struct lock_delay_arg *la)
121 struct lock_delay_config *lc = la->config;
124 for (i = la->delay; i > 0; i--)
126 la->spin_cnt += la->delay;
129 if (__predict_false(la->delay > (u_int)lc->max))
134 lock_roundup_2(u_int val)
138 for (res = 1; res <= val; res <<= 1)
145 lock_delay_default_init(struct lock_delay_config *lc)
149 lc->max = min(lock_roundup_2(mp_ncpus) * 256, SHRT_MAX);
152 struct lock_delay_config __read_frequently locks_delay;
153 u_short __read_frequently locks_delay_retries;
154 u_short __read_frequently locks_delay_loops;
156 SYSCTL_U16(_debug_lock, OID_AUTO, delay_base, CTLFLAG_RW, &locks_delay.base,
158 SYSCTL_U16(_debug_lock, OID_AUTO, delay_max, CTLFLAG_RW, &locks_delay.max,
160 SYSCTL_U16(_debug_lock, OID_AUTO, delay_retries, CTLFLAG_RW, &locks_delay_retries,
162 SYSCTL_U16(_debug_lock, OID_AUTO, delay_loops, CTLFLAG_RW, &locks_delay_loops,
166 locks_delay_init(void *arg __unused)
169 lock_delay_default_init(&locks_delay);
170 locks_delay_retries = 10;
171 locks_delay_loops = max(10000, locks_delay.max);
173 LOCK_DELAY_SYSINIT(locks_delay_init);
176 DB_SHOW_COMMAND(lock, db_show_lock)
178 struct lock_object *lock;
179 struct lock_class *class;
183 lock = (struct lock_object *)addr;
184 if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
185 db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
188 class = LOCK_CLASS(lock);
189 db_printf(" class: %s\n", class->lc_name);
190 db_printf(" name: %s\n", lock->lo_name);
191 class->lc_ddb_show(lock);
195 #ifdef LOCK_PROFILING
198 * One object per-thread for each lock the thread owns. Tracks individual
201 struct lock_profile_object {
202 LIST_ENTRY(lock_profile_object) lpo_link;
203 struct lock_object *lpo_obj;
204 const char *lpo_file;
208 uint64_t lpo_acqtime;
209 uint64_t lpo_waittime;
210 u_int lpo_contest_locking;
214 * One lock_prof for each (file, line, lock object) triple.
217 SLIST_ENTRY(lock_prof) link;
218 struct lock_class *class;
223 uintmax_t cnt_wait_max;
228 uintmax_t cnt_contest_locking;
231 SLIST_HEAD(lphead, lock_prof);
233 #define LPROF_HASH_SIZE 4096
234 #define LPROF_HASH_MASK (LPROF_HASH_SIZE - 1)
235 #define LPROF_CACHE_SIZE 4096
238 * Array of objects and profs for each type of object for each cpu. Spinlocks
239 * are handled separately because a thread may be preempted and acquire a
240 * spinlock while in the lock profiling code of a non-spinlock. In this way
241 * we only need a critical section to protect the per-cpu lists.
243 struct lock_prof_type {
244 struct lphead lpt_lpalloc;
245 struct lpohead lpt_lpoalloc;
246 struct lphead lpt_hash[LPROF_HASH_SIZE];
247 struct lock_prof lpt_prof[LPROF_CACHE_SIZE];
248 struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
251 struct lock_prof_cpu {
252 struct lock_prof_type lpc_types[2]; /* One for spin one for other. */
255 DPCPU_DEFINE_STATIC(struct lock_prof_cpu, lp);
256 #define LP_CPU_SELF (DPCPU_PTR(lp))
257 #define LP_CPU(cpu) (DPCPU_ID_PTR((cpu), lp))
259 volatile int __read_mostly lock_prof_enable;
260 int __read_mostly lock_contested_only;
261 static volatile int lock_prof_resetting;
263 #define LPROF_SBUF_SIZE 256
265 static int lock_prof_rejected;
266 static int lock_prof_skipspin;
268 #ifndef USE_CPU_NANOSECONDS
276 /* From bintime2timespec */
277 ns = bt.sec * (uint64_t)1000000000;
278 ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
284 lock_prof_init_type(struct lock_prof_type *type)
288 SLIST_INIT(&type->lpt_lpalloc);
289 LIST_INIT(&type->lpt_lpoalloc);
290 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
291 SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
293 LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
299 lock_prof_init(void *arg)
304 lock_prof_init_type(&LP_CPU(cpu)->lpc_types[0]);
305 lock_prof_init_type(&LP_CPU(cpu)->lpc_types[1]);
308 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
311 lock_prof_reset_wait(void)
315 * Spin relinquishing our cpu so that quiesce_all_cpus may
318 while (lock_prof_resetting)
319 sched_relinquish(curthread);
323 lock_prof_reset(void)
325 struct lock_prof_cpu *lpc;
329 * We not only race with acquiring and releasing locks but also
330 * thread exit. To be certain that threads exit without valid head
331 * pointers they must see resetting set before enabled is cleared.
332 * Otherwise a lock may not be removed from a per-thread list due
333 * to disabled being set but not wait for reset() to remove it below.
335 atomic_store_rel_int(&lock_prof_resetting, 1);
336 enabled = lock_prof_enable;
337 lock_prof_enable = 0;
339 * This both publishes lock_prof_enable as disabled and makes sure
340 * everyone else reads it if they are not far enough. We wait for the
343 cpus_fence_seq_cst();
344 quiesce_all_critical();
346 * Some objects may have migrated between CPUs. Clear all links
347 * before we zero the structures. Some items may still be linked
348 * into per-thread lists as well.
352 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
353 LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
354 LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
359 bzero(lpc, sizeof(*lpc));
360 lock_prof_init_type(&lpc->lpc_types[0]);
361 lock_prof_init_type(&lpc->lpc_types[1]);
364 * Paired with the fence from cpus_fence_seq_cst()
366 atomic_store_rel_int(&lock_prof_resetting, 0);
367 lock_prof_enable = enabled;
371 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
375 for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
377 "%8ju %9ju %11ju %11ju %11ju %6ju %6ju %2ju %6ju %s:%d (%s:%s)\n",
378 lp->cnt_max / 1000, lp->cnt_wait_max / 1000, lp->cnt_tot / 1000,
379 lp->cnt_wait / 1000, lp->cnt_cur,
380 lp->cnt_cur == 0 ? (uintmax_t)0 :
381 lp->cnt_tot / (lp->cnt_cur * 1000),
382 lp->cnt_cur == 0 ? (uintmax_t)0 :
383 lp->cnt_wait / (lp->cnt_cur * 1000),
384 (uintmax_t)0, lp->cnt_contest_locking,
385 p, lp->line, lp->class->lc_name, lp->name);
389 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
392 struct lock_prof_type *type;
396 dst->file = match->file;
397 dst->line = match->line;
398 dst->class = match->class;
399 dst->name = match->name;
402 type = &LP_CPU(cpu)->lpc_types[spin];
403 SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
406 if (l->file != match->file || l->line != match->line ||
407 l->name != match->name)
410 if (l->cnt_max > dst->cnt_max)
411 dst->cnt_max = l->cnt_max;
412 if (l->cnt_wait_max > dst->cnt_wait_max)
413 dst->cnt_wait_max = l->cnt_wait_max;
414 dst->cnt_tot += l->cnt_tot;
415 dst->cnt_wait += l->cnt_wait;
416 dst->cnt_cur += l->cnt_cur;
417 dst->cnt_contest_locking += l->cnt_contest_locking;
423 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
429 for (i = 0; i < LPROF_HASH_SIZE; ++i) {
430 SLIST_FOREACH(l, &type->lpt_hash[i], link) {
431 struct lock_prof lp = {};
435 lock_prof_sum(l, &lp, i, spin, t);
436 lock_prof_output(&lp, sb);
442 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
448 error = sysctl_wire_old_buffer(req, 0);
451 sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
452 sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
453 "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
454 enabled = lock_prof_enable;
455 lock_prof_enable = 0;
457 * See the comment in lock_prof_reset
459 cpus_fence_seq_cst();
460 quiesce_all_critical();
463 lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[0], sb, 0, t);
464 lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[1], sb, 1, t);
466 atomic_thread_fence_rel();
467 lock_prof_enable = enabled;
469 error = sbuf_finish(sb);
470 /* Output a trailing NUL. */
472 error = SYSCTL_OUT(req, "", 1);
478 enable_lock_prof(SYSCTL_HANDLER_ARGS)
482 v = lock_prof_enable;
483 error = sysctl_handle_int(oidp, &v, v, req);
486 if (req->newptr == NULL)
488 if (v == lock_prof_enable)
492 lock_prof_enable = !!v;
498 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
503 error = sysctl_handle_int(oidp, &v, 0, req);
506 if (req->newptr == NULL)
515 static struct lock_prof *
516 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
519 const char *unknown = "(unknown)";
520 struct lock_prof_type *type;
521 struct lock_prof *lp;
527 if (p == NULL || *p == '\0')
529 hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
530 hash &= LPROF_HASH_MASK;
531 type = &LP_CPU_SELF->lpc_types[spin];
532 head = &type->lpt_hash[hash];
533 SLIST_FOREACH(lp, head, link) {
534 if (lp->line == line && lp->file == p &&
535 lp->name == lo->lo_name)
538 lp = SLIST_FIRST(&type->lpt_lpalloc);
540 lock_prof_rejected++;
543 SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
546 lp->class = LOCK_CLASS(lo);
547 lp->name = lo->lo_name;
548 SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
552 static struct lock_profile_object *
553 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
556 struct lock_profile_object *l;
557 struct lock_prof_type *type;
558 struct lpohead *head;
560 head = &curthread->td_lprof[spin];
561 LIST_FOREACH(l, head, lpo_link)
562 if (l->lpo_obj == lo && l->lpo_file == file &&
565 type = &LP_CPU_SELF->lpc_types[spin];
566 l = LIST_FIRST(&type->lpt_lpoalloc);
568 lock_prof_rejected++;
571 LIST_REMOVE(l, lpo_link);
576 LIST_INSERT_HEAD(head, l, lpo_link);
582 lock_profile_obtain_lock_success(struct lock_object *lo, bool spin,
583 int contested, uint64_t waittime, const char *file, int line)
585 struct lock_profile_object *l;
587 #ifdef LOCK_PROFILING_DEBUG_SPIN
588 bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
589 if ((spin && !is_spin) || (!spin && is_spin))
590 printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
591 lo->lo_name, spin, is_spin);
594 /* don't reset the timer when/if recursing */
595 if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
597 if (lock_contested_only && !contested)
599 if (spin && lock_prof_skipspin == 1)
602 if (SCHEDULER_STOPPED())
606 /* Recheck enabled now that we're in a critical section. */
607 if (lock_prof_enable == 0)
609 l = lock_profile_object_lookup(lo, spin, file, line);
613 if (++l->lpo_ref > 1)
615 l->lpo_contest_locking = contested;
616 l->lpo_acqtime = nanoseconds();
617 if (waittime && (l->lpo_acqtime > waittime))
618 l->lpo_waittime = l->lpo_acqtime - waittime;
623 * Paired with cpus_fence_seq_cst().
625 atomic_thread_fence_rel();
630 lock_profile_thread_exit(struct thread *td)
633 struct lock_profile_object *l;
635 MPASS(curthread->td_critnest == 0);
638 * If lock profiling was disabled we have to wait for reset to
639 * clear our pointers before we can exit safely.
641 lock_prof_reset_wait();
643 LIST_FOREACH(l, &td->td_lprof[0], lpo_link)
644 printf("thread still holds lock acquired at %s:%d\n",
645 l->lpo_file, l->lpo_line);
646 LIST_FOREACH(l, &td->td_lprof[1], lpo_link)
647 printf("thread still holds lock acquired at %s:%d\n",
648 l->lpo_file, l->lpo_line);
650 MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
651 MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
655 lock_profile_release_lock(struct lock_object *lo, bool spin)
657 struct lock_profile_object *l;
658 struct lock_prof_type *type;
659 struct lock_prof *lp;
660 uint64_t curtime, holdtime;
661 struct lpohead *head;
663 #ifdef LOCK_PROFILING_DEBUG_SPIN
664 bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
665 if ((spin && !is_spin) || (!spin && is_spin))
666 printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
667 lo->lo_name, spin, is_spin);
670 if (lo->lo_flags & LO_NOPROFILE)
672 head = &curthread->td_lprof[spin];
673 if (LIST_FIRST(head) == NULL)
675 if (SCHEDULER_STOPPED())
678 /* Recheck enabled now that we're in a critical section. */
679 if (lock_prof_enable == 0 && lock_prof_resetting == 1)
682 * If lock profiling is not enabled we still want to remove the
683 * lpo from our queue.
685 LIST_FOREACH(l, head, lpo_link)
686 if (l->lpo_obj == lo)
690 if (--l->lpo_ref > 0)
692 lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
695 curtime = nanoseconds();
696 if (curtime < l->lpo_acqtime)
698 holdtime = curtime - l->lpo_acqtime;
701 * Record if the lock has been held longer now than ever
704 if (holdtime > lp->cnt_max)
705 lp->cnt_max = holdtime;
706 if (l->lpo_waittime > lp->cnt_wait_max)
707 lp->cnt_wait_max = l->lpo_waittime;
708 lp->cnt_tot += holdtime;
709 lp->cnt_wait += l->lpo_waittime;
710 lp->cnt_contest_locking += l->lpo_contest_locking;
711 lp->cnt_cur += l->lpo_cnt;
713 LIST_REMOVE(l, lpo_link);
714 type = &LP_CPU_SELF->lpc_types[spin];
715 LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
718 * Paired with cpus_fence_seq_cst().
720 atomic_thread_fence_rel();
724 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof,
725 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
727 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
728 &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
729 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
730 &lock_prof_rejected, 0, "Number of rejected profiling records");
731 SYSCTL_INT(_debug_lock_prof, OID_AUTO, contested_only, CTLFLAG_RW,
732 &lock_contested_only, 0, "Only profile contested acquires");
733 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats,
734 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
735 dump_lock_prof_stats, "A",
736 "Lock profiling statistics");
737 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset,
738 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
739 reset_lock_prof_stats, "I",
740 "Reset lock profiling statistics");
741 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable,
742 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
743 enable_lock_prof, "I",
744 "Enable lock profiling");