1 // SPDX-License-Identifier: GPL-2.0
7 #include "util/evlist.h" // for struct evsel_str_handler
8 #include "util/evsel.h"
9 #include "util/symbol.h"
10 #include "util/thread.h"
11 #include "util/header.h"
12 #include "util/target.h"
13 #include "util/callchain.h"
14 #include "util/lock-contention.h"
16 #include <subcmd/pager.h>
17 #include <subcmd/parse-options.h>
18 #include "util/trace-event.h"
19 #include "util/tracepoint.h"
21 #include "util/debug.h"
22 #include "util/session.h"
23 #include "util/tool.h"
24 #include "util/data.h"
25 #include "util/string2.h"
28 #include <sys/types.h>
29 #include <sys/prctl.h>
30 #include <semaphore.h>
34 #include <linux/list.h>
35 #include <linux/hash.h>
36 #include <linux/kernel.h>
37 #include <linux/zalloc.h>
38 #include <linux/err.h>
39 #include <linux/stringify.h>
41 static struct perf_session *session;
42 static struct target target;
44 /* based on kernel/lockdep.c */
45 #define LOCKHASH_BITS 12
46 #define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
48 static struct hlist_head lockhash_table[LOCKHASH_SIZE];
50 #define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
51 #define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
53 static struct rb_root thread_stats;
55 static bool combine_locks;
56 static bool show_thread_stats;
58 static unsigned long bpf_map_entries = 10240;
59 static int max_stack_depth = CONTENTION_STACK_DEPTH;
60 static int stack_skip = CONTENTION_STACK_SKIP;
61 static int print_nr_entries = INT_MAX / 2;
67 } aggr_mode = LOCK_AGGR_ADDR;
69 static u64 sched_text_start;
70 static u64 sched_text_end;
71 static u64 lock_text_start;
72 static u64 lock_text_end;
74 static struct thread_stat *thread_stat_find(u32 tid)
77 struct thread_stat *st;
79 node = thread_stats.rb_node;
81 st = container_of(node, struct thread_stat, rb);
84 else if (tid < st->tid)
87 node = node->rb_right;
93 static void thread_stat_insert(struct thread_stat *new)
95 struct rb_node **rb = &thread_stats.rb_node;
96 struct rb_node *parent = NULL;
97 struct thread_stat *p;
100 p = container_of(*rb, struct thread_stat, rb);
103 if (new->tid < p->tid)
104 rb = &(*rb)->rb_left;
105 else if (new->tid > p->tid)
106 rb = &(*rb)->rb_right;
108 BUG_ON("inserting invalid thread_stat\n");
111 rb_link_node(&new->rb, parent, rb);
112 rb_insert_color(&new->rb, &thread_stats);
115 static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
117 struct thread_stat *st;
119 st = thread_stat_find(tid);
123 st = zalloc(sizeof(struct thread_stat));
125 pr_err("memory allocation failed\n");
130 INIT_LIST_HEAD(&st->seq_list);
132 thread_stat_insert(st);
137 static struct thread_stat *thread_stat_findnew_first(u32 tid);
138 static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
139 thread_stat_findnew_first;
141 static struct thread_stat *thread_stat_findnew_first(u32 tid)
143 struct thread_stat *st;
145 st = zalloc(sizeof(struct thread_stat));
147 pr_err("memory allocation failed\n");
151 INIT_LIST_HEAD(&st->seq_list);
153 rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
154 rb_insert_color(&st->rb, &thread_stats);
156 thread_stat_findnew = thread_stat_findnew_after_first;
160 /* build simple key function one is bigger than two */
161 #define SINGLE_KEY(member) \
162 static int lock_stat_key_ ## member(struct lock_stat *one, \
163 struct lock_stat *two) \
165 return one->member > two->member; \
168 SINGLE_KEY(nr_acquired)
169 SINGLE_KEY(nr_contended)
170 SINGLE_KEY(avg_wait_time)
171 SINGLE_KEY(wait_time_total)
172 SINGLE_KEY(wait_time_max)
174 static int lock_stat_key_wait_time_min(struct lock_stat *one,
175 struct lock_stat *two)
177 u64 s1 = one->wait_time_min;
178 u64 s2 = two->wait_time_min;
179 if (s1 == ULLONG_MAX)
181 if (s2 == ULLONG_MAX)
188 * name: the value for specify by user
189 * this should be simpler than raw name of member
190 * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
193 /* header: the string printed on the header line */
195 /* len: the printing width of the field */
197 /* key: a pointer to function to compare two lock stats for sorting */
198 int (*key)(struct lock_stat*, struct lock_stat*);
199 /* print: a pointer to function to print a given lock stats */
200 void (*print)(struct lock_key*, struct lock_stat*);
201 /* list: list entry to link this */
202 struct list_head list;
205 static void lock_stat_key_print_time(unsigned long long nsec, int len)
207 static const struct {
211 { 1e9 * 3600, "h " },
219 for (int i = 0; table[i].unit; i++) {
220 if (nsec < table[i].base)
223 pr_info("%*.2f %s", len - 3, nsec / table[i].base, table[i].unit);
227 pr_info("%*llu %s", len - 3, nsec, "ns");
230 #define PRINT_KEY(member) \
231 static void lock_stat_key_print_ ## member(struct lock_key *key, \
232 struct lock_stat *ls) \
234 pr_info("%*llu", key->len, (unsigned long long)ls->member); \
237 #define PRINT_TIME(member) \
238 static void lock_stat_key_print_ ## member(struct lock_key *key, \
239 struct lock_stat *ls) \
241 lock_stat_key_print_time((unsigned long long)ls->member, key->len); \
244 PRINT_KEY(nr_acquired)
245 PRINT_KEY(nr_contended)
246 PRINT_TIME(avg_wait_time)
247 PRINT_TIME(wait_time_total)
248 PRINT_TIME(wait_time_max)
250 static void lock_stat_key_print_wait_time_min(struct lock_key *key,
251 struct lock_stat *ls)
253 u64 wait_time = ls->wait_time_min;
255 if (wait_time == ULLONG_MAX)
258 lock_stat_key_print_time(wait_time, key->len);
262 static const char *sort_key = "acquired";
264 static int (*compare)(struct lock_stat *, struct lock_stat *);
266 static struct rb_root sorted; /* place to store intermediate data */
267 static struct rb_root result; /* place to store sorted data */
269 static LIST_HEAD(lock_keys);
270 static const char *output_fields;
272 #define DEF_KEY_LOCK(name, header, fn_suffix, len) \
273 { #name, header, len, lock_stat_key_ ## fn_suffix, lock_stat_key_print_ ## fn_suffix, {} }
274 static struct lock_key report_keys[] = {
275 DEF_KEY_LOCK(acquired, "acquired", nr_acquired, 10),
276 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
277 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
278 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
279 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
280 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
282 /* extra comparisons much complicated should be here */
286 static struct lock_key contention_keys[] = {
287 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
288 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
289 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
290 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
291 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
293 /* extra comparisons much complicated should be here */
297 static int select_key(bool contention)
300 struct lock_key *keys = report_keys;
303 keys = contention_keys;
305 for (i = 0; keys[i].name; i++) {
306 if (!strcmp(keys[i].name, sort_key)) {
307 compare = keys[i].key;
309 /* selected key should be in the output fields */
310 if (list_empty(&keys[i].list))
311 list_add_tail(&keys[i].list, &lock_keys);
317 pr_err("Unknown compare key: %s\n", sort_key);
321 static int add_output_field(bool contention, char *name)
324 struct lock_key *keys = report_keys;
327 keys = contention_keys;
329 for (i = 0; keys[i].name; i++) {
330 if (strcmp(keys[i].name, name))
333 /* prevent double link */
334 if (list_empty(&keys[i].list))
335 list_add_tail(&keys[i].list, &lock_keys);
340 pr_err("Unknown output field: %s\n", name);
344 static int setup_output_field(bool contention, const char *str)
346 char *tok, *tmp, *orig;
348 struct lock_key *keys = report_keys;
351 keys = contention_keys;
353 /* no output field given: use all of them */
355 for (i = 0; keys[i].name; i++)
356 list_add_tail(&keys[i].list, &lock_keys);
360 for (i = 0; keys[i].name; i++)
361 INIT_LIST_HEAD(&keys[i].list);
363 orig = tmp = strdup(str);
367 while ((tok = strsep(&tmp, ",")) != NULL){
368 ret = add_output_field(contention, tok);
377 static void combine_lock_stats(struct lock_stat *st)
379 struct rb_node **rb = &sorted.rb_node;
380 struct rb_node *parent = NULL;
385 p = container_of(*rb, struct lock_stat, rb);
388 if (st->name && p->name)
389 ret = strcmp(st->name, p->name);
391 ret = !!st->name - !!p->name;
394 p->nr_acquired += st->nr_acquired;
395 p->nr_contended += st->nr_contended;
396 p->wait_time_total += st->wait_time_total;
399 p->avg_wait_time = p->wait_time_total / p->nr_contended;
401 if (p->wait_time_min > st->wait_time_min)
402 p->wait_time_min = st->wait_time_min;
403 if (p->wait_time_max < st->wait_time_max)
404 p->wait_time_max = st->wait_time_max;
406 p->broken |= st->broken;
412 rb = &(*rb)->rb_left;
414 rb = &(*rb)->rb_right;
417 rb_link_node(&st->rb, parent, rb);
418 rb_insert_color(&st->rb, &sorted);
421 static void insert_to_result(struct lock_stat *st,
422 int (*bigger)(struct lock_stat *, struct lock_stat *))
424 struct rb_node **rb = &result.rb_node;
425 struct rb_node *parent = NULL;
428 if (combine_locks && st->combined)
432 p = container_of(*rb, struct lock_stat, rb);
436 rb = &(*rb)->rb_left;
438 rb = &(*rb)->rb_right;
441 rb_link_node(&st->rb, parent, rb);
442 rb_insert_color(&st->rb, &result);
445 /* returns left most element of result, and erase it */
446 static struct lock_stat *pop_from_result(void)
448 struct rb_node *node = result.rb_node;
453 while (node->rb_left)
454 node = node->rb_left;
456 rb_erase(node, &result);
457 return container_of(node, struct lock_stat, rb);
460 static struct lock_stat *lock_stat_find(u64 addr)
462 struct hlist_head *entry = lockhashentry(addr);
463 struct lock_stat *ret;
465 hlist_for_each_entry(ret, entry, hash_entry) {
466 if (ret->addr == addr)
472 static struct lock_stat *lock_stat_findnew(u64 addr, const char *name, int flags)
474 struct hlist_head *entry = lockhashentry(addr);
475 struct lock_stat *ret, *new;
477 hlist_for_each_entry(ret, entry, hash_entry) {
478 if (ret->addr == addr)
482 new = zalloc(sizeof(struct lock_stat));
487 new->name = strdup(name);
494 new->wait_time_min = ULLONG_MAX;
496 hlist_add_head(&new->hash_entry, entry);
500 pr_err("memory allocation failed\n");
504 struct trace_lock_handler {
505 /* it's used on CONFIG_LOCKDEP */
506 int (*acquire_event)(struct evsel *evsel,
507 struct perf_sample *sample);
509 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
510 int (*acquired_event)(struct evsel *evsel,
511 struct perf_sample *sample);
513 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
514 int (*contended_event)(struct evsel *evsel,
515 struct perf_sample *sample);
517 /* it's used on CONFIG_LOCKDEP */
518 int (*release_event)(struct evsel *evsel,
519 struct perf_sample *sample);
521 /* it's used when CONFIG_LOCKDEP is off */
522 int (*contention_begin_event)(struct evsel *evsel,
523 struct perf_sample *sample);
525 /* it's used when CONFIG_LOCKDEP is off */
526 int (*contention_end_event)(struct evsel *evsel,
527 struct perf_sample *sample);
530 static struct lock_seq_stat *get_seq(struct thread_stat *ts, u64 addr)
532 struct lock_seq_stat *seq;
534 list_for_each_entry(seq, &ts->seq_list, list) {
535 if (seq->addr == addr)
539 seq = zalloc(sizeof(struct lock_seq_stat));
541 pr_err("memory allocation failed\n");
544 seq->state = SEQ_STATE_UNINITIALIZED;
547 list_add(&seq->list, &ts->seq_list);
559 static int bad_hist[BROKEN_MAX];
566 static int get_key_by_aggr_mode_simple(u64 *key, u64 addr, u32 tid)
575 case LOCK_AGGR_CALLER:
577 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
583 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample);
585 static int get_key_by_aggr_mode(u64 *key, u64 addr, struct evsel *evsel,
586 struct perf_sample *sample)
588 if (aggr_mode == LOCK_AGGR_CALLER) {
589 *key = callchain_id(evsel, sample);
592 return get_key_by_aggr_mode_simple(key, addr, sample->tid);
595 static int report_lock_acquire_event(struct evsel *evsel,
596 struct perf_sample *sample)
598 struct lock_stat *ls;
599 struct thread_stat *ts;
600 struct lock_seq_stat *seq;
601 const char *name = evsel__strval(evsel, sample, "name");
602 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
603 int flag = evsel__intval(evsel, sample, "flags");
607 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
611 ls = lock_stat_findnew(key, name, 0);
615 ts = thread_stat_findnew(sample->tid);
619 seq = get_seq(ts, addr);
623 switch (seq->state) {
624 case SEQ_STATE_UNINITIALIZED:
625 case SEQ_STATE_RELEASED:
627 seq->state = SEQ_STATE_ACQUIRING;
631 if (flag & READ_LOCK)
633 seq->state = SEQ_STATE_READ_ACQUIRED;
638 case SEQ_STATE_READ_ACQUIRED:
639 if (flag & READ_LOCK) {
647 case SEQ_STATE_ACQUIRED:
648 case SEQ_STATE_ACQUIRING:
649 case SEQ_STATE_CONTENDED:
651 /* broken lock sequence */
654 bad_hist[BROKEN_ACQUIRE]++;
656 list_del_init(&seq->list);
660 BUG_ON("Unknown state of lock sequence found!\n");
665 seq->prev_event_time = sample->time;
670 static int report_lock_acquired_event(struct evsel *evsel,
671 struct perf_sample *sample)
673 struct lock_stat *ls;
674 struct thread_stat *ts;
675 struct lock_seq_stat *seq;
677 const char *name = evsel__strval(evsel, sample, "name");
678 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
682 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
686 ls = lock_stat_findnew(key, name, 0);
690 ts = thread_stat_findnew(sample->tid);
694 seq = get_seq(ts, addr);
698 switch (seq->state) {
699 case SEQ_STATE_UNINITIALIZED:
700 /* orphan event, do nothing */
702 case SEQ_STATE_ACQUIRING:
704 case SEQ_STATE_CONTENDED:
705 contended_term = sample->time - seq->prev_event_time;
706 ls->wait_time_total += contended_term;
707 if (contended_term < ls->wait_time_min)
708 ls->wait_time_min = contended_term;
709 if (ls->wait_time_max < contended_term)
710 ls->wait_time_max = contended_term;
712 case SEQ_STATE_RELEASED:
713 case SEQ_STATE_ACQUIRED:
714 case SEQ_STATE_READ_ACQUIRED:
715 /* broken lock sequence */
718 bad_hist[BROKEN_ACQUIRED]++;
720 list_del_init(&seq->list);
724 BUG_ON("Unknown state of lock sequence found!\n");
728 seq->state = SEQ_STATE_ACQUIRED;
730 ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
731 seq->prev_event_time = sample->time;
736 static int report_lock_contended_event(struct evsel *evsel,
737 struct perf_sample *sample)
739 struct lock_stat *ls;
740 struct thread_stat *ts;
741 struct lock_seq_stat *seq;
742 const char *name = evsel__strval(evsel, sample, "name");
743 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
747 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
751 ls = lock_stat_findnew(key, name, 0);
755 ts = thread_stat_findnew(sample->tid);
759 seq = get_seq(ts, addr);
763 switch (seq->state) {
764 case SEQ_STATE_UNINITIALIZED:
765 /* orphan event, do nothing */
767 case SEQ_STATE_ACQUIRING:
769 case SEQ_STATE_RELEASED:
770 case SEQ_STATE_ACQUIRED:
771 case SEQ_STATE_READ_ACQUIRED:
772 case SEQ_STATE_CONTENDED:
773 /* broken lock sequence */
776 bad_hist[BROKEN_CONTENDED]++;
778 list_del_init(&seq->list);
782 BUG_ON("Unknown state of lock sequence found!\n");
786 seq->state = SEQ_STATE_CONTENDED;
788 ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
789 seq->prev_event_time = sample->time;
794 static int report_lock_release_event(struct evsel *evsel,
795 struct perf_sample *sample)
797 struct lock_stat *ls;
798 struct thread_stat *ts;
799 struct lock_seq_stat *seq;
800 const char *name = evsel__strval(evsel, sample, "name");
801 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
805 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
809 ls = lock_stat_findnew(key, name, 0);
813 ts = thread_stat_findnew(sample->tid);
817 seq = get_seq(ts, addr);
821 switch (seq->state) {
822 case SEQ_STATE_UNINITIALIZED:
824 case SEQ_STATE_ACQUIRED:
826 case SEQ_STATE_READ_ACQUIRED:
828 BUG_ON(seq->read_count < 0);
829 if (seq->read_count) {
834 case SEQ_STATE_ACQUIRING:
835 case SEQ_STATE_CONTENDED:
836 case SEQ_STATE_RELEASED:
837 /* broken lock sequence */
840 bad_hist[BROKEN_RELEASE]++;
844 BUG_ON("Unknown state of lock sequence found!\n");
850 list_del_init(&seq->list);
856 bool is_lock_function(struct machine *machine, u64 addr)
858 if (!sched_text_start) {
862 sym = machine__find_kernel_symbol_by_name(machine,
863 "__sched_text_start",
867 sched_text_start = 1;
871 sched_text_start = kmap->unmap_ip(kmap, sym->start);
873 /* should not fail from here */
874 sym = machine__find_kernel_symbol_by_name(machine,
877 sched_text_end = kmap->unmap_ip(kmap, sym->start);
879 sym = machine__find_kernel_symbol_by_name(machine,
882 lock_text_start = kmap->unmap_ip(kmap, sym->start);
884 sym = machine__find_kernel_symbol_by_name(machine,
887 lock_text_end = kmap->unmap_ip(kmap, sym->start);
890 /* failed to get kernel symbols */
891 if (sched_text_start == 1)
894 /* mutex and rwsem functions are in sched text section */
895 if (sched_text_start <= addr && addr < sched_text_end)
898 /* spinlock functions are in lock text section */
899 if (lock_text_start <= addr && addr < lock_text_end)
905 static int get_symbol_name_offset(struct map *map, struct symbol *sym, u64 ip,
910 if (map == NULL || sym == NULL) {
915 offset = map->map_ip(map, ip) - sym->start;
918 return scnprintf(buf, size, "%s+%#lx", sym->name, offset);
920 return strlcpy(buf, sym->name, size);
922 static int lock_contention_caller(struct evsel *evsel, struct perf_sample *sample,
925 struct thread *thread;
926 struct callchain_cursor *cursor = &callchain_cursor;
927 struct machine *machine = &session->machines.host;
932 /* lock names will be replaced to task name later */
933 if (show_thread_stats)
936 thread = machine__findnew_thread(machine, -1, sample->pid);
940 /* use caller function name from the callchain */
941 ret = thread__resolve_callchain(thread, cursor, evsel, sample,
942 NULL, NULL, max_stack_depth);
948 callchain_cursor_commit(cursor);
952 struct callchain_cursor_node *node;
954 node = callchain_cursor_current(cursor);
958 /* skip first few entries - for lock functions */
959 if (++skip <= stack_skip)
963 if (sym && !is_lock_function(machine, node->ip)) {
964 get_symbol_name_offset(node->ms.map, sym, node->ip,
970 callchain_cursor_advance(cursor);
975 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample)
977 struct callchain_cursor *cursor = &callchain_cursor;
978 struct machine *machine = &session->machines.host;
979 struct thread *thread;
984 thread = machine__findnew_thread(machine, -1, sample->pid);
988 /* use caller function name from the callchain */
989 ret = thread__resolve_callchain(thread, cursor, evsel, sample,
990 NULL, NULL, max_stack_depth);
996 callchain_cursor_commit(cursor);
999 struct callchain_cursor_node *node;
1001 node = callchain_cursor_current(cursor);
1005 /* skip first few entries - for lock functions */
1006 if (++skip <= stack_skip)
1009 if (node->ms.sym && is_lock_function(machine, node->ip))
1012 hash ^= hash_long((unsigned long)node->ip, 64);
1015 callchain_cursor_advance(cursor);
1020 static u64 *get_callstack(struct perf_sample *sample, int max_stack)
1026 callstack = calloc(max_stack, sizeof(*callstack));
1027 if (callstack == NULL)
1030 for (i = 0, c = 0; i < sample->callchain->nr && c < max_stack; i++) {
1031 u64 ip = sample->callchain->ips[i];
1033 if (ip >= PERF_CONTEXT_MAX)
1036 callstack[c++] = ip;
1041 static int report_lock_contention_begin_event(struct evsel *evsel,
1042 struct perf_sample *sample)
1044 struct lock_stat *ls;
1045 struct thread_stat *ts;
1046 struct lock_seq_stat *seq;
1047 u64 addr = evsel__intval(evsel, sample, "lock_addr");
1051 ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1055 ls = lock_stat_find(key);
1058 const char *caller = buf;
1059 unsigned int flags = evsel__intval(evsel, sample, "flags");
1061 if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
1064 ls = lock_stat_findnew(key, caller, flags);
1068 if (aggr_mode == LOCK_AGGR_CALLER && verbose) {
1069 ls->callstack = get_callstack(sample, max_stack_depth);
1070 if (ls->callstack == NULL)
1075 ts = thread_stat_findnew(sample->tid);
1079 seq = get_seq(ts, addr);
1083 switch (seq->state) {
1084 case SEQ_STATE_UNINITIALIZED:
1085 case SEQ_STATE_ACQUIRED:
1087 case SEQ_STATE_CONTENDED:
1089 * It can have nested contention begin with mutex spinning,
1090 * then we would use the original contention begin event and
1091 * ignore the second one.
1094 case SEQ_STATE_ACQUIRING:
1095 case SEQ_STATE_READ_ACQUIRED:
1096 case SEQ_STATE_RELEASED:
1097 /* broken lock sequence */
1100 bad_hist[BROKEN_CONTENDED]++;
1102 list_del_init(&seq->list);
1106 BUG_ON("Unknown state of lock sequence found!\n");
1110 if (seq->state != SEQ_STATE_CONTENDED) {
1111 seq->state = SEQ_STATE_CONTENDED;
1112 seq->prev_event_time = sample->time;
1119 static int report_lock_contention_end_event(struct evsel *evsel,
1120 struct perf_sample *sample)
1122 struct lock_stat *ls;
1123 struct thread_stat *ts;
1124 struct lock_seq_stat *seq;
1126 u64 addr = evsel__intval(evsel, sample, "lock_addr");
1130 ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1134 ls = lock_stat_find(key);
1138 ts = thread_stat_find(sample->tid);
1142 seq = get_seq(ts, addr);
1146 switch (seq->state) {
1147 case SEQ_STATE_UNINITIALIZED:
1149 case SEQ_STATE_CONTENDED:
1150 contended_term = sample->time - seq->prev_event_time;
1151 ls->wait_time_total += contended_term;
1152 if (contended_term < ls->wait_time_min)
1153 ls->wait_time_min = contended_term;
1154 if (ls->wait_time_max < contended_term)
1155 ls->wait_time_max = contended_term;
1157 case SEQ_STATE_ACQUIRING:
1158 case SEQ_STATE_ACQUIRED:
1159 case SEQ_STATE_READ_ACQUIRED:
1160 case SEQ_STATE_RELEASED:
1161 /* broken lock sequence */
1164 bad_hist[BROKEN_ACQUIRED]++;
1166 list_del_init(&seq->list);
1170 BUG_ON("Unknown state of lock sequence found!\n");
1174 seq->state = SEQ_STATE_ACQUIRED;
1176 ls->avg_wait_time = ls->wait_time_total/ls->nr_acquired;
1181 /* lock oriented handlers */
1182 /* TODO: handlers for CPU oriented, thread oriented */
1183 static struct trace_lock_handler report_lock_ops = {
1184 .acquire_event = report_lock_acquire_event,
1185 .acquired_event = report_lock_acquired_event,
1186 .contended_event = report_lock_contended_event,
1187 .release_event = report_lock_release_event,
1188 .contention_begin_event = report_lock_contention_begin_event,
1189 .contention_end_event = report_lock_contention_end_event,
1192 static struct trace_lock_handler contention_lock_ops = {
1193 .contention_begin_event = report_lock_contention_begin_event,
1194 .contention_end_event = report_lock_contention_end_event,
1198 static struct trace_lock_handler *trace_handler;
1200 static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
1202 if (trace_handler->acquire_event)
1203 return trace_handler->acquire_event(evsel, sample);
1207 static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
1209 if (trace_handler->acquired_event)
1210 return trace_handler->acquired_event(evsel, sample);
1214 static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
1216 if (trace_handler->contended_event)
1217 return trace_handler->contended_event(evsel, sample);
1221 static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
1223 if (trace_handler->release_event)
1224 return trace_handler->release_event(evsel, sample);
1228 static int evsel__process_contention_begin(struct evsel *evsel, struct perf_sample *sample)
1230 if (trace_handler->contention_begin_event)
1231 return trace_handler->contention_begin_event(evsel, sample);
1235 static int evsel__process_contention_end(struct evsel *evsel, struct perf_sample *sample)
1237 if (trace_handler->contention_end_event)
1238 return trace_handler->contention_end_event(evsel, sample);
1242 static void print_bad_events(int bad, int total)
1244 /* Output for debug, this have to be removed */
1247 const char *name[4] =
1248 { "acquire", "acquired", "contended", "release" };
1250 for (i = 0; i < BROKEN_MAX; i++)
1251 broken += bad_hist[i];
1253 if (quiet || (broken == 0 && !verbose))
1256 pr_info("\n=== output for debug===\n\n");
1257 pr_info("bad: %d, total: %d\n", bad, total);
1258 pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
1259 pr_info("histogram of events caused bad sequence\n");
1260 for (i = 0; i < BROKEN_MAX; i++)
1261 pr_info(" %10s: %d\n", name[i], bad_hist[i]);
1264 /* TODO: various way to print, coloring, nano or milli sec */
1265 static void print_result(void)
1267 struct lock_stat *st;
1268 struct lock_key *key;
1270 int bad, total, printed;
1273 pr_info("%20s ", "Name");
1274 list_for_each_entry(key, &lock_keys, list)
1275 pr_info("%*s ", key->len, key->header);
1279 bad = total = printed = 0;
1280 while ((st = pop_from_result())) {
1284 if (!st->nr_acquired)
1287 bzero(cut_name, 20);
1289 if (strlen(st->name) < 20) {
1290 /* output raw name */
1291 const char *name = st->name;
1293 if (show_thread_stats) {
1296 /* st->addr contains tid of thread */
1297 t = perf_session__findnew(session, st->addr);
1298 name = thread__comm_str(t);
1301 pr_info("%20s ", name);
1303 strncpy(cut_name, st->name, 16);
1307 cut_name[19] = '\0';
1308 /* cut off name for saving output style */
1309 pr_info("%20s ", cut_name);
1312 list_for_each_entry(key, &lock_keys, list) {
1313 key->print(key, st);
1318 if (++printed >= print_nr_entries)
1322 print_bad_events(bad, total);
1325 static bool info_threads, info_map;
1327 static void dump_threads(void)
1329 struct thread_stat *st;
1330 struct rb_node *node;
1333 pr_info("%10s: comm\n", "Thread ID");
1335 node = rb_first(&thread_stats);
1337 st = container_of(node, struct thread_stat, rb);
1338 t = perf_session__findnew(session, st->tid);
1339 pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
1340 node = rb_next(node);
1345 static int compare_maps(struct lock_stat *a, struct lock_stat *b)
1349 if (a->name && b->name)
1350 ret = strcmp(a->name, b->name);
1352 ret = !!a->name - !!b->name;
1355 return a->addr < b->addr;
1360 static void dump_map(void)
1363 struct lock_stat *st;
1365 pr_info("Address of instance: name of class\n");
1366 for (i = 0; i < LOCKHASH_SIZE; i++) {
1367 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1368 insert_to_result(st, compare_maps);
1372 while ((st = pop_from_result()))
1373 pr_info(" %#llx: %s\n", (unsigned long long)st->addr, st->name);
1376 static int dump_info(void)
1386 pr_err("Unknown type of information\n");
1392 typedef int (*tracepoint_handler)(struct evsel *evsel,
1393 struct perf_sample *sample);
1395 static int process_sample_event(struct perf_tool *tool __maybe_unused,
1396 union perf_event *event,
1397 struct perf_sample *sample,
1398 struct evsel *evsel,
1399 struct machine *machine)
1402 struct thread *thread = machine__findnew_thread(machine, sample->pid,
1405 if (thread == NULL) {
1406 pr_debug("problem processing %d event, skipping it.\n",
1407 event->header.type);
1411 if (evsel->handler != NULL) {
1412 tracepoint_handler f = evsel->handler;
1413 err = f(evsel, sample);
1416 thread__put(thread);
1421 static void combine_result(void)
1424 struct lock_stat *st;
1429 for (i = 0; i < LOCKHASH_SIZE; i++) {
1430 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1431 combine_lock_stats(st);
1436 static void sort_result(void)
1439 struct lock_stat *st;
1441 for (i = 0; i < LOCKHASH_SIZE; i++) {
1442 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1443 insert_to_result(st, compare);
1448 static const char *get_type_str(struct lock_stat *st)
1450 static const struct {
1455 { LCB_F_SPIN, "spinlock" },
1456 { LCB_F_SPIN | LCB_F_READ, "rwlock:R" },
1457 { LCB_F_SPIN | LCB_F_WRITE, "rwlock:W"},
1458 { LCB_F_READ, "rwsem:R" },
1459 { LCB_F_WRITE, "rwsem:W" },
1460 { LCB_F_RT, "rtmutex" },
1461 { LCB_F_RT | LCB_F_READ, "rwlock-rt:R" },
1462 { LCB_F_RT | LCB_F_WRITE, "rwlock-rt:W"},
1463 { LCB_F_PERCPU | LCB_F_READ, "pcpu-sem:R" },
1464 { LCB_F_PERCPU | LCB_F_WRITE, "pcpu-sem:W" },
1465 { LCB_F_MUTEX, "mutex" },
1466 { LCB_F_MUTEX | LCB_F_SPIN, "mutex" },
1469 for (unsigned int i = 0; i < ARRAY_SIZE(table); i++) {
1470 if (table[i].flags == st->flags)
1471 return table[i].name;
1476 static void sort_contention_result(void)
1481 static void print_contention_result(struct lock_contention *con)
1483 struct lock_stat *st;
1484 struct lock_key *key;
1485 int bad, total, printed;
1488 list_for_each_entry(key, &lock_keys, list)
1489 pr_info("%*s ", key->len, key->header);
1491 if (show_thread_stats)
1492 pr_info(" %10s %s\n\n", "pid", "comm");
1494 pr_info(" %10s %s\n\n", "type", "caller");
1497 bad = total = printed = 0;
1499 bad = bad_hist[BROKEN_CONTENDED];
1501 while ((st = pop_from_result())) {
1502 total += use_bpf ? st->nr_contended : 1;
1506 list_for_each_entry(key, &lock_keys, list) {
1507 key->print(key, st);
1511 if (show_thread_stats) {
1515 /* st->addr contains tid of thread */
1516 t = perf_session__findnew(session, pid);
1517 pr_info(" %10d %s\n", pid, thread__comm_str(t));
1521 pr_info(" %10s %s\n", get_type_str(st), st->name);
1528 for (int i = 0; i < max_stack_depth; i++) {
1529 if (!st->callstack || !st->callstack[i])
1532 ip = st->callstack[i];
1533 sym = machine__find_kernel_symbol(con->machine, ip, &kmap);
1534 get_symbol_name_offset(kmap, sym, ip, buf, sizeof(buf));
1535 pr_info("\t\t\t%#lx %s\n", (unsigned long)ip, buf);
1540 if (++printed >= print_nr_entries)
1544 print_bad_events(bad, total);
1547 static const struct evsel_str_handler lock_tracepoints[] = {
1548 { "lock:lock_acquire", evsel__process_lock_acquire, }, /* CONFIG_LOCKDEP */
1549 { "lock:lock_acquired", evsel__process_lock_acquired, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1550 { "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1551 { "lock:lock_release", evsel__process_lock_release, }, /* CONFIG_LOCKDEP */
1554 static const struct evsel_str_handler contention_tracepoints[] = {
1555 { "lock:contention_begin", evsel__process_contention_begin, },
1556 { "lock:contention_end", evsel__process_contention_end, },
1561 static int __cmd_report(bool display_info)
1564 struct perf_tool eops = {
1565 .sample = process_sample_event,
1566 .comm = perf_event__process_comm,
1567 .mmap = perf_event__process_mmap,
1568 .namespaces = perf_event__process_namespaces,
1569 .ordered_events = true,
1571 struct perf_data data = {
1573 .mode = PERF_DATA_MODE_READ,
1577 session = perf_session__new(&data, &eops);
1578 if (IS_ERR(session)) {
1579 pr_err("Initializing perf session failed\n");
1580 return PTR_ERR(session);
1583 /* for lock function check */
1584 symbol_conf.sort_by_name = true;
1585 symbol_conf.allow_aliases = true;
1586 symbol__init(&session->header.env);
1588 if (!perf_session__has_traces(session, "lock record"))
1591 if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
1592 pr_err("Initializing perf session tracepoint handlers failed\n");
1596 if (perf_session__set_tracepoints_handlers(session, contention_tracepoints)) {
1597 pr_err("Initializing perf session tracepoint handlers failed\n");
1601 if (setup_output_field(false, output_fields))
1604 if (select_key(false))
1607 if (show_thread_stats)
1608 aggr_mode = LOCK_AGGR_TASK;
1610 err = perf_session__process_events(session);
1615 if (display_info) /* used for info subcommand */
1624 perf_session__delete(session);
1628 static void sighandler(int sig __maybe_unused)
1632 static int __cmd_contention(int argc, const char **argv)
1635 struct perf_tool eops = {
1636 .sample = process_sample_event,
1637 .comm = perf_event__process_comm,
1638 .mmap = perf_event__process_mmap,
1639 .ordered_events = true,
1641 struct perf_data data = {
1643 .mode = PERF_DATA_MODE_READ,
1646 struct lock_contention con = {
1648 .result = &lockhash_table[0],
1649 .map_nr_entries = bpf_map_entries,
1650 .max_stack = max_stack_depth,
1651 .stack_skip = stack_skip,
1654 session = perf_session__new(use_bpf ? NULL : &data, &eops);
1655 if (IS_ERR(session)) {
1656 pr_err("Initializing perf session failed\n");
1657 return PTR_ERR(session);
1660 con.machine = &session->machines.host;
1662 /* for lock function check */
1663 symbol_conf.sort_by_name = true;
1664 symbol_conf.allow_aliases = true;
1665 symbol__init(&session->header.env);
1668 err = target__validate(&target);
1672 target__strerror(&target, err, errbuf, 512);
1673 pr_err("%s\n", errbuf);
1677 signal(SIGINT, sighandler);
1678 signal(SIGCHLD, sighandler);
1679 signal(SIGTERM, sighandler);
1681 con.evlist = evlist__new();
1682 if (con.evlist == NULL) {
1687 err = evlist__create_maps(con.evlist, &target);
1692 err = evlist__prepare_workload(con.evlist, &target,
1698 if (lock_contention_prepare(&con) < 0) {
1699 pr_err("lock contention BPF setup failed\n");
1703 if (!perf_session__has_traces(session, "lock record"))
1706 if (!evlist__find_evsel_by_str(session->evlist,
1707 "lock:contention_begin")) {
1708 pr_err("lock contention evsel not found\n");
1712 if (perf_session__set_tracepoints_handlers(session,
1713 contention_tracepoints)) {
1714 pr_err("Initializing perf session tracepoint handlers failed\n");
1719 if (setup_output_field(true, output_fields))
1722 if (select_key(true))
1725 if (show_thread_stats)
1726 aggr_mode = LOCK_AGGR_TASK;
1728 aggr_mode = LOCK_AGGR_CALLER;
1731 lock_contention_start();
1733 evlist__start_workload(con.evlist);
1735 /* wait for signal */
1738 lock_contention_stop();
1739 lock_contention_read(&con);
1741 /* abuse bad hist stats for lost entries */
1742 bad_hist[BROKEN_CONTENDED] = con.lost;
1744 err = perf_session__process_events(session);
1751 sort_contention_result();
1752 print_contention_result(&con);
1755 evlist__delete(con.evlist);
1756 lock_contention_finish();
1757 perf_session__delete(session);
1762 static int __cmd_record(int argc, const char **argv)
1764 const char *record_args[] = {
1765 "record", "-R", "-m", "1024", "-c", "1", "--synth", "task",
1767 const char *callgraph_args[] = {
1768 "--call-graph", "fp," __stringify(CONTENTION_STACK_DEPTH),
1770 unsigned int rec_argc, i, j, ret;
1771 unsigned int nr_tracepoints;
1772 unsigned int nr_callgraph_args = 0;
1773 const char **rec_argv;
1774 bool has_lock_stat = true;
1776 for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
1777 if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
1778 pr_debug("tracepoint %s is not enabled. "
1779 "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
1780 lock_tracepoints[i].name);
1781 has_lock_stat = false;
1789 for (i = 0; i < ARRAY_SIZE(contention_tracepoints); i++) {
1790 if (!is_valid_tracepoint(contention_tracepoints[i].name)) {
1791 pr_err("tracepoint %s is not enabled.\n",
1792 contention_tracepoints[i].name);
1797 nr_callgraph_args = ARRAY_SIZE(callgraph_args);
1800 rec_argc = ARRAY_SIZE(record_args) + nr_callgraph_args + argc - 1;
1803 nr_tracepoints = ARRAY_SIZE(lock_tracepoints);
1805 nr_tracepoints = ARRAY_SIZE(contention_tracepoints);
1807 /* factor of 2 is for -e in front of each tracepoint */
1808 rec_argc += 2 * nr_tracepoints;
1810 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1814 for (i = 0; i < ARRAY_SIZE(record_args); i++)
1815 rec_argv[i] = strdup(record_args[i]);
1817 for (j = 0; j < nr_tracepoints; j++) {
1818 const char *ev_name;
1821 ev_name = strdup(lock_tracepoints[j].name);
1823 ev_name = strdup(contention_tracepoints[j].name);
1828 rec_argv[i++] = "-e";
1829 rec_argv[i++] = ev_name;
1832 for (j = 0; j < nr_callgraph_args; j++, i++)
1833 rec_argv[i] = callgraph_args[j];
1835 for (j = 1; j < (unsigned int)argc; j++, i++)
1836 rec_argv[i] = argv[j];
1838 BUG_ON(i != rec_argc);
1840 ret = cmd_record(i, rec_argv);
1845 static int parse_map_entry(const struct option *opt, const char *str,
1846 int unset __maybe_unused)
1848 unsigned long *len = (unsigned long *)opt->value;
1853 val = strtoul(str, &endptr, 0);
1854 if (*endptr != '\0' || errno != 0) {
1855 pr_err("invalid BPF map length: %s\n", str);
1863 int cmd_lock(int argc, const char **argv)
1865 const struct option lock_options[] = {
1866 OPT_STRING('i', "input", &input_name, "file", "input file name"),
1867 OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
1868 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
1869 OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
1870 OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
1871 "file", "vmlinux pathname"),
1872 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1873 "file", "kallsyms pathname"),
1874 OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
1878 const struct option info_options[] = {
1879 OPT_BOOLEAN('t', "threads", &info_threads,
1880 "dump thread list in perf.data"),
1881 OPT_BOOLEAN('m', "map", &info_map,
1882 "map of lock instances (address:name table)"),
1883 OPT_PARENT(lock_options)
1886 const struct option report_options[] = {
1887 OPT_STRING('k', "key", &sort_key, "acquired",
1888 "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1889 OPT_STRING('F', "field", &output_fields, NULL,
1890 "output fields (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1892 OPT_BOOLEAN('c', "combine-locks", &combine_locks,
1893 "combine locks in the same class"),
1894 OPT_BOOLEAN('t', "threads", &show_thread_stats,
1895 "show per-thread lock stats"),
1896 OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
1897 OPT_PARENT(lock_options)
1900 struct option contention_options[] = {
1901 OPT_STRING('k', "key", &sort_key, "wait_total",
1902 "key for sorting (contended / wait_total / wait_max / wait_min / avg_wait)"),
1903 OPT_STRING('F', "field", &output_fields, "contended,wait_total,wait_max,avg_wait",
1904 "output fields (contended / wait_total / wait_max / wait_min / avg_wait)"),
1905 OPT_BOOLEAN('t', "threads", &show_thread_stats,
1906 "show per-thread lock stats"),
1907 OPT_BOOLEAN('b', "use-bpf", &use_bpf, "use BPF program to collect lock contention stats"),
1908 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1909 "System-wide collection from all CPUs"),
1910 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1911 "List of cpus to monitor"),
1912 OPT_STRING('p', "pid", &target.pid, "pid",
1913 "Trace on existing process id"),
1914 OPT_STRING(0, "tid", &target.tid, "tid",
1915 "Trace on existing thread id (exclusive to --pid)"),
1916 OPT_CALLBACK(0, "map-nr-entries", &bpf_map_entries, "num",
1917 "Max number of BPF map entries", parse_map_entry),
1918 OPT_INTEGER(0, "max-stack", &max_stack_depth,
1919 "Set the maximum stack depth when collecting lock contention, "
1920 "Default: " __stringify(CONTENTION_STACK_DEPTH)),
1921 OPT_INTEGER(0, "stack-skip", &stack_skip,
1922 "Set the number of stack depth to skip when finding a lock caller, "
1923 "Default: " __stringify(CONTENTION_STACK_SKIP)),
1924 OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
1925 OPT_PARENT(lock_options)
1928 const char * const info_usage[] = {
1929 "perf lock info [<options>]",
1932 const char *const lock_subcommands[] = { "record", "report", "script",
1933 "info", "contention", NULL };
1934 const char *lock_usage[] = {
1938 const char * const report_usage[] = {
1939 "perf lock report [<options>]",
1942 const char * const contention_usage[] = {
1943 "perf lock contention [<options>]",
1949 for (i = 0; i < LOCKHASH_SIZE; i++)
1950 INIT_HLIST_HEAD(lockhash_table + i);
1952 argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
1953 lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
1955 usage_with_options(lock_usage, lock_options);
1957 if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
1958 return __cmd_record(argc, argv);
1959 } else if (strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
1960 trace_handler = &report_lock_ops;
1962 argc = parse_options(argc, argv,
1963 report_options, report_usage, 0);
1965 usage_with_options(report_usage, report_options);
1967 rc = __cmd_report(false);
1968 } else if (!strcmp(argv[0], "script")) {
1969 /* Aliased to 'perf script' */
1970 return cmd_script(argc, argv);
1971 } else if (!strcmp(argv[0], "info")) {
1973 argc = parse_options(argc, argv,
1974 info_options, info_usage, 0);
1976 usage_with_options(info_usage, info_options);
1978 /* recycling report_lock_ops */
1979 trace_handler = &report_lock_ops;
1980 rc = __cmd_report(true);
1981 } else if (strlen(argv[0]) > 2 && strstarts("contention", argv[0])) {
1982 trace_handler = &contention_lock_ops;
1983 sort_key = "wait_total";
1984 output_fields = "contended,wait_total,wait_max,avg_wait";
1986 #ifndef HAVE_BPF_SKEL
1987 set_option_nobuild(contention_options, 'b', "use-bpf",
1988 "no BUILD_BPF_SKEL=1", false);
1991 argc = parse_options(argc, argv, contention_options,
1992 contention_usage, 0);
1994 rc = __cmd_contention(argc, argv);
1996 usage_with_options(lock_usage, lock_options);