xref: /freebsd/sys/kern/subr_lock.c (revision 2dd94b045e8c069c1a748d40d30d979e30e02fc9)
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 struct lock_delay_config __read_frequently locks_delay;
165 u_short __read_frequently locks_delay_retries;
166 u_short __read_frequently locks_delay_loops;
167 
168 SYSCTL_U16(_debug_lock, OID_AUTO, delay_base, CTLFLAG_RW, &locks_delay.base,
169     0, "");
170 SYSCTL_U16(_debug_lock, OID_AUTO, delay_max, CTLFLAG_RW, &locks_delay.max,
171     0, "");
172 SYSCTL_U16(_debug_lock, OID_AUTO, delay_retries, CTLFLAG_RW, &locks_delay_retries,
173     0, "");
174 SYSCTL_U16(_debug_lock, OID_AUTO, delay_loops, CTLFLAG_RW, &locks_delay_loops,
175     0, "");
176 
177 static void
178 locks_delay_init(void *arg __unused)
179 {
180 
181 	lock_delay_default_init(&locks_delay);
182 	locks_delay_retries = 10;
183 	locks_delay_loops = max(10000, locks_delay.max);
184 }
185 LOCK_DELAY_SYSINIT(locks_delay_init);
186 
187 #ifdef DDB
188 DB_SHOW_COMMAND(lock, db_show_lock)
189 {
190 	struct lock_object *lock;
191 	struct lock_class *class;
192 
193 	if (!have_addr)
194 		return;
195 	lock = (struct lock_object *)addr;
196 	if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
197 		db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
198 		return;
199 	}
200 	class = LOCK_CLASS(lock);
201 	db_printf(" class: %s\n", class->lc_name);
202 	db_printf(" name: %s\n", lock->lo_name);
203 	class->lc_ddb_show(lock);
204 }
205 #endif
206 
207 #ifdef LOCK_PROFILING
208 
209 /*
210  * One object per-thread for each lock the thread owns.  Tracks individual
211  * lock instances.
212  */
213 struct lock_profile_object {
214 	LIST_ENTRY(lock_profile_object) lpo_link;
215 	struct lock_object *lpo_obj;
216 	const char	*lpo_file;
217 	int		lpo_line;
218 	uint16_t	lpo_ref;
219 	uint16_t	lpo_cnt;
220 	uint64_t	lpo_acqtime;
221 	uint64_t	lpo_waittime;
222 	u_int		lpo_contest_locking;
223 };
224 
225 /*
226  * One lock_prof for each (file, line, lock object) triple.
227  */
228 struct lock_prof {
229 	SLIST_ENTRY(lock_prof) link;
230 	struct lock_class *class;
231 	const char	*file;
232 	const char	*name;
233 	int		line;
234 	int		ticks;
235 	uintmax_t	cnt_wait_max;
236 	uintmax_t	cnt_max;
237 	uintmax_t	cnt_tot;
238 	uintmax_t	cnt_wait;
239 	uintmax_t	cnt_cur;
240 	uintmax_t	cnt_contest_locking;
241 };
242 
243 SLIST_HEAD(lphead, lock_prof);
244 
245 #define	LPROF_HASH_SIZE		4096
246 #define	LPROF_HASH_MASK		(LPROF_HASH_SIZE - 1)
247 #define	LPROF_CACHE_SIZE	4096
248 
249 /*
250  * Array of objects and profs for each type of object for each cpu.  Spinlocks
251  * are handled separately because a thread may be preempted and acquire a
252  * spinlock while in the lock profiling code of a non-spinlock.  In this way
253  * we only need a critical section to protect the per-cpu lists.
254  */
255 struct lock_prof_type {
256 	struct lphead		lpt_lpalloc;
257 	struct lpohead		lpt_lpoalloc;
258 	struct lphead		lpt_hash[LPROF_HASH_SIZE];
259 	struct lock_prof	lpt_prof[LPROF_CACHE_SIZE];
260 	struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
261 };
262 
263 struct lock_prof_cpu {
264 	struct lock_prof_type	lpc_types[2]; /* One for spin one for other. */
265 };
266 
267 DPCPU_DEFINE_STATIC(struct lock_prof_cpu, lp);
268 #define	LP_CPU_SELF	(DPCPU_PTR(lp))
269 #define	LP_CPU(cpu)	(DPCPU_ID_PTR((cpu), lp))
270 
271 volatile int __read_mostly lock_prof_enable;
272 static volatile int lock_prof_resetting;
273 
274 #define LPROF_SBUF_SIZE		256
275 
276 static int lock_prof_rejected;
277 static int lock_prof_skipspin;
278 static int lock_prof_skipcount;
279 
280 #ifndef USE_CPU_NANOSECONDS
281 uint64_t
282 nanoseconds(void)
283 {
284 	struct bintime bt;
285 	uint64_t ns;
286 
287 	binuptime(&bt);
288 	/* From bintime2timespec */
289 	ns = bt.sec * (uint64_t)1000000000;
290 	ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
291 	return (ns);
292 }
293 #endif
294 
295 static void
296 lock_prof_init_type(struct lock_prof_type *type)
297 {
298 	int i;
299 
300 	SLIST_INIT(&type->lpt_lpalloc);
301 	LIST_INIT(&type->lpt_lpoalloc);
302 	for (i = 0; i < LPROF_CACHE_SIZE; i++) {
303 		SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
304 		    link);
305 		LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
306 		    lpo_link);
307 	}
308 }
309 
310 static void
311 lock_prof_init(void *arg)
312 {
313 	int cpu;
314 
315 	CPU_FOREACH(cpu) {
316 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[0]);
317 		lock_prof_init_type(&LP_CPU(cpu)->lpc_types[1]);
318 	}
319 }
320 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
321 
322 static void
323 lock_prof_reset_wait(void)
324 {
325 
326 	/*
327 	 * Spin relinquishing our cpu so that quiesce_all_cpus may
328 	 * complete.
329 	 */
330 	while (lock_prof_resetting)
331 		sched_relinquish(curthread);
332 }
333 
334 static void
335 lock_prof_reset(void)
336 {
337 	struct lock_prof_cpu *lpc;
338 	int enabled, i, cpu;
339 
340 	/*
341 	 * We not only race with acquiring and releasing locks but also
342 	 * thread exit.  To be certain that threads exit without valid head
343 	 * pointers they must see resetting set before enabled is cleared.
344 	 * Otherwise a lock may not be removed from a per-thread list due
345 	 * to disabled being set but not wait for reset() to remove it below.
346 	 */
347 	atomic_store_rel_int(&lock_prof_resetting, 1);
348 	enabled = lock_prof_enable;
349 	lock_prof_enable = 0;
350 	/*
351 	 * This both publishes lock_prof_enable as disabled and makes sure
352 	 * everyone else reads it if they are not far enough. We wait for the
353 	 * rest down below.
354 	 */
355 	cpus_fence_seq_cst();
356 	quiesce_all_critical();
357 	/*
358 	 * Some objects may have migrated between CPUs.  Clear all links
359 	 * before we zero the structures.  Some items may still be linked
360 	 * into per-thread lists as well.
361 	 */
362 	CPU_FOREACH(cpu) {
363 		lpc = LP_CPU(cpu);
364 		for (i = 0; i < LPROF_CACHE_SIZE; i++) {
365 			LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
366 			LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
367 		}
368 	}
369 	CPU_FOREACH(cpu) {
370 		lpc = LP_CPU(cpu);
371 		bzero(lpc, sizeof(*lpc));
372 		lock_prof_init_type(&lpc->lpc_types[0]);
373 		lock_prof_init_type(&lpc->lpc_types[1]);
374 	}
375 	/*
376 	 * Paired with the fence from cpus_fence_seq_cst()
377 	 */
378 	atomic_store_rel_int(&lock_prof_resetting, 0);
379 	lock_prof_enable = enabled;
380 }
381 
382 static void
383 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
384 {
385 	const char *p;
386 
387 	for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
388 	sbuf_printf(sb,
389 	    "%8ju %9ju %11ju %11ju %11ju %6ju %6ju %2ju %6ju %s:%d (%s:%s)\n",
390 	    lp->cnt_max / 1000, lp->cnt_wait_max / 1000, lp->cnt_tot / 1000,
391 	    lp->cnt_wait / 1000, lp->cnt_cur,
392 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
393 	    lp->cnt_tot / (lp->cnt_cur * 1000),
394 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
395 	    lp->cnt_wait / (lp->cnt_cur * 1000),
396 	    (uintmax_t)0, lp->cnt_contest_locking,
397 	    p, lp->line, lp->class->lc_name, lp->name);
398 }
399 
400 static void
401 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
402     int spin, int t)
403 {
404 	struct lock_prof_type *type;
405 	struct lock_prof *l;
406 	int cpu;
407 
408 	dst->file = match->file;
409 	dst->line = match->line;
410 	dst->class = match->class;
411 	dst->name = match->name;
412 
413 	CPU_FOREACH(cpu) {
414 		type = &LP_CPU(cpu)->lpc_types[spin];
415 		SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
416 			if (l->ticks == t)
417 				continue;
418 			if (l->file != match->file || l->line != match->line ||
419 			    l->name != match->name)
420 				continue;
421 			l->ticks = t;
422 			if (l->cnt_max > dst->cnt_max)
423 				dst->cnt_max = l->cnt_max;
424 			if (l->cnt_wait_max > dst->cnt_wait_max)
425 				dst->cnt_wait_max = l->cnt_wait_max;
426 			dst->cnt_tot += l->cnt_tot;
427 			dst->cnt_wait += l->cnt_wait;
428 			dst->cnt_cur += l->cnt_cur;
429 			dst->cnt_contest_locking += l->cnt_contest_locking;
430 		}
431 	}
432 }
433 
434 static void
435 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
436     int t)
437 {
438 	struct lock_prof *l;
439 	int i;
440 
441 	for (i = 0; i < LPROF_HASH_SIZE; ++i) {
442 		SLIST_FOREACH(l, &type->lpt_hash[i], link) {
443 			struct lock_prof lp = {};
444 
445 			if (l->ticks == t)
446 				continue;
447 			lock_prof_sum(l, &lp, i, spin, t);
448 			lock_prof_output(&lp, sb);
449 		}
450 	}
451 }
452 
453 static int
454 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
455 {
456 	struct sbuf *sb;
457 	int error, cpu, t;
458 	int enabled;
459 
460 	error = sysctl_wire_old_buffer(req, 0);
461 	if (error != 0)
462 		return (error);
463 	sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
464 	sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
465 	    "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
466 	enabled = lock_prof_enable;
467 	lock_prof_enable = 0;
468 	/*
469 	 * See the comment in lock_prof_reset
470 	 */
471 	cpus_fence_seq_cst();
472 	quiesce_all_critical();
473 	t = ticks;
474 	CPU_FOREACH(cpu) {
475 		lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[0], sb, 0, t);
476 		lock_prof_type_stats(&LP_CPU(cpu)->lpc_types[1], sb, 1, t);
477 	}
478 	atomic_thread_fence_rel();
479 	lock_prof_enable = enabled;
480 
481 	error = sbuf_finish(sb);
482 	/* Output a trailing NUL. */
483 	if (error == 0)
484 		error = SYSCTL_OUT(req, "", 1);
485 	sbuf_delete(sb);
486 	return (error);
487 }
488 
489 static int
490 enable_lock_prof(SYSCTL_HANDLER_ARGS)
491 {
492 	int error, v;
493 
494 	v = lock_prof_enable;
495 	error = sysctl_handle_int(oidp, &v, v, req);
496 	if (error)
497 		return (error);
498 	if (req->newptr == NULL)
499 		return (error);
500 	if (v == lock_prof_enable)
501 		return (0);
502 	if (v == 1)
503 		lock_prof_reset();
504 	lock_prof_enable = !!v;
505 
506 	return (0);
507 }
508 
509 static int
510 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
511 {
512 	int error, v;
513 
514 	v = 0;
515 	error = sysctl_handle_int(oidp, &v, 0, req);
516 	if (error)
517 		return (error);
518 	if (req->newptr == NULL)
519 		return (error);
520 	if (v == 0)
521 		return (0);
522 	lock_prof_reset();
523 
524 	return (0);
525 }
526 
527 static struct lock_prof *
528 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
529     int line)
530 {
531 	const char *unknown = "(unknown)";
532 	struct lock_prof_type *type;
533 	struct lock_prof *lp;
534 	struct lphead *head;
535 	const char *p;
536 	u_int hash;
537 
538 	p = file;
539 	if (p == NULL || *p == '\0')
540 		p = unknown;
541 	hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
542 	hash &= LPROF_HASH_MASK;
543 	type = &LP_CPU_SELF->lpc_types[spin];
544 	head = &type->lpt_hash[hash];
545 	SLIST_FOREACH(lp, head, link) {
546 		if (lp->line == line && lp->file == p &&
547 		    lp->name == lo->lo_name)
548 			return (lp);
549 
550 	}
551 	lp = SLIST_FIRST(&type->lpt_lpalloc);
552 	if (lp == NULL) {
553 		lock_prof_rejected++;
554 		return (lp);
555 	}
556 	SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
557 	lp->file = p;
558 	lp->line = line;
559 	lp->class = LOCK_CLASS(lo);
560 	lp->name = lo->lo_name;
561 	SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
562 	return (lp);
563 }
564 
565 static struct lock_profile_object *
566 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
567     int line)
568 {
569 	struct lock_profile_object *l;
570 	struct lock_prof_type *type;
571 	struct lpohead *head;
572 
573 	head = &curthread->td_lprof[spin];
574 	LIST_FOREACH(l, head, lpo_link)
575 		if (l->lpo_obj == lo && l->lpo_file == file &&
576 		    l->lpo_line == line)
577 			return (l);
578 	type = &LP_CPU_SELF->lpc_types[spin];
579 	l = LIST_FIRST(&type->lpt_lpoalloc);
580 	if (l == NULL) {
581 		lock_prof_rejected++;
582 		return (NULL);
583 	}
584 	LIST_REMOVE(l, lpo_link);
585 	l->lpo_obj = lo;
586 	l->lpo_file = file;
587 	l->lpo_line = line;
588 	l->lpo_cnt = 0;
589 	LIST_INSERT_HEAD(head, l, lpo_link);
590 
591 	return (l);
592 }
593 
594 void
595 lock_profile_obtain_lock_success(struct lock_object *lo, int contested,
596     uint64_t waittime, const char *file, int line)
597 {
598 	static int lock_prof_count;
599 	struct lock_profile_object *l;
600 	int spin;
601 
602 	if (SCHEDULER_STOPPED())
603 		return;
604 
605 	/* don't reset the timer when/if recursing */
606 	if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
607 		return;
608 	if (lock_prof_skipcount &&
609 	    (++lock_prof_count % lock_prof_skipcount) != 0)
610 		return;
611 	spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
612 	if (spin && lock_prof_skipspin == 1)
613 		return;
614 	critical_enter();
615 	/* Recheck enabled now that we're in a critical section. */
616 	if (lock_prof_enable == 0)
617 		goto out;
618 	l = lock_profile_object_lookup(lo, spin, file, line);
619 	if (l == NULL)
620 		goto out;
621 	l->lpo_cnt++;
622 	if (++l->lpo_ref > 1)
623 		goto out;
624 	l->lpo_contest_locking = contested;
625 	l->lpo_acqtime = nanoseconds();
626 	if (waittime && (l->lpo_acqtime > waittime))
627 		l->lpo_waittime = l->lpo_acqtime - waittime;
628 	else
629 		l->lpo_waittime = 0;
630 out:
631 	/*
632 	 * Paired with cpus_fence_seq_cst().
633 	 */
634 	atomic_thread_fence_rel();
635 	critical_exit();
636 }
637 
638 void
639 lock_profile_thread_exit(struct thread *td)
640 {
641 #ifdef INVARIANTS
642 	struct lock_profile_object *l;
643 
644 	MPASS(curthread->td_critnest == 0);
645 #endif
646 	/*
647 	 * If lock profiling was disabled we have to wait for reset to
648 	 * clear our pointers before we can exit safely.
649 	 */
650 	lock_prof_reset_wait();
651 #ifdef INVARIANTS
652 	LIST_FOREACH(l, &td->td_lprof[0], lpo_link)
653 		printf("thread still holds lock acquired at %s:%d\n",
654 		    l->lpo_file, l->lpo_line);
655 	LIST_FOREACH(l, &td->td_lprof[1], lpo_link)
656 		printf("thread still holds lock acquired at %s:%d\n",
657 		    l->lpo_file, l->lpo_line);
658 #endif
659 	MPASS(LIST_FIRST(&td->td_lprof[0]) == NULL);
660 	MPASS(LIST_FIRST(&td->td_lprof[1]) == NULL);
661 }
662 
663 void
664 lock_profile_release_lock(struct lock_object *lo)
665 {
666 	struct lock_profile_object *l;
667 	struct lock_prof_type *type;
668 	struct lock_prof *lp;
669 	uint64_t curtime, holdtime;
670 	struct lpohead *head;
671 	int spin;
672 
673 	if (SCHEDULER_STOPPED())
674 		return;
675 	if (lo->lo_flags & LO_NOPROFILE)
676 		return;
677 	spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
678 	head = &curthread->td_lprof[spin];
679 	if (LIST_FIRST(head) == NULL)
680 		return;
681 	critical_enter();
682 	/* Recheck enabled now that we're in a critical section. */
683 	if (lock_prof_enable == 0 && lock_prof_resetting == 1)
684 		goto out;
685 	/*
686 	 * If lock profiling is not enabled we still want to remove the
687 	 * lpo from our queue.
688 	 */
689 	LIST_FOREACH(l, head, lpo_link)
690 		if (l->lpo_obj == lo)
691 			break;
692 	if (l == NULL)
693 		goto out;
694 	if (--l->lpo_ref > 0)
695 		goto out;
696 	lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
697 	if (lp == NULL)
698 		goto release;
699 	curtime = nanoseconds();
700 	if (curtime < l->lpo_acqtime)
701 		goto release;
702 	holdtime = curtime - l->lpo_acqtime;
703 
704 	/*
705 	 * Record if the lock has been held longer now than ever
706 	 * before.
707 	 */
708 	if (holdtime > lp->cnt_max)
709 		lp->cnt_max = holdtime;
710 	if (l->lpo_waittime > lp->cnt_wait_max)
711 		lp->cnt_wait_max = l->lpo_waittime;
712 	lp->cnt_tot += holdtime;
713 	lp->cnt_wait += l->lpo_waittime;
714 	lp->cnt_contest_locking += l->lpo_contest_locking;
715 	lp->cnt_cur += l->lpo_cnt;
716 release:
717 	LIST_REMOVE(l, lpo_link);
718 	type = &LP_CPU_SELF->lpc_types[spin];
719 	LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
720 out:
721 	/*
722 	 * Paired with cpus_fence_seq_cst().
723 	 */
724 	atomic_thread_fence_rel();
725 	critical_exit();
726 }
727 
728 static SYSCTL_NODE(_debug_lock, OID_AUTO, prof, CTLFLAG_RD, NULL,
729     "lock profiling");
730 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
731     &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
732 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipcount, CTLFLAG_RW,
733     &lock_prof_skipcount, 0, "Sample approximately every N lock acquisitions.");
734 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
735     &lock_prof_rejected, 0, "Number of rejected profiling records");
736 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
737     NULL, 0, dump_lock_prof_stats, "A", "Lock profiling statistics");
738 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
739     NULL, 0, reset_lock_prof_stats, "I", "Reset lock profiling statistics");
740 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
741     NULL, 0, enable_lock_prof, "I", "Enable lock profiling");
742 
743 #endif
744