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