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"
15 #include "util/bpf_skel/lock_data.h"
17 #include <subcmd/pager.h>
18 #include <subcmd/parse-options.h>
19 #include "util/trace-event.h"
20 #include "util/tracepoint.h"
22 #include "util/debug.h"
23 #include "util/session.h"
24 #include "util/tool.h"
25 #include "util/data.h"
26 #include "util/string2.h"
28 #include "util/util.h"
31 #include <sys/types.h>
32 #include <sys/prctl.h>
33 #include <semaphore.h>
38 #include <linux/list.h>
39 #include <linux/hash.h>
40 #include <linux/kernel.h>
41 #include <linux/zalloc.h>
42 #include <linux/err.h>
43 #include <linux/stringify.h>
45 static struct perf_session *session;
46 static struct target target;
48 /* based on kernel/lockdep.c */
49 #define LOCKHASH_BITS 12
50 #define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
52 static struct hlist_head *lockhash_table;
54 #define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
55 #define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
57 static struct rb_root thread_stats;
59 static bool combine_locks;
60 static bool show_thread_stats;
61 static bool show_lock_addrs;
62 static bool show_lock_owner;
64 static unsigned long bpf_map_entries = MAX_ENTRIES;
65 static int max_stack_depth = CONTENTION_STACK_DEPTH;
66 static int stack_skip = CONTENTION_STACK_SKIP;
67 static int print_nr_entries = INT_MAX / 2;
68 static LIST_HEAD(callstack_filters);
69 static const char *output_name = NULL;
70 static FILE *lock_output;
72 struct callstack_filter {
73 struct list_head list;
77 static struct lock_filter filters;
79 static enum lock_aggr_mode aggr_mode = LOCK_AGGR_ADDR;
81 static bool needs_callstack(void)
83 return !list_empty(&callstack_filters);
86 static struct thread_stat *thread_stat_find(u32 tid)
89 struct thread_stat *st;
91 node = thread_stats.rb_node;
93 st = container_of(node, struct thread_stat, rb);
96 else if (tid < st->tid)
99 node = node->rb_right;
105 static void thread_stat_insert(struct thread_stat *new)
107 struct rb_node **rb = &thread_stats.rb_node;
108 struct rb_node *parent = NULL;
109 struct thread_stat *p;
112 p = container_of(*rb, struct thread_stat, rb);
115 if (new->tid < p->tid)
116 rb = &(*rb)->rb_left;
117 else if (new->tid > p->tid)
118 rb = &(*rb)->rb_right;
120 BUG_ON("inserting invalid thread_stat\n");
123 rb_link_node(&new->rb, parent, rb);
124 rb_insert_color(&new->rb, &thread_stats);
127 static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
129 struct thread_stat *st;
131 st = thread_stat_find(tid);
135 st = zalloc(sizeof(struct thread_stat));
137 pr_err("memory allocation failed\n");
142 INIT_LIST_HEAD(&st->seq_list);
144 thread_stat_insert(st);
149 static struct thread_stat *thread_stat_findnew_first(u32 tid);
150 static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
151 thread_stat_findnew_first;
153 static struct thread_stat *thread_stat_findnew_first(u32 tid)
155 struct thread_stat *st;
157 st = zalloc(sizeof(struct thread_stat));
159 pr_err("memory allocation failed\n");
163 INIT_LIST_HEAD(&st->seq_list);
165 rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
166 rb_insert_color(&st->rb, &thread_stats);
168 thread_stat_findnew = thread_stat_findnew_after_first;
172 /* build simple key function one is bigger than two */
173 #define SINGLE_KEY(member) \
174 static int lock_stat_key_ ## member(struct lock_stat *one, \
175 struct lock_stat *two) \
177 return one->member > two->member; \
180 SINGLE_KEY(nr_acquired)
181 SINGLE_KEY(nr_contended)
182 SINGLE_KEY(avg_wait_time)
183 SINGLE_KEY(wait_time_total)
184 SINGLE_KEY(wait_time_max)
186 static int lock_stat_key_wait_time_min(struct lock_stat *one,
187 struct lock_stat *two)
189 u64 s1 = one->wait_time_min;
190 u64 s2 = two->wait_time_min;
191 if (s1 == ULLONG_MAX)
193 if (s2 == ULLONG_MAX)
200 * name: the value for specify by user
201 * this should be simpler than raw name of member
202 * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
205 /* header: the string printed on the header line */
207 /* len: the printing width of the field */
209 /* key: a pointer to function to compare two lock stats for sorting */
210 int (*key)(struct lock_stat*, struct lock_stat*);
211 /* print: a pointer to function to print a given lock stats */
212 void (*print)(struct lock_key*, struct lock_stat*);
213 /* list: list entry to link this */
214 struct list_head list;
217 static void lock_stat_key_print_time(unsigned long long nsec, int len)
219 static const struct {
223 { 1e9 * 3600, "h " },
233 fprintf(lock_output, "%llu", nsec);
237 for (int i = 0; table[i].unit; i++) {
238 if (nsec < table[i].base)
241 fprintf(lock_output, "%*.2f %s", len - 3, nsec / table[i].base, table[i].unit);
245 fprintf(lock_output, "%*llu %s", len - 3, nsec, "ns");
248 #define PRINT_KEY(member) \
249 static void lock_stat_key_print_ ## member(struct lock_key *key, \
250 struct lock_stat *ls) \
252 fprintf(lock_output, "%*llu", key->len, (unsigned long long)ls->member);\
255 #define PRINT_TIME(member) \
256 static void lock_stat_key_print_ ## member(struct lock_key *key, \
257 struct lock_stat *ls) \
259 lock_stat_key_print_time((unsigned long long)ls->member, key->len); \
262 PRINT_KEY(nr_acquired)
263 PRINT_KEY(nr_contended)
264 PRINT_TIME(avg_wait_time)
265 PRINT_TIME(wait_time_total)
266 PRINT_TIME(wait_time_max)
268 static void lock_stat_key_print_wait_time_min(struct lock_key *key,
269 struct lock_stat *ls)
271 u64 wait_time = ls->wait_time_min;
273 if (wait_time == ULLONG_MAX)
276 lock_stat_key_print_time(wait_time, key->len);
280 static const char *sort_key = "acquired";
282 static int (*compare)(struct lock_stat *, struct lock_stat *);
284 static struct rb_root sorted; /* place to store intermediate data */
285 static struct rb_root result; /* place to store sorted data */
287 static LIST_HEAD(lock_keys);
288 static const char *output_fields;
290 #define DEF_KEY_LOCK(name, header, fn_suffix, len) \
291 { #name, header, len, lock_stat_key_ ## fn_suffix, lock_stat_key_print_ ## fn_suffix, {} }
292 static struct lock_key report_keys[] = {
293 DEF_KEY_LOCK(acquired, "acquired", nr_acquired, 10),
294 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
295 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
296 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
297 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
298 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
300 /* extra comparisons much complicated should be here */
304 static struct lock_key contention_keys[] = {
305 DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
306 DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
307 DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
308 DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
309 DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
311 /* extra comparisons much complicated should be here */
315 static int select_key(bool contention)
318 struct lock_key *keys = report_keys;
321 keys = contention_keys;
323 for (i = 0; keys[i].name; i++) {
324 if (!strcmp(keys[i].name, sort_key)) {
325 compare = keys[i].key;
327 /* selected key should be in the output fields */
328 if (list_empty(&keys[i].list))
329 list_add_tail(&keys[i].list, &lock_keys);
335 pr_err("Unknown compare key: %s\n", sort_key);
339 static int add_output_field(bool contention, char *name)
342 struct lock_key *keys = report_keys;
345 keys = contention_keys;
347 for (i = 0; keys[i].name; i++) {
348 if (strcmp(keys[i].name, name))
351 /* prevent double link */
352 if (list_empty(&keys[i].list))
353 list_add_tail(&keys[i].list, &lock_keys);
358 pr_err("Unknown output field: %s\n", name);
362 static int setup_output_field(bool contention, const char *str)
364 char *tok, *tmp, *orig;
366 struct lock_key *keys = report_keys;
369 keys = contention_keys;
371 /* no output field given: use all of them */
373 for (i = 0; keys[i].name; i++)
374 list_add_tail(&keys[i].list, &lock_keys);
378 for (i = 0; keys[i].name; i++)
379 INIT_LIST_HEAD(&keys[i].list);
381 orig = tmp = strdup(str);
385 while ((tok = strsep(&tmp, ",")) != NULL){
386 ret = add_output_field(contention, tok);
395 static void combine_lock_stats(struct lock_stat *st)
397 struct rb_node **rb = &sorted.rb_node;
398 struct rb_node *parent = NULL;
403 p = container_of(*rb, struct lock_stat, rb);
406 if (st->name && p->name)
407 ret = strcmp(st->name, p->name);
409 ret = !!st->name - !!p->name;
412 p->nr_acquired += st->nr_acquired;
413 p->nr_contended += st->nr_contended;
414 p->wait_time_total += st->wait_time_total;
417 p->avg_wait_time = p->wait_time_total / p->nr_contended;
419 if (p->wait_time_min > st->wait_time_min)
420 p->wait_time_min = st->wait_time_min;
421 if (p->wait_time_max < st->wait_time_max)
422 p->wait_time_max = st->wait_time_max;
424 p->broken |= st->broken;
430 rb = &(*rb)->rb_left;
432 rb = &(*rb)->rb_right;
435 rb_link_node(&st->rb, parent, rb);
436 rb_insert_color(&st->rb, &sorted);
439 static void insert_to_result(struct lock_stat *st,
440 int (*bigger)(struct lock_stat *, struct lock_stat *))
442 struct rb_node **rb = &result.rb_node;
443 struct rb_node *parent = NULL;
446 if (combine_locks && st->combined)
450 p = container_of(*rb, struct lock_stat, rb);
454 rb = &(*rb)->rb_left;
456 rb = &(*rb)->rb_right;
459 rb_link_node(&st->rb, parent, rb);
460 rb_insert_color(&st->rb, &result);
463 /* returns left most element of result, and erase it */
464 static struct lock_stat *pop_from_result(void)
466 struct rb_node *node = result.rb_node;
471 while (node->rb_left)
472 node = node->rb_left;
474 rb_erase(node, &result);
475 return container_of(node, struct lock_stat, rb);
478 struct lock_stat *lock_stat_find(u64 addr)
480 struct hlist_head *entry = lockhashentry(addr);
481 struct lock_stat *ret;
483 hlist_for_each_entry(ret, entry, hash_entry) {
484 if (ret->addr == addr)
490 struct lock_stat *lock_stat_findnew(u64 addr, const char *name, int flags)
492 struct hlist_head *entry = lockhashentry(addr);
493 struct lock_stat *ret, *new;
495 hlist_for_each_entry(ret, entry, hash_entry) {
496 if (ret->addr == addr)
500 new = zalloc(sizeof(struct lock_stat));
505 new->name = strdup(name);
512 new->wait_time_min = ULLONG_MAX;
514 hlist_add_head(&new->hash_entry, entry);
518 pr_err("memory allocation failed\n");
522 bool match_callstack_filter(struct machine *machine, u64 *callstack)
528 if (list_empty(&callstack_filters))
531 for (int i = 0; i < max_stack_depth; i++) {
532 struct callstack_filter *filter;
534 if (!callstack || !callstack[i])
538 sym = machine__find_kernel_symbol(machine, ip, &kmap);
542 list_for_each_entry(filter, &callstack_filters, list) {
543 if (strstr(sym->name, filter->name))
550 struct trace_lock_handler {
551 /* it's used on CONFIG_LOCKDEP */
552 int (*acquire_event)(struct evsel *evsel,
553 struct perf_sample *sample);
555 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
556 int (*acquired_event)(struct evsel *evsel,
557 struct perf_sample *sample);
559 /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
560 int (*contended_event)(struct evsel *evsel,
561 struct perf_sample *sample);
563 /* it's used on CONFIG_LOCKDEP */
564 int (*release_event)(struct evsel *evsel,
565 struct perf_sample *sample);
567 /* it's used when CONFIG_LOCKDEP is off */
568 int (*contention_begin_event)(struct evsel *evsel,
569 struct perf_sample *sample);
571 /* it's used when CONFIG_LOCKDEP is off */
572 int (*contention_end_event)(struct evsel *evsel,
573 struct perf_sample *sample);
576 static struct lock_seq_stat *get_seq(struct thread_stat *ts, u64 addr)
578 struct lock_seq_stat *seq;
580 list_for_each_entry(seq, &ts->seq_list, list) {
581 if (seq->addr == addr)
585 seq = zalloc(sizeof(struct lock_seq_stat));
587 pr_err("memory allocation failed\n");
590 seq->state = SEQ_STATE_UNINITIALIZED;
593 list_add(&seq->list, &ts->seq_list);
605 static int bad_hist[BROKEN_MAX];
612 static int get_key_by_aggr_mode_simple(u64 *key, u64 addr, u32 tid)
621 case LOCK_AGGR_CALLER:
623 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
629 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample);
631 static int get_key_by_aggr_mode(u64 *key, u64 addr, struct evsel *evsel,
632 struct perf_sample *sample)
634 if (aggr_mode == LOCK_AGGR_CALLER) {
635 *key = callchain_id(evsel, sample);
638 return get_key_by_aggr_mode_simple(key, addr, sample->tid);
641 static int report_lock_acquire_event(struct evsel *evsel,
642 struct perf_sample *sample)
644 struct lock_stat *ls;
645 struct thread_stat *ts;
646 struct lock_seq_stat *seq;
647 const char *name = evsel__strval(evsel, sample, "name");
648 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
649 int flag = evsel__intval(evsel, sample, "flags");
653 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
657 ls = lock_stat_findnew(key, name, 0);
661 ts = thread_stat_findnew(sample->tid);
665 seq = get_seq(ts, addr);
669 switch (seq->state) {
670 case SEQ_STATE_UNINITIALIZED:
671 case SEQ_STATE_RELEASED:
673 seq->state = SEQ_STATE_ACQUIRING;
677 if (flag & READ_LOCK)
679 seq->state = SEQ_STATE_READ_ACQUIRED;
684 case SEQ_STATE_READ_ACQUIRED:
685 if (flag & READ_LOCK) {
693 case SEQ_STATE_ACQUIRED:
694 case SEQ_STATE_ACQUIRING:
695 case SEQ_STATE_CONTENDED:
697 /* broken lock sequence */
700 bad_hist[BROKEN_ACQUIRE]++;
702 list_del_init(&seq->list);
706 BUG_ON("Unknown state of lock sequence found!\n");
711 seq->prev_event_time = sample->time;
716 static int report_lock_acquired_event(struct evsel *evsel,
717 struct perf_sample *sample)
719 struct lock_stat *ls;
720 struct thread_stat *ts;
721 struct lock_seq_stat *seq;
723 const char *name = evsel__strval(evsel, sample, "name");
724 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
728 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
732 ls = lock_stat_findnew(key, name, 0);
736 ts = thread_stat_findnew(sample->tid);
740 seq = get_seq(ts, addr);
744 switch (seq->state) {
745 case SEQ_STATE_UNINITIALIZED:
746 /* orphan event, do nothing */
748 case SEQ_STATE_ACQUIRING:
750 case SEQ_STATE_CONTENDED:
751 contended_term = sample->time - seq->prev_event_time;
752 ls->wait_time_total += contended_term;
753 if (contended_term < ls->wait_time_min)
754 ls->wait_time_min = contended_term;
755 if (ls->wait_time_max < contended_term)
756 ls->wait_time_max = contended_term;
758 case SEQ_STATE_RELEASED:
759 case SEQ_STATE_ACQUIRED:
760 case SEQ_STATE_READ_ACQUIRED:
761 /* broken lock sequence */
764 bad_hist[BROKEN_ACQUIRED]++;
766 list_del_init(&seq->list);
770 BUG_ON("Unknown state of lock sequence found!\n");
774 seq->state = SEQ_STATE_ACQUIRED;
776 ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
777 seq->prev_event_time = sample->time;
782 static int report_lock_contended_event(struct evsel *evsel,
783 struct perf_sample *sample)
785 struct lock_stat *ls;
786 struct thread_stat *ts;
787 struct lock_seq_stat *seq;
788 const char *name = evsel__strval(evsel, sample, "name");
789 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
793 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
797 ls = lock_stat_findnew(key, name, 0);
801 ts = thread_stat_findnew(sample->tid);
805 seq = get_seq(ts, addr);
809 switch (seq->state) {
810 case SEQ_STATE_UNINITIALIZED:
811 /* orphan event, do nothing */
813 case SEQ_STATE_ACQUIRING:
815 case SEQ_STATE_RELEASED:
816 case SEQ_STATE_ACQUIRED:
817 case SEQ_STATE_READ_ACQUIRED:
818 case SEQ_STATE_CONTENDED:
819 /* broken lock sequence */
822 bad_hist[BROKEN_CONTENDED]++;
824 list_del_init(&seq->list);
828 BUG_ON("Unknown state of lock sequence found!\n");
832 seq->state = SEQ_STATE_CONTENDED;
834 ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
835 seq->prev_event_time = sample->time;
840 static int report_lock_release_event(struct evsel *evsel,
841 struct perf_sample *sample)
843 struct lock_stat *ls;
844 struct thread_stat *ts;
845 struct lock_seq_stat *seq;
846 const char *name = evsel__strval(evsel, sample, "name");
847 u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
851 ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
855 ls = lock_stat_findnew(key, name, 0);
859 ts = thread_stat_findnew(sample->tid);
863 seq = get_seq(ts, addr);
867 switch (seq->state) {
868 case SEQ_STATE_UNINITIALIZED:
870 case SEQ_STATE_ACQUIRED:
872 case SEQ_STATE_READ_ACQUIRED:
874 BUG_ON(seq->read_count < 0);
875 if (seq->read_count) {
880 case SEQ_STATE_ACQUIRING:
881 case SEQ_STATE_CONTENDED:
882 case SEQ_STATE_RELEASED:
883 /* broken lock sequence */
886 bad_hist[BROKEN_RELEASE]++;
890 BUG_ON("Unknown state of lock sequence found!\n");
896 list_del_init(&seq->list);
902 static int get_symbol_name_offset(struct map *map, struct symbol *sym, u64 ip,
907 if (map == NULL || sym == NULL) {
912 offset = map__map_ip(map, ip) - sym->start;
915 return scnprintf(buf, size, "%s+%#lx", sym->name, offset);
917 return strlcpy(buf, sym->name, size);
919 static int lock_contention_caller(struct evsel *evsel, struct perf_sample *sample,
922 struct thread *thread;
923 struct callchain_cursor *cursor;
924 struct machine *machine = &session->machines.host;
929 /* lock names will be replaced to task name later */
930 if (show_thread_stats)
933 thread = machine__findnew_thread(machine, -1, sample->pid);
937 cursor = get_tls_callchain_cursor();
939 /* use caller function name from the callchain */
940 ret = thread__resolve_callchain(thread, cursor, evsel, sample,
941 NULL, NULL, max_stack_depth);
947 callchain_cursor_commit(cursor);
951 struct callchain_cursor_node *node;
953 node = callchain_cursor_current(cursor);
957 /* skip first few entries - for lock functions */
958 if (++skip <= stack_skip)
962 if (sym && !machine__is_lock_function(machine, node->ip)) {
963 get_symbol_name_offset(node->ms.map, sym, node->ip,
969 callchain_cursor_advance(cursor);
974 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample)
976 struct callchain_cursor *cursor;
977 struct machine *machine = &session->machines.host;
978 struct thread *thread;
983 thread = machine__findnew_thread(machine, -1, sample->pid);
987 cursor = get_tls_callchain_cursor();
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 && machine__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");
1048 unsigned int flags = evsel__intval(evsel, sample, "flags");
1051 static bool kmap_loaded;
1052 struct machine *machine = &session->machines.host;
1056 ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1061 unsigned long *addrs;
1063 /* make sure it loads the kernel map to find lock symbols */
1064 map__load(machine__kernel_map(machine));
1067 /* convert (kernel) symbols to addresses */
1068 for (i = 0; i < filters.nr_syms; i++) {
1069 sym = machine__find_kernel_symbol_by_name(machine,
1073 pr_warning("ignore unknown symbol: %s\n",
1078 addrs = realloc(filters.addrs,
1079 (filters.nr_addrs + 1) * sizeof(*addrs));
1080 if (addrs == NULL) {
1081 pr_warning("memory allocation failure\n");
1085 addrs[filters.nr_addrs++] = map__unmap_ip(kmap, sym->start);
1086 filters.addrs = addrs;
1090 ls = lock_stat_find(key);
1093 const char *name = "";
1095 switch (aggr_mode) {
1096 case LOCK_AGGR_ADDR:
1097 sym = machine__find_kernel_symbol(machine, key, &kmap);
1101 case LOCK_AGGR_CALLER:
1103 if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
1106 case LOCK_AGGR_TASK:
1111 ls = lock_stat_findnew(key, name, flags);
1116 if (filters.nr_types) {
1119 for (i = 0; i < filters.nr_types; i++) {
1120 if (flags == filters.types[i]) {
1130 if (filters.nr_addrs) {
1133 for (i = 0; i < filters.nr_addrs; i++) {
1134 if (addr == filters.addrs[i]) {
1144 if (needs_callstack()) {
1145 u64 *callstack = get_callstack(sample, max_stack_depth);
1146 if (callstack == NULL)
1149 if (!match_callstack_filter(machine, callstack)) {
1154 if (ls->callstack == NULL)
1155 ls->callstack = callstack;
1160 ts = thread_stat_findnew(sample->tid);
1164 seq = get_seq(ts, addr);
1168 switch (seq->state) {
1169 case SEQ_STATE_UNINITIALIZED:
1170 case SEQ_STATE_ACQUIRED:
1172 case SEQ_STATE_CONTENDED:
1174 * It can have nested contention begin with mutex spinning,
1175 * then we would use the original contention begin event and
1176 * ignore the second one.
1179 case SEQ_STATE_ACQUIRING:
1180 case SEQ_STATE_READ_ACQUIRED:
1181 case SEQ_STATE_RELEASED:
1182 /* broken lock sequence */
1185 bad_hist[BROKEN_CONTENDED]++;
1187 list_del_init(&seq->list);
1191 BUG_ON("Unknown state of lock sequence found!\n");
1195 if (seq->state != SEQ_STATE_CONTENDED) {
1196 seq->state = SEQ_STATE_CONTENDED;
1197 seq->prev_event_time = sample->time;
1204 static int report_lock_contention_end_event(struct evsel *evsel,
1205 struct perf_sample *sample)
1207 struct lock_stat *ls;
1208 struct thread_stat *ts;
1209 struct lock_seq_stat *seq;
1211 u64 addr = evsel__intval(evsel, sample, "lock_addr");
1215 ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1219 ls = lock_stat_find(key);
1223 ts = thread_stat_find(sample->tid);
1227 seq = get_seq(ts, addr);
1231 switch (seq->state) {
1232 case SEQ_STATE_UNINITIALIZED:
1234 case SEQ_STATE_CONTENDED:
1235 contended_term = sample->time - seq->prev_event_time;
1236 ls->wait_time_total += contended_term;
1237 if (contended_term < ls->wait_time_min)
1238 ls->wait_time_min = contended_term;
1239 if (ls->wait_time_max < contended_term)
1240 ls->wait_time_max = contended_term;
1242 case SEQ_STATE_ACQUIRING:
1243 case SEQ_STATE_ACQUIRED:
1244 case SEQ_STATE_READ_ACQUIRED:
1245 case SEQ_STATE_RELEASED:
1246 /* broken lock sequence */
1249 bad_hist[BROKEN_ACQUIRED]++;
1251 list_del_init(&seq->list);
1255 BUG_ON("Unknown state of lock sequence found!\n");
1259 seq->state = SEQ_STATE_ACQUIRED;
1261 ls->avg_wait_time = ls->wait_time_total/ls->nr_acquired;
1266 /* lock oriented handlers */
1267 /* TODO: handlers for CPU oriented, thread oriented */
1268 static struct trace_lock_handler report_lock_ops = {
1269 .acquire_event = report_lock_acquire_event,
1270 .acquired_event = report_lock_acquired_event,
1271 .contended_event = report_lock_contended_event,
1272 .release_event = report_lock_release_event,
1273 .contention_begin_event = report_lock_contention_begin_event,
1274 .contention_end_event = report_lock_contention_end_event,
1277 static struct trace_lock_handler contention_lock_ops = {
1278 .contention_begin_event = report_lock_contention_begin_event,
1279 .contention_end_event = report_lock_contention_end_event,
1283 static struct trace_lock_handler *trace_handler;
1285 static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
1287 if (trace_handler->acquire_event)
1288 return trace_handler->acquire_event(evsel, sample);
1292 static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
1294 if (trace_handler->acquired_event)
1295 return trace_handler->acquired_event(evsel, sample);
1299 static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
1301 if (trace_handler->contended_event)
1302 return trace_handler->contended_event(evsel, sample);
1306 static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
1308 if (trace_handler->release_event)
1309 return trace_handler->release_event(evsel, sample);
1313 static int evsel__process_contention_begin(struct evsel *evsel, struct perf_sample *sample)
1315 if (trace_handler->contention_begin_event)
1316 return trace_handler->contention_begin_event(evsel, sample);
1320 static int evsel__process_contention_end(struct evsel *evsel, struct perf_sample *sample)
1322 if (trace_handler->contention_end_event)
1323 return trace_handler->contention_end_event(evsel, sample);
1327 static void print_bad_events(int bad, int total)
1329 /* Output for debug, this have to be removed */
1332 const char *name[4] =
1333 { "acquire", "acquired", "contended", "release" };
1335 for (i = 0; i < BROKEN_MAX; i++)
1336 broken += bad_hist[i];
1338 if (quiet || total == 0 || (broken == 0 && verbose <= 0))
1341 fprintf(lock_output, "\n=== output for debug ===\n\n");
1342 fprintf(lock_output, "bad: %d, total: %d\n", bad, total);
1343 fprintf(lock_output, "bad rate: %.2f %%\n", (double)bad / (double)total * 100);
1344 fprintf(lock_output, "histogram of events caused bad sequence\n");
1345 for (i = 0; i < BROKEN_MAX; i++)
1346 fprintf(lock_output, " %10s: %d\n", name[i], bad_hist[i]);
1349 /* TODO: various way to print, coloring, nano or milli sec */
1350 static void print_result(void)
1352 struct lock_stat *st;
1353 struct lock_key *key;
1355 int bad, total, printed;
1358 fprintf(lock_output, "%20s ", "Name");
1359 list_for_each_entry(key, &lock_keys, list)
1360 fprintf(lock_output, "%*s ", key->len, key->header);
1361 fprintf(lock_output, "\n\n");
1364 bad = total = printed = 0;
1365 while ((st = pop_from_result())) {
1369 if (!st->nr_acquired)
1372 bzero(cut_name, 20);
1374 if (strlen(st->name) < 20) {
1375 /* output raw name */
1376 const char *name = st->name;
1378 if (show_thread_stats) {
1381 /* st->addr contains tid of thread */
1382 t = perf_session__findnew(session, st->addr);
1383 name = thread__comm_str(t);
1386 fprintf(lock_output, "%20s ", name);
1388 strncpy(cut_name, st->name, 16);
1392 cut_name[19] = '\0';
1393 /* cut off name for saving output style */
1394 fprintf(lock_output, "%20s ", cut_name);
1397 list_for_each_entry(key, &lock_keys, list) {
1398 key->print(key, st);
1399 fprintf(lock_output, " ");
1401 fprintf(lock_output, "\n");
1403 if (++printed >= print_nr_entries)
1407 print_bad_events(bad, total);
1410 static bool info_threads, info_map;
1412 static void dump_threads(void)
1414 struct thread_stat *st;
1415 struct rb_node *node;
1418 fprintf(lock_output, "%10s: comm\n", "Thread ID");
1420 node = rb_first(&thread_stats);
1422 st = container_of(node, struct thread_stat, rb);
1423 t = perf_session__findnew(session, st->tid);
1424 fprintf(lock_output, "%10d: %s\n", st->tid, thread__comm_str(t));
1425 node = rb_next(node);
1430 static int compare_maps(struct lock_stat *a, struct lock_stat *b)
1434 if (a->name && b->name)
1435 ret = strcmp(a->name, b->name);
1437 ret = !!a->name - !!b->name;
1440 return a->addr < b->addr;
1445 static void dump_map(void)
1448 struct lock_stat *st;
1450 fprintf(lock_output, "Address of instance: name of class\n");
1451 for (i = 0; i < LOCKHASH_SIZE; i++) {
1452 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1453 insert_to_result(st, compare_maps);
1457 while ((st = pop_from_result()))
1458 fprintf(lock_output, " %#llx: %s\n", (unsigned long long)st->addr, st->name);
1461 static int dump_info(void)
1471 pr_err("Unknown type of information\n");
1477 static const struct evsel_str_handler lock_tracepoints[] = {
1478 { "lock:lock_acquire", evsel__process_lock_acquire, }, /* CONFIG_LOCKDEP */
1479 { "lock:lock_acquired", evsel__process_lock_acquired, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1480 { "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1481 { "lock:lock_release", evsel__process_lock_release, }, /* CONFIG_LOCKDEP */
1484 static const struct evsel_str_handler contention_tracepoints[] = {
1485 { "lock:contention_begin", evsel__process_contention_begin, },
1486 { "lock:contention_end", evsel__process_contention_end, },
1489 static int process_event_update(struct perf_tool *tool,
1490 union perf_event *event,
1491 struct evlist **pevlist)
1495 ret = perf_event__process_event_update(tool, event, pevlist);
1499 /* this can return -EEXIST since we call it for each evsel */
1500 perf_session__set_tracepoints_handlers(session, lock_tracepoints);
1501 perf_session__set_tracepoints_handlers(session, contention_tracepoints);
1505 typedef int (*tracepoint_handler)(struct evsel *evsel,
1506 struct perf_sample *sample);
1508 static int process_sample_event(struct perf_tool *tool __maybe_unused,
1509 union perf_event *event,
1510 struct perf_sample *sample,
1511 struct evsel *evsel,
1512 struct machine *machine)
1515 struct thread *thread = machine__findnew_thread(machine, sample->pid,
1518 if (thread == NULL) {
1519 pr_debug("problem processing %d event, skipping it.\n",
1520 event->header.type);
1524 if (evsel->handler != NULL) {
1525 tracepoint_handler f = evsel->handler;
1526 err = f(evsel, sample);
1529 thread__put(thread);
1534 static void combine_result(void)
1537 struct lock_stat *st;
1542 for (i = 0; i < LOCKHASH_SIZE; i++) {
1543 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1544 combine_lock_stats(st);
1549 static void sort_result(void)
1552 struct lock_stat *st;
1554 for (i = 0; i < LOCKHASH_SIZE; i++) {
1555 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1556 insert_to_result(st, compare);
1561 static const struct {
1565 } lock_type_table[] = {
1566 { 0, "semaphore", "semaphore" },
1567 { LCB_F_SPIN, "spinlock", "spinlock" },
1568 { LCB_F_SPIN | LCB_F_READ, "rwlock:R", "rwlock" },
1569 { LCB_F_SPIN | LCB_F_WRITE, "rwlock:W", "rwlock" },
1570 { LCB_F_READ, "rwsem:R", "rwsem" },
1571 { LCB_F_WRITE, "rwsem:W", "rwsem" },
1572 { LCB_F_RT, "rt-mutex", "rt-mutex" },
1573 { LCB_F_RT | LCB_F_READ, "rwlock-rt:R", "rwlock-rt" },
1574 { LCB_F_RT | LCB_F_WRITE, "rwlock-rt:W", "rwlock-rt" },
1575 { LCB_F_PERCPU | LCB_F_READ, "pcpu-sem:R", "percpu-rwsem" },
1576 { LCB_F_PERCPU | LCB_F_WRITE, "pcpu-sem:W", "percpu-rwsem" },
1577 { LCB_F_MUTEX, "mutex", "mutex" },
1578 { LCB_F_MUTEX | LCB_F_SPIN, "mutex", "mutex" },
1579 /* alias for get_type_flag() */
1580 { LCB_F_MUTEX | LCB_F_SPIN, "mutex-spin", "mutex" },
1583 static const char *get_type_str(unsigned int flags)
1585 flags &= LCB_F_MAX_FLAGS - 1;
1587 for (unsigned int i = 0; i < ARRAY_SIZE(lock_type_table); i++) {
1588 if (lock_type_table[i].flags == flags)
1589 return lock_type_table[i].str;
1594 static const char *get_type_name(unsigned int flags)
1596 flags &= LCB_F_MAX_FLAGS - 1;
1598 for (unsigned int i = 0; i < ARRAY_SIZE(lock_type_table); i++) {
1599 if (lock_type_table[i].flags == flags)
1600 return lock_type_table[i].name;
1605 static unsigned int get_type_flag(const char *str)
1607 for (unsigned int i = 0; i < ARRAY_SIZE(lock_type_table); i++) {
1608 if (!strcmp(lock_type_table[i].name, str))
1609 return lock_type_table[i].flags;
1611 for (unsigned int i = 0; i < ARRAY_SIZE(lock_type_table); i++) {
1612 if (!strcmp(lock_type_table[i].str, str))
1613 return lock_type_table[i].flags;
1618 static void lock_filter_finish(void)
1620 zfree(&filters.types);
1621 filters.nr_types = 0;
1623 zfree(&filters.addrs);
1624 filters.nr_addrs = 0;
1626 for (int i = 0; i < filters.nr_syms; i++)
1627 free(filters.syms[i]);
1629 zfree(&filters.syms);
1630 filters.nr_syms = 0;
1633 static void sort_contention_result(void)
1638 static void print_header_stdio(void)
1640 struct lock_key *key;
1642 list_for_each_entry(key, &lock_keys, list)
1643 fprintf(lock_output, "%*s ", key->len, key->header);
1645 switch (aggr_mode) {
1646 case LOCK_AGGR_TASK:
1647 fprintf(lock_output, " %10s %s\n\n", "pid",
1648 show_lock_owner ? "owner" : "comm");
1650 case LOCK_AGGR_CALLER:
1651 fprintf(lock_output, " %10s %s\n\n", "type", "caller");
1653 case LOCK_AGGR_ADDR:
1654 fprintf(lock_output, " %16s %s\n\n", "address", "symbol");
1661 static void print_header_csv(const char *sep)
1663 struct lock_key *key;
1665 fprintf(lock_output, "# output: ");
1666 list_for_each_entry(key, &lock_keys, list)
1667 fprintf(lock_output, "%s%s ", key->header, sep);
1669 switch (aggr_mode) {
1670 case LOCK_AGGR_TASK:
1671 fprintf(lock_output, "%s%s %s\n", "pid", sep,
1672 show_lock_owner ? "owner" : "comm");
1674 case LOCK_AGGR_CALLER:
1675 fprintf(lock_output, "%s%s %s", "type", sep, "caller");
1677 fprintf(lock_output, "%s %s", sep, "stacktrace");
1678 fprintf(lock_output, "\n");
1680 case LOCK_AGGR_ADDR:
1681 fprintf(lock_output, "%s%s %s%s %s\n", "address", sep, "symbol", sep, "type");
1688 static void print_header(void)
1691 if (symbol_conf.field_sep)
1692 print_header_csv(symbol_conf.field_sep);
1694 print_header_stdio();
1698 static void print_lock_stat_stdio(struct lock_contention *con, struct lock_stat *st)
1700 struct lock_key *key;
1704 list_for_each_entry(key, &lock_keys, list) {
1705 key->print(key, st);
1706 fprintf(lock_output, " ");
1709 switch (aggr_mode) {
1710 case LOCK_AGGR_CALLER:
1711 fprintf(lock_output, " %10s %s\n", get_type_str(st->flags), st->name);
1713 case LOCK_AGGR_TASK:
1715 t = perf_session__findnew(session, pid);
1716 fprintf(lock_output, " %10d %s\n",
1717 pid, pid == -1 ? "Unknown" : thread__comm_str(t));
1719 case LOCK_AGGR_ADDR:
1720 fprintf(lock_output, " %016llx %s (%s)\n", (unsigned long long)st->addr,
1721 st->name, get_type_name(st->flags));
1727 if (aggr_mode == LOCK_AGGR_CALLER && verbose > 0) {
1733 for (int i = 0; i < max_stack_depth; i++) {
1734 if (!st->callstack || !st->callstack[i])
1737 ip = st->callstack[i];
1738 sym = machine__find_kernel_symbol(con->machine, ip, &kmap);
1739 get_symbol_name_offset(kmap, sym, ip, buf, sizeof(buf));
1740 fprintf(lock_output, "\t\t\t%#lx %s\n", (unsigned long)ip, buf);
1745 static void print_lock_stat_csv(struct lock_contention *con, struct lock_stat *st,
1748 struct lock_key *key;
1752 list_for_each_entry(key, &lock_keys, list) {
1753 key->print(key, st);
1754 fprintf(lock_output, "%s ", sep);
1757 switch (aggr_mode) {
1758 case LOCK_AGGR_CALLER:
1759 fprintf(lock_output, "%s%s %s", get_type_str(st->flags), sep, st->name);
1761 fprintf(lock_output, "\n");
1763 case LOCK_AGGR_TASK:
1765 t = perf_session__findnew(session, pid);
1766 fprintf(lock_output, "%d%s %s\n", pid, sep,
1767 pid == -1 ? "Unknown" : thread__comm_str(t));
1769 case LOCK_AGGR_ADDR:
1770 fprintf(lock_output, "%llx%s %s%s %s\n", (unsigned long long)st->addr, sep,
1771 st->name, sep, get_type_name(st->flags));
1777 if (aggr_mode == LOCK_AGGR_CALLER && verbose > 0) {
1783 for (int i = 0; i < max_stack_depth; i++) {
1784 if (!st->callstack || !st->callstack[i])
1787 ip = st->callstack[i];
1788 sym = machine__find_kernel_symbol(con->machine, ip, &kmap);
1789 get_symbol_name_offset(kmap, sym, ip, buf, sizeof(buf));
1790 fprintf(lock_output, "%s %#lx %s", i ? ":" : sep, (unsigned long) ip, buf);
1792 fprintf(lock_output, "\n");
1796 static void print_lock_stat(struct lock_contention *con, struct lock_stat *st)
1798 if (symbol_conf.field_sep)
1799 print_lock_stat_csv(con, st, symbol_conf.field_sep);
1801 print_lock_stat_stdio(con, st);
1804 static void print_footer_stdio(int total, int bad, struct lock_contention_fails *fails)
1806 /* Output for debug, this have to be removed */
1807 int broken = fails->task + fails->stack + fails->time + fails->data;
1810 print_bad_events(bad, total);
1812 if (quiet || total == 0 || (broken == 0 && verbose <= 0))
1816 fprintf(lock_output, "\n=== output for debug ===\n\n");
1817 fprintf(lock_output, "bad: %d, total: %d\n", broken, total);
1818 fprintf(lock_output, "bad rate: %.2f %%\n", 100.0 * broken / total);
1820 fprintf(lock_output, "histogram of failure reasons\n");
1821 fprintf(lock_output, " %10s: %d\n", "task", fails->task);
1822 fprintf(lock_output, " %10s: %d\n", "stack", fails->stack);
1823 fprintf(lock_output, " %10s: %d\n", "time", fails->time);
1824 fprintf(lock_output, " %10s: %d\n", "data", fails->data);
1827 static void print_footer_csv(int total, int bad, struct lock_contention_fails *fails,
1830 /* Output for debug, this have to be removed */
1832 bad = fails->task + fails->stack + fails->time + fails->data;
1834 if (quiet || total == 0 || (bad == 0 && verbose <= 0))
1838 fprintf(lock_output, "# debug: total=%d%s bad=%d", total, sep, bad);
1841 fprintf(lock_output, "%s bad_%s=%d", sep, "task", fails->task);
1842 fprintf(lock_output, "%s bad_%s=%d", sep, "stack", fails->stack);
1843 fprintf(lock_output, "%s bad_%s=%d", sep, "time", fails->time);
1844 fprintf(lock_output, "%s bad_%s=%d", sep, "data", fails->data);
1847 const char *name[4] = { "acquire", "acquired", "contended", "release" };
1849 for (i = 0; i < BROKEN_MAX; i++)
1850 fprintf(lock_output, "%s bad_%s=%d", sep, name[i], bad_hist[i]);
1852 fprintf(lock_output, "\n");
1855 static void print_footer(int total, int bad, struct lock_contention_fails *fails)
1857 if (symbol_conf.field_sep)
1858 print_footer_csv(total, bad, fails, symbol_conf.field_sep);
1860 print_footer_stdio(total, bad, fails);
1863 static void print_contention_result(struct lock_contention *con)
1865 struct lock_stat *st;
1866 int bad, total, printed;
1871 bad = total = printed = 0;
1873 while ((st = pop_from_result())) {
1874 total += use_bpf ? st->nr_contended : 1;
1878 if (!st->wait_time_total)
1881 print_lock_stat(con, st);
1883 if (++printed >= print_nr_entries)
1887 if (print_nr_entries) {
1888 /* update the total/bad stats */
1889 while ((st = pop_from_result())) {
1890 total += use_bpf ? st->nr_contended : 1;
1895 /* some entries are collected but hidden by the callstack filter */
1896 total += con->nr_filtered;
1898 print_footer(total, bad, &con->fails);
1903 static int __cmd_report(bool display_info)
1906 struct perf_tool eops = {
1907 .attr = perf_event__process_attr,
1908 .event_update = process_event_update,
1909 .sample = process_sample_event,
1910 .comm = perf_event__process_comm,
1911 .mmap = perf_event__process_mmap,
1912 .namespaces = perf_event__process_namespaces,
1913 .tracing_data = perf_event__process_tracing_data,
1914 .ordered_events = true,
1916 struct perf_data data = {
1918 .mode = PERF_DATA_MODE_READ,
1922 session = perf_session__new(&data, &eops);
1923 if (IS_ERR(session)) {
1924 pr_err("Initializing perf session failed\n");
1925 return PTR_ERR(session);
1928 symbol_conf.allow_aliases = true;
1929 symbol__init(&session->header.env);
1931 if (!data.is_pipe) {
1932 if (!perf_session__has_traces(session, "lock record"))
1935 if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
1936 pr_err("Initializing perf session tracepoint handlers failed\n");
1940 if (perf_session__set_tracepoints_handlers(session, contention_tracepoints)) {
1941 pr_err("Initializing perf session tracepoint handlers failed\n");
1946 if (setup_output_field(false, output_fields))
1949 if (select_key(false))
1952 if (show_thread_stats)
1953 aggr_mode = LOCK_AGGR_TASK;
1955 err = perf_session__process_events(session);
1960 if (display_info) /* used for info subcommand */
1969 perf_session__delete(session);
1973 static void sighandler(int sig __maybe_unused)
1977 static int check_lock_contention_options(const struct option *options,
1978 const char * const *usage)
1981 if (show_thread_stats && show_lock_addrs) {
1982 pr_err("Cannot use thread and addr mode together\n");
1983 parse_options_usage(usage, options, "threads", 0);
1984 parse_options_usage(NULL, options, "lock-addr", 0);
1988 if (show_lock_owner && !use_bpf) {
1989 pr_err("Lock owners are available only with BPF\n");
1990 parse_options_usage(usage, options, "lock-owner", 0);
1991 parse_options_usage(NULL, options, "use-bpf", 0);
1995 if (show_lock_owner && show_lock_addrs) {
1996 pr_err("Cannot use owner and addr mode together\n");
1997 parse_options_usage(usage, options, "lock-owner", 0);
1998 parse_options_usage(NULL, options, "lock-addr", 0);
2002 if (symbol_conf.field_sep) {
2003 if (strstr(symbol_conf.field_sep, ":") || /* part of type flags */
2004 strstr(symbol_conf.field_sep, "+") || /* part of caller offset */
2005 strstr(symbol_conf.field_sep, ".")) { /* can be in a symbol name */
2006 pr_err("Cannot use the separator that is already used\n");
2007 parse_options_usage(usage, options, "x", 1);
2012 if (show_lock_owner)
2013 show_thread_stats = true;
2018 static int __cmd_contention(int argc, const char **argv)
2021 struct perf_tool eops = {
2022 .attr = perf_event__process_attr,
2023 .event_update = process_event_update,
2024 .sample = process_sample_event,
2025 .comm = perf_event__process_comm,
2026 .mmap = perf_event__process_mmap,
2027 .tracing_data = perf_event__process_tracing_data,
2028 .ordered_events = true,
2030 struct perf_data data = {
2032 .mode = PERF_DATA_MODE_READ,
2035 struct lock_contention con = {
2037 .map_nr_entries = bpf_map_entries,
2038 .max_stack = max_stack_depth,
2039 .stack_skip = stack_skip,
2040 .filters = &filters,
2041 .save_callstack = needs_callstack(),
2042 .owner = show_lock_owner,
2045 lockhash_table = calloc(LOCKHASH_SIZE, sizeof(*lockhash_table));
2046 if (!lockhash_table)
2049 con.result = &lockhash_table[0];
2051 session = perf_session__new(use_bpf ? NULL : &data, &eops);
2052 if (IS_ERR(session)) {
2053 pr_err("Initializing perf session failed\n");
2054 err = PTR_ERR(session);
2058 con.machine = &session->machines.host;
2060 con.aggr_mode = aggr_mode = show_thread_stats ? LOCK_AGGR_TASK :
2061 show_lock_addrs ? LOCK_AGGR_ADDR : LOCK_AGGR_CALLER;
2063 if (con.aggr_mode == LOCK_AGGR_CALLER)
2064 con.save_callstack = true;
2066 symbol_conf.allow_aliases = true;
2067 symbol__init(&session->header.env);
2070 err = target__validate(&target);
2074 target__strerror(&target, err, errbuf, 512);
2075 pr_err("%s\n", errbuf);
2079 signal(SIGINT, sighandler);
2080 signal(SIGCHLD, sighandler);
2081 signal(SIGTERM, sighandler);
2083 con.evlist = evlist__new();
2084 if (con.evlist == NULL) {
2089 err = evlist__create_maps(con.evlist, &target);
2094 err = evlist__prepare_workload(con.evlist, &target,
2100 if (lock_contention_prepare(&con) < 0) {
2101 pr_err("lock contention BPF setup failed\n");
2104 } else if (!data.is_pipe) {
2105 if (!perf_session__has_traces(session, "lock record"))
2108 if (!evlist__find_evsel_by_str(session->evlist,
2109 "lock:contention_begin")) {
2110 pr_err("lock contention evsel not found\n");
2114 if (perf_session__set_tracepoints_handlers(session,
2115 contention_tracepoints)) {
2116 pr_err("Initializing perf session tracepoint handlers failed\n");
2121 if (setup_output_field(true, output_fields))
2124 if (select_key(true))
2127 if (symbol_conf.field_sep) {
2129 struct lock_key *keys = contention_keys;
2131 /* do not align output in CSV format */
2132 for (i = 0; keys[i].name; i++)
2137 lock_contention_start();
2139 evlist__start_workload(con.evlist);
2141 /* wait for signal */
2144 lock_contention_stop();
2145 lock_contention_read(&con);
2147 err = perf_session__process_events(session);
2154 sort_contention_result();
2155 print_contention_result(&con);
2158 lock_filter_finish();
2159 evlist__delete(con.evlist);
2160 lock_contention_finish();
2161 perf_session__delete(session);
2162 zfree(&lockhash_table);
2167 static int __cmd_record(int argc, const char **argv)
2169 const char *record_args[] = {
2170 "record", "-R", "-m", "1024", "-c", "1", "--synth", "task",
2172 const char *callgraph_args[] = {
2173 "--call-graph", "fp," __stringify(CONTENTION_STACK_DEPTH),
2175 unsigned int rec_argc, i, j, ret;
2176 unsigned int nr_tracepoints;
2177 unsigned int nr_callgraph_args = 0;
2178 const char **rec_argv;
2179 bool has_lock_stat = true;
2181 for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
2182 if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
2183 pr_debug("tracepoint %s is not enabled. "
2184 "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
2185 lock_tracepoints[i].name);
2186 has_lock_stat = false;
2194 for (i = 0; i < ARRAY_SIZE(contention_tracepoints); i++) {
2195 if (!is_valid_tracepoint(contention_tracepoints[i].name)) {
2196 pr_err("tracepoint %s is not enabled.\n",
2197 contention_tracepoints[i].name);
2202 nr_callgraph_args = ARRAY_SIZE(callgraph_args);
2205 rec_argc = ARRAY_SIZE(record_args) + nr_callgraph_args + argc - 1;
2208 nr_tracepoints = ARRAY_SIZE(lock_tracepoints);
2210 nr_tracepoints = ARRAY_SIZE(contention_tracepoints);
2212 /* factor of 2 is for -e in front of each tracepoint */
2213 rec_argc += 2 * nr_tracepoints;
2215 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2219 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2220 rec_argv[i] = strdup(record_args[i]);
2222 for (j = 0; j < nr_tracepoints; j++) {
2223 const char *ev_name;
2226 ev_name = strdup(lock_tracepoints[j].name);
2228 ev_name = strdup(contention_tracepoints[j].name);
2233 rec_argv[i++] = "-e";
2234 rec_argv[i++] = ev_name;
2237 for (j = 0; j < nr_callgraph_args; j++, i++)
2238 rec_argv[i] = callgraph_args[j];
2240 for (j = 1; j < (unsigned int)argc; j++, i++)
2241 rec_argv[i] = argv[j];
2243 BUG_ON(i != rec_argc);
2245 ret = cmd_record(i, rec_argv);
2250 static int parse_map_entry(const struct option *opt, const char *str,
2251 int unset __maybe_unused)
2253 unsigned long *len = (unsigned long *)opt->value;
2258 val = strtoul(str, &endptr, 0);
2259 if (*endptr != '\0' || errno != 0) {
2260 pr_err("invalid BPF map length: %s\n", str);
2268 static int parse_max_stack(const struct option *opt, const char *str,
2269 int unset __maybe_unused)
2271 unsigned long *len = (unsigned long *)opt->value;
2276 val = strtol(str, &endptr, 0);
2277 if (*endptr != '\0' || errno != 0) {
2278 pr_err("invalid max stack depth: %s\n", str);
2282 if (val < 0 || val > sysctl__max_stack()) {
2283 pr_err("invalid max stack depth: %ld\n", val);
2291 static bool add_lock_type(unsigned int flags)
2295 tmp = realloc(filters.types, (filters.nr_types + 1) * sizeof(*filters.types));
2299 tmp[filters.nr_types++] = flags;
2300 filters.types = tmp;
2304 static int parse_lock_type(const struct option *opt __maybe_unused, const char *str,
2305 int unset __maybe_unused)
2307 char *s, *tmp, *tok;
2314 for (tok = strtok_r(s, ", ", &tmp); tok; tok = strtok_r(NULL, ", ", &tmp)) {
2315 unsigned int flags = get_type_flag(tok);
2318 pr_err("Unknown lock flags: %s\n", tok);
2323 if (!add_lock_type(flags)) {
2333 static bool add_lock_addr(unsigned long addr)
2337 tmp = realloc(filters.addrs, (filters.nr_addrs + 1) * sizeof(*filters.addrs));
2339 pr_err("Memory allocation failure\n");
2343 tmp[filters.nr_addrs++] = addr;
2344 filters.addrs = tmp;
2348 static bool add_lock_sym(char *name)
2351 char *sym = strdup(name);
2354 pr_err("Memory allocation failure\n");
2358 tmp = realloc(filters.syms, (filters.nr_syms + 1) * sizeof(*filters.syms));
2360 pr_err("Memory allocation failure\n");
2365 tmp[filters.nr_syms++] = sym;
2370 static int parse_lock_addr(const struct option *opt __maybe_unused, const char *str,
2371 int unset __maybe_unused)
2373 char *s, *tmp, *tok;
2381 for (tok = strtok_r(s, ", ", &tmp); tok; tok = strtok_r(NULL, ", ", &tmp)) {
2384 addr = strtoul(tok, &end, 16);
2386 if (!add_lock_addr(addr)) {
2394 * At this moment, we don't have kernel symbols. Save the symbols
2395 * in a separate list and resolve them to addresses later.
2397 if (!add_lock_sym(tok)) {
2407 static int parse_call_stack(const struct option *opt __maybe_unused, const char *str,
2408 int unset __maybe_unused)
2410 char *s, *tmp, *tok;
2417 for (tok = strtok_r(s, ", ", &tmp); tok; tok = strtok_r(NULL, ", ", &tmp)) {
2418 struct callstack_filter *entry;
2420 entry = malloc(sizeof(*entry) + strlen(tok) + 1);
2421 if (entry == NULL) {
2422 pr_err("Memory allocation failure\n");
2426 strcpy(entry->name, tok);
2427 list_add_tail(&entry->list, &callstack_filters);
2434 static int parse_output(const struct option *opt __maybe_unused, const char *str,
2435 int unset __maybe_unused)
2437 const char **name = (const char **)opt->value;
2442 lock_output = fopen(str, "w");
2443 if (lock_output == NULL) {
2444 pr_err("Cannot open %s\n", str);
2452 int cmd_lock(int argc, const char **argv)
2454 const struct option lock_options[] = {
2455 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2456 OPT_CALLBACK(0, "output", &output_name, "file", "output file name", parse_output),
2457 OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
2458 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
2459 OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
2460 OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
2461 "file", "vmlinux pathname"),
2462 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
2463 "file", "kallsyms pathname"),
2464 OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
2468 const struct option info_options[] = {
2469 OPT_BOOLEAN('t', "threads", &info_threads,
2470 "dump thread list in perf.data"),
2471 OPT_BOOLEAN('m', "map", &info_map,
2472 "map of lock instances (address:name table)"),
2473 OPT_PARENT(lock_options)
2476 const struct option report_options[] = {
2477 OPT_STRING('k', "key", &sort_key, "acquired",
2478 "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
2479 OPT_STRING('F', "field", &output_fields, NULL,
2480 "output fields (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
2482 OPT_BOOLEAN('c', "combine-locks", &combine_locks,
2483 "combine locks in the same class"),
2484 OPT_BOOLEAN('t', "threads", &show_thread_stats,
2485 "show per-thread lock stats"),
2486 OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
2487 OPT_PARENT(lock_options)
2490 struct option contention_options[] = {
2491 OPT_STRING('k', "key", &sort_key, "wait_total",
2492 "key for sorting (contended / wait_total / wait_max / wait_min / avg_wait)"),
2493 OPT_STRING('F', "field", &output_fields, "contended,wait_total,wait_max,avg_wait",
2494 "output fields (contended / wait_total / wait_max / wait_min / avg_wait)"),
2495 OPT_BOOLEAN('t', "threads", &show_thread_stats,
2496 "show per-thread lock stats"),
2497 OPT_BOOLEAN('b', "use-bpf", &use_bpf, "use BPF program to collect lock contention stats"),
2498 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
2499 "System-wide collection from all CPUs"),
2500 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
2501 "List of cpus to monitor"),
2502 OPT_STRING('p', "pid", &target.pid, "pid",
2503 "Trace on existing process id"),
2504 OPT_STRING(0, "tid", &target.tid, "tid",
2505 "Trace on existing thread id (exclusive to --pid)"),
2506 OPT_CALLBACK('M', "map-nr-entries", &bpf_map_entries, "num",
2507 "Max number of BPF map entries", parse_map_entry),
2508 OPT_CALLBACK(0, "max-stack", &max_stack_depth, "num",
2509 "Set the maximum stack depth when collecting lopck contention, "
2510 "Default: " __stringify(CONTENTION_STACK_DEPTH), parse_max_stack),
2511 OPT_INTEGER(0, "stack-skip", &stack_skip,
2512 "Set the number of stack depth to skip when finding a lock caller, "
2513 "Default: " __stringify(CONTENTION_STACK_SKIP)),
2514 OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
2515 OPT_BOOLEAN('l', "lock-addr", &show_lock_addrs, "show lock stats by address"),
2516 OPT_CALLBACK('Y', "type-filter", NULL, "FLAGS",
2517 "Filter specific type of locks", parse_lock_type),
2518 OPT_CALLBACK('L', "lock-filter", NULL, "ADDRS/NAMES",
2519 "Filter specific address/symbol of locks", parse_lock_addr),
2520 OPT_CALLBACK('S', "callstack-filter", NULL, "NAMES",
2521 "Filter specific function in the callstack", parse_call_stack),
2522 OPT_BOOLEAN('o', "lock-owner", &show_lock_owner, "show lock owners instead of waiters"),
2523 OPT_STRING_NOEMPTY('x', "field-separator", &symbol_conf.field_sep, "separator",
2524 "print result in CSV format with custom separator"),
2525 OPT_PARENT(lock_options)
2528 const char * const info_usage[] = {
2529 "perf lock info [<options>]",
2532 const char *const lock_subcommands[] = { "record", "report", "script",
2533 "info", "contention", NULL };
2534 const char *lock_usage[] = {
2538 const char * const report_usage[] = {
2539 "perf lock report [<options>]",
2542 const char * const contention_usage[] = {
2543 "perf lock contention [<options>]",
2549 lockhash_table = calloc(LOCKHASH_SIZE, sizeof(*lockhash_table));
2550 if (!lockhash_table)
2553 for (i = 0; i < LOCKHASH_SIZE; i++)
2554 INIT_HLIST_HEAD(lockhash_table + i);
2556 lock_output = stderr;
2557 argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
2558 lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
2560 usage_with_options(lock_usage, lock_options);
2562 if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2563 return __cmd_record(argc, argv);
2564 } else if (strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
2565 trace_handler = &report_lock_ops;
2567 argc = parse_options(argc, argv,
2568 report_options, report_usage, 0);
2570 usage_with_options(report_usage, report_options);
2572 rc = __cmd_report(false);
2573 } else if (!strcmp(argv[0], "script")) {
2574 /* Aliased to 'perf script' */
2575 rc = cmd_script(argc, argv);
2576 } else if (!strcmp(argv[0], "info")) {
2578 argc = parse_options(argc, argv,
2579 info_options, info_usage, 0);
2581 usage_with_options(info_usage, info_options);
2583 /* recycling report_lock_ops */
2584 trace_handler = &report_lock_ops;
2585 rc = __cmd_report(true);
2586 } else if (strlen(argv[0]) > 2 && strstarts("contention", argv[0])) {
2587 trace_handler = &contention_lock_ops;
2588 sort_key = "wait_total";
2589 output_fields = "contended,wait_total,wait_max,avg_wait";
2591 #ifndef HAVE_BPF_SKEL
2592 set_option_nobuild(contention_options, 'b', "use-bpf",
2593 "no BUILD_BPF_SKEL=1", false);
2596 argc = parse_options(argc, argv, contention_options,
2597 contention_usage, 0);
2600 if (check_lock_contention_options(contention_options,
2601 contention_usage) < 0)
2604 rc = __cmd_contention(argc, argv);
2606 usage_with_options(lock_usage, lock_options);
2609 zfree(&lockhash_table);