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>
35 #include <linux/list.h>
36 #include <linux/hash.h>
37 #include <linux/kernel.h>
38 #include <linux/zalloc.h>
39 #include <linux/err.h>
40 #include <linux/stringify.h>
42 static struct perf_session *session;
43 static struct target target;
45 /* based on kernel/lockdep.c */
46 #define LOCKHASH_BITS 12
47 #define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
49 static struct hlist_head lockhash_table[LOCKHASH_SIZE];
51 #define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
52 #define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
54 static struct rb_root thread_stats;
56 static bool combine_locks;
57 static bool show_thread_stats;
59 static unsigned long bpf_map_entries = 10240;
65 } aggr_mode = LOCK_AGGR_ADDR;
67 static u64 sched_text_start;
68 static u64 sched_text_end;
69 static u64 lock_text_start;
70 static u64 lock_text_end;
72 static struct thread_stat *thread_stat_find(u32 tid)
75 struct thread_stat *st;
77 node = thread_stats.rb_node;
79 st = container_of(node, struct thread_stat, rb);
82 else if (tid < st->tid)
85 node = node->rb_right;
91 static void thread_stat_insert(struct thread_stat *new)
93 struct rb_node **rb = &thread_stats.rb_node;
94 struct rb_node *parent = NULL;
95 struct thread_stat *p;
98 p = container_of(*rb, struct thread_stat, rb);
101 if (new->tid < p->tid)
102 rb = &(*rb)->rb_left;
103 else if (new->tid > p->tid)
104 rb = &(*rb)->rb_right;
106 BUG_ON("inserting invalid thread_stat\n");
109 rb_link_node(&new->rb, parent, rb);
110 rb_insert_color(&new->rb, &thread_stats);
113 static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
115 struct thread_stat *st;
117 st = thread_stat_find(tid);
121 st = zalloc(sizeof(struct thread_stat));
123 pr_err("memory allocation failed\n");
128 INIT_LIST_HEAD(&st->seq_list);
130 thread_stat_insert(st);
135 static struct thread_stat *thread_stat_findnew_first(u32 tid);
136 static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
137 thread_stat_findnew_first;
139 static struct thread_stat *thread_stat_findnew_first(u32 tid)
141 struct thread_stat *st;
143 st = zalloc(sizeof(struct thread_stat));
145 pr_err("memory allocation failed\n");
149 INIT_LIST_HEAD(&st->seq_list);
151 rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
152 rb_insert_color(&st->rb, &thread_stats);
154 thread_stat_findnew = thread_stat_findnew_after_first;
158 /* build simple key function one is bigger than two */
159 #define SINGLE_KEY(member) \
160 static int lock_stat_key_ ## member(struct lock_stat *one, \
161 struct lock_stat *two) \
163 return one->member > two->member; \
166 SINGLE_KEY(nr_acquired)
167 SINGLE_KEY(nr_contended)
168 SINGLE_KEY(avg_wait_time)
169 SINGLE_KEY(wait_time_total)
170 SINGLE_KEY(wait_time_max)
172 static int lock_stat_key_wait_time_min(struct lock_stat *one,
173 struct lock_stat *two)
175 u64 s1 = one->wait_time_min;
176 u64 s2 = two->wait_time_min;
177 if (s1 == ULLONG_MAX)
179 if (s2 == ULLONG_MAX)
186 * name: the value for specify by user
187 * this should be simpler than raw name of member
188 * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
191 /* header: the string printed on the header line */
193 /* len: the printing width of the field */
195 /* key: a pointer to function to compare two lock stats for sorting */
196 int (*key)(struct lock_stat*, struct lock_stat*);
197 /* print: a pointer to function to print a given lock stats */
198 void (*print)(struct lock_key*, struct lock_stat*);
199 /* list: list entry to link this */
200 struct list_head list;
203 static void lock_stat_key_print_time(unsigned long long nsec, int len)
205 static const struct {
209 { 1e9 * 3600, "h " },
217 for (int i = 0; table[i].unit; i++) {
218 if (nsec < table[i].base)
221 pr_info("%*.2f %s", len - 3, nsec / table[i].base, table[i].unit);
225 pr_info("%*llu %s", len - 3, nsec, "ns");
228 #define PRINT_KEY(member) \
229 static void lock_stat_key_print_ ## member(struct lock_key *key, \
230 struct lock_stat *ls) \
232 pr_info("%*llu", key->len, (unsigned long long)ls->member); \
235 #define PRINT_TIME(member) \
236 static void lock_stat_key_print_ ## member(struct lock_key *key, \
237 struct lock_stat *ls) \
239 lock_stat_key_print_time((unsigned long long)ls->member, key->len); \
242 PRINT_KEY(nr_acquired)
243 PRINT_KEY(nr_contended)
244 PRINT_TIME(avg_wait_time)
245 PRINT_TIME(wait_time_total)
246 PRINT_TIME(wait_time_max)
248 static void lock_stat_key_print_wait_time_min(struct lock_key *key,
249 struct lock_stat *ls)
251 u64 wait_time = ls->wait_time_min;
253 if (wait_time == ULLONG_MAX)
256 lock_stat_key_print_time(wait_time, key->len);
260 static const char *sort_key = "acquired";
262 static int (*compare)(struct lock_stat *, struct lock_stat *);
264 static struct rb_root sorted; /* place to store intermediate data */
265 static struct rb_root result; /* place to store sorted data */
267 static LIST_HEAD(lock_keys);
268 static const char *output_fields;
270 #define DEF_KEY_LOCK(name, header, fn_suffix, len) \
271 { #name, header, len, lock_stat_key_ ## fn_suffix, lock_stat_key_print_ ## fn_suffix, {} }
272 static struct lock_key report_keys[] = {
273 DEF_KEY_LOCK(acquired, "acquired", nr_acquired, 10),
274 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
275 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
276 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
277 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
278 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
280 /* extra comparisons much complicated should be here */
284 static struct lock_key contention_keys[] = {
285 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
286 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
287 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
288 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
289 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
291 /* extra comparisons much complicated should be here */
295 static int select_key(bool contention)
298 struct lock_key *keys = report_keys;
301 keys = contention_keys;
303 for (i = 0; keys[i].name; i++) {
304 if (!strcmp(keys[i].name, sort_key)) {
305 compare = keys[i].key;
307 /* selected key should be in the output fields */
308 if (list_empty(&keys[i].list))
309 list_add_tail(&keys[i].list, &lock_keys);
315 pr_err("Unknown compare key: %s\n", sort_key);
319 static int add_output_field(bool contention, char *name)
322 struct lock_key *keys = report_keys;
325 keys = contention_keys;
327 for (i = 0; keys[i].name; i++) {
328 if (strcmp(keys[i].name, name))
331 /* prevent double link */
332 if (list_empty(&keys[i].list))
333 list_add_tail(&keys[i].list, &lock_keys);
338 pr_err("Unknown output field: %s\n", name);
342 static int setup_output_field(bool contention, const char *str)
344 char *tok, *tmp, *orig;
346 struct lock_key *keys = report_keys;
349 keys = contention_keys;
351 /* no output field given: use all of them */
353 for (i = 0; keys[i].name; i++)
354 list_add_tail(&keys[i].list, &lock_keys);
358 for (i = 0; keys[i].name; i++)
359 INIT_LIST_HEAD(&keys[i].list);
361 orig = tmp = strdup(str);
365 while ((tok = strsep(&tmp, ",")) != NULL){
366 ret = add_output_field(contention, tok);
375 static void combine_lock_stats(struct lock_stat *st)
377 struct rb_node **rb = &sorted.rb_node;
378 struct rb_node *parent = NULL;
383 p = container_of(*rb, struct lock_stat, rb);
386 if (st->name && p->name)
387 ret = strcmp(st->name, p->name);
389 ret = !!st->name - !!p->name;
392 p->nr_acquired += st->nr_acquired;
393 p->nr_contended += st->nr_contended;
394 p->wait_time_total += st->wait_time_total;
397 p->avg_wait_time = p->wait_time_total / p->nr_contended;
399 if (p->wait_time_min > st->wait_time_min)
400 p->wait_time_min = st->wait_time_min;
401 if (p->wait_time_max < st->wait_time_max)
402 p->wait_time_max = st->wait_time_max;
404 p->broken |= st->broken;
410 rb = &(*rb)->rb_left;
412 rb = &(*rb)->rb_right;
415 rb_link_node(&st->rb, parent, rb);
416 rb_insert_color(&st->rb, &sorted);
419 static void insert_to_result(struct lock_stat *st,
420 int (*bigger)(struct lock_stat *, struct lock_stat *))
422 struct rb_node **rb = &result.rb_node;
423 struct rb_node *parent = NULL;
426 if (combine_locks && st->combined)
430 p = container_of(*rb, struct lock_stat, rb);
434 rb = &(*rb)->rb_left;
436 rb = &(*rb)->rb_right;
439 rb_link_node(&st->rb, parent, rb);
440 rb_insert_color(&st->rb, &result);
443 /* returns left most element of result, and erase it */
444 static struct lock_stat *pop_from_result(void)
446 struct rb_node *node = result.rb_node;
451 while (node->rb_left)
452 node = node->rb_left;
454 rb_erase(node, &result);
455 return container_of(node, struct lock_stat, rb);
458 static struct lock_stat *lock_stat_find(u64 addr)
460 struct hlist_head *entry = lockhashentry(addr);
461 struct lock_stat *ret;
463 hlist_for_each_entry(ret, entry, hash_entry) {
464 if (ret->addr == addr)
470 static struct lock_stat *lock_stat_findnew(u64 addr, const char *name, int flags)
472 struct hlist_head *entry = lockhashentry(addr);
473 struct lock_stat *ret, *new;
475 hlist_for_each_entry(ret, entry, hash_entry) {
476 if (ret->addr == addr)
480 new = zalloc(sizeof(struct lock_stat));
485 new->name = strdup(name);
492 new->wait_time_min = ULLONG_MAX;
494 hlist_add_head(&new->hash_entry, entry);
498 pr_err("memory allocation failed\n");
502 struct trace_lock_handler {
503 /* it's used on CONFIG_LOCKDEP */
504 int (*acquire_event)(struct evsel *evsel,
505 struct perf_sample *sample);
507 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
508 int (*acquired_event)(struct evsel *evsel,
509 struct perf_sample *sample);
511 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
512 int (*contended_event)(struct evsel *evsel,
513 struct perf_sample *sample);
515 /* it's used on CONFIG_LOCKDEP */
516 int (*release_event)(struct evsel *evsel,
517 struct perf_sample *sample);
519 /* it's used when CONFIG_LOCKDEP is off */
520 int (*contention_begin_event)(struct evsel *evsel,
521 struct perf_sample *sample);
523 /* it's used when CONFIG_LOCKDEP is off */
524 int (*contention_end_event)(struct evsel *evsel,
525 struct perf_sample *sample);
528 static struct lock_seq_stat *get_seq(struct thread_stat *ts, u64 addr)
530 struct lock_seq_stat *seq;
532 list_for_each_entry(seq, &ts->seq_list, list) {
533 if (seq->addr == addr)
537 seq = zalloc(sizeof(struct lock_seq_stat));
539 pr_err("memory allocation failed\n");
542 seq->state = SEQ_STATE_UNINITIALIZED;
545 list_add(&seq->list, &ts->seq_list);
557 static int bad_hist[BROKEN_MAX];
564 static int report_lock_acquire_event(struct evsel *evsel,
565 struct perf_sample *sample)
567 struct lock_stat *ls;
568 struct thread_stat *ts;
569 struct lock_seq_stat *seq;
570 const char *name = evsel__strval(evsel, sample, "name");
571 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
572 int flag = evsel__intval(evsel, sample, "flags");
582 case LOCK_AGGR_CALLER:
584 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
588 ls = lock_stat_findnew(key, name, 0);
592 ts = thread_stat_findnew(sample->tid);
596 seq = get_seq(ts, addr);
600 switch (seq->state) {
601 case SEQ_STATE_UNINITIALIZED:
602 case SEQ_STATE_RELEASED:
604 seq->state = SEQ_STATE_ACQUIRING;
608 if (flag & READ_LOCK)
610 seq->state = SEQ_STATE_READ_ACQUIRED;
615 case SEQ_STATE_READ_ACQUIRED:
616 if (flag & READ_LOCK) {
624 case SEQ_STATE_ACQUIRED:
625 case SEQ_STATE_ACQUIRING:
626 case SEQ_STATE_CONTENDED:
628 /* broken lock sequence */
631 bad_hist[BROKEN_ACQUIRE]++;
633 list_del_init(&seq->list);
637 BUG_ON("Unknown state of lock sequence found!\n");
642 seq->prev_event_time = sample->time;
647 static int report_lock_acquired_event(struct evsel *evsel,
648 struct perf_sample *sample)
650 struct lock_stat *ls;
651 struct thread_stat *ts;
652 struct lock_seq_stat *seq;
654 const char *name = evsel__strval(evsel, sample, "name");
655 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
665 case LOCK_AGGR_CALLER:
667 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
671 ls = lock_stat_findnew(key, name, 0);
675 ts = thread_stat_findnew(sample->tid);
679 seq = get_seq(ts, addr);
683 switch (seq->state) {
684 case SEQ_STATE_UNINITIALIZED:
685 /* orphan event, do nothing */
687 case SEQ_STATE_ACQUIRING:
689 case SEQ_STATE_CONTENDED:
690 contended_term = sample->time - seq->prev_event_time;
691 ls->wait_time_total += contended_term;
692 if (contended_term < ls->wait_time_min)
693 ls->wait_time_min = contended_term;
694 if (ls->wait_time_max < contended_term)
695 ls->wait_time_max = contended_term;
697 case SEQ_STATE_RELEASED:
698 case SEQ_STATE_ACQUIRED:
699 case SEQ_STATE_READ_ACQUIRED:
700 /* broken lock sequence */
703 bad_hist[BROKEN_ACQUIRED]++;
705 list_del_init(&seq->list);
709 BUG_ON("Unknown state of lock sequence found!\n");
713 seq->state = SEQ_STATE_ACQUIRED;
715 ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
716 seq->prev_event_time = sample->time;
721 static int report_lock_contended_event(struct evsel *evsel,
722 struct perf_sample *sample)
724 struct lock_stat *ls;
725 struct thread_stat *ts;
726 struct lock_seq_stat *seq;
727 const char *name = evsel__strval(evsel, sample, "name");
728 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
738 case LOCK_AGGR_CALLER:
740 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
744 ls = lock_stat_findnew(key, name, 0);
748 ts = thread_stat_findnew(sample->tid);
752 seq = get_seq(ts, addr);
756 switch (seq->state) {
757 case SEQ_STATE_UNINITIALIZED:
758 /* orphan event, do nothing */
760 case SEQ_STATE_ACQUIRING:
762 case SEQ_STATE_RELEASED:
763 case SEQ_STATE_ACQUIRED:
764 case SEQ_STATE_READ_ACQUIRED:
765 case SEQ_STATE_CONTENDED:
766 /* broken lock sequence */
769 bad_hist[BROKEN_CONTENDED]++;
771 list_del_init(&seq->list);
775 BUG_ON("Unknown state of lock sequence found!\n");
779 seq->state = SEQ_STATE_CONTENDED;
781 ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
782 seq->prev_event_time = sample->time;
787 static int report_lock_release_event(struct evsel *evsel,
788 struct perf_sample *sample)
790 struct lock_stat *ls;
791 struct thread_stat *ts;
792 struct lock_seq_stat *seq;
793 const char *name = evsel__strval(evsel, sample, "name");
794 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
804 case LOCK_AGGR_CALLER:
806 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
810 ls = lock_stat_findnew(key, name, 0);
814 ts = thread_stat_findnew(sample->tid);
818 seq = get_seq(ts, addr);
822 switch (seq->state) {
823 case SEQ_STATE_UNINITIALIZED:
825 case SEQ_STATE_ACQUIRED:
827 case SEQ_STATE_READ_ACQUIRED:
829 BUG_ON(seq->read_count < 0);
830 if (seq->read_count) {
835 case SEQ_STATE_ACQUIRING:
836 case SEQ_STATE_CONTENDED:
837 case SEQ_STATE_RELEASED:
838 /* broken lock sequence */
841 bad_hist[BROKEN_RELEASE]++;
845 BUG_ON("Unknown state of lock sequence found!\n");
851 list_del_init(&seq->list);
857 bool is_lock_function(struct machine *machine, u64 addr)
859 if (!sched_text_start) {
863 sym = machine__find_kernel_symbol_by_name(machine,
864 "__sched_text_start",
868 sched_text_start = 1;
872 sched_text_start = kmap->unmap_ip(kmap, sym->start);
874 /* should not fail from here */
875 sym = machine__find_kernel_symbol_by_name(machine,
878 sched_text_end = kmap->unmap_ip(kmap, sym->start);
880 sym = machine__find_kernel_symbol_by_name(machine,
883 lock_text_start = kmap->unmap_ip(kmap, sym->start);
885 sym = machine__find_kernel_symbol_by_name(machine,
888 lock_text_end = kmap->unmap_ip(kmap, sym->start);
891 /* failed to get kernel symbols */
892 if (sched_text_start == 1)
895 /* mutex and rwsem functions are in sched text section */
896 if (sched_text_start <= addr && addr < sched_text_end)
899 /* spinlock functions are in lock text section */
900 if (lock_text_start <= addr && addr < lock_text_end)
906 static int lock_contention_caller(struct evsel *evsel, struct perf_sample *sample,
909 struct thread *thread;
910 struct callchain_cursor *cursor = &callchain_cursor;
911 struct machine *machine = &session->machines.host;
916 /* lock names will be replaced to task name later */
917 if (show_thread_stats)
920 thread = machine__findnew_thread(machine, -1, sample->pid);
924 /* use caller function name from the callchain */
925 ret = thread__resolve_callchain(thread, cursor, evsel, sample,
926 NULL, NULL, CONTENTION_STACK_DEPTH);
932 callchain_cursor_commit(cursor);
936 struct callchain_cursor_node *node;
938 node = callchain_cursor_current(cursor);
942 /* skip first few entries - for lock functions */
943 if (++skip <= CONTENTION_STACK_SKIP)
947 if (sym && !is_lock_function(machine, node->ip)) {
948 struct map *map = node->ms.map;
951 offset = map->map_ip(map, node->ip) - sym->start;
954 scnprintf(buf, size, "%s+%#lx", sym->name, offset);
956 strlcpy(buf, sym->name, size);
961 callchain_cursor_advance(cursor);
966 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample)
968 struct callchain_cursor *cursor = &callchain_cursor;
969 struct machine *machine = &session->machines.host;
970 struct thread *thread;
975 thread = machine__findnew_thread(machine, -1, sample->pid);
979 /* use caller function name from the callchain */
980 ret = thread__resolve_callchain(thread, cursor, evsel, sample,
981 NULL, NULL, CONTENTION_STACK_DEPTH);
987 callchain_cursor_commit(cursor);
990 struct callchain_cursor_node *node;
992 node = callchain_cursor_current(cursor);
996 /* skip first few entries - for lock functions */
997 if (++skip <= CONTENTION_STACK_SKIP)
1000 if (node->ms.sym && is_lock_function(machine, node->ip))
1003 hash ^= hash_long((unsigned long)node->ip, 64);
1006 callchain_cursor_advance(cursor);
1011 static int report_lock_contention_begin_event(struct evsel *evsel,
1012 struct perf_sample *sample)
1014 struct lock_stat *ls;
1015 struct thread_stat *ts;
1016 struct lock_seq_stat *seq;
1017 u64 addr = evsel__intval(evsel, sample, "lock_addr");
1020 switch (aggr_mode) {
1021 case LOCK_AGGR_ADDR:
1024 case LOCK_AGGR_TASK:
1027 case LOCK_AGGR_CALLER:
1028 key = callchain_id(evsel, sample);
1031 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
1035 ls = lock_stat_find(key);
1038 const char *caller = buf;
1039 unsigned int flags = evsel__intval(evsel, sample, "flags");
1041 if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
1044 ls = lock_stat_findnew(key, caller, flags);
1049 ts = thread_stat_findnew(sample->tid);
1053 seq = get_seq(ts, addr);
1057 switch (seq->state) {
1058 case SEQ_STATE_UNINITIALIZED:
1059 case SEQ_STATE_ACQUIRED:
1061 case SEQ_STATE_CONTENDED:
1063 * It can have nested contention begin with mutex spinning,
1064 * then we would use the original contention begin event and
1065 * ignore the second one.
1068 case SEQ_STATE_ACQUIRING:
1069 case SEQ_STATE_READ_ACQUIRED:
1070 case SEQ_STATE_RELEASED:
1071 /* broken lock sequence */
1074 bad_hist[BROKEN_CONTENDED]++;
1076 list_del_init(&seq->list);
1080 BUG_ON("Unknown state of lock sequence found!\n");
1084 if (seq->state != SEQ_STATE_CONTENDED) {
1085 seq->state = SEQ_STATE_CONTENDED;
1086 seq->prev_event_time = sample->time;
1093 static int report_lock_contention_end_event(struct evsel *evsel,
1094 struct perf_sample *sample)
1096 struct lock_stat *ls;
1097 struct thread_stat *ts;
1098 struct lock_seq_stat *seq;
1100 u64 addr = evsel__intval(evsel, sample, "lock_addr");
1103 switch (aggr_mode) {
1104 case LOCK_AGGR_ADDR:
1107 case LOCK_AGGR_TASK:
1110 case LOCK_AGGR_CALLER:
1111 key = callchain_id(evsel, sample);
1114 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
1118 ls = lock_stat_find(key);
1122 ts = thread_stat_find(sample->tid);
1126 seq = get_seq(ts, addr);
1130 switch (seq->state) {
1131 case SEQ_STATE_UNINITIALIZED:
1133 case SEQ_STATE_CONTENDED:
1134 contended_term = sample->time - seq->prev_event_time;
1135 ls->wait_time_total += contended_term;
1136 if (contended_term < ls->wait_time_min)
1137 ls->wait_time_min = contended_term;
1138 if (ls->wait_time_max < contended_term)
1139 ls->wait_time_max = contended_term;
1141 case SEQ_STATE_ACQUIRING:
1142 case SEQ_STATE_ACQUIRED:
1143 case SEQ_STATE_READ_ACQUIRED:
1144 case SEQ_STATE_RELEASED:
1145 /* broken lock sequence */
1148 bad_hist[BROKEN_ACQUIRED]++;
1150 list_del_init(&seq->list);
1154 BUG_ON("Unknown state of lock sequence found!\n");
1158 seq->state = SEQ_STATE_ACQUIRED;
1160 ls->avg_wait_time = ls->wait_time_total/ls->nr_acquired;
1165 /* lock oriented handlers */
1166 /* TODO: handlers for CPU oriented, thread oriented */
1167 static struct trace_lock_handler report_lock_ops = {
1168 .acquire_event = report_lock_acquire_event,
1169 .acquired_event = report_lock_acquired_event,
1170 .contended_event = report_lock_contended_event,
1171 .release_event = report_lock_release_event,
1172 .contention_begin_event = report_lock_contention_begin_event,
1173 .contention_end_event = report_lock_contention_end_event,
1176 static struct trace_lock_handler contention_lock_ops = {
1177 .contention_begin_event = report_lock_contention_begin_event,
1178 .contention_end_event = report_lock_contention_end_event,
1182 static struct trace_lock_handler *trace_handler;
1184 static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
1186 if (trace_handler->acquire_event)
1187 return trace_handler->acquire_event(evsel, sample);
1191 static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
1193 if (trace_handler->acquired_event)
1194 return trace_handler->acquired_event(evsel, sample);
1198 static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
1200 if (trace_handler->contended_event)
1201 return trace_handler->contended_event(evsel, sample);
1205 static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
1207 if (trace_handler->release_event)
1208 return trace_handler->release_event(evsel, sample);
1212 static int evsel__process_contention_begin(struct evsel *evsel, struct perf_sample *sample)
1214 if (trace_handler->contention_begin_event)
1215 return trace_handler->contention_begin_event(evsel, sample);
1219 static int evsel__process_contention_end(struct evsel *evsel, struct perf_sample *sample)
1221 if (trace_handler->contention_end_event)
1222 return trace_handler->contention_end_event(evsel, sample);
1226 static void print_bad_events(int bad, int total)
1228 /* Output for debug, this have to be removed */
1231 const char *name[4] =
1232 { "acquire", "acquired", "contended", "release" };
1234 for (i = 0; i < BROKEN_MAX; i++)
1235 broken += bad_hist[i];
1237 if (broken == 0 && !verbose)
1240 pr_info("\n=== output for debug===\n\n");
1241 pr_info("bad: %d, total: %d\n", bad, total);
1242 pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
1243 pr_info("histogram of events caused bad sequence\n");
1244 for (i = 0; i < BROKEN_MAX; i++)
1245 pr_info(" %10s: %d\n", name[i], bad_hist[i]);
1248 /* TODO: various way to print, coloring, nano or milli sec */
1249 static void print_result(void)
1251 struct lock_stat *st;
1252 struct lock_key *key;
1256 pr_info("%20s ", "Name");
1257 list_for_each_entry(key, &lock_keys, list)
1258 pr_info("%*s ", key->len, key->header);
1262 while ((st = pop_from_result())) {
1266 if (!st->nr_acquired)
1269 bzero(cut_name, 20);
1271 if (strlen(st->name) < 20) {
1272 /* output raw name */
1273 const char *name = st->name;
1275 if (show_thread_stats) {
1278 /* st->addr contains tid of thread */
1279 t = perf_session__findnew(session, st->addr);
1280 name = thread__comm_str(t);
1283 pr_info("%20s ", name);
1285 strncpy(cut_name, st->name, 16);
1289 cut_name[19] = '\0';
1290 /* cut off name for saving output style */
1291 pr_info("%20s ", cut_name);
1294 list_for_each_entry(key, &lock_keys, list) {
1295 key->print(key, st);
1301 print_bad_events(bad, total);
1304 static bool info_threads, info_map;
1306 static void dump_threads(void)
1308 struct thread_stat *st;
1309 struct rb_node *node;
1312 pr_info("%10s: comm\n", "Thread ID");
1314 node = rb_first(&thread_stats);
1316 st = container_of(node, struct thread_stat, rb);
1317 t = perf_session__findnew(session, st->tid);
1318 pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
1319 node = rb_next(node);
1324 static int compare_maps(struct lock_stat *a, struct lock_stat *b)
1328 if (a->name && b->name)
1329 ret = strcmp(a->name, b->name);
1331 ret = !!a->name - !!b->name;
1334 return a->addr < b->addr;
1339 static void dump_map(void)
1342 struct lock_stat *st;
1344 pr_info("Address of instance: name of class\n");
1345 for (i = 0; i < LOCKHASH_SIZE; i++) {
1346 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1347 insert_to_result(st, compare_maps);
1351 while ((st = pop_from_result()))
1352 pr_info(" %#llx: %s\n", (unsigned long long)st->addr, st->name);
1355 static int dump_info(void)
1365 pr_err("Unknown type of information\n");
1371 typedef int (*tracepoint_handler)(struct evsel *evsel,
1372 struct perf_sample *sample);
1374 static int process_sample_event(struct perf_tool *tool __maybe_unused,
1375 union perf_event *event,
1376 struct perf_sample *sample,
1377 struct evsel *evsel,
1378 struct machine *machine)
1381 struct thread *thread = machine__findnew_thread(machine, sample->pid,
1384 if (thread == NULL) {
1385 pr_debug("problem processing %d event, skipping it.\n",
1386 event->header.type);
1390 if (evsel->handler != NULL) {
1391 tracepoint_handler f = evsel->handler;
1392 err = f(evsel, sample);
1395 thread__put(thread);
1400 static void combine_result(void)
1403 struct lock_stat *st;
1408 for (i = 0; i < LOCKHASH_SIZE; i++) {
1409 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1410 combine_lock_stats(st);
1415 static void sort_result(void)
1418 struct lock_stat *st;
1420 for (i = 0; i < LOCKHASH_SIZE; i++) {
1421 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1422 insert_to_result(st, compare);
1427 static const char *get_type_str(struct lock_stat *st)
1429 static const struct {
1434 { LCB_F_SPIN, "spinlock" },
1435 { LCB_F_SPIN | LCB_F_READ, "rwlock:R" },
1436 { LCB_F_SPIN | LCB_F_WRITE, "rwlock:W"},
1437 { LCB_F_READ, "rwsem:R" },
1438 { LCB_F_WRITE, "rwsem:W" },
1439 { LCB_F_RT, "rtmutex" },
1440 { LCB_F_RT | LCB_F_READ, "rwlock-rt:R" },
1441 { LCB_F_RT | LCB_F_WRITE, "rwlock-rt:W"},
1442 { LCB_F_PERCPU | LCB_F_READ, "pcpu-sem:R" },
1443 { LCB_F_PERCPU | LCB_F_WRITE, "pcpu-sem:W" },
1444 { LCB_F_MUTEX, "mutex" },
1445 { LCB_F_MUTEX | LCB_F_SPIN, "mutex" },
1448 for (unsigned int i = 0; i < ARRAY_SIZE(table); i++) {
1449 if (table[i].flags == st->flags)
1450 return table[i].name;
1455 static void sort_contention_result(void)
1460 static void print_contention_result(void)
1462 struct lock_stat *st;
1463 struct lock_key *key;
1466 list_for_each_entry(key, &lock_keys, list)
1467 pr_info("%*s ", key->len, key->header);
1469 if (show_thread_stats)
1470 pr_info(" %10s %s\n\n", "pid", "comm");
1472 pr_info(" %10s %s\n\n", "type", "caller");
1476 bad = bad_hist[BROKEN_CONTENDED];
1478 while ((st = pop_from_result())) {
1479 total += use_bpf ? st->nr_contended : 1;
1483 list_for_each_entry(key, &lock_keys, list) {
1484 key->print(key, st);
1488 if (show_thread_stats) {
1492 /* st->addr contains tid of thread */
1493 t = perf_session__findnew(session, pid);
1494 pr_info(" %10d %s\n", pid, thread__comm_str(t));
1498 pr_info(" %10s %s\n", get_type_str(st), st->name);
1501 print_bad_events(bad, total);
1504 static const struct evsel_str_handler lock_tracepoints[] = {
1505 { "lock:lock_acquire", evsel__process_lock_acquire, }, /* CONFIG_LOCKDEP */
1506 { "lock:lock_acquired", evsel__process_lock_acquired, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1507 { "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1508 { "lock:lock_release", evsel__process_lock_release, }, /* CONFIG_LOCKDEP */
1511 static const struct evsel_str_handler contention_tracepoints[] = {
1512 { "lock:contention_begin", evsel__process_contention_begin, },
1513 { "lock:contention_end", evsel__process_contention_end, },
1518 static int __cmd_report(bool display_info)
1521 struct perf_tool eops = {
1522 .sample = process_sample_event,
1523 .comm = perf_event__process_comm,
1524 .mmap = perf_event__process_mmap,
1525 .namespaces = perf_event__process_namespaces,
1526 .ordered_events = true,
1528 struct perf_data data = {
1530 .mode = PERF_DATA_MODE_READ,
1534 session = perf_session__new(&data, &eops);
1535 if (IS_ERR(session)) {
1536 pr_err("Initializing perf session failed\n");
1537 return PTR_ERR(session);
1540 /* for lock function check */
1541 symbol_conf.sort_by_name = true;
1542 symbol__init(&session->header.env);
1544 if (!perf_session__has_traces(session, "lock record"))
1547 if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
1548 pr_err("Initializing perf session tracepoint handlers failed\n");
1552 if (perf_session__set_tracepoints_handlers(session, contention_tracepoints)) {
1553 pr_err("Initializing perf session tracepoint handlers failed\n");
1557 if (setup_output_field(false, output_fields))
1560 if (select_key(false))
1563 if (show_thread_stats)
1564 aggr_mode = LOCK_AGGR_TASK;
1566 err = perf_session__process_events(session);
1571 if (display_info) /* used for info subcommand */
1580 perf_session__delete(session);
1584 static void sighandler(int sig __maybe_unused)
1588 static int __cmd_contention(int argc, const char **argv)
1591 struct perf_tool eops = {
1592 .sample = process_sample_event,
1593 .comm = perf_event__process_comm,
1594 .mmap = perf_event__process_mmap,
1595 .ordered_events = true,
1597 struct perf_data data = {
1599 .mode = PERF_DATA_MODE_READ,
1602 struct lock_contention con = {
1604 .result = &lockhash_table[0],
1605 .map_nr_entries = bpf_map_entries,
1608 session = perf_session__new(use_bpf ? NULL : &data, &eops);
1609 if (IS_ERR(session)) {
1610 pr_err("Initializing perf session failed\n");
1611 return PTR_ERR(session);
1614 /* for lock function check */
1615 symbol_conf.sort_by_name = true;
1616 symbol__init(&session->header.env);
1619 err = target__validate(&target);
1623 target__strerror(&target, err, errbuf, 512);
1624 pr_err("%s\n", errbuf);
1628 signal(SIGINT, sighandler);
1629 signal(SIGCHLD, sighandler);
1630 signal(SIGTERM, sighandler);
1632 con.machine = &session->machines.host;
1634 con.evlist = evlist__new();
1635 if (con.evlist == NULL) {
1640 err = evlist__create_maps(con.evlist, &target);
1645 err = evlist__prepare_workload(con.evlist, &target,
1651 if (lock_contention_prepare(&con) < 0) {
1652 pr_err("lock contention BPF setup failed\n");
1656 if (!perf_session__has_traces(session, "lock record"))
1659 if (!evlist__find_evsel_by_str(session->evlist,
1660 "lock:contention_begin")) {
1661 pr_err("lock contention evsel not found\n");
1665 if (perf_session__set_tracepoints_handlers(session,
1666 contention_tracepoints)) {
1667 pr_err("Initializing perf session tracepoint handlers failed\n");
1672 if (setup_output_field(true, output_fields))
1675 if (select_key(true))
1678 if (show_thread_stats)
1679 aggr_mode = LOCK_AGGR_TASK;
1681 aggr_mode = LOCK_AGGR_CALLER;
1684 lock_contention_start();
1686 evlist__start_workload(con.evlist);
1688 /* wait for signal */
1691 lock_contention_stop();
1692 lock_contention_read(&con);
1694 /* abuse bad hist stats for lost entries */
1695 bad_hist[BROKEN_CONTENDED] = con.lost;
1697 err = perf_session__process_events(session);
1704 sort_contention_result();
1705 print_contention_result();
1708 evlist__delete(con.evlist);
1709 lock_contention_finish();
1710 perf_session__delete(session);
1715 static int __cmd_record(int argc, const char **argv)
1717 const char *record_args[] = {
1718 "record", "-R", "-m", "1024", "-c", "1", "--synth", "task",
1720 const char *callgraph_args[] = {
1721 "--call-graph", "fp," __stringify(CONTENTION_STACK_DEPTH),
1723 unsigned int rec_argc, i, j, ret;
1724 unsigned int nr_tracepoints;
1725 unsigned int nr_callgraph_args = 0;
1726 const char **rec_argv;
1727 bool has_lock_stat = true;
1729 for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
1730 if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
1731 pr_debug("tracepoint %s is not enabled. "
1732 "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
1733 lock_tracepoints[i].name);
1734 has_lock_stat = false;
1742 for (i = 0; i < ARRAY_SIZE(contention_tracepoints); i++) {
1743 if (!is_valid_tracepoint(contention_tracepoints[i].name)) {
1744 pr_err("tracepoint %s is not enabled.\n",
1745 contention_tracepoints[i].name);
1750 nr_callgraph_args = ARRAY_SIZE(callgraph_args);
1753 rec_argc = ARRAY_SIZE(record_args) + nr_callgraph_args + argc - 1;
1756 nr_tracepoints = ARRAY_SIZE(lock_tracepoints);
1758 nr_tracepoints = ARRAY_SIZE(contention_tracepoints);
1760 /* factor of 2 is for -e in front of each tracepoint */
1761 rec_argc += 2 * nr_tracepoints;
1763 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1767 for (i = 0; i < ARRAY_SIZE(record_args); i++)
1768 rec_argv[i] = strdup(record_args[i]);
1770 for (j = 0; j < nr_tracepoints; j++) {
1771 const char *ev_name;
1774 ev_name = strdup(lock_tracepoints[j].name);
1776 ev_name = strdup(contention_tracepoints[j].name);
1781 rec_argv[i++] = "-e";
1782 rec_argv[i++] = ev_name;
1785 for (j = 0; j < nr_callgraph_args; j++, i++)
1786 rec_argv[i] = callgraph_args[j];
1788 for (j = 1; j < (unsigned int)argc; j++, i++)
1789 rec_argv[i] = argv[j];
1791 BUG_ON(i != rec_argc);
1793 ret = cmd_record(i, rec_argv);
1798 static int parse_map_entry(const struct option *opt, const char *str,
1799 int unset __maybe_unused)
1801 unsigned long *len = (unsigned long *)opt->value;
1806 val = strtoul(str, &endptr, 0);
1807 if (*endptr != '\0' || errno != 0) {
1808 pr_err("invalid BPF map length: %s\n", str);
1816 int cmd_lock(int argc, const char **argv)
1818 const struct option lock_options[] = {
1819 OPT_STRING('i', "input", &input_name, "file", "input file name"),
1820 OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
1821 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
1822 OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
1823 OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
1824 "file", "vmlinux pathname"),
1825 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1826 "file", "kallsyms pathname"),
1830 const struct option info_options[] = {
1831 OPT_BOOLEAN('t', "threads", &info_threads,
1832 "dump thread list in perf.data"),
1833 OPT_BOOLEAN('m', "map", &info_map,
1834 "map of lock instances (address:name table)"),
1835 OPT_PARENT(lock_options)
1838 const struct option report_options[] = {
1839 OPT_STRING('k', "key", &sort_key, "acquired",
1840 "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1841 OPT_STRING('F', "field", &output_fields, NULL,
1842 "output fields (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1844 OPT_BOOLEAN('c', "combine-locks", &combine_locks,
1845 "combine locks in the same class"),
1846 OPT_BOOLEAN('t', "threads", &show_thread_stats,
1847 "show per-thread lock stats"),
1848 OPT_PARENT(lock_options)
1851 struct option contention_options[] = {
1852 OPT_STRING('k', "key", &sort_key, "wait_total",
1853 "key for sorting (contended / wait_total / wait_max / wait_min / avg_wait)"),
1854 OPT_STRING('F', "field", &output_fields, "contended,wait_total,wait_max,avg_wait",
1855 "output fields (contended / wait_total / wait_max / wait_min / avg_wait)"),
1856 OPT_BOOLEAN('t', "threads", &show_thread_stats,
1857 "show per-thread lock stats"),
1858 OPT_BOOLEAN('b', "use-bpf", &use_bpf, "use BPF program to collect lock contention stats"),
1859 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1860 "System-wide collection from all CPUs"),
1861 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1862 "List of cpus to monitor"),
1863 OPT_STRING('p', "pid", &target.pid, "pid",
1864 "Trace on existing process id"),
1865 OPT_STRING(0, "tid", &target.tid, "tid",
1866 "Trace on existing thread id (exclusive to --pid)"),
1867 OPT_CALLBACK(0, "map-nr-entries", &bpf_map_entries, "num",
1868 "Max number of BPF map entries", parse_map_entry),
1869 OPT_PARENT(lock_options)
1872 const char * const info_usage[] = {
1873 "perf lock info [<options>]",
1876 const char *const lock_subcommands[] = { "record", "report", "script",
1877 "info", "contention",
1878 "contention", NULL };
1879 const char *lock_usage[] = {
1883 const char * const report_usage[] = {
1884 "perf lock report [<options>]",
1887 const char * const contention_usage[] = {
1888 "perf lock contention [<options>]",
1894 for (i = 0; i < LOCKHASH_SIZE; i++)
1895 INIT_HLIST_HEAD(lockhash_table + i);
1897 argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
1898 lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
1900 usage_with_options(lock_usage, lock_options);
1902 if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
1903 return __cmd_record(argc, argv);
1904 } else if (strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
1905 trace_handler = &report_lock_ops;
1907 argc = parse_options(argc, argv,
1908 report_options, report_usage, 0);
1910 usage_with_options(report_usage, report_options);
1912 rc = __cmd_report(false);
1913 } else if (!strcmp(argv[0], "script")) {
1914 /* Aliased to 'perf script' */
1915 return cmd_script(argc, argv);
1916 } else if (!strcmp(argv[0], "info")) {
1918 argc = parse_options(argc, argv,
1919 info_options, info_usage, 0);
1921 usage_with_options(info_usage, info_options);
1923 /* recycling report_lock_ops */
1924 trace_handler = &report_lock_ops;
1925 rc = __cmd_report(true);
1926 } else if (strlen(argv[0]) > 2 && strstarts("contention", argv[0])) {
1927 trace_handler = &contention_lock_ops;
1928 sort_key = "wait_total";
1929 output_fields = "contended,wait_total,wait_max,avg_wait";
1931 #ifndef HAVE_BPF_SKEL
1932 set_option_nobuild(contention_options, 'b', "use-bpf",
1933 "no BUILD_BPF_SKEL=1", false);
1936 argc = parse_options(argc, argv, contention_options,
1937 contention_usage, 0);
1939 rc = __cmd_contention(argc, argv);
1941 usage_with_options(lock_usage, lock_options);