xref: /freebsd/sys/kern/subr_lock.c (revision 721351876cd4d3a8a700f62d2061331fa951a488)
1 /*-
2  * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * This module holds the global variables and functions used to maintain
32  * lock_object structures.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_ddb.h"
39 #include "opt_mprof.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/ktr.h>
45 #include <sys/linker_set.h>
46 #include <sys/lock.h>
47 #include <sys/lock_profile.h>
48 #include <sys/malloc.h>
49 #include <sys/pcpu.h>
50 #include <sys/proc.h>
51 #include <sys/sbuf.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 CTASSERT(LOCK_CLASS_MAX == 15);
62 
63 struct lock_class *lock_classes[LOCK_CLASS_MAX + 1] = {
64 	&lock_class_mtx_spin,
65 	&lock_class_mtx_sleep,
66 	&lock_class_sx,
67 	&lock_class_rm,
68 	&lock_class_rw,
69 	&lock_class_lockmgr,
70 };
71 
72 void
73 lock_init(struct lock_object *lock, struct lock_class *class, const char *name,
74     const char *type, int flags)
75 {
76 	int i;
77 
78 	/* Check for double-init and zero object. */
79 	KASSERT(!lock_initalized(lock), ("lock \"%s\" %p already initialized",
80 	    name, lock));
81 
82 	/* Look up lock class to find its index. */
83 	for (i = 0; i < LOCK_CLASS_MAX; i++)
84 		if (lock_classes[i] == class) {
85 			lock->lo_flags = i << LO_CLASSSHIFT;
86 			break;
87 		}
88 	KASSERT(i < LOCK_CLASS_MAX, ("unknown lock class %p", class));
89 
90 	/* Initialize the lock object. */
91 	lock->lo_name = name;
92 	lock->lo_flags |= flags | LO_INITIALIZED;
93 	LOCK_LOG_INIT(lock, 0);
94 	WITNESS_INIT(lock, (type != NULL) ? type : name);
95 }
96 
97 void
98 lock_destroy(struct lock_object *lock)
99 {
100 
101 	KASSERT(lock_initalized(lock), ("lock %p is not initialized", lock));
102 	WITNESS_DESTROY(lock);
103 	LOCK_LOG_DESTROY(lock, 0);
104 	lock->lo_flags &= ~LO_INITIALIZED;
105 }
106 
107 #ifdef DDB
108 DB_SHOW_COMMAND(lock, db_show_lock)
109 {
110 	struct lock_object *lock;
111 	struct lock_class *class;
112 
113 	if (!have_addr)
114 		return;
115 	lock = (struct lock_object *)addr;
116 	if (LO_CLASSINDEX(lock) > LOCK_CLASS_MAX) {
117 		db_printf("Unknown lock class: %d\n", LO_CLASSINDEX(lock));
118 		return;
119 	}
120 	class = LOCK_CLASS(lock);
121 	db_printf(" class: %s\n", class->lc_name);
122 	db_printf(" name: %s\n", lock->lo_name);
123 	class->lc_ddb_show(lock);
124 }
125 #endif
126 
127 #ifdef LOCK_PROFILING
128 
129 /*
130  * One object per-thread for each lock the thread owns.  Tracks individual
131  * lock instances.
132  */
133 struct lock_profile_object {
134 	LIST_ENTRY(lock_profile_object) lpo_link;
135 	struct lock_object *lpo_obj;
136 	const char	*lpo_file;
137 	int		lpo_line;
138 	uint16_t	lpo_ref;
139 	uint16_t	lpo_cnt;
140 	u_int64_t	lpo_acqtime;
141 	u_int64_t	lpo_waittime;
142 	u_int		lpo_contest_locking;
143 };
144 
145 /*
146  * One lock_prof for each (file, line, lock object) triple.
147  */
148 struct lock_prof {
149 	SLIST_ENTRY(lock_prof) link;
150 	struct lock_class *class;
151 	const char	*file;
152 	const char	*name;
153 	int		line;
154 	int		ticks;
155 	uintmax_t	cnt_max;
156 	uintmax_t	cnt_tot;
157 	uintmax_t	cnt_wait;
158 	uintmax_t	cnt_cur;
159 	uintmax_t	cnt_contest_locking;
160 };
161 
162 SLIST_HEAD(lphead, lock_prof);
163 
164 #define	LPROF_HASH_SIZE		4096
165 #define	LPROF_HASH_MASK		(LPROF_HASH_SIZE - 1)
166 #define	LPROF_CACHE_SIZE	4096
167 
168 /*
169  * Array of objects and profs for each type of object for each cpu.  Spinlocks
170  * are handled seperately because a thread may be preempted and acquire a
171  * spinlock while in the lock profiling code of a non-spinlock.  In this way
172  * we only need a critical section to protect the per-cpu lists.
173  */
174 struct lock_prof_type {
175 	struct lphead		lpt_lpalloc;
176 	struct lpohead		lpt_lpoalloc;
177 	struct lphead		lpt_hash[LPROF_HASH_SIZE];
178 	struct lock_prof	lpt_prof[LPROF_CACHE_SIZE];
179 	struct lock_profile_object lpt_objs[LPROF_CACHE_SIZE];
180 };
181 
182 struct lock_prof_cpu {
183 	struct lock_prof_type	lpc_types[2]; /* One for spin one for other. */
184 };
185 
186 struct lock_prof_cpu *lp_cpu[MAXCPU];
187 
188 int lock_prof_enable = 0;
189 
190 /* SWAG: sbuf size = avg stat. line size * number of locks */
191 #define LPROF_SBUF_SIZE		256 * 400
192 
193 static int lock_prof_rejected;
194 static int lock_prof_skipspin;
195 static int lock_prof_skipcount;
196 
197 #ifndef USE_CPU_NANOSECONDS
198 u_int64_t
199 nanoseconds(void)
200 {
201 	struct bintime bt;
202 	u_int64_t ns;
203 
204 	binuptime(&bt);
205 	/* From bintime2timespec */
206 	ns = bt.sec * (u_int64_t)1000000000;
207 	ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32;
208 	return (ns);
209 }
210 #endif
211 
212 static void
213 lock_prof_init_type(struct lock_prof_type *type)
214 {
215 	int i;
216 
217 	SLIST_INIT(&type->lpt_lpalloc);
218 	LIST_INIT(&type->lpt_lpoalloc);
219 	for (i = 0; i < LPROF_CACHE_SIZE; i++) {
220 		SLIST_INSERT_HEAD(&type->lpt_lpalloc, &type->lpt_prof[i],
221 		    link);
222 		LIST_INSERT_HEAD(&type->lpt_lpoalloc, &type->lpt_objs[i],
223 		    lpo_link);
224 	}
225 }
226 
227 static void
228 lock_prof_init(void *arg)
229 {
230 	int cpu;
231 
232 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
233 		lp_cpu[cpu] = malloc(sizeof(*lp_cpu[cpu]), M_DEVBUF,
234 		    M_WAITOK | M_ZERO);
235 		lock_prof_init_type(&lp_cpu[cpu]->lpc_types[0]);
236 		lock_prof_init_type(&lp_cpu[cpu]->lpc_types[1]);
237 	}
238 }
239 SYSINIT(lockprof, SI_SUB_SMP, SI_ORDER_ANY, lock_prof_init, NULL);
240 
241 static void
242 lock_prof_reset(void)
243 {
244 	struct lock_prof_cpu *lpc;
245 	int enabled, i, cpu;
246 
247 	enabled = lock_prof_enable;
248 	lock_prof_enable = 0;
249 	pause("lpreset", hz / 10);
250 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
251 		lpc = lp_cpu[cpu];
252 		for (i = 0; i < LPROF_CACHE_SIZE; i++) {
253 			LIST_REMOVE(&lpc->lpc_types[0].lpt_objs[i], lpo_link);
254 			LIST_REMOVE(&lpc->lpc_types[1].lpt_objs[i], lpo_link);
255 		}
256 		bzero(lpc, sizeof(*lpc));
257 		lock_prof_init_type(&lpc->lpc_types[0]);
258 		lock_prof_init_type(&lpc->lpc_types[1]);
259 	}
260 	lock_prof_enable = enabled;
261 }
262 
263 static void
264 lock_prof_output(struct lock_prof *lp, struct sbuf *sb)
265 {
266 	const char *p;
267 
268 	for (p = lp->file; p != NULL && strncmp(p, "../", 3) == 0; p += 3);
269 	sbuf_printf(sb,
270 	    "%6ju %12ju %12ju %11ju %5ju %5ju %12ju %12ju %s:%d (%s:%s)\n",
271 	    lp->cnt_max / 1000, lp->cnt_tot / 1000,
272 	    lp->cnt_wait / 1000, lp->cnt_cur,
273 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
274 	    lp->cnt_tot / (lp->cnt_cur * 1000),
275 	    lp->cnt_cur == 0 ? (uintmax_t)0 :
276 	    lp->cnt_wait / (lp->cnt_cur * 1000),
277 	    (uintmax_t)0, lp->cnt_contest_locking,
278 	    p, lp->line, lp->class->lc_name, lp->name);
279 }
280 
281 static void
282 lock_prof_sum(struct lock_prof *match, struct lock_prof *dst, int hash,
283     int spin, int t)
284 {
285 	struct lock_prof_type *type;
286 	struct lock_prof *l;
287 	int cpu;
288 
289 	dst->file = match->file;
290 	dst->line = match->line;
291 	dst->class = match->class;
292 	dst->name = match->name;
293 
294 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
295 		if (lp_cpu[cpu] == NULL)
296 			continue;
297 		type = &lp_cpu[cpu]->lpc_types[spin];
298 		SLIST_FOREACH(l, &type->lpt_hash[hash], link) {
299 			if (l->ticks == t)
300 				continue;
301 			if (l->file != match->file || l->line != match->line ||
302 			    l->name != match->name)
303 				continue;
304 			l->ticks = t;
305 			if (l->cnt_max > dst->cnt_max)
306 				dst->cnt_max = l->cnt_max;
307 			dst->cnt_tot += l->cnt_tot;
308 			dst->cnt_wait += l->cnt_wait;
309 			dst->cnt_cur += l->cnt_cur;
310 			dst->cnt_contest_locking += l->cnt_contest_locking;
311 		}
312 	}
313 
314 }
315 
316 static void
317 lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
318     int t)
319 {
320 	struct lock_prof *l;
321 	int i;
322 
323 	for (i = 0; i < LPROF_HASH_SIZE; ++i) {
324 		SLIST_FOREACH(l, &type->lpt_hash[i], link) {
325 			struct lock_prof lp = {};
326 
327 			if (l->ticks == t)
328 				continue;
329 			lock_prof_sum(l, &lp, i, spin, t);
330 			lock_prof_output(&lp, sb);
331 			if (sbuf_overflowed(sb))
332 				return;
333 		}
334 	}
335 }
336 
337 static int
338 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
339 {
340 	static int multiplier = 1;
341 	struct sbuf *sb;
342 	int error, cpu, t;
343 	int enabled;
344 
345 retry_sbufops:
346 	sb = sbuf_new(NULL, NULL, LPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
347 	sbuf_printf(sb, "\n%6s %12s %12s %11s %5s %5s %12s %12s %s\n",
348 	    "max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
349 	enabled = lock_prof_enable;
350 	lock_prof_enable = 0;
351 	pause("lpreset", hz / 10);
352 	t = ticks;
353 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
354 		if (lp_cpu[cpu] == NULL)
355 			continue;
356 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[0], sb, 0, t);
357 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[1], sb, 1, t);
358 		if (sbuf_overflowed(sb)) {
359 			sbuf_delete(sb);
360 			multiplier++;
361 			goto retry_sbufops;
362 		}
363 	}
364 	lock_prof_enable = enabled;
365 
366 	sbuf_finish(sb);
367 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
368 	sbuf_delete(sb);
369 	return (error);
370 }
371 
372 static int
373 enable_lock_prof(SYSCTL_HANDLER_ARGS)
374 {
375 	int error, v;
376 
377 	v = lock_prof_enable;
378 	error = sysctl_handle_int(oidp, &v, v, req);
379 	if (error)
380 		return (error);
381 	if (req->newptr == NULL)
382 		return (error);
383 	if (v == lock_prof_enable)
384 		return (0);
385 	if (v == 1)
386 		lock_prof_reset();
387 	lock_prof_enable = !!v;
388 
389 	return (0);
390 }
391 
392 static int
393 reset_lock_prof_stats(SYSCTL_HANDLER_ARGS)
394 {
395 	int error, v;
396 
397 	v = 0;
398 	error = sysctl_handle_int(oidp, &v, 0, req);
399 	if (error)
400 		return (error);
401 	if (req->newptr == NULL)
402 		return (error);
403 	if (v == 0)
404 		return (0);
405 	lock_prof_reset();
406 
407 	return (0);
408 }
409 
410 static struct lock_prof *
411 lock_profile_lookup(struct lock_object *lo, int spin, const char *file,
412     int line)
413 {
414 	const char *unknown = "(unknown)";
415 	struct lock_prof_type *type;
416 	struct lock_prof *lp;
417 	struct lphead *head;
418 	const char *p;
419 	u_int hash;
420 
421 	p = file;
422 	if (p == NULL || *p == '\0')
423 		p = unknown;
424 	hash = (uintptr_t)lo->lo_name * 31 + (uintptr_t)p * 31 + line;
425 	hash &= LPROF_HASH_MASK;
426 	type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
427 	head = &type->lpt_hash[hash];
428 	SLIST_FOREACH(lp, head, link) {
429 		if (lp->line == line && lp->file == p &&
430 		    lp->name == lo->lo_name)
431 			return (lp);
432 
433 	}
434 	lp = SLIST_FIRST(&type->lpt_lpalloc);
435 	if (lp == NULL) {
436 		lock_prof_rejected++;
437 		return (lp);
438 	}
439 	SLIST_REMOVE_HEAD(&type->lpt_lpalloc, link);
440 	lp->file = p;
441 	lp->line = line;
442 	lp->class = LOCK_CLASS(lo);
443 	lp->name = lo->lo_name;
444 	SLIST_INSERT_HEAD(&type->lpt_hash[hash], lp, link);
445 	return (lp);
446 }
447 
448 static struct lock_profile_object *
449 lock_profile_object_lookup(struct lock_object *lo, int spin, const char *file,
450     int line)
451 {
452 	struct lock_profile_object *l;
453 	struct lock_prof_type *type;
454 	struct lpohead *head;
455 
456 	head = &curthread->td_lprof[spin];
457 	LIST_FOREACH(l, head, lpo_link)
458 		if (l->lpo_obj == lo && l->lpo_file == file &&
459 		    l->lpo_line == line)
460 			return (l);
461 	critical_enter();
462 	type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
463 	l = LIST_FIRST(&type->lpt_lpoalloc);
464 	if (l == NULL) {
465 		lock_prof_rejected++;
466 		critical_exit();
467 		return (NULL);
468 	}
469 	LIST_REMOVE(l, lpo_link);
470 	critical_exit();
471 	l->lpo_obj = lo;
472 	l->lpo_file = file;
473 	l->lpo_line = line;
474 	l->lpo_cnt = 0;
475 	LIST_INSERT_HEAD(head, l, lpo_link);
476 
477 	return (l);
478 }
479 
480 void
481 lock_profile_obtain_lock_success(struct lock_object *lo, int contested,
482     uint64_t waittime, const char *file, int line)
483 {
484 	static int lock_prof_count;
485 	struct lock_profile_object *l;
486 	int spin;
487 
488 	/* don't reset the timer when/if recursing */
489 	if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
490 		return;
491 	if (lock_prof_skipcount &&
492 	    (++lock_prof_count % lock_prof_skipcount) != 0)
493 		return;
494 	spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
495 	if (spin && lock_prof_skipspin == 1)
496 		return;
497 	l = lock_profile_object_lookup(lo, spin, file, line);
498 	if (l == NULL)
499 		return;
500 	l->lpo_cnt++;
501 	if (++l->lpo_ref > 1)
502 		return;
503 	l->lpo_contest_locking = contested;
504 	l->lpo_acqtime = nanoseconds();
505 	if (waittime && (l->lpo_acqtime > waittime))
506 		l->lpo_waittime = l->lpo_acqtime - waittime;
507 	else
508 		l->lpo_waittime = 0;
509 }
510 
511 void
512 lock_profile_release_lock(struct lock_object *lo)
513 {
514 	struct lock_profile_object *l;
515 	struct lock_prof_type *type;
516 	struct lock_prof *lp;
517 	u_int64_t holdtime;
518 	struct lpohead *head;
519 	int spin;
520 
521 	if (!lock_prof_enable || (lo->lo_flags & LO_NOPROFILE))
522 		return;
523 	spin = (LOCK_CLASS(lo)->lc_flags & LC_SPINLOCK) ? 1 : 0;
524 	head = &curthread->td_lprof[spin];
525 	critical_enter();
526 	LIST_FOREACH(l, head, lpo_link)
527 		if (l->lpo_obj == lo)
528 			break;
529 	if (l == NULL)
530 		goto out;
531 	if (--l->lpo_ref > 0)
532 		goto out;
533 	lp = lock_profile_lookup(lo, spin, l->lpo_file, l->lpo_line);
534 	if (lp == NULL)
535 		goto release;
536 	holdtime = nanoseconds() - l->lpo_acqtime;
537 	if (holdtime < 0)
538 		goto release;
539 	/*
540 	 * Record if the lock has been held longer now than ever
541 	 * before.
542 	 */
543 	if (holdtime > lp->cnt_max)
544 		lp->cnt_max = holdtime;
545 	lp->cnt_tot += holdtime;
546 	lp->cnt_wait += l->lpo_waittime;
547 	lp->cnt_contest_locking += l->lpo_contest_locking;
548 	lp->cnt_cur += l->lpo_cnt;
549 release:
550 	LIST_REMOVE(l, lpo_link);
551 	type = &lp_cpu[PCPU_GET(cpuid)]->lpc_types[spin];
552 	LIST_INSERT_HEAD(&type->lpt_lpoalloc, l, lpo_link);
553 out:
554 	critical_exit();
555 }
556 
557 SYSCTL_NODE(_debug, OID_AUTO, lock, CTLFLAG_RD, NULL, "lock debugging");
558 SYSCTL_NODE(_debug_lock, OID_AUTO, prof, CTLFLAG_RD, NULL, "lock profiling");
559 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipspin, CTLFLAG_RW,
560     &lock_prof_skipspin, 0, "Skip profiling on spinlocks.");
561 SYSCTL_INT(_debug_lock_prof, OID_AUTO, skipcount, CTLFLAG_RW,
562     &lock_prof_skipcount, 0, "Sample approximately every N lock acquisitions.");
563 SYSCTL_INT(_debug_lock_prof, OID_AUTO, rejected, CTLFLAG_RD,
564     &lock_prof_rejected, 0, "Number of rejected profiling records");
565 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
566     NULL, 0, dump_lock_prof_stats, "A", "Lock profiling statistics");
567 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW,
568     NULL, 0, reset_lock_prof_stats, "I", "Reset lock profiling statistics");
569 SYSCTL_PROC(_debug_lock_prof, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
570     NULL, 0, enable_lock_prof, "I", "Enable lock profiling");
571 
572 #endif
573