1 // SPDX-License-Identifier: GPL-2.0
7 #include "util/evlist.h"
8 #include "util/evsel.h"
10 #include "util/cache.h"
11 #include "util/symbol.h"
12 #include "util/thread.h"
13 #include "util/header.h"
15 #include <subcmd/parse-options.h>
16 #include "util/trace-event.h"
18 #include "util/debug.h"
19 #include "util/session.h"
20 #include "util/tool.h"
21 #include "util/data.h"
23 #include <sys/types.h>
24 #include <sys/prctl.h>
25 #include <semaphore.h>
30 #include <linux/list.h>
31 #include <linux/hash.h>
32 #include <linux/kernel.h>
34 static struct perf_session *session;
36 /* based on kernel/lockdep.c */
37 #define LOCKHASH_BITS 12
38 #define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
40 static struct list_head lockhash_table[LOCKHASH_SIZE];
42 #define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
43 #define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
46 struct list_head hash_entry;
47 struct rb_node rb; /* used for sorting */
50 * FIXME: perf_evsel__intval() returns u64,
51 * so address of lockdep_map should be dealed as 64bit.
52 * Is there more better solution?
54 void *addr; /* address of lockdep_map, used as ID */
55 char *name; /* for strcpy(), we cannot use const */
57 unsigned int nr_acquire;
58 unsigned int nr_acquired;
59 unsigned int nr_contended;
60 unsigned int nr_release;
62 unsigned int nr_readlock;
63 unsigned int nr_trylock;
65 /* these times are in nano sec. */
71 int discard; /* flag of blacklist */
75 * States of lock_seq_stat
77 * UNINITIALIZED is required for detecting first event of acquire.
78 * As the nature of lock events, there is no guarantee
79 * that the first event for the locks are acquire,
80 * it can be acquired, contended or release.
82 #define SEQ_STATE_UNINITIALIZED 0 /* initial state */
83 #define SEQ_STATE_RELEASED 1
84 #define SEQ_STATE_ACQUIRING 2
85 #define SEQ_STATE_ACQUIRED 3
86 #define SEQ_STATE_READ_ACQUIRED 4
87 #define SEQ_STATE_CONTENDED 5
91 * Imported from include/linux/sched.h.
92 * Should this be synchronized?
94 #define MAX_LOCK_DEPTH 48
97 * struct lock_seq_stat:
98 * Place to put on state of one lock sequence
99 * 1) acquire -> acquired -> release
100 * 2) acquire -> contended -> acquired -> release
101 * 3) acquire (with read or try) -> release
102 * 4) Are there other patterns?
104 struct lock_seq_stat {
105 struct list_head list;
117 struct list_head seq_list;
120 static struct rb_root thread_stats;
122 static struct thread_stat *thread_stat_find(u32 tid)
124 struct rb_node *node;
125 struct thread_stat *st;
127 node = thread_stats.rb_node;
129 st = container_of(node, struct thread_stat, rb);
132 else if (tid < st->tid)
133 node = node->rb_left;
135 node = node->rb_right;
141 static void thread_stat_insert(struct thread_stat *new)
143 struct rb_node **rb = &thread_stats.rb_node;
144 struct rb_node *parent = NULL;
145 struct thread_stat *p;
148 p = container_of(*rb, struct thread_stat, rb);
151 if (new->tid < p->tid)
152 rb = &(*rb)->rb_left;
153 else if (new->tid > p->tid)
154 rb = &(*rb)->rb_right;
156 BUG_ON("inserting invalid thread_stat\n");
159 rb_link_node(&new->rb, parent, rb);
160 rb_insert_color(&new->rb, &thread_stats);
163 static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
165 struct thread_stat *st;
167 st = thread_stat_find(tid);
171 st = zalloc(sizeof(struct thread_stat));
173 pr_err("memory allocation failed\n");
178 INIT_LIST_HEAD(&st->seq_list);
180 thread_stat_insert(st);
185 static struct thread_stat *thread_stat_findnew_first(u32 tid);
186 static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
187 thread_stat_findnew_first;
189 static struct thread_stat *thread_stat_findnew_first(u32 tid)
191 struct thread_stat *st;
193 st = zalloc(sizeof(struct thread_stat));
195 pr_err("memory allocation failed\n");
199 INIT_LIST_HEAD(&st->seq_list);
201 rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
202 rb_insert_color(&st->rb, &thread_stats);
204 thread_stat_findnew = thread_stat_findnew_after_first;
208 /* build simple key function one is bigger than two */
209 #define SINGLE_KEY(member) \
210 static int lock_stat_key_ ## member(struct lock_stat *one, \
211 struct lock_stat *two) \
213 return one->member > two->member; \
216 SINGLE_KEY(nr_acquired)
217 SINGLE_KEY(nr_contended)
218 SINGLE_KEY(avg_wait_time)
219 SINGLE_KEY(wait_time_total)
220 SINGLE_KEY(wait_time_max)
222 static int lock_stat_key_wait_time_min(struct lock_stat *one,
223 struct lock_stat *two)
225 u64 s1 = one->wait_time_min;
226 u64 s2 = two->wait_time_min;
227 if (s1 == ULLONG_MAX)
229 if (s2 == ULLONG_MAX)
236 * name: the value for specify by user
237 * this should be simpler than raw name of member
238 * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
241 int (*key)(struct lock_stat*, struct lock_stat*);
244 static const char *sort_key = "acquired";
246 static int (*compare)(struct lock_stat *, struct lock_stat *);
248 static struct rb_root result; /* place to store sorted data */
250 #define DEF_KEY_LOCK(name, fn_suffix) \
251 { #name, lock_stat_key_ ## fn_suffix }
252 struct lock_key keys[] = {
253 DEF_KEY_LOCK(acquired, nr_acquired),
254 DEF_KEY_LOCK(contended, nr_contended),
255 DEF_KEY_LOCK(avg_wait, avg_wait_time),
256 DEF_KEY_LOCK(wait_total, wait_time_total),
257 DEF_KEY_LOCK(wait_min, wait_time_min),
258 DEF_KEY_LOCK(wait_max, wait_time_max),
260 /* extra comparisons much complicated should be here */
265 static int select_key(void)
269 for (i = 0; keys[i].name; i++) {
270 if (!strcmp(keys[i].name, sort_key)) {
271 compare = keys[i].key;
276 pr_err("Unknown compare key: %s\n", sort_key);
281 static void insert_to_result(struct lock_stat *st,
282 int (*bigger)(struct lock_stat *, struct lock_stat *))
284 struct rb_node **rb = &result.rb_node;
285 struct rb_node *parent = NULL;
289 p = container_of(*rb, struct lock_stat, rb);
293 rb = &(*rb)->rb_left;
295 rb = &(*rb)->rb_right;
298 rb_link_node(&st->rb, parent, rb);
299 rb_insert_color(&st->rb, &result);
302 /* returns left most element of result, and erase it */
303 static struct lock_stat *pop_from_result(void)
305 struct rb_node *node = result.rb_node;
310 while (node->rb_left)
311 node = node->rb_left;
313 rb_erase(node, &result);
314 return container_of(node, struct lock_stat, rb);
317 static struct lock_stat *lock_stat_findnew(void *addr, const char *name)
319 struct list_head *entry = lockhashentry(addr);
320 struct lock_stat *ret, *new;
322 list_for_each_entry(ret, entry, hash_entry) {
323 if (ret->addr == addr)
327 new = zalloc(sizeof(struct lock_stat));
332 new->name = zalloc(sizeof(char) * strlen(name) + 1);
338 strcpy(new->name, name);
339 new->wait_time_min = ULLONG_MAX;
341 list_add(&new->hash_entry, entry);
345 pr_err("memory allocation failed\n");
349 struct trace_lock_handler {
350 int (*acquire_event)(struct perf_evsel *evsel,
351 struct perf_sample *sample);
353 int (*acquired_event)(struct perf_evsel *evsel,
354 struct perf_sample *sample);
356 int (*contended_event)(struct perf_evsel *evsel,
357 struct perf_sample *sample);
359 int (*release_event)(struct perf_evsel *evsel,
360 struct perf_sample *sample);
363 static struct lock_seq_stat *get_seq(struct thread_stat *ts, void *addr)
365 struct lock_seq_stat *seq;
367 list_for_each_entry(seq, &ts->seq_list, list) {
368 if (seq->addr == addr)
372 seq = zalloc(sizeof(struct lock_seq_stat));
374 pr_err("memory allocation failed\n");
377 seq->state = SEQ_STATE_UNINITIALIZED;
380 list_add(&seq->list, &ts->seq_list);
392 static int bad_hist[BROKEN_MAX];
399 static int report_lock_acquire_event(struct perf_evsel *evsel,
400 struct perf_sample *sample)
403 struct lock_stat *ls;
404 struct thread_stat *ts;
405 struct lock_seq_stat *seq;
406 const char *name = perf_evsel__strval(evsel, sample, "name");
407 u64 tmp = perf_evsel__intval(evsel, sample, "lockdep_addr");
408 int flag = perf_evsel__intval(evsel, sample, "flag");
410 memcpy(&addr, &tmp, sizeof(void *));
412 ls = lock_stat_findnew(addr, name);
418 ts = thread_stat_findnew(sample->tid);
422 seq = get_seq(ts, addr);
426 switch (seq->state) {
427 case SEQ_STATE_UNINITIALIZED:
428 case SEQ_STATE_RELEASED:
430 seq->state = SEQ_STATE_ACQUIRING;
434 if (flag & READ_LOCK)
436 seq->state = SEQ_STATE_READ_ACQUIRED;
441 case SEQ_STATE_READ_ACQUIRED:
442 if (flag & READ_LOCK) {
450 case SEQ_STATE_ACQUIRED:
451 case SEQ_STATE_ACQUIRING:
452 case SEQ_STATE_CONTENDED:
454 /* broken lock sequence, discard it */
456 bad_hist[BROKEN_ACQUIRE]++;
457 list_del(&seq->list);
461 BUG_ON("Unknown state of lock sequence found!\n");
466 seq->prev_event_time = sample->time;
471 static int report_lock_acquired_event(struct perf_evsel *evsel,
472 struct perf_sample *sample)
475 struct lock_stat *ls;
476 struct thread_stat *ts;
477 struct lock_seq_stat *seq;
479 const char *name = perf_evsel__strval(evsel, sample, "name");
480 u64 tmp = perf_evsel__intval(evsel, sample, "lockdep_addr");
482 memcpy(&addr, &tmp, sizeof(void *));
484 ls = lock_stat_findnew(addr, name);
490 ts = thread_stat_findnew(sample->tid);
494 seq = get_seq(ts, addr);
498 switch (seq->state) {
499 case SEQ_STATE_UNINITIALIZED:
500 /* orphan event, do nothing */
502 case SEQ_STATE_ACQUIRING:
504 case SEQ_STATE_CONTENDED:
505 contended_term = sample->time - seq->prev_event_time;
506 ls->wait_time_total += contended_term;
507 if (contended_term < ls->wait_time_min)
508 ls->wait_time_min = contended_term;
509 if (ls->wait_time_max < contended_term)
510 ls->wait_time_max = contended_term;
512 case SEQ_STATE_RELEASED:
513 case SEQ_STATE_ACQUIRED:
514 case SEQ_STATE_READ_ACQUIRED:
515 /* broken lock sequence, discard it */
517 bad_hist[BROKEN_ACQUIRED]++;
518 list_del(&seq->list);
522 BUG_ON("Unknown state of lock sequence found!\n");
526 seq->state = SEQ_STATE_ACQUIRED;
528 ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
529 seq->prev_event_time = sample->time;
534 static int report_lock_contended_event(struct perf_evsel *evsel,
535 struct perf_sample *sample)
538 struct lock_stat *ls;
539 struct thread_stat *ts;
540 struct lock_seq_stat *seq;
541 const char *name = perf_evsel__strval(evsel, sample, "name");
542 u64 tmp = perf_evsel__intval(evsel, sample, "lockdep_addr");
544 memcpy(&addr, &tmp, sizeof(void *));
546 ls = lock_stat_findnew(addr, name);
552 ts = thread_stat_findnew(sample->tid);
556 seq = get_seq(ts, addr);
560 switch (seq->state) {
561 case SEQ_STATE_UNINITIALIZED:
562 /* orphan event, do nothing */
564 case SEQ_STATE_ACQUIRING:
566 case SEQ_STATE_RELEASED:
567 case SEQ_STATE_ACQUIRED:
568 case SEQ_STATE_READ_ACQUIRED:
569 case SEQ_STATE_CONTENDED:
570 /* broken lock sequence, discard it */
572 bad_hist[BROKEN_CONTENDED]++;
573 list_del(&seq->list);
577 BUG_ON("Unknown state of lock sequence found!\n");
581 seq->state = SEQ_STATE_CONTENDED;
583 ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
584 seq->prev_event_time = sample->time;
589 static int report_lock_release_event(struct perf_evsel *evsel,
590 struct perf_sample *sample)
593 struct lock_stat *ls;
594 struct thread_stat *ts;
595 struct lock_seq_stat *seq;
596 const char *name = perf_evsel__strval(evsel, sample, "name");
597 u64 tmp = perf_evsel__intval(evsel, sample, "lockdep_addr");
599 memcpy(&addr, &tmp, sizeof(void *));
601 ls = lock_stat_findnew(addr, name);
607 ts = thread_stat_findnew(sample->tid);
611 seq = get_seq(ts, addr);
615 switch (seq->state) {
616 case SEQ_STATE_UNINITIALIZED:
618 case SEQ_STATE_ACQUIRED:
620 case SEQ_STATE_READ_ACQUIRED:
622 BUG_ON(seq->read_count < 0);
623 if (seq->read_count) {
628 case SEQ_STATE_ACQUIRING:
629 case SEQ_STATE_CONTENDED:
630 case SEQ_STATE_RELEASED:
631 /* broken lock sequence, discard it */
633 bad_hist[BROKEN_RELEASE]++;
636 BUG_ON("Unknown state of lock sequence found!\n");
642 list_del(&seq->list);
648 /* lock oriented handlers */
649 /* TODO: handlers for CPU oriented, thread oriented */
650 static struct trace_lock_handler report_lock_ops = {
651 .acquire_event = report_lock_acquire_event,
652 .acquired_event = report_lock_acquired_event,
653 .contended_event = report_lock_contended_event,
654 .release_event = report_lock_release_event,
657 static struct trace_lock_handler *trace_handler;
659 static int perf_evsel__process_lock_acquire(struct perf_evsel *evsel,
660 struct perf_sample *sample)
662 if (trace_handler->acquire_event)
663 return trace_handler->acquire_event(evsel, sample);
667 static int perf_evsel__process_lock_acquired(struct perf_evsel *evsel,
668 struct perf_sample *sample)
670 if (trace_handler->acquired_event)
671 return trace_handler->acquired_event(evsel, sample);
675 static int perf_evsel__process_lock_contended(struct perf_evsel *evsel,
676 struct perf_sample *sample)
678 if (trace_handler->contended_event)
679 return trace_handler->contended_event(evsel, sample);
683 static int perf_evsel__process_lock_release(struct perf_evsel *evsel,
684 struct perf_sample *sample)
686 if (trace_handler->release_event)
687 return trace_handler->release_event(evsel, sample);
691 static void print_bad_events(int bad, int total)
693 /* Output for debug, this have to be removed */
695 const char *name[4] =
696 { "acquire", "acquired", "contended", "release" };
698 pr_info("\n=== output for debug===\n\n");
699 pr_info("bad: %d, total: %d\n", bad, total);
700 pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
701 pr_info("histogram of events caused bad sequence\n");
702 for (i = 0; i < BROKEN_MAX; i++)
703 pr_info(" %10s: %d\n", name[i], bad_hist[i]);
706 /* TODO: various way to print, coloring, nano or milli sec */
707 static void print_result(void)
709 struct lock_stat *st;
713 pr_info("%20s ", "Name");
714 pr_info("%10s ", "acquired");
715 pr_info("%10s ", "contended");
717 pr_info("%15s ", "avg wait (ns)");
718 pr_info("%15s ", "total wait (ns)");
719 pr_info("%15s ", "max wait (ns)");
720 pr_info("%15s ", "min wait (ns)");
725 while ((st = pop_from_result())) {
733 if (strlen(st->name) < 16) {
734 /* output raw name */
735 pr_info("%20s ", st->name);
737 strncpy(cut_name, st->name, 16);
742 /* cut off name for saving output style */
743 pr_info("%20s ", cut_name);
746 pr_info("%10u ", st->nr_acquired);
747 pr_info("%10u ", st->nr_contended);
749 pr_info("%15" PRIu64 " ", st->avg_wait_time);
750 pr_info("%15" PRIu64 " ", st->wait_time_total);
751 pr_info("%15" PRIu64 " ", st->wait_time_max);
752 pr_info("%15" PRIu64 " ", st->wait_time_min == ULLONG_MAX ?
753 0 : st->wait_time_min);
757 print_bad_events(bad, total);
760 static bool info_threads, info_map;
762 static void dump_threads(void)
764 struct thread_stat *st;
765 struct rb_node *node;
768 pr_info("%10s: comm\n", "Thread ID");
770 node = rb_first(&thread_stats);
772 st = container_of(node, struct thread_stat, rb);
773 t = perf_session__findnew(session, st->tid);
774 pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
775 node = rb_next(node);
780 static void dump_map(void)
783 struct lock_stat *st;
785 pr_info("Address of instance: name of class\n");
786 for (i = 0; i < LOCKHASH_SIZE; i++) {
787 list_for_each_entry(st, &lockhash_table[i], hash_entry) {
788 pr_info(" %p: %s\n", st->addr, st->name);
793 static int dump_info(void)
803 pr_err("Unknown type of information\n");
809 typedef int (*tracepoint_handler)(struct perf_evsel *evsel,
810 struct perf_sample *sample);
812 static int process_sample_event(struct perf_tool *tool __maybe_unused,
813 union perf_event *event,
814 struct perf_sample *sample,
815 struct perf_evsel *evsel,
816 struct machine *machine)
819 struct thread *thread = machine__findnew_thread(machine, sample->pid,
822 if (thread == NULL) {
823 pr_debug("problem processing %d event, skipping it.\n",
828 if (evsel->handler != NULL) {
829 tracepoint_handler f = evsel->handler;
830 err = f(evsel, sample);
838 static void sort_result(void)
841 struct lock_stat *st;
843 for (i = 0; i < LOCKHASH_SIZE; i++) {
844 list_for_each_entry(st, &lockhash_table[i], hash_entry) {
845 insert_to_result(st, compare);
850 static const struct perf_evsel_str_handler lock_tracepoints[] = {
851 { "lock:lock_acquire", perf_evsel__process_lock_acquire, }, /* CONFIG_LOCKDEP */
852 { "lock:lock_acquired", perf_evsel__process_lock_acquired, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
853 { "lock:lock_contended", perf_evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
854 { "lock:lock_release", perf_evsel__process_lock_release, }, /* CONFIG_LOCKDEP */
859 static int __cmd_report(bool display_info)
862 struct perf_tool eops = {
863 .sample = process_sample_event,
864 .comm = perf_event__process_comm,
865 .namespaces = perf_event__process_namespaces,
866 .ordered_events = true,
868 struct perf_data data = {
872 .mode = PERF_DATA_MODE_READ,
876 session = perf_session__new(&data, false, &eops);
878 pr_err("Initializing perf session failed\n");
882 symbol__init(&session->header.env);
884 if (!perf_session__has_traces(session, "lock record"))
887 if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
888 pr_err("Initializing perf session tracepoint handlers failed\n");
895 err = perf_session__process_events(session);
900 if (display_info) /* used for info subcommand */
908 perf_session__delete(session);
912 static int __cmd_record(int argc, const char **argv)
914 const char *record_args[] = {
915 "record", "-R", "-m", "1024", "-c", "1",
917 unsigned int rec_argc, i, j, ret;
918 const char **rec_argv;
920 for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
921 if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
922 pr_err("tracepoint %s is not enabled. "
923 "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
924 lock_tracepoints[i].name);
929 rec_argc = ARRAY_SIZE(record_args) + argc - 1;
930 /* factor of 2 is for -e in front of each tracepoint */
931 rec_argc += 2 * ARRAY_SIZE(lock_tracepoints);
933 rec_argv = calloc(rec_argc + 1, sizeof(char *));
937 for (i = 0; i < ARRAY_SIZE(record_args); i++)
938 rec_argv[i] = strdup(record_args[i]);
940 for (j = 0; j < ARRAY_SIZE(lock_tracepoints); j++) {
941 rec_argv[i++] = "-e";
942 rec_argv[i++] = strdup(lock_tracepoints[j].name);
945 for (j = 1; j < (unsigned int)argc; j++, i++)
946 rec_argv[i] = argv[j];
948 BUG_ON(i != rec_argc);
950 ret = cmd_record(i, rec_argv);
955 int cmd_lock(int argc, const char **argv)
957 const struct option lock_options[] = {
958 OPT_STRING('i', "input", &input_name, "file", "input file name"),
959 OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
960 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
961 OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
965 const struct option info_options[] = {
966 OPT_BOOLEAN('t', "threads", &info_threads,
967 "dump thread list in perf.data"),
968 OPT_BOOLEAN('m', "map", &info_map,
969 "map of lock instances (address:name table)"),
970 OPT_PARENT(lock_options)
973 const struct option report_options[] = {
974 OPT_STRING('k', "key", &sort_key, "acquired",
975 "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
977 OPT_PARENT(lock_options)
980 const char * const info_usage[] = {
981 "perf lock info [<options>]",
984 const char *const lock_subcommands[] = { "record", "report", "script",
986 const char *lock_usage[] = {
990 const char * const report_usage[] = {
991 "perf lock report [<options>]",
997 for (i = 0; i < LOCKHASH_SIZE; i++)
998 INIT_LIST_HEAD(lockhash_table + i);
1000 argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
1001 lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
1003 usage_with_options(lock_usage, lock_options);
1005 if (!strncmp(argv[0], "rec", 3)) {
1006 return __cmd_record(argc, argv);
1007 } else if (!strncmp(argv[0], "report", 6)) {
1008 trace_handler = &report_lock_ops;
1010 argc = parse_options(argc, argv,
1011 report_options, report_usage, 0);
1013 usage_with_options(report_usage, report_options);
1015 rc = __cmd_report(false);
1016 } else if (!strcmp(argv[0], "script")) {
1017 /* Aliased to 'perf script' */
1018 return cmd_script(argc, argv);
1019 } else if (!strcmp(argv[0], "info")) {
1021 argc = parse_options(argc, argv,
1022 info_options, info_usage, 0);
1024 usage_with_options(info_usage, info_options);
1026 /* recycling report_lock_ops */
1027 trace_handler = &report_lock_ops;
1028 rc = __cmd_report(true);
1030 usage_with_options(lock_usage, lock_options);