xref: /freebsd/sys/kern/subr_lock.c (revision 257e70f1d5ee61037c8c59b116538d3b6b1427a2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  *
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
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * This module holds the global variables and functions used to maintain
30  * lock_object structures.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_ddb.h"
35 #include "opt_mprof.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/limits.h>
42 #include <sys/lock.h>
43 #include <sys/lock_profile.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
46 #include <sys/pcpu.h>
47 #include <sys/proc.h>
48 #include <sys/sbuf.h>
49 #include <sys/sched.h>
50 #include <sys/smp.h>
51 #include <sys/sysctl.h>
52 
53 #ifdef DDB
54 #include <ddb/ddb.h>
55 #endif
56 
57 #include <machine/cpufunc.h>
58 
59 /*
60  * Uncomment to validate that spin argument to acquire/release routines matches
61  * the flag in the lock
62  */
63 //#define	LOCK_PROFILING_DEBUG_SPIN
64 
65 CTASSERT(LOCK_CLASS_MAX == 15);
66 
67 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
68 	&lock_class_mtx_spin,
69 	&lock_class_mtx_sleep,
70 	&lock_class_sx,
71 	&lock_class_rm,
72 	&lock_class_rm_sleepable,
73 	&lock_class_rw,
74 	&lock_class_lockmgr,
75 };
76 
77 void
78 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
79     const char *type, int flags)
80 {
81 	int i;
82 
83 	/* Check for double-init and zero object. */
84 	KASSERT(flags & LO_NEW || !lock_initialized(lock),
85 	    ("lock \"%s\" %p already initialized", name, lock));
86 
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;
91 			break;
92 		}
93 	KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
94 
95 	/* Initialize the lock object. */
96 	lock->lo_name = name;
97 	lock->lo_flags |= flags | LO_INITIALIZED;
98 	LOCK_LOG_INIT(lock, 0);
99 	WITNESS_INIT(lock, (type != NULL) ? type : name);
100 }
101 
102 void
103 lock_destroy(struct lock_object *lock)
104 {
105 
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;
110 }
111 
112 static SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
113     "lock debugging");
114 static SYSCTL_NODE(_debug_lock, OID_AUTO, delay,
115     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
116     "lock delay");
117 
118 void
119 lock_delay(struct lock_delay_arg *la)
120 {
121 	struct lock_delay_config *lc = la->config;
122 	u_int i;
123 
124 	for (i = la->delay; i > 0; i--)
125 		cpu_spinwait();
126 	la->spin_cnt += la->delay;
127 
128 	la->delay <<= 1;
129 	if (__predict_false(la->delay > (u_int)lc->max))
130 		la->delay = lc->max;
131 }
132 
133 static u_int
134 lock_roundup_2(u_int val)
135 {
136 	u_int res;
137 
138 	for (res = 1; res <= val; res <<= 1)
139 		continue;
140 
141 	return (res);
142 }
143 
144 void
145 lock_delay_default_init(struct lock_delay_config *lc)
146 {
147 
148 	lc->base = 1;
149 	lc->max = min(lock_roundup_2(mp_ncpus) * 256, SHRT_MAX);
150 }
151 
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;
155 
156 SYSCTL_U16(_debug_lock, OID_AUTO, delay_base, CTLFLAG_RW, &locks_delay.base,
157     0, "");
158 SYSCTL_U16(_debug_lock, OID_AUTO, delay_max, CTLFLAG_RW, &locks_delay.max,
159     0, "");
160 SYSCTL_U16(_debug_lock, OID_AUTO, delay_retries, CTLFLAG_RW, &locks_delay_retries,
161     0, "");
162 SYSCTL_U16(_debug_lock, OID_AUTO, delay_loops, CTLFLAG_RW, &locks_delay_loops,
163     0, "");
164 
165 static void
166 locks_delay_init(void *arg __unused)
167 {
168 
169 	lock_delay_default_init(&locks_delay);
170 	locks_delay_retries = 10;
171 	locks_delay_loops = max(10000, locks_delay.max);
172 }
173 LOCK_DELAY_SYSINIT(locks_delay_init);
174 
175 #ifdef DDB
176 DB_SHOW_COMMAND(lock, db_show_lock)
177 {
178 	struct lock_object *lock;
179 	struct lock_class *class;
180 
181 	if (!have_addr)
182 		return;
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));
186 		return;
187 	}
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);
192 }
193 #endif
194 
195 #ifdef LOCK_PROFILING
196 
197 /*
198  * One object per-thread for each lock the thread owns.  Tracks individual
199  * lock instances.
200  */
201 struct lock_profile_object {
202 	LIST_ENTRY(lock_profile_object) lpo_link;
203 	struct lock_object *lpo_obj;
204 	const char	*lpo_file;
205 	int		lpo_line;
206 	uint16_t	lpo_ref;
207 	uint16_t	lpo_cnt;
208 	uint64_t	lpo_acqtime;
209 	uint64_t	lpo_waittime;
210 	u_int		lpo_contest_locking;
211 };
212 
213 /*
214  * One lock_prof for each (file, line, lock object) triple.
215  */
216 struct lock_prof {
217 	SLIST_ENTRY(lock_prof) link;
218 	struct lock_class *class;
219 	const char	*file;
220 	const char	*name;
221 	int		line;
222 	int		ticks;
223 	uintmax_t	cnt_wait_max;
224 	uintmax_t	cnt_max;
225 	uintmax_t	cnt_tot;
226 	uintmax_t	cnt_wait;
227 	uintmax_t	cnt_cur;
228 	uintmax_t	cnt_contest_locking;
229 };
230 
231 SLIST_HEAD(lphead, lock_prof);
232 
233 #define	LPROF_HASH_SIZE		4096
234 #define	LPROF_HASH_MASK		(LPROF_HASH_SIZE - 1)
235 #define	LPROF_CACHE_SIZE	4096
236 
237 /*
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.
242  */
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];
249 };
250 
251 struct lock_prof_cpu {
252 	struct lock_prof_type	lpc_types[2]; /* One for spin one for other. */
253 };
254 
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))
258 
259 volatile int __read_mostly lock_prof_enable;
260 int __read_mostly lock_contested_only;
261 static volatile int lock_prof_resetting;
262 
263 #define LPROF_SBUF_SIZE		256
264 
265 static int lock_prof_rejected;
266 static int lock_prof_skipspin;
267 
268 #ifndef USE_CPU_NANOSECONDS
269 uint64_t
270 nanoseconds(void)
271 {
272 	struct bintime bt;
273 	uint64_t ns;
274 
275 	binuptime(&bt);
276 	/* From bintime2timespec */
277 	ns = bt.sec * (uint64_t)1000000000;
278 	ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
279 	return (ns);
280 }
281 #endif
282 
283 static void
284 lock_prof_init_type(struct lock_prof_type *type)
285 {
286 	int i;
287 
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],
292 		    link);
293 		LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
294 		    lpo_link);
295 	}
296 }
297 
298 static void
299 lock_prof_init(void *arg)
300 {
301 	int cpu;
302 
303 	CPU_FOREACH(cpu) {
304 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[0]);
305 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[1]);
306 	}
307 }
308 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
309 
310 static void
311 lock_prof_reset_wait(void)
312 {
313 
314 	/*
315 	 * Spin relinquishing our cpu so that quiesce_all_cpus may
316 	 * complete.
317 	 */
318 	while (lock_prof_resetting)
319 		sched_relinquish(curthread);
320 }
321 
322 static void
323 lock_prof_reset(void)
324 {
325 	struct lock_prof_cpu *lpc;
326 	int enabled, i, cpu;
327 
328 	/*
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.
334 	 */
335 	atomic_store_rel_int(&lock_prof_resetting, 1);
336 	enabled = lock_prof_enable;
337 	lock_prof_enable = 0;
338 	/*
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
341 	 * rest down below.
342 	 */
343 	cpus_fence_seq_cst();
344 	quiesce_all_critical();
345 	/*
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.
349 	 */
350 	CPU_FOREACH(cpu) {
351 		lpc = LP_CPU(cpu);
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);
355 		}
356 	}
357 	CPU_FOREACH(cpu) {
358 		lpc = LP_CPU(cpu);
359 		bzero(lpc, sizeof(*lpc));
360 		lock_prof_init_type(&lpc->lpc_types[0]);
361 		lock_prof_init_type(&lpc->lpc_types[1]);
362 	}
363 	/*
364 	 * Paired with the fence from cpus_fence_seq_cst()
365 	 */
366 	atomic_store_rel_int(&lock_prof_resetting, 0);
367 	lock_prof_enable = enabled;
368 }
369 
370 static void
371 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
372 {
373 	const char *p;
374 
375 	for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
376 	sbuf_printf(sb,
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);
386 }
387 
388 static void
389 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
390     int spin, int t)
391 {
392 	struct lock_prof_type *type;
393 	struct lock_prof *l;
394 	int cpu;
395 
396 	dst->file = match->file;
397 	dst->line = match->line;
398 	dst->class = match->class;
399 	dst->name = match->name;
400 
401 	CPU_FOREACH(cpu) {
402 		type = &LP_CPU(cpu)->lpc_types[spin];
403 		SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
404 			if (l->ticks == t)
405 				continue;
406 			if (l->file != match->file || l->line != match->line ||
407 			    l->name != match->name)
408 				continue;
409 			l->ticks = t;
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;
418 		}
419 	}
420 }
421 
422 static void
423 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
424     int t)
425 {
426 	struct lock_prof *l;
427 	int i;
428 
429 	for (i = 0; i < LPROF_HASH_SIZE; ++i) {
430 		SLIST_FOREACH(l, &type->lpt_hash[i], link) {
431 			struct lock_prof lp = {};
432 
433 			if (l->ticks == t)
434 				continue;
435 			lock_prof_sum(l, &lp, i, spin, t);
436 			lock_prof_output(&lp, sb);
437 		}
438 	}
439 }
440 
441 static int
442 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
443 {
444 	struct sbuf *sb;
445 	int error, cpu, t;
446 	int enabled;
447 
448 	error = sysctl_wire_old_buffer(req, 0);
449 	if (error != 0)
450 		return (error);
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;
456 	/*
457 	 * See the comment in lock_prof_reset
458 	 */
459 	cpus_fence_seq_cst();
460 	quiesce_all_critical();
461 	t = ticks;
462 	CPU_FOREACH(cpu) {
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);
465 	}
466 	atomic_thread_fence_rel();
467 	lock_prof_enable = enabled;
468 
469 	error = sbuf_finish(sb);
470 	/* Output a trailing NUL. */
471 	if (error == 0)
472 		error = SYSCTL_OUT(req, "", 1);
473 	sbuf_delete(sb);
474 	return (error);
475 }
476 
477 static int
478 enable_lock_prof(SYSCTL_HANDLER_ARGS)
479 {
480 	int error, v;
481 
482 	v = lock_prof_enable;
483 	error = sysctl_handle_int(oidp, &v, v, req);
484 	if (error)
485 		return (error);
486 	if (req->newptr == NULL)
487 		return (error);
488 	if (v == lock_prof_enable)
489 		return (0);
490 	if (v == 1)
491 		lock_prof_reset();
492 	lock_prof_enable = !!v;
493 
494 	return (0);
495 }
496 
497 static int
498 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
499 {
500 	int error, v;
501 
502 	v = 0;
503 	error = sysctl_handle_int(oidp, &v, 0, req);
504 	if (error)
505 		return (error);
506 	if (req->newptr == NULL)
507 		return (error);
508 	if (v == 0)
509 		return (0);
510 	lock_prof_reset();
511 
512 	return (0);
513 }
514 
515 static struct lock_prof *
516 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
517     int line)
518 {
519 	const char *unknown = "(unknown)";
520 	struct lock_prof_type *type;
521 	struct lock_prof *lp;
522 	struct lphead *head;
523 	const char *p;
524 	u_int hash;
525 
526 	p = file;
527 	if (p == NULL || *p == '\0')
528 		p = unknown;
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)
536 			return (lp);
537 	}
538 	lp = SLIST_FIRST(&type->lpt_lpalloc);
539 	if (lp == NULL) {
540 		lock_prof_rejected++;
541 		return (lp);
542 	}
543 	SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
544 	lp->file = p;
545 	lp->line = line;
546 	lp->class = LOCK_CLASS(lo);
547 	lp->name = lo->lo_name;
548 	SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
549 	return (lp);
550 }
551 
552 static struct lock_profile_object *
553 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
554     int line)
555 {
556 	struct lock_profile_object *l;
557 	struct lock_prof_type *type;
558 	struct lpohead *head;
559 
560 	head = &curthread->td_lprof[spin];
561 	LIST_FOREACH(l, head, lpo_link)
562 		if (l->lpo_obj == lo && l->lpo_file == file &&
563 		    l->lpo_line == line)
564 			return (l);
565 	type = &LP_CPU_SELF->lpc_types[spin];
566 	l = LIST_FIRST(&type->lpt_lpoalloc);
567 	if (l == NULL) {
568 		lock_prof_rejected++;
569 		return (NULL);
570 	}
571 	LIST_REMOVE(l, lpo_link);
572 	l->lpo_obj = lo;
573 	l->lpo_file = file;
574 	l->lpo_line = line;
575 	l->lpo_cnt = 0;
576 	LIST_INSERT_HEAD(head, l, lpo_link);
577 
578 	return (l);
579 }
580 
581 void
582 lock_profile_obtain_lock_success(struct lock_object *lo, bool spin,
583     int contested, uint64_t waittime, const char *file, int line)
584 {
585 	struct lock_profile_object *l;
586 
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);
592 #endif
593 
594 	/* don't reset the timer when/if recursing */
595 	if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
596 		return;
597 	if (lock_contested_only && !contested)
598 		return;
599 	if (spin && lock_prof_skipspin == 1)
600 		return;
601 
602 	if (SCHEDULER_STOPPED())
603 		return;
604 
605 	critical_enter();
606 	/* Recheck enabled now that we're in a critical section. */
607 	if (lock_prof_enable == 0)
608 		goto out;
609 	l = lock_profile_object_lookup(lo, spin, file, line);
610 	if (l == NULL)
611 		goto out;
612 	l->lpo_cnt++;
613 	if (++l->lpo_ref > 1)
614 		goto out;
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;
619 	else
620 		l->lpo_waittime = 0;
621 out:
622 	/*
623 	 * Paired with cpus_fence_seq_cst().
624 	 */
625 	atomic_thread_fence_rel();
626 	critical_exit();
627 }
628 
629 void
630 lock_profile_thread_exit(struct thread *td)
631 {
632 #ifdef INVARIANTS
633 	struct lock_profile_object *l;
634 
635 	MPASS(curthread->td_critnest == 0);
636 #endif
637 	/*
638 	 * If lock profiling was disabled we have to wait for reset to
639 	 * clear our pointers before we can exit safely.
640 	 */
641 	lock_prof_reset_wait();
642 #ifdef INVARIANTS
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);
649 #endif
650 	MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
651 	MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
652 }
653 
654 void
655 lock_profile_release_lock(struct lock_object *lo, bool spin)
656 {
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;
662 
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);
668 #endif
669 
670 	if (lo->lo_flags & LO_NOPROFILE)
671 		return;
672 	head = &curthread->td_lprof[spin];
673 	if (LIST_FIRST(head) == NULL)
674 		return;
675 	if (SCHEDULER_STOPPED())
676 		return;
677 	critical_enter();
678 	/* Recheck enabled now that we're in a critical section. */
679 	if (lock_prof_enable == 0 && lock_prof_resetting == 1)
680 		goto out;
681 	/*
682 	 * If lock profiling is not enabled we still want to remove the
683 	 * lpo from our queue.
684 	 */
685 	LIST_FOREACH(l, head, lpo_link)
686 		if (l->lpo_obj == lo)
687 			break;
688 	if (l == NULL)
689 		goto out;
690 	if (--l->lpo_ref > 0)
691 		goto out;
692 	lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
693 	if (lp == NULL)
694 		goto release;
695 	curtime = nanoseconds();
696 	if (curtime < l->lpo_acqtime)
697 		goto release;
698 	holdtime = curtime - l->lpo_acqtime;
699 
700 	/*
701 	 * Record if the lock has been held longer now than ever
702 	 * before.
703 	 */
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;
712 release:
713 	LIST_REMOVE(l, lpo_link);
714 	type = &LP_CPU_SELF->lpc_types[spin];
715 	LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
716 out:
717 	/*
718 	 * Paired with cpus_fence_seq_cst().
719 	 */
720 	atomic_thread_fence_rel();
721 	critical_exit();
722 }
723 
724 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof,
725     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
726     "lock profiling");
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");
745 
746 #endif
747