xref: /freebsd/sys/kern/subr_lock.c (revision f161abf9f2cd7fdd28543f9774de82c89675477c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 __FBSDID("$FreeBSD$");
35 
36 #include "opt_ddb.h"
37 #include "opt_mprof.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/ktr.h>
43 #include <sys/limits.h>
44 #include <sys/lock.h>
45 #include <sys/lock_profile.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
48 #include <sys/pcpu.h>
49 #include <sys/proc.h>
50 #include <sys/sbuf.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/sysctl.h>
54 
55 #ifdef DDB
56 #include <ddb/ddb.h>
57 #endif
58 
59 #include <machine/cpufunc.h>
60 
61 /*
62  * Uncomment to validate that spin argument to acquire/release routines matches
63  * the flag in the lock
64  */
65 //#define	LOCK_PROFILING_DEBUG_SPIN
66 
67 SDT_PROVIDER_DEFINE(lock);
68 SDT_PROBE_DEFINE1(lock, , , starvation, "u_int");
69 
70 CTASSERT(LOCK_CLASS_MAX == 15);
71 
72 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
73 	&lock_class_mtx_spin,
74 	&lock_class_mtx_sleep,
75 	&lock_class_sx,
76 	&lock_class_rm,
77 	&lock_class_rm_sleepable,
78 	&lock_class_rw,
79 	&lock_class_lockmgr,
80 };
81 
82 void
83 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
84     const char *type, int flags)
85 {
86 	int i;
87 
88 	/* Check for double-init and zero object. */
89 	KASSERT(flags & LO_NEW || !lock_initialized(lock),
90 	    ("lock \"%s\" %p already initialized", name, lock));
91 
92 	/* Look up lock class to find its index. */
93 	for (i = 0; i < LOCK_CLASS_MAX; i++)
94 		if (lock_classes[i] == class) {
95 			lock->lo_flags = i << LO_CLASSSHIFT;
96 			break;
97 		}
98 	KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
99 
100 	/* Initialize the lock object. */
101 	lock->lo_name = name;
102 	lock->lo_flags |= flags | LO_INITIALIZED;
103 	LOCK_LOG_INIT(lock, 0);
104 	WITNESS_INIT(lock, (type != NULL) ? type : name);
105 }
106 
107 void
108 lock_destroy(struct lock_object *lock)
109 {
110 
111 	KASSERT(lock_initialized(lock), ("lock %p is not initialized", lock));
112 	WITNESS_DESTROY(lock);
113 	LOCK_LOG_DESTROY(lock, 0);
114 	lock->lo_flags &= ~LO_INITIALIZED;
115 }
116 
117 static SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
118     "lock debugging");
119 static SYSCTL_NODE(_debug_lock, OID_AUTO, delay,
120     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
121     "lock delay");
122 
123 static u_int __read_mostly starvation_limit = 131072;
124 SYSCTL_INT(_debug_lock_delay, OID_AUTO, starvation_limit, CTLFLAG_RW,
125     &starvation_limit, 0, "");
126 
127 static u_int __read_mostly restrict_starvation = 0;
128 SYSCTL_INT(_debug_lock_delay, OID_AUTO, restrict_starvation, CTLFLAG_RW,
129     &restrict_starvation, 0, "");
130 
131 void
132 lock_delay(struct lock_delay_arg *la)
133 {
134 	struct lock_delay_config *lc = la->config;
135 	u_short i;
136 
137 	for (i = la->delay; i > 0; i--)
138 		cpu_spinwait();
139 	la->spin_cnt += la->delay;
140 
141 	la->delay <<= 1;
142 	if (__predict_false(la->delay > lc->max))
143 		la->delay = lc->max;
144 
145 	if (__predict_false(la->spin_cnt > starvation_limit)) {
146 		SDT_PROBE1(lock, , , starvation, la->delay);
147 		if (restrict_starvation)
148 			la->delay = lc->base;
149 	}
150 }
151 
152 static u_int
153 lock_roundup_2(u_int val)
154 {
155 	u_int res;
156 
157 	for (res = 1; res <= val; res <<= 1)
158 		continue;
159 
160 	return (res);
161 }
162 
163 void
164 lock_delay_default_init(struct lock_delay_config *lc)
165 {
166 
167 	lc->base = 1;
168 	lc->max = lock_roundup_2(mp_ncpus) * 256;
169 	if (lc->max > 32678)
170 		lc->max = 32678;
171 }
172 
173 struct lock_delay_config __read_frequently locks_delay;
174 u_short __read_frequently locks_delay_retries;
175 u_short __read_frequently locks_delay_loops;
176 
177 SYSCTL_U16(_debug_lock, OID_AUTO, delay_base, CTLFLAG_RW, &locks_delay.base,
178     0, "");
179 SYSCTL_U16(_debug_lock, OID_AUTO, delay_max, CTLFLAG_RW, &locks_delay.max,
180     0, "");
181 SYSCTL_U16(_debug_lock, OID_AUTO, delay_retries, CTLFLAG_RW, &locks_delay_retries,
182     0, "");
183 SYSCTL_U16(_debug_lock, OID_AUTO, delay_loops, CTLFLAG_RW, &locks_delay_loops,
184     0, "");
185 
186 static void
187 locks_delay_init(void *arg __unused)
188 {
189 
190 	lock_delay_default_init(&locks_delay);
191 	locks_delay_retries = 10;
192 	locks_delay_loops = max(10000, locks_delay.max);
193 }
194 LOCK_DELAY_SYSINIT(locks_delay_init);
195 
196 #ifdef DDB
197 DB_SHOW_COMMAND(lock, db_show_lock)
198 {
199 	struct lock_object *lock;
200 	struct lock_class *class;
201 
202 	if (!have_addr)
203 		return;
204 	lock = (struct lock_object *)addr;
205 	if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
206 		db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
207 		return;
208 	}
209 	class = LOCK_CLASS(lock);
210 	db_printf(" class: %s\n", class->lc_name);
211 	db_printf(" name: %s\n", lock->lo_name);
212 	class->lc_ddb_show(lock);
213 }
214 #endif
215 
216 #ifdef LOCK_PROFILING
217 
218 /*
219  * One object per-thread for each lock the thread owns.  Tracks individual
220  * lock instances.
221  */
222 struct lock_profile_object {
223 	LIST_ENTRY(lock_profile_object) lpo_link;
224 	struct lock_object *lpo_obj;
225 	const char	*lpo_file;
226 	int		lpo_line;
227 	uint16_t	lpo_ref;
228 	uint16_t	lpo_cnt;
229 	uint64_t	lpo_acqtime;
230 	uint64_t	lpo_waittime;
231 	u_int		lpo_contest_locking;
232 };
233 
234 /*
235  * One lock_prof for each (file, line, lock object) triple.
236  */
237 struct lock_prof {
238 	SLIST_ENTRY(lock_prof) link;
239 	struct lock_class *class;
240 	const char	*file;
241 	const char	*name;
242 	int		line;
243 	int		ticks;
244 	uintmax_t	cnt_wait_max;
245 	uintmax_t	cnt_max;
246 	uintmax_t	cnt_tot;
247 	uintmax_t	cnt_wait;
248 	uintmax_t	cnt_cur;
249 	uintmax_t	cnt_contest_locking;
250 };
251 
252 SLIST_HEAD(lphead, lock_prof);
253 
254 #define	LPROF_HASH_SIZE		4096
255 #define	LPROF_HASH_MASK		(LPROF_HASH_SIZE - 1)
256 #define	LPROF_CACHE_SIZE	4096
257 
258 /*
259  * Array of objects and profs for each type of object for each cpu.  Spinlocks
260  * are handled separately because a thread may be preempted and acquire a
261  * spinlock while in the lock profiling code of a non-spinlock.  In this way
262  * we only need a critical section to protect the per-cpu lists.
263  */
264 struct lock_prof_type {
265 	struct lphead		lpt_lpalloc;
266 	struct lpohead		lpt_lpoalloc;
267 	struct lphead		lpt_hash[LPROF_HASH_SIZE];
268 	struct lock_prof	lpt_prof[LPROF_CACHE_SIZE];
269 	struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
270 };
271 
272 struct lock_prof_cpu {
273 	struct lock_prof_type	lpc_types[2]; /* One for spin one for other. */
274 };
275 
276 DPCPU_DEFINE_STATIC(struct lock_prof_cpu, lp);
277 #define	LP_CPU_SELF	(DPCPU_PTR(lp))
278 #define	LP_CPU(cpu)	(DPCPU_ID_PTR((cpu), lp))
279 
280 volatile int __read_mostly lock_prof_enable;
281 int __read_mostly lock_contested_only;
282 static volatile int lock_prof_resetting;
283 
284 #define LPROF_SBUF_SIZE		256
285 
286 static int lock_prof_rejected;
287 static int lock_prof_skipspin;
288 
289 #ifndef USE_CPU_NANOSECONDS
290 uint64_t
291 nanoseconds(void)
292 {
293 	struct bintime bt;
294 	uint64_t ns;
295 
296 	binuptime(&bt);
297 	/* From bintime2timespec */
298 	ns = bt.sec * (uint64_t)1000000000;
299 	ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
300 	return (ns);
301 }
302 #endif
303 
304 static void
305 lock_prof_init_type(struct lock_prof_type *type)
306 {
307 	int i;
308 
309 	SLIST_INIT(&type->lpt_lpalloc);
310 	LIST_INIT(&type->lpt_lpoalloc);
311 	for (i = 0; i < LPROF_CACHE_SIZE; i++) {
312 		SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
313 		    link);
314 		LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
315 		    lpo_link);
316 	}
317 }
318 
319 static void
320 lock_prof_init(void *arg)
321 {
322 	int cpu;
323 
324 	CPU_FOREACH(cpu) {
325 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[0]);
326 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[1]);
327 	}
328 }
329 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
330 
331 static void
332 lock_prof_reset_wait(void)
333 {
334 
335 	/*
336 	 * Spin relinquishing our cpu so that quiesce_all_cpus may
337 	 * complete.
338 	 */
339 	while (lock_prof_resetting)
340 		sched_relinquish(curthread);
341 }
342 
343 static void
344 lock_prof_reset(void)
345 {
346 	struct lock_prof_cpu *lpc;
347 	int enabled, i, cpu;
348 
349 	/*
350 	 * We not only race with acquiring and releasing locks but also
351 	 * thread exit.  To be certain that threads exit without valid head
352 	 * pointers they must see resetting set before enabled is cleared.
353 	 * Otherwise a lock may not be removed from a per-thread list due
354 	 * to disabled being set but not wait for reset() to remove it below.
355 	 */
356 	atomic_store_rel_int(&lock_prof_resetting, 1);
357 	enabled = lock_prof_enable;
358 	lock_prof_enable = 0;
359 	/*
360 	 * This both publishes lock_prof_enable as disabled and makes sure
361 	 * everyone else reads it if they are not far enough. We wait for the
362 	 * rest down below.
363 	 */
364 	cpus_fence_seq_cst();
365 	quiesce_all_critical();
366 	/*
367 	 * Some objects may have migrated between CPUs.  Clear all links
368 	 * before we zero the structures.  Some items may still be linked
369 	 * into per-thread lists as well.
370 	 */
371 	CPU_FOREACH(cpu) {
372 		lpc = LP_CPU(cpu);
373 		for (i = 0; i < LPROF_CACHE_SIZE; i++) {
374 			LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
375 			LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
376 		}
377 	}
378 	CPU_FOREACH(cpu) {
379 		lpc = LP_CPU(cpu);
380 		bzero(lpc, sizeof(*lpc));
381 		lock_prof_init_type(&lpc->lpc_types[0]);
382 		lock_prof_init_type(&lpc->lpc_types[1]);
383 	}
384 	/*
385 	 * Paired with the fence from cpus_fence_seq_cst()
386 	 */
387 	atomic_store_rel_int(&lock_prof_resetting, 0);
388 	lock_prof_enable = enabled;
389 }
390 
391 static void
392 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
393 {
394 	const char *p;
395 
396 	for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
397 	sbuf_printf(sb,
398 	    "%8ju %9ju %11ju %11ju %11ju %6ju %6ju %2ju %6ju %s:%d (%s:%s)\n",
399 	    lp->cnt_max / 1000, lp->cnt_wait_max / 1000, lp->cnt_tot / 1000,
400 	    lp->cnt_wait / 1000, lp->cnt_cur,
401 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
402 	    lp->cnt_tot / (lp->cnt_cur * 1000),
403 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
404 	    lp->cnt_wait / (lp->cnt_cur * 1000),
405 	    (uintmax_t)0, lp->cnt_contest_locking,
406 	    p, lp->line, lp->class->lc_name, lp->name);
407 }
408 
409 static void
410 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
411     int spin, int t)
412 {
413 	struct lock_prof_type *type;
414 	struct lock_prof *l;
415 	int cpu;
416 
417 	dst->file = match->file;
418 	dst->line = match->line;
419 	dst->class = match->class;
420 	dst->name = match->name;
421 
422 	CPU_FOREACH(cpu) {
423 		type = &LP_CPU(cpu)->lpc_types[spin];
424 		SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
425 			if (l->ticks == t)
426 				continue;
427 			if (l->file != match->file || l->line != match->line ||
428 			    l->name != match->name)
429 				continue;
430 			l->ticks = t;
431 			if (l->cnt_max > dst->cnt_max)
432 				dst->cnt_max = l->cnt_max;
433 			if (l->cnt_wait_max > dst->cnt_wait_max)
434 				dst->cnt_wait_max = l->cnt_wait_max;
435 			dst->cnt_tot += l->cnt_tot;
436 			dst->cnt_wait += l->cnt_wait;
437 			dst->cnt_cur += l->cnt_cur;
438 			dst->cnt_contest_locking += l->cnt_contest_locking;
439 		}
440 	}
441 }
442 
443 static void
444 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
445     int t)
446 {
447 	struct lock_prof *l;
448 	int i;
449 
450 	for (i = 0; i < LPROF_HASH_SIZE; ++i) {
451 		SLIST_FOREACH(l, &type->lpt_hash[i], link) {
452 			struct lock_prof lp = {};
453 
454 			if (l->ticks == t)
455 				continue;
456 			lock_prof_sum(l, &lp, i, spin, t);
457 			lock_prof_output(&lp, sb);
458 		}
459 	}
460 }
461 
462 static int
463 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
464 {
465 	struct sbuf *sb;
466 	int error, cpu, t;
467 	int enabled;
468 
469 	error = sysctl_wire_old_buffer(req, 0);
470 	if (error != 0)
471 		return (error);
472 	sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
473 	sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
474 	    "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
475 	enabled = lock_prof_enable;
476 	lock_prof_enable = 0;
477 	/*
478 	 * See the comment in lock_prof_reset
479 	 */
480 	cpus_fence_seq_cst();
481 	quiesce_all_critical();
482 	t = ticks;
483 	CPU_FOREACH(cpu) {
484 		lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[0], sb, 0, t);
485 		lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[1], sb, 1, t);
486 	}
487 	atomic_thread_fence_rel();
488 	lock_prof_enable = enabled;
489 
490 	error = sbuf_finish(sb);
491 	/* Output a trailing NUL. */
492 	if (error == 0)
493 		error = SYSCTL_OUT(req, "", 1);
494 	sbuf_delete(sb);
495 	return (error);
496 }
497 
498 static int
499 enable_lock_prof(SYSCTL_HANDLER_ARGS)
500 {
501 	int error, v;
502 
503 	v = lock_prof_enable;
504 	error = sysctl_handle_int(oidp, &v, v, req);
505 	if (error)
506 		return (error);
507 	if (req->newptr == NULL)
508 		return (error);
509 	if (v == lock_prof_enable)
510 		return (0);
511 	if (v == 1)
512 		lock_prof_reset();
513 	lock_prof_enable = !!v;
514 
515 	return (0);
516 }
517 
518 static int
519 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
520 {
521 	int error, v;
522 
523 	v = 0;
524 	error = sysctl_handle_int(oidp, &v, 0, req);
525 	if (error)
526 		return (error);
527 	if (req->newptr == NULL)
528 		return (error);
529 	if (v == 0)
530 		return (0);
531 	lock_prof_reset();
532 
533 	return (0);
534 }
535 
536 static struct lock_prof *
537 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
538     int line)
539 {
540 	const char *unknown = "(unknown)";
541 	struct lock_prof_type *type;
542 	struct lock_prof *lp;
543 	struct lphead *head;
544 	const char *p;
545 	u_int hash;
546 
547 	p = file;
548 	if (p == NULL || *p == '\0')
549 		p = unknown;
550 	hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
551 	hash &= LPROF_HASH_MASK;
552 	type = &LP_CPU_SELF->lpc_types[spin];
553 	head = &type->lpt_hash[hash];
554 	SLIST_FOREACH(lp, head, link) {
555 		if (lp->line == line && lp->file == p &&
556 		    lp->name == lo->lo_name)
557 			return (lp);
558 	}
559 	lp = SLIST_FIRST(&type->lpt_lpalloc);
560 	if (lp == NULL) {
561 		lock_prof_rejected++;
562 		return (lp);
563 	}
564 	SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
565 	lp->file = p;
566 	lp->line = line;
567 	lp->class = LOCK_CLASS(lo);
568 	lp->name = lo->lo_name;
569 	SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
570 	return (lp);
571 }
572 
573 static struct lock_profile_object *
574 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
575     int line)
576 {
577 	struct lock_profile_object *l;
578 	struct lock_prof_type *type;
579 	struct lpohead *head;
580 
581 	head = &curthread->td_lprof[spin];
582 	LIST_FOREACH(l, head, lpo_link)
583 		if (l->lpo_obj == lo && l->lpo_file == file &&
584 		    l->lpo_line == line)
585 			return (l);
586 	type = &LP_CPU_SELF->lpc_types[spin];
587 	l = LIST_FIRST(&type->lpt_lpoalloc);
588 	if (l == NULL) {
589 		lock_prof_rejected++;
590 		return (NULL);
591 	}
592 	LIST_REMOVE(l, lpo_link);
593 	l->lpo_obj = lo;
594 	l->lpo_file = file;
595 	l->lpo_line = line;
596 	l->lpo_cnt = 0;
597 	LIST_INSERT_HEAD(head, l, lpo_link);
598 
599 	return (l);
600 }
601 
602 void
603 lock_profile_obtain_lock_success(struct lock_object *lo, bool spin,
604     int contested, uint64_t waittime, const char *file, int line)
605 {
606 	struct lock_profile_object *l;
607 
608 #ifdef LOCK_PROFILING_DEBUG_SPIN
609 	bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
610 	if ((spin && !is_spin) || (!spin && is_spin))
611 		printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
612 		    lo->lo_name, spin, is_spin);
613 #endif
614 
615 	/* don't reset the timer when/if recursing */
616 	if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
617 		return;
618 	if (lock_contested_only && !contested)
619 		return;
620 	if (spin && lock_prof_skipspin == 1)
621 		return;
622 
623 	if (SCHEDULER_STOPPED())
624 		return;
625 
626 	critical_enter();
627 	/* Recheck enabled now that we're in a critical section. */
628 	if (lock_prof_enable == 0)
629 		goto out;
630 	l = lock_profile_object_lookup(lo, spin, file, line);
631 	if (l == NULL)
632 		goto out;
633 	l->lpo_cnt++;
634 	if (++l->lpo_ref > 1)
635 		goto out;
636 	l->lpo_contest_locking = contested;
637 	l->lpo_acqtime = nanoseconds();
638 	if (waittime && (l->lpo_acqtime > waittime))
639 		l->lpo_waittime = l->lpo_acqtime - waittime;
640 	else
641 		l->lpo_waittime = 0;
642 out:
643 	/*
644 	 * Paired with cpus_fence_seq_cst().
645 	 */
646 	atomic_thread_fence_rel();
647 	critical_exit();
648 }
649 
650 void
651 lock_profile_thread_exit(struct thread *td)
652 {
653 #ifdef INVARIANTS
654 	struct lock_profile_object *l;
655 
656 	MPASS(curthread->td_critnest == 0);
657 #endif
658 	/*
659 	 * If lock profiling was disabled we have to wait for reset to
660 	 * clear our pointers before we can exit safely.
661 	 */
662 	lock_prof_reset_wait();
663 #ifdef INVARIANTS
664 	LIST_FOREACH(l, &td->td_lprof[0], lpo_link)
665 		printf("thread still holds lock acquired at %s:%d\n",
666 		    l->lpo_file, l->lpo_line);
667 	LIST_FOREACH(l, &td->td_lprof[1], lpo_link)
668 		printf("thread still holds lock acquired at %s:%d\n",
669 		    l->lpo_file, l->lpo_line);
670 #endif
671 	MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
672 	MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
673 }
674 
675 void
676 lock_profile_release_lock(struct lock_object *lo, bool spin)
677 {
678 	struct lock_profile_object *l;
679 	struct lock_prof_type *type;
680 	struct lock_prof *lp;
681 	uint64_t curtime, holdtime;
682 	struct lpohead *head;
683 
684 #ifdef LOCK_PROFILING_DEBUG_SPIN
685 	bool is_spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK);
686 	if ((spin && !is_spin) || (!spin && is_spin))
687 		printf("%s: lock %s spin mismatch (arg %d, flag %d)\n", __func__,
688 		    lo->lo_name, spin, is_spin);
689 #endif
690 
691 	if (lo->lo_flags & LO_NOPROFILE)
692 		return;
693 	head = &curthread->td_lprof[spin];
694 	if (LIST_FIRST(head) == NULL)
695 		return;
696 	if (SCHEDULER_STOPPED())
697 		return;
698 	critical_enter();
699 	/* Recheck enabled now that we're in a critical section. */
700 	if (lock_prof_enable == 0 && lock_prof_resetting == 1)
701 		goto out;
702 	/*
703 	 * If lock profiling is not enabled we still want to remove the
704 	 * lpo from our queue.
705 	 */
706 	LIST_FOREACH(l, head, lpo_link)
707 		if (l->lpo_obj == lo)
708 			break;
709 	if (l == NULL)
710 		goto out;
711 	if (--l->lpo_ref > 0)
712 		goto out;
713 	lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
714 	if (lp == NULL)
715 		goto release;
716 	curtime = nanoseconds();
717 	if (curtime < l->lpo_acqtime)
718 		goto release;
719 	holdtime = curtime - l->lpo_acqtime;
720 
721 	/*
722 	 * Record if the lock has been held longer now than ever
723 	 * before.
724 	 */
725 	if (holdtime > lp->cnt_max)
726 		lp->cnt_max = holdtime;
727 	if (l->lpo_waittime > lp->cnt_wait_max)
728 		lp->cnt_wait_max = l->lpo_waittime;
729 	lp->cnt_tot += holdtime;
730 	lp->cnt_wait += l->lpo_waittime;
731 	lp->cnt_contest_locking += l->lpo_contest_locking;
732 	lp->cnt_cur += l->lpo_cnt;
733 release:
734 	LIST_REMOVE(l, lpo_link);
735 	type = &LP_CPU_SELF->lpc_types[spin];
736 	LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
737 out:
738 	/*
739 	 * Paired with cpus_fence_seq_cst().
740 	 */
741 	atomic_thread_fence_rel();
742 	critical_exit();
743 }
744 
745 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof,
746     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
747     "lock profiling");
748 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
749     &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
750 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
751     &lock_prof_rejected, 0, "Number of rejected profiling records");
752 SYSCTL_INT(_debug_lock_prof, OID_AUTO, contested_only, CTLFLAG_RW,
753     &lock_contested_only, 0, "Only profile contested acquires");
754 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats,
755     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
756     dump_lock_prof_stats, "A",
757     "Lock profiling statistics");
758 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset,
759     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
760     reset_lock_prof_stats, "I",
761     "Reset lock profiling statistics");
762 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable,
763     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
764     enable_lock_prof, "I",
765     "Enable lock profiling");
766 
767 #endif
768