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>
44 #include <sys/lock_profile.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
50 #include <sys/sched.h>
52 #include <sys/sysctl.h>
58 #include <machine/cpufunc.h>
60 SDT_PROVIDER_DEFINE(lock);
61 SDT_PROBE_DEFINE1(lock, , , starvation, "u_int");
63 CTASSERT(LOCK_CLASS_MAX == 15);
65 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
67 &lock_class_mtx_sleep,
70 &lock_class_rm_sleepable,
76 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
77 const char *type, int flags)
81 /* Check for double-init and zero object. */
82 KASSERT(flags & LO_NEW || !lock_initialized(lock),
83 ("lock \"%s\" %p already initialized", name, lock));
85 /* Look up lock class to find its index. */
86 for (i = 0; i < LOCK_CLASS_MAX; i++)
87 if (lock_classes[i] == class) {
88 lock->lo_flags = i << LO_CLASSSHIFT;
91 KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
93 /* Initialize the lock object. */
95 lock->lo_flags |= flags | LO_INITIALIZED;
96 LOCK_LOG_INIT(lock, 0);
97 WITNESS_INIT(lock, (type != NULL) ? type : name);
101 lock_destroy(struct lock_object *lock)
104 KASSERT(lock_initialized(lock), ("lock %p is not initialized", lock));
105 WITNESS_DESTROY(lock);
106 LOCK_LOG_DESTROY(lock, 0);
107 lock->lo_flags &= ~LO_INITIALIZED;
110 static SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD, NULL, "lock debugging");
111 static SYSCTL_NODE(_debug_lock, OID_AUTO, delay, CTLFLAG_RD, NULL,
114 static u_int __read_mostly starvation_limit = 131072;
115 SYSCTL_INT(_debug_lock_delay, OID_AUTO, starvation_limit, CTLFLAG_RW,
116 &starvation_limit, 0, "");
118 static u_int __read_mostly restrict_starvation = 0;
119 SYSCTL_INT(_debug_lock_delay, OID_AUTO, restrict_starvation, CTLFLAG_RW,
120 &restrict_starvation, 0, "");
123 lock_delay(struct lock_delay_arg *la)
125 struct lock_delay_config *lc = la->config;
129 if (__predict_false(la->delay > lc->max))
132 for (i = la->delay; i > 0; i--)
135 la->spin_cnt += la->delay;
136 if (__predict_false(la->spin_cnt > starvation_limit)) {
137 SDT_PROBE1(lock, , , starvation, la->delay);
138 if (restrict_starvation)
139 la->delay = lc->base;
144 lock_roundup_2(u_int val)
148 for (res = 1; res <= val; res <<= 1)
155 lock_delay_default_init(struct lock_delay_config *lc)
159 lc->max = lock_roundup_2(mp_ncpus) * 256;
165 DB_SHOW_COMMAND(lock, db_show_lock)
167 struct lock_object *lock;
168 struct lock_class *class;
172 lock = (struct lock_object *)addr;
173 if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
174 db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
177 class = LOCK_CLASS(lock);
178 db_printf(" class: %s\n", class->lc_name);
179 db_printf(" name: %s\n", lock->lo_name);
180 class->lc_ddb_show(lock);
184 #ifdef LOCK_PROFILING
187 * One object per-thread for each lock the thread owns. Tracks individual
190 struct lock_profile_object {
191 LIST_ENTRY(lock_profile_object) lpo_link;
192 struct lock_object *lpo_obj;
193 const char *lpo_file;
197 uint64_t lpo_acqtime;
198 uint64_t lpo_waittime;
199 u_int lpo_contest_locking;
203 * One lock_prof for each (file, line, lock object) triple.
206 SLIST_ENTRY(lock_prof) link;
207 struct lock_class *class;
212 uintmax_t cnt_wait_max;
217 uintmax_t cnt_contest_locking;
220 SLIST_HEAD(lphead, lock_prof);
222 #define LPROF_HASH_SIZE 4096
223 #define LPROF_HASH_MASK (LPROF_HASH_SIZE - 1)
224 #define LPROF_CACHE_SIZE 4096
227 * Array of objects and profs for each type of object for each cpu. Spinlocks
228 * are handled separately because a thread may be preempted and acquire a
229 * spinlock while in the lock profiling code of a non-spinlock. In this way
230 * we only need a critical section to protect the per-cpu lists.
232 struct lock_prof_type {
233 struct lphead lpt_lpalloc;
234 struct lpohead lpt_lpoalloc;
235 struct lphead lpt_hash[LPROF_HASH_SIZE];
236 struct lock_prof lpt_prof[LPROF_CACHE_SIZE];
237 struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
240 struct lock_prof_cpu {
241 struct lock_prof_type lpc_types[2]; /* One for spin one for other. */
244 struct lock_prof_cpu *lp_cpu[MAXCPU];
246 volatile int __read_mostly lock_prof_enable;
247 static volatile int lock_prof_resetting;
249 #define LPROF_SBUF_SIZE 256
251 static int lock_prof_rejected;
252 static int lock_prof_skipspin;
253 static int lock_prof_skipcount;
255 #ifndef USE_CPU_NANOSECONDS
263 /* From bintime2timespec */
264 ns = bt.sec * (uint64_t)1000000000;
265 ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
271 lock_prof_init_type(struct lock_prof_type *type)
275 SLIST_INIT(&type->lpt_lpalloc);
276 LIST_INIT(&type->lpt_lpoalloc);
277 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
278 SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
280 LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
286 lock_prof_init(void *arg)
290 for (cpu = 0; cpu <= mp_maxid; cpu++) {
291 lp_cpu[cpu] = malloc(sizeof(*lp_cpu[cpu]), M_DEVBUF,
293 lock_prof_init_type(&lp_cpu[cpu]->lpc_types[0]);
294 lock_prof_init_type(&lp_cpu[cpu]->lpc_types[1]);
297 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
300 lock_prof_reset_wait(void)
304 * Spin relinquishing our cpu so that quiesce_all_cpus may
307 while (lock_prof_resetting)
308 sched_relinquish(curthread);
312 lock_prof_reset(void)
314 struct lock_prof_cpu *lpc;
318 * We not only race with acquiring and releasing locks but also
319 * thread exit. To be certain that threads exit without valid head
320 * pointers they must see resetting set before enabled is cleared.
321 * Otherwise a lock may not be removed from a per-thread list due
322 * to disabled being set but not wait for reset() to remove it below.
324 atomic_store_rel_int(&lock_prof_resetting, 1);
325 enabled = lock_prof_enable;
326 lock_prof_enable = 0;
327 quiesce_all_cpus("profreset", 0);
329 * Some objects may have migrated between CPUs. Clear all links
330 * before we zero the structures. Some items may still be linked
331 * into per-thread lists as well.
333 for (cpu = 0; cpu <= mp_maxid; cpu++) {
335 for (i = 0; i < LPROF_CACHE_SIZE; i++) {
336 LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
337 LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
340 for (cpu = 0; cpu <= mp_maxid; cpu++) {
342 bzero(lpc, sizeof(*lpc));
343 lock_prof_init_type(&lpc->lpc_types[0]);
344 lock_prof_init_type(&lpc->lpc_types[1]);
346 atomic_store_rel_int(&lock_prof_resetting, 0);
347 lock_prof_enable = enabled;
351 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
355 for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
357 "%8ju %9ju %11ju %11ju %11ju %6ju %6ju %2ju %6ju %s:%d (%s:%s)\n",
358 lp->cnt_max / 1000, lp->cnt_wait_max / 1000, lp->cnt_tot / 1000,
359 lp->cnt_wait / 1000, lp->cnt_cur,
360 lp->cnt_cur == 0 ? (uintmax_t)0 :
361 lp->cnt_tot / (lp->cnt_cur * 1000),
362 lp->cnt_cur == 0 ? (uintmax_t)0 :
363 lp->cnt_wait / (lp->cnt_cur * 1000),
364 (uintmax_t)0, lp->cnt_contest_locking,
365 p, lp->line, lp->class->lc_name, lp->name);
369 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
372 struct lock_prof_type *type;
376 dst->file = match->file;
377 dst->line = match->line;
378 dst->class = match->class;
379 dst->name = match->name;
381 for (cpu = 0; cpu <= mp_maxid; cpu++) {
382 if (lp_cpu[cpu] == NULL)
384 type = &lp_cpu[cpu]->lpc_types[spin];
385 SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
388 if (l->file != match->file || l->line != match->line ||
389 l->name != match->name)
392 if (l->cnt_max > dst->cnt_max)
393 dst->cnt_max = l->cnt_max;
394 if (l->cnt_wait_max > dst->cnt_wait_max)
395 dst->cnt_wait_max = l->cnt_wait_max;
396 dst->cnt_tot += l->cnt_tot;
397 dst->cnt_wait += l->cnt_wait;
398 dst->cnt_cur += l->cnt_cur;
399 dst->cnt_contest_locking += l->cnt_contest_locking;
406 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
412 for (i = 0; i < LPROF_HASH_SIZE; ++i) {
413 SLIST_FOREACH(l, &type->lpt_hash[i], link) {
414 struct lock_prof lp = {};
418 lock_prof_sum(l, &lp, i, spin, t);
419 lock_prof_output(&lp, sb);
425 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
431 error = sysctl_wire_old_buffer(req, 0);
434 sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
435 sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
436 "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
437 enabled = lock_prof_enable;
438 lock_prof_enable = 0;
439 quiesce_all_cpus("profstat", 0);
441 for (cpu = 0; cpu <= mp_maxid; cpu++) {
442 if (lp_cpu[cpu] == NULL)
444 lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[0], sb, 0, t);
445 lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[1], sb, 1, t);
447 lock_prof_enable = enabled;
449 error = sbuf_finish(sb);
450 /* Output a trailing NUL. */
452 error = SYSCTL_OUT(req, "", 1);
458 enable_lock_prof(SYSCTL_HANDLER_ARGS)
462 v = lock_prof_enable;
463 error = sysctl_handle_int(oidp, &v, v, req);
466 if (req->newptr == NULL)
468 if (v == lock_prof_enable)
472 lock_prof_enable = !!v;
478 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
483 error = sysctl_handle_int(oidp, &v, 0, req);
486 if (req->newptr == NULL)
495 static struct lock_prof *
496 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
499 const char *unknown = "(unknown)";
500 struct lock_prof_type *type;
501 struct lock_prof *lp;
507 if (p == NULL || *p == '\0')
509 hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
510 hash &= LPROF_HASH_MASK;
511 type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
512 head = &type->lpt_hash[hash];
513 SLIST_FOREACH(lp, head, link) {
514 if (lp->line == line && lp->file == p &&
515 lp->name == lo->lo_name)
519 lp = SLIST_FIRST(&type->lpt_lpalloc);
521 lock_prof_rejected++;
524 SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
527 lp->class = LOCK_CLASS(lo);
528 lp->name = lo->lo_name;
529 SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
533 static struct lock_profile_object *
534 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
537 struct lock_profile_object *l;
538 struct lock_prof_type *type;
539 struct lpohead *head;
541 head = &curthread->td_lprof[spin];
542 LIST_FOREACH(l, head, lpo_link)
543 if (l->lpo_obj == lo && l->lpo_file == file &&
546 type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
547 l = LIST_FIRST(&type->lpt_lpoalloc);
549 lock_prof_rejected++;
552 LIST_REMOVE(l, lpo_link);
557 LIST_INSERT_HEAD(head, l, lpo_link);
563 lock_profile_obtain_lock_success(struct lock_object *lo, int contested,
564 uint64_t waittime, const char *file, int line)
566 static int lock_prof_count;
567 struct lock_profile_object *l;
570 if (SCHEDULER_STOPPED())
573 /* don't reset the timer when/if recursing */
574 if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
576 if (lock_prof_skipcount &&
577 (++lock_prof_count % lock_prof_skipcount) != 0)
579 spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
580 if (spin && lock_prof_skipspin == 1)
583 /* Recheck enabled now that we're in a critical section. */
584 if (lock_prof_enable == 0)
586 l = lock_profile_object_lookup(lo, spin, file, line);
590 if (++l->lpo_ref > 1)
592 l->lpo_contest_locking = contested;
593 l->lpo_acqtime = nanoseconds();
594 if (waittime && (l->lpo_acqtime > waittime))
595 l->lpo_waittime = l->lpo_acqtime - waittime;
603 lock_profile_thread_exit(struct thread *td)
606 struct lock_profile_object *l;
608 MPASS(curthread->td_critnest == 0);
611 * If lock profiling was disabled we have to wait for reset to
612 * clear our pointers before we can exit safely.
614 lock_prof_reset_wait();
616 LIST_FOREACH(l, &td->td_lprof[0], lpo_link)
617 printf("thread still holds lock acquired at %s:%d\n",
618 l->lpo_file, l->lpo_line);
619 LIST_FOREACH(l, &td->td_lprof[1], lpo_link)
620 printf("thread still holds lock acquired at %s:%d\n",
621 l->lpo_file, l->lpo_line);
623 MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
624 MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
628 lock_profile_release_lock(struct lock_object *lo)
630 struct lock_profile_object *l;
631 struct lock_prof_type *type;
632 struct lock_prof *lp;
633 uint64_t curtime, holdtime;
634 struct lpohead *head;
637 if (SCHEDULER_STOPPED())
639 if (lo->lo_flags & LO_NOPROFILE)
641 spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
642 head = &curthread->td_lprof[spin];
643 if (LIST_FIRST(head) == NULL)
646 /* Recheck enabled now that we're in a critical section. */
647 if (lock_prof_enable == 0 && lock_prof_resetting == 1)
650 * If lock profiling is not enabled we still want to remove the
651 * lpo from our queue.
653 LIST_FOREACH(l, head, lpo_link)
654 if (l->lpo_obj == lo)
658 if (--l->lpo_ref > 0)
660 lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
663 curtime = nanoseconds();
664 if (curtime < l->lpo_acqtime)
666 holdtime = curtime - l->lpo_acqtime;
669 * Record if the lock has been held longer now than ever
672 if (holdtime > lp->cnt_max)
673 lp->cnt_max = holdtime;
674 if (l->lpo_waittime > lp->cnt_wait_max)
675 lp->cnt_wait_max = l->lpo_waittime;
676 lp->cnt_tot += holdtime;
677 lp->cnt_wait += l->lpo_waittime;
678 lp->cnt_contest_locking += l->lpo_contest_locking;
679 lp->cnt_cur += l->lpo_cnt;
681 LIST_REMOVE(l, lpo_link);
682 type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
683 LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
688 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof, CTLFLAG_RD, NULL,
690 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
691 &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
692 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipcount, CTLFLAG_RW,
693 &lock_prof_skipcount, 0, "Sample approximately every N lock acquisitions.");
694 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
695 &lock_prof_rejected, 0, "Number of rejected profiling records");
696 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
697 NULL, 0, dump_lock_prof_stats, "A", "Lock profiling statistics");
698 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
699 NULL, 0, reset_lock_prof_stats, "I", "Reset lock profiling statistics");
700 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
701 NULL, 0, enable_lock_prof, "I", "Enable lock profiling");