Merge tag 'hyperv-fixes-signed-20221125' of git://git.kernel.org/pub/scm/linux/kernel...
[platform/kernel/linux-starfive.git] / tools / perf / builtin-lock.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <inttypes.h>
4 #include "builtin.h"
5 #include "perf.h"
6
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
16 #include <subcmd/pager.h>
17 #include <subcmd/parse-options.h>
18 #include "util/trace-event.h"
19 #include "util/tracepoint.h"
20
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"
26 #include "util/map.h"
27
28 #include <sys/types.h>
29 #include <sys/prctl.h>
30 #include <semaphore.h>
31 #include <math.h>
32 #include <limits.h>
33
34 #include <linux/list.h>
35 #include <linux/hash.h>
36 #include <linux/kernel.h>
37 #include <linux/zalloc.h>
38 #include <linux/err.h>
39 #include <linux/stringify.h>
40
41 static struct perf_session *session;
42 static struct target target;
43
44 /* based on kernel/lockdep.c */
45 #define LOCKHASH_BITS           12
46 #define LOCKHASH_SIZE           (1UL << LOCKHASH_BITS)
47
48 static struct hlist_head lockhash_table[LOCKHASH_SIZE];
49
50 #define __lockhashfn(key)       hash_long((unsigned long)key, LOCKHASH_BITS)
51 #define lockhashentry(key)      (lockhash_table + __lockhashfn((key)))
52
53 static struct rb_root           thread_stats;
54
55 static bool combine_locks;
56 static bool show_thread_stats;
57 static bool use_bpf;
58 static unsigned long bpf_map_entries = 10240;
59 static int max_stack_depth = CONTENTION_STACK_DEPTH;
60 static int stack_skip = CONTENTION_STACK_SKIP;
61 static int print_nr_entries = INT_MAX / 2;
62
63 static enum {
64         LOCK_AGGR_ADDR,
65         LOCK_AGGR_TASK,
66         LOCK_AGGR_CALLER,
67 } aggr_mode = LOCK_AGGR_ADDR;
68
69 static u64 sched_text_start;
70 static u64 sched_text_end;
71 static u64 lock_text_start;
72 static u64 lock_text_end;
73
74 static struct thread_stat *thread_stat_find(u32 tid)
75 {
76         struct rb_node *node;
77         struct thread_stat *st;
78
79         node = thread_stats.rb_node;
80         while (node) {
81                 st = container_of(node, struct thread_stat, rb);
82                 if (st->tid == tid)
83                         return st;
84                 else if (tid < st->tid)
85                         node = node->rb_left;
86                 else
87                         node = node->rb_right;
88         }
89
90         return NULL;
91 }
92
93 static void thread_stat_insert(struct thread_stat *new)
94 {
95         struct rb_node **rb = &thread_stats.rb_node;
96         struct rb_node *parent = NULL;
97         struct thread_stat *p;
98
99         while (*rb) {
100                 p = container_of(*rb, struct thread_stat, rb);
101                 parent = *rb;
102
103                 if (new->tid < p->tid)
104                         rb = &(*rb)->rb_left;
105                 else if (new->tid > p->tid)
106                         rb = &(*rb)->rb_right;
107                 else
108                         BUG_ON("inserting invalid thread_stat\n");
109         }
110
111         rb_link_node(&new->rb, parent, rb);
112         rb_insert_color(&new->rb, &thread_stats);
113 }
114
115 static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
116 {
117         struct thread_stat *st;
118
119         st = thread_stat_find(tid);
120         if (st)
121                 return st;
122
123         st = zalloc(sizeof(struct thread_stat));
124         if (!st) {
125                 pr_err("memory allocation failed\n");
126                 return NULL;
127         }
128
129         st->tid = tid;
130         INIT_LIST_HEAD(&st->seq_list);
131
132         thread_stat_insert(st);
133
134         return st;
135 }
136
137 static struct thread_stat *thread_stat_findnew_first(u32 tid);
138 static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
139         thread_stat_findnew_first;
140
141 static struct thread_stat *thread_stat_findnew_first(u32 tid)
142 {
143         struct thread_stat *st;
144
145         st = zalloc(sizeof(struct thread_stat));
146         if (!st) {
147                 pr_err("memory allocation failed\n");
148                 return NULL;
149         }
150         st->tid = tid;
151         INIT_LIST_HEAD(&st->seq_list);
152
153         rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
154         rb_insert_color(&st->rb, &thread_stats);
155
156         thread_stat_findnew = thread_stat_findnew_after_first;
157         return st;
158 }
159
160 /* build simple key function one is bigger than two */
161 #define SINGLE_KEY(member)                                              \
162         static int lock_stat_key_ ## member(struct lock_stat *one,      \
163                                          struct lock_stat *two)         \
164         {                                                               \
165                 return one->member > two->member;                       \
166         }
167
168 SINGLE_KEY(nr_acquired)
169 SINGLE_KEY(nr_contended)
170 SINGLE_KEY(avg_wait_time)
171 SINGLE_KEY(wait_time_total)
172 SINGLE_KEY(wait_time_max)
173
174 static int lock_stat_key_wait_time_min(struct lock_stat *one,
175                                         struct lock_stat *two)
176 {
177         u64 s1 = one->wait_time_min;
178         u64 s2 = two->wait_time_min;
179         if (s1 == ULLONG_MAX)
180                 s1 = 0;
181         if (s2 == ULLONG_MAX)
182                 s2 = 0;
183         return s1 > s2;
184 }
185
186 struct lock_key {
187         /*
188          * name: the value for specify by user
189          * this should be simpler than raw name of member
190          * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
191          */
192         const char              *name;
193         /* header: the string printed on the header line */
194         const char              *header;
195         /* len: the printing width of the field */
196         int                     len;
197         /* key: a pointer to function to compare two lock stats for sorting */
198         int                     (*key)(struct lock_stat*, struct lock_stat*);
199         /* print: a pointer to function to print a given lock stats */
200         void                    (*print)(struct lock_key*, struct lock_stat*);
201         /* list: list entry to link this */
202         struct list_head        list;
203 };
204
205 static void lock_stat_key_print_time(unsigned long long nsec, int len)
206 {
207         static const struct {
208                 float base;
209                 const char *unit;
210         } table[] = {
211                 { 1e9 * 3600, "h " },
212                 { 1e9 * 60, "m " },
213                 { 1e9, "s " },
214                 { 1e6, "ms" },
215                 { 1e3, "us" },
216                 { 0, NULL },
217         };
218
219         for (int i = 0; table[i].unit; i++) {
220                 if (nsec < table[i].base)
221                         continue;
222
223                 pr_info("%*.2f %s", len - 3, nsec / table[i].base, table[i].unit);
224                 return;
225         }
226
227         pr_info("%*llu %s", len - 3, nsec, "ns");
228 }
229
230 #define PRINT_KEY(member)                                               \
231 static void lock_stat_key_print_ ## member(struct lock_key *key,        \
232                                            struct lock_stat *ls)        \
233 {                                                                       \
234         pr_info("%*llu", key->len, (unsigned long long)ls->member);     \
235 }
236
237 #define PRINT_TIME(member)                                              \
238 static void lock_stat_key_print_ ## member(struct lock_key *key,        \
239                                            struct lock_stat *ls)        \
240 {                                                                       \
241         lock_stat_key_print_time((unsigned long long)ls->member, key->len);     \
242 }
243
244 PRINT_KEY(nr_acquired)
245 PRINT_KEY(nr_contended)
246 PRINT_TIME(avg_wait_time)
247 PRINT_TIME(wait_time_total)
248 PRINT_TIME(wait_time_max)
249
250 static void lock_stat_key_print_wait_time_min(struct lock_key *key,
251                                               struct lock_stat *ls)
252 {
253         u64 wait_time = ls->wait_time_min;
254
255         if (wait_time == ULLONG_MAX)
256                 wait_time = 0;
257
258         lock_stat_key_print_time(wait_time, key->len);
259 }
260
261
262 static const char               *sort_key = "acquired";
263
264 static int                      (*compare)(struct lock_stat *, struct lock_stat *);
265
266 static struct rb_root           sorted; /* place to store intermediate data */
267 static struct rb_root           result; /* place to store sorted data */
268
269 static LIST_HEAD(lock_keys);
270 static const char               *output_fields;
271
272 #define DEF_KEY_LOCK(name, header, fn_suffix, len)                      \
273         { #name, header, len, lock_stat_key_ ## fn_suffix, lock_stat_key_print_ ## fn_suffix, {} }
274 static struct lock_key report_keys[] = {
275         DEF_KEY_LOCK(acquired, "acquired", nr_acquired, 10),
276         DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
277         DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
278         DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
279         DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
280         DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
281
282         /* extra comparisons much complicated should be here */
283         { }
284 };
285
286 static struct lock_key contention_keys[] = {
287         DEF_KEY_LOCK(contended, "contended", nr_contended, 10),
288         DEF_KEY_LOCK(wait_total, "total wait", wait_time_total, 12),
289         DEF_KEY_LOCK(wait_max, "max wait", wait_time_max, 12),
290         DEF_KEY_LOCK(wait_min, "min wait", wait_time_min, 12),
291         DEF_KEY_LOCK(avg_wait, "avg wait", avg_wait_time, 12),
292
293         /* extra comparisons much complicated should be here */
294         { }
295 };
296
297 static int select_key(bool contention)
298 {
299         int i;
300         struct lock_key *keys = report_keys;
301
302         if (contention)
303                 keys = contention_keys;
304
305         for (i = 0; keys[i].name; i++) {
306                 if (!strcmp(keys[i].name, sort_key)) {
307                         compare = keys[i].key;
308
309                         /* selected key should be in the output fields */
310                         if (list_empty(&keys[i].list))
311                                 list_add_tail(&keys[i].list, &lock_keys);
312
313                         return 0;
314                 }
315         }
316
317         pr_err("Unknown compare key: %s\n", sort_key);
318         return -1;
319 }
320
321 static int add_output_field(bool contention, char *name)
322 {
323         int i;
324         struct lock_key *keys = report_keys;
325
326         if (contention)
327                 keys = contention_keys;
328
329         for (i = 0; keys[i].name; i++) {
330                 if (strcmp(keys[i].name, name))
331                         continue;
332
333                 /* prevent double link */
334                 if (list_empty(&keys[i].list))
335                         list_add_tail(&keys[i].list, &lock_keys);
336
337                 return 0;
338         }
339
340         pr_err("Unknown output field: %s\n", name);
341         return -1;
342 }
343
344 static int setup_output_field(bool contention, const char *str)
345 {
346         char *tok, *tmp, *orig;
347         int i, ret = 0;
348         struct lock_key *keys = report_keys;
349
350         if (contention)
351                 keys = contention_keys;
352
353         /* no output field given: use all of them */
354         if (str == NULL) {
355                 for (i = 0; keys[i].name; i++)
356                         list_add_tail(&keys[i].list, &lock_keys);
357                 return 0;
358         }
359
360         for (i = 0; keys[i].name; i++)
361                 INIT_LIST_HEAD(&keys[i].list);
362
363         orig = tmp = strdup(str);
364         if (orig == NULL)
365                 return -ENOMEM;
366
367         while ((tok = strsep(&tmp, ",")) != NULL){
368                 ret = add_output_field(contention, tok);
369                 if (ret < 0)
370                         break;
371         }
372         free(orig);
373
374         return ret;
375 }
376
377 static void combine_lock_stats(struct lock_stat *st)
378 {
379         struct rb_node **rb = &sorted.rb_node;
380         struct rb_node *parent = NULL;
381         struct lock_stat *p;
382         int ret;
383
384         while (*rb) {
385                 p = container_of(*rb, struct lock_stat, rb);
386                 parent = *rb;
387
388                 if (st->name && p->name)
389                         ret = strcmp(st->name, p->name);
390                 else
391                         ret = !!st->name - !!p->name;
392
393                 if (ret == 0) {
394                         p->nr_acquired += st->nr_acquired;
395                         p->nr_contended += st->nr_contended;
396                         p->wait_time_total += st->wait_time_total;
397
398                         if (p->nr_contended)
399                                 p->avg_wait_time = p->wait_time_total / p->nr_contended;
400
401                         if (p->wait_time_min > st->wait_time_min)
402                                 p->wait_time_min = st->wait_time_min;
403                         if (p->wait_time_max < st->wait_time_max)
404                                 p->wait_time_max = st->wait_time_max;
405
406                         p->broken |= st->broken;
407                         st->combined = 1;
408                         return;
409                 }
410
411                 if (ret < 0)
412                         rb = &(*rb)->rb_left;
413                 else
414                         rb = &(*rb)->rb_right;
415         }
416
417         rb_link_node(&st->rb, parent, rb);
418         rb_insert_color(&st->rb, &sorted);
419 }
420
421 static void insert_to_result(struct lock_stat *st,
422                              int (*bigger)(struct lock_stat *, struct lock_stat *))
423 {
424         struct rb_node **rb = &result.rb_node;
425         struct rb_node *parent = NULL;
426         struct lock_stat *p;
427
428         if (combine_locks && st->combined)
429                 return;
430
431         while (*rb) {
432                 p = container_of(*rb, struct lock_stat, rb);
433                 parent = *rb;
434
435                 if (bigger(st, p))
436                         rb = &(*rb)->rb_left;
437                 else
438                         rb = &(*rb)->rb_right;
439         }
440
441         rb_link_node(&st->rb, parent, rb);
442         rb_insert_color(&st->rb, &result);
443 }
444
445 /* returns left most element of result, and erase it */
446 static struct lock_stat *pop_from_result(void)
447 {
448         struct rb_node *node = result.rb_node;
449
450         if (!node)
451                 return NULL;
452
453         while (node->rb_left)
454                 node = node->rb_left;
455
456         rb_erase(node, &result);
457         return container_of(node, struct lock_stat, rb);
458 }
459
460 static struct lock_stat *lock_stat_find(u64 addr)
461 {
462         struct hlist_head *entry = lockhashentry(addr);
463         struct lock_stat *ret;
464
465         hlist_for_each_entry(ret, entry, hash_entry) {
466                 if (ret->addr == addr)
467                         return ret;
468         }
469         return NULL;
470 }
471
472 static struct lock_stat *lock_stat_findnew(u64 addr, const char *name, int flags)
473 {
474         struct hlist_head *entry = lockhashentry(addr);
475         struct lock_stat *ret, *new;
476
477         hlist_for_each_entry(ret, entry, hash_entry) {
478                 if (ret->addr == addr)
479                         return ret;
480         }
481
482         new = zalloc(sizeof(struct lock_stat));
483         if (!new)
484                 goto alloc_failed;
485
486         new->addr = addr;
487         new->name = strdup(name);
488         if (!new->name) {
489                 free(new);
490                 goto alloc_failed;
491         }
492
493         new->flags = flags;
494         new->wait_time_min = ULLONG_MAX;
495
496         hlist_add_head(&new->hash_entry, entry);
497         return new;
498
499 alloc_failed:
500         pr_err("memory allocation failed\n");
501         return NULL;
502 }
503
504 struct trace_lock_handler {
505         /* it's used on CONFIG_LOCKDEP */
506         int (*acquire_event)(struct evsel *evsel,
507                              struct perf_sample *sample);
508
509         /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
510         int (*acquired_event)(struct evsel *evsel,
511                               struct perf_sample *sample);
512
513         /* it's used on CONFIG_LOCKDEP && CONFIG_LOCK_STAT */
514         int (*contended_event)(struct evsel *evsel,
515                                struct perf_sample *sample);
516
517         /* it's used on CONFIG_LOCKDEP */
518         int (*release_event)(struct evsel *evsel,
519                              struct perf_sample *sample);
520
521         /* it's used when CONFIG_LOCKDEP is off */
522         int (*contention_begin_event)(struct evsel *evsel,
523                                       struct perf_sample *sample);
524
525         /* it's used when CONFIG_LOCKDEP is off */
526         int (*contention_end_event)(struct evsel *evsel,
527                                     struct perf_sample *sample);
528 };
529
530 static struct lock_seq_stat *get_seq(struct thread_stat *ts, u64 addr)
531 {
532         struct lock_seq_stat *seq;
533
534         list_for_each_entry(seq, &ts->seq_list, list) {
535                 if (seq->addr == addr)
536                         return seq;
537         }
538
539         seq = zalloc(sizeof(struct lock_seq_stat));
540         if (!seq) {
541                 pr_err("memory allocation failed\n");
542                 return NULL;
543         }
544         seq->state = SEQ_STATE_UNINITIALIZED;
545         seq->addr = addr;
546
547         list_add(&seq->list, &ts->seq_list);
548         return seq;
549 }
550
551 enum broken_state {
552         BROKEN_ACQUIRE,
553         BROKEN_ACQUIRED,
554         BROKEN_CONTENDED,
555         BROKEN_RELEASE,
556         BROKEN_MAX,
557 };
558
559 static int bad_hist[BROKEN_MAX];
560
561 enum acquire_flags {
562         TRY_LOCK = 1,
563         READ_LOCK = 2,
564 };
565
566 static int get_key_by_aggr_mode_simple(u64 *key, u64 addr, u32 tid)
567 {
568         switch (aggr_mode) {
569         case LOCK_AGGR_ADDR:
570                 *key = addr;
571                 break;
572         case LOCK_AGGR_TASK:
573                 *key = tid;
574                 break;
575         case LOCK_AGGR_CALLER:
576         default:
577                 pr_err("Invalid aggregation mode: %d\n", aggr_mode);
578                 return -EINVAL;
579         }
580         return 0;
581 }
582
583 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample);
584
585 static int get_key_by_aggr_mode(u64 *key, u64 addr, struct evsel *evsel,
586                                  struct perf_sample *sample)
587 {
588         if (aggr_mode == LOCK_AGGR_CALLER) {
589                 *key = callchain_id(evsel, sample);
590                 return 0;
591         }
592         return get_key_by_aggr_mode_simple(key, addr, sample->tid);
593 }
594
595 static int report_lock_acquire_event(struct evsel *evsel,
596                                      struct perf_sample *sample)
597 {
598         struct lock_stat *ls;
599         struct thread_stat *ts;
600         struct lock_seq_stat *seq;
601         const char *name = evsel__strval(evsel, sample, "name");
602         u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
603         int flag = evsel__intval(evsel, sample, "flags");
604         u64 key;
605         int ret;
606
607         ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
608         if (ret < 0)
609                 return ret;
610
611         ls = lock_stat_findnew(key, name, 0);
612         if (!ls)
613                 return -ENOMEM;
614
615         ts = thread_stat_findnew(sample->tid);
616         if (!ts)
617                 return -ENOMEM;
618
619         seq = get_seq(ts, addr);
620         if (!seq)
621                 return -ENOMEM;
622
623         switch (seq->state) {
624         case SEQ_STATE_UNINITIALIZED:
625         case SEQ_STATE_RELEASED:
626                 if (!flag) {
627                         seq->state = SEQ_STATE_ACQUIRING;
628                 } else {
629                         if (flag & TRY_LOCK)
630                                 ls->nr_trylock++;
631                         if (flag & READ_LOCK)
632                                 ls->nr_readlock++;
633                         seq->state = SEQ_STATE_READ_ACQUIRED;
634                         seq->read_count = 1;
635                         ls->nr_acquired++;
636                 }
637                 break;
638         case SEQ_STATE_READ_ACQUIRED:
639                 if (flag & READ_LOCK) {
640                         seq->read_count++;
641                         ls->nr_acquired++;
642                         goto end;
643                 } else {
644                         goto broken;
645                 }
646                 break;
647         case SEQ_STATE_ACQUIRED:
648         case SEQ_STATE_ACQUIRING:
649         case SEQ_STATE_CONTENDED:
650 broken:
651                 /* broken lock sequence */
652                 if (!ls->broken) {
653                         ls->broken = 1;
654                         bad_hist[BROKEN_ACQUIRE]++;
655                 }
656                 list_del_init(&seq->list);
657                 free(seq);
658                 goto end;
659         default:
660                 BUG_ON("Unknown state of lock sequence found!\n");
661                 break;
662         }
663
664         ls->nr_acquire++;
665         seq->prev_event_time = sample->time;
666 end:
667         return 0;
668 }
669
670 static int report_lock_acquired_event(struct evsel *evsel,
671                                       struct perf_sample *sample)
672 {
673         struct lock_stat *ls;
674         struct thread_stat *ts;
675         struct lock_seq_stat *seq;
676         u64 contended_term;
677         const char *name = evsel__strval(evsel, sample, "name");
678         u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
679         u64 key;
680         int ret;
681
682         ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
683         if (ret < 0)
684                 return ret;
685
686         ls = lock_stat_findnew(key, name, 0);
687         if (!ls)
688                 return -ENOMEM;
689
690         ts = thread_stat_findnew(sample->tid);
691         if (!ts)
692                 return -ENOMEM;
693
694         seq = get_seq(ts, addr);
695         if (!seq)
696                 return -ENOMEM;
697
698         switch (seq->state) {
699         case SEQ_STATE_UNINITIALIZED:
700                 /* orphan event, do nothing */
701                 return 0;
702         case SEQ_STATE_ACQUIRING:
703                 break;
704         case SEQ_STATE_CONTENDED:
705                 contended_term = sample->time - seq->prev_event_time;
706                 ls->wait_time_total += contended_term;
707                 if (contended_term < ls->wait_time_min)
708                         ls->wait_time_min = contended_term;
709                 if (ls->wait_time_max < contended_term)
710                         ls->wait_time_max = contended_term;
711                 break;
712         case SEQ_STATE_RELEASED:
713         case SEQ_STATE_ACQUIRED:
714         case SEQ_STATE_READ_ACQUIRED:
715                 /* broken lock sequence */
716                 if (!ls->broken) {
717                         ls->broken = 1;
718                         bad_hist[BROKEN_ACQUIRED]++;
719                 }
720                 list_del_init(&seq->list);
721                 free(seq);
722                 goto end;
723         default:
724                 BUG_ON("Unknown state of lock sequence found!\n");
725                 break;
726         }
727
728         seq->state = SEQ_STATE_ACQUIRED;
729         ls->nr_acquired++;
730         ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
731         seq->prev_event_time = sample->time;
732 end:
733         return 0;
734 }
735
736 static int report_lock_contended_event(struct evsel *evsel,
737                                        struct perf_sample *sample)
738 {
739         struct lock_stat *ls;
740         struct thread_stat *ts;
741         struct lock_seq_stat *seq;
742         const char *name = evsel__strval(evsel, sample, "name");
743         u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
744         u64 key;
745         int ret;
746
747         ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
748         if (ret < 0)
749                 return ret;
750
751         ls = lock_stat_findnew(key, name, 0);
752         if (!ls)
753                 return -ENOMEM;
754
755         ts = thread_stat_findnew(sample->tid);
756         if (!ts)
757                 return -ENOMEM;
758
759         seq = get_seq(ts, addr);
760         if (!seq)
761                 return -ENOMEM;
762
763         switch (seq->state) {
764         case SEQ_STATE_UNINITIALIZED:
765                 /* orphan event, do nothing */
766                 return 0;
767         case SEQ_STATE_ACQUIRING:
768                 break;
769         case SEQ_STATE_RELEASED:
770         case SEQ_STATE_ACQUIRED:
771         case SEQ_STATE_READ_ACQUIRED:
772         case SEQ_STATE_CONTENDED:
773                 /* broken lock sequence */
774                 if (!ls->broken) {
775                         ls->broken = 1;
776                         bad_hist[BROKEN_CONTENDED]++;
777                 }
778                 list_del_init(&seq->list);
779                 free(seq);
780                 goto end;
781         default:
782                 BUG_ON("Unknown state of lock sequence found!\n");
783                 break;
784         }
785
786         seq->state = SEQ_STATE_CONTENDED;
787         ls->nr_contended++;
788         ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
789         seq->prev_event_time = sample->time;
790 end:
791         return 0;
792 }
793
794 static int report_lock_release_event(struct evsel *evsel,
795                                      struct perf_sample *sample)
796 {
797         struct lock_stat *ls;
798         struct thread_stat *ts;
799         struct lock_seq_stat *seq;
800         const char *name = evsel__strval(evsel, sample, "name");
801         u64 addr = evsel__intval(evsel, sample, "lockdep_addr");
802         u64 key;
803         int ret;
804
805         ret = get_key_by_aggr_mode_simple(&key, addr, sample->tid);
806         if (ret < 0)
807                 return ret;
808
809         ls = lock_stat_findnew(key, name, 0);
810         if (!ls)
811                 return -ENOMEM;
812
813         ts = thread_stat_findnew(sample->tid);
814         if (!ts)
815                 return -ENOMEM;
816
817         seq = get_seq(ts, addr);
818         if (!seq)
819                 return -ENOMEM;
820
821         switch (seq->state) {
822         case SEQ_STATE_UNINITIALIZED:
823                 goto end;
824         case SEQ_STATE_ACQUIRED:
825                 break;
826         case SEQ_STATE_READ_ACQUIRED:
827                 seq->read_count--;
828                 BUG_ON(seq->read_count < 0);
829                 if (seq->read_count) {
830                         ls->nr_release++;
831                         goto end;
832                 }
833                 break;
834         case SEQ_STATE_ACQUIRING:
835         case SEQ_STATE_CONTENDED:
836         case SEQ_STATE_RELEASED:
837                 /* broken lock sequence */
838                 if (!ls->broken) {
839                         ls->broken = 1;
840                         bad_hist[BROKEN_RELEASE]++;
841                 }
842                 goto free_seq;
843         default:
844                 BUG_ON("Unknown state of lock sequence found!\n");
845                 break;
846         }
847
848         ls->nr_release++;
849 free_seq:
850         list_del_init(&seq->list);
851         free(seq);
852 end:
853         return 0;
854 }
855
856 bool is_lock_function(struct machine *machine, u64 addr)
857 {
858         if (!sched_text_start) {
859                 struct map *kmap;
860                 struct symbol *sym;
861
862                 sym = machine__find_kernel_symbol_by_name(machine,
863                                                           "__sched_text_start",
864                                                           &kmap);
865                 if (!sym) {
866                         /* to avoid retry */
867                         sched_text_start = 1;
868                         return false;
869                 }
870
871                 sched_text_start = kmap->unmap_ip(kmap, sym->start);
872
873                 /* should not fail from here */
874                 sym = machine__find_kernel_symbol_by_name(machine,
875                                                           "__sched_text_end",
876                                                           &kmap);
877                 sched_text_end = kmap->unmap_ip(kmap, sym->start);
878
879                 sym = machine__find_kernel_symbol_by_name(machine,
880                                                           "__lock_text_start",
881                                                           &kmap);
882                 lock_text_start = kmap->unmap_ip(kmap, sym->start);
883
884                 sym = machine__find_kernel_symbol_by_name(machine,
885                                                           "__lock_text_end",
886                                                           &kmap);
887                 lock_text_end = kmap->unmap_ip(kmap, sym->start);
888         }
889
890         /* failed to get kernel symbols */
891         if (sched_text_start == 1)
892                 return false;
893
894         /* mutex and rwsem functions are in sched text section */
895         if (sched_text_start <= addr && addr < sched_text_end)
896                 return true;
897
898         /* spinlock functions are in lock text section */
899         if (lock_text_start <= addr && addr < lock_text_end)
900                 return true;
901
902         return false;
903 }
904
905 static int get_symbol_name_offset(struct map *map, struct symbol *sym, u64 ip,
906                                   char *buf, int size)
907 {
908         u64 offset;
909
910         if (map == NULL || sym == NULL) {
911                 buf[0] = '\0';
912                 return 0;
913         }
914
915         offset = map->map_ip(map, ip) - sym->start;
916
917         if (offset)
918                 return scnprintf(buf, size, "%s+%#lx", sym->name, offset);
919         else
920                 return strlcpy(buf, sym->name, size);
921 }
922 static int lock_contention_caller(struct evsel *evsel, struct perf_sample *sample,
923                                   char *buf, int size)
924 {
925         struct thread *thread;
926         struct callchain_cursor *cursor = &callchain_cursor;
927         struct machine *machine = &session->machines.host;
928         struct symbol *sym;
929         int skip = 0;
930         int ret;
931
932         /* lock names will be replaced to task name later */
933         if (show_thread_stats)
934                 return -1;
935
936         thread = machine__findnew_thread(machine, -1, sample->pid);
937         if (thread == NULL)
938                 return -1;
939
940         /* use caller function name from the callchain */
941         ret = thread__resolve_callchain(thread, cursor, evsel, sample,
942                                         NULL, NULL, max_stack_depth);
943         if (ret != 0) {
944                 thread__put(thread);
945                 return -1;
946         }
947
948         callchain_cursor_commit(cursor);
949         thread__put(thread);
950
951         while (true) {
952                 struct callchain_cursor_node *node;
953
954                 node = callchain_cursor_current(cursor);
955                 if (node == NULL)
956                         break;
957
958                 /* skip first few entries - for lock functions */
959                 if (++skip <= stack_skip)
960                         goto next;
961
962                 sym = node->ms.sym;
963                 if (sym && !is_lock_function(machine, node->ip)) {
964                         get_symbol_name_offset(node->ms.map, sym, node->ip,
965                                                buf, size);
966                         return 0;
967                 }
968
969 next:
970                 callchain_cursor_advance(cursor);
971         }
972         return -1;
973 }
974
975 static u64 callchain_id(struct evsel *evsel, struct perf_sample *sample)
976 {
977         struct callchain_cursor *cursor = &callchain_cursor;
978         struct machine *machine = &session->machines.host;
979         struct thread *thread;
980         u64 hash = 0;
981         int skip = 0;
982         int ret;
983
984         thread = machine__findnew_thread(machine, -1, sample->pid);
985         if (thread == NULL)
986                 return -1;
987
988         /* use caller function name from the callchain */
989         ret = thread__resolve_callchain(thread, cursor, evsel, sample,
990                                         NULL, NULL, max_stack_depth);
991         thread__put(thread);
992
993         if (ret != 0)
994                 return -1;
995
996         callchain_cursor_commit(cursor);
997
998         while (true) {
999                 struct callchain_cursor_node *node;
1000
1001                 node = callchain_cursor_current(cursor);
1002                 if (node == NULL)
1003                         break;
1004
1005                 /* skip first few entries - for lock functions */
1006                 if (++skip <= stack_skip)
1007                         goto next;
1008
1009                 if (node->ms.sym && is_lock_function(machine, node->ip))
1010                         goto next;
1011
1012                 hash ^= hash_long((unsigned long)node->ip, 64);
1013
1014 next:
1015                 callchain_cursor_advance(cursor);
1016         }
1017         return hash;
1018 }
1019
1020 static u64 *get_callstack(struct perf_sample *sample, int max_stack)
1021 {
1022         u64 *callstack;
1023         u64 i;
1024         int c;
1025
1026         callstack = calloc(max_stack, sizeof(*callstack));
1027         if (callstack == NULL)
1028                 return NULL;
1029
1030         for (i = 0, c = 0; i < sample->callchain->nr && c < max_stack; i++) {
1031                 u64 ip = sample->callchain->ips[i];
1032
1033                 if (ip >= PERF_CONTEXT_MAX)
1034                         continue;
1035
1036                 callstack[c++] = ip;
1037         }
1038         return callstack;
1039 }
1040
1041 static int report_lock_contention_begin_event(struct evsel *evsel,
1042                                               struct perf_sample *sample)
1043 {
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         u64 key;
1049         int ret;
1050
1051         ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1052         if (ret < 0)
1053                 return ret;
1054
1055         ls = lock_stat_find(key);
1056         if (!ls) {
1057                 char buf[128];
1058                 const char *caller = buf;
1059                 unsigned int flags = evsel__intval(evsel, sample, "flags");
1060
1061                 if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
1062                         caller = "Unknown";
1063
1064                 ls = lock_stat_findnew(key, caller, flags);
1065                 if (!ls)
1066                         return -ENOMEM;
1067
1068                 if (aggr_mode == LOCK_AGGR_CALLER && verbose) {
1069                         ls->callstack = get_callstack(sample, max_stack_depth);
1070                         if (ls->callstack == NULL)
1071                                 return -ENOMEM;
1072                 }
1073         }
1074
1075         ts = thread_stat_findnew(sample->tid);
1076         if (!ts)
1077                 return -ENOMEM;
1078
1079         seq = get_seq(ts, addr);
1080         if (!seq)
1081                 return -ENOMEM;
1082
1083         switch (seq->state) {
1084         case SEQ_STATE_UNINITIALIZED:
1085         case SEQ_STATE_ACQUIRED:
1086                 break;
1087         case SEQ_STATE_CONTENDED:
1088                 /*
1089                  * It can have nested contention begin with mutex spinning,
1090                  * then we would use the original contention begin event and
1091                  * ignore the second one.
1092                  */
1093                 goto end;
1094         case SEQ_STATE_ACQUIRING:
1095         case SEQ_STATE_READ_ACQUIRED:
1096         case SEQ_STATE_RELEASED:
1097                 /* broken lock sequence */
1098                 if (!ls->broken) {
1099                         ls->broken = 1;
1100                         bad_hist[BROKEN_CONTENDED]++;
1101                 }
1102                 list_del_init(&seq->list);
1103                 free(seq);
1104                 goto end;
1105         default:
1106                 BUG_ON("Unknown state of lock sequence found!\n");
1107                 break;
1108         }
1109
1110         if (seq->state != SEQ_STATE_CONTENDED) {
1111                 seq->state = SEQ_STATE_CONTENDED;
1112                 seq->prev_event_time = sample->time;
1113                 ls->nr_contended++;
1114         }
1115 end:
1116         return 0;
1117 }
1118
1119 static int report_lock_contention_end_event(struct evsel *evsel,
1120                                             struct perf_sample *sample)
1121 {
1122         struct lock_stat *ls;
1123         struct thread_stat *ts;
1124         struct lock_seq_stat *seq;
1125         u64 contended_term;
1126         u64 addr = evsel__intval(evsel, sample, "lock_addr");
1127         u64 key;
1128         int ret;
1129
1130         ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
1131         if (ret < 0)
1132                 return ret;
1133
1134         ls = lock_stat_find(key);
1135         if (!ls)
1136                 return 0;
1137
1138         ts = thread_stat_find(sample->tid);
1139         if (!ts)
1140                 return 0;
1141
1142         seq = get_seq(ts, addr);
1143         if (!seq)
1144                 return -ENOMEM;
1145
1146         switch (seq->state) {
1147         case SEQ_STATE_UNINITIALIZED:
1148                 goto end;
1149         case SEQ_STATE_CONTENDED:
1150                 contended_term = sample->time - seq->prev_event_time;
1151                 ls->wait_time_total += contended_term;
1152                 if (contended_term < ls->wait_time_min)
1153                         ls->wait_time_min = contended_term;
1154                 if (ls->wait_time_max < contended_term)
1155                         ls->wait_time_max = contended_term;
1156                 break;
1157         case SEQ_STATE_ACQUIRING:
1158         case SEQ_STATE_ACQUIRED:
1159         case SEQ_STATE_READ_ACQUIRED:
1160         case SEQ_STATE_RELEASED:
1161                 /* broken lock sequence */
1162                 if (!ls->broken) {
1163                         ls->broken = 1;
1164                         bad_hist[BROKEN_ACQUIRED]++;
1165                 }
1166                 list_del_init(&seq->list);
1167                 free(seq);
1168                 goto end;
1169         default:
1170                 BUG_ON("Unknown state of lock sequence found!\n");
1171                 break;
1172         }
1173
1174         seq->state = SEQ_STATE_ACQUIRED;
1175         ls->nr_acquired++;
1176         ls->avg_wait_time = ls->wait_time_total/ls->nr_acquired;
1177 end:
1178         return 0;
1179 }
1180
1181 /* lock oriented handlers */
1182 /* TODO: handlers for CPU oriented, thread oriented */
1183 static struct trace_lock_handler report_lock_ops  = {
1184         .acquire_event          = report_lock_acquire_event,
1185         .acquired_event         = report_lock_acquired_event,
1186         .contended_event        = report_lock_contended_event,
1187         .release_event          = report_lock_release_event,
1188         .contention_begin_event = report_lock_contention_begin_event,
1189         .contention_end_event   = report_lock_contention_end_event,
1190 };
1191
1192 static struct trace_lock_handler contention_lock_ops  = {
1193         .contention_begin_event = report_lock_contention_begin_event,
1194         .contention_end_event   = report_lock_contention_end_event,
1195 };
1196
1197
1198 static struct trace_lock_handler *trace_handler;
1199
1200 static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
1201 {
1202         if (trace_handler->acquire_event)
1203                 return trace_handler->acquire_event(evsel, sample);
1204         return 0;
1205 }
1206
1207 static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
1208 {
1209         if (trace_handler->acquired_event)
1210                 return trace_handler->acquired_event(evsel, sample);
1211         return 0;
1212 }
1213
1214 static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
1215 {
1216         if (trace_handler->contended_event)
1217                 return trace_handler->contended_event(evsel, sample);
1218         return 0;
1219 }
1220
1221 static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
1222 {
1223         if (trace_handler->release_event)
1224                 return trace_handler->release_event(evsel, sample);
1225         return 0;
1226 }
1227
1228 static int evsel__process_contention_begin(struct evsel *evsel, struct perf_sample *sample)
1229 {
1230         if (trace_handler->contention_begin_event)
1231                 return trace_handler->contention_begin_event(evsel, sample);
1232         return 0;
1233 }
1234
1235 static int evsel__process_contention_end(struct evsel *evsel, struct perf_sample *sample)
1236 {
1237         if (trace_handler->contention_end_event)
1238                 return trace_handler->contention_end_event(evsel, sample);
1239         return 0;
1240 }
1241
1242 static void print_bad_events(int bad, int total)
1243 {
1244         /* Output for debug, this have to be removed */
1245         int i;
1246         int broken = 0;
1247         const char *name[4] =
1248                 { "acquire", "acquired", "contended", "release" };
1249
1250         for (i = 0; i < BROKEN_MAX; i++)
1251                 broken += bad_hist[i];
1252
1253         if (quiet || (broken == 0 && !verbose))
1254                 return;
1255
1256         pr_info("\n=== output for debug===\n\n");
1257         pr_info("bad: %d, total: %d\n", bad, total);
1258         pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
1259         pr_info("histogram of events caused bad sequence\n");
1260         for (i = 0; i < BROKEN_MAX; i++)
1261                 pr_info(" %10s: %d\n", name[i], bad_hist[i]);
1262 }
1263
1264 /* TODO: various way to print, coloring, nano or milli sec */
1265 static void print_result(void)
1266 {
1267         struct lock_stat *st;
1268         struct lock_key *key;
1269         char cut_name[20];
1270         int bad, total, printed;
1271
1272         if (!quiet) {
1273                 pr_info("%20s ", "Name");
1274                 list_for_each_entry(key, &lock_keys, list)
1275                         pr_info("%*s ", key->len, key->header);
1276                 pr_info("\n\n");
1277         }
1278
1279         bad = total = printed = 0;
1280         while ((st = pop_from_result())) {
1281                 total++;
1282                 if (st->broken)
1283                         bad++;
1284                 if (!st->nr_acquired)
1285                         continue;
1286
1287                 bzero(cut_name, 20);
1288
1289                 if (strlen(st->name) < 20) {
1290                         /* output raw name */
1291                         const char *name = st->name;
1292
1293                         if (show_thread_stats) {
1294                                 struct thread *t;
1295
1296                                 /* st->addr contains tid of thread */
1297                                 t = perf_session__findnew(session, st->addr);
1298                                 name = thread__comm_str(t);
1299                         }
1300
1301                         pr_info("%20s ", name);
1302                 } else {
1303                         strncpy(cut_name, st->name, 16);
1304                         cut_name[16] = '.';
1305                         cut_name[17] = '.';
1306                         cut_name[18] = '.';
1307                         cut_name[19] = '\0';
1308                         /* cut off name for saving output style */
1309                         pr_info("%20s ", cut_name);
1310                 }
1311
1312                 list_for_each_entry(key, &lock_keys, list) {
1313                         key->print(key, st);
1314                         pr_info(" ");
1315                 }
1316                 pr_info("\n");
1317
1318                 if (++printed >= print_nr_entries)
1319                         break;
1320         }
1321
1322         print_bad_events(bad, total);
1323 }
1324
1325 static bool info_threads, info_map;
1326
1327 static void dump_threads(void)
1328 {
1329         struct thread_stat *st;
1330         struct rb_node *node;
1331         struct thread *t;
1332
1333         pr_info("%10s: comm\n", "Thread ID");
1334
1335         node = rb_first(&thread_stats);
1336         while (node) {
1337                 st = container_of(node, struct thread_stat, rb);
1338                 t = perf_session__findnew(session, st->tid);
1339                 pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
1340                 node = rb_next(node);
1341                 thread__put(t);
1342         }
1343 }
1344
1345 static int compare_maps(struct lock_stat *a, struct lock_stat *b)
1346 {
1347         int ret;
1348
1349         if (a->name && b->name)
1350                 ret = strcmp(a->name, b->name);
1351         else
1352                 ret = !!a->name - !!b->name;
1353
1354         if (!ret)
1355                 return a->addr < b->addr;
1356         else
1357                 return ret < 0;
1358 }
1359
1360 static void dump_map(void)
1361 {
1362         unsigned int i;
1363         struct lock_stat *st;
1364
1365         pr_info("Address of instance: name of class\n");
1366         for (i = 0; i < LOCKHASH_SIZE; i++) {
1367                 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1368                         insert_to_result(st, compare_maps);
1369                 }
1370         }
1371
1372         while ((st = pop_from_result()))
1373                 pr_info(" %#llx: %s\n", (unsigned long long)st->addr, st->name);
1374 }
1375
1376 static int dump_info(void)
1377 {
1378         int rc = 0;
1379
1380         if (info_threads)
1381                 dump_threads();
1382         else if (info_map)
1383                 dump_map();
1384         else {
1385                 rc = -1;
1386                 pr_err("Unknown type of information\n");
1387         }
1388
1389         return rc;
1390 }
1391
1392 typedef int (*tracepoint_handler)(struct evsel *evsel,
1393                                   struct perf_sample *sample);
1394
1395 static int process_sample_event(struct perf_tool *tool __maybe_unused,
1396                                 union perf_event *event,
1397                                 struct perf_sample *sample,
1398                                 struct evsel *evsel,
1399                                 struct machine *machine)
1400 {
1401         int err = 0;
1402         struct thread *thread = machine__findnew_thread(machine, sample->pid,
1403                                                         sample->tid);
1404
1405         if (thread == NULL) {
1406                 pr_debug("problem processing %d event, skipping it.\n",
1407                         event->header.type);
1408                 return -1;
1409         }
1410
1411         if (evsel->handler != NULL) {
1412                 tracepoint_handler f = evsel->handler;
1413                 err = f(evsel, sample);
1414         }
1415
1416         thread__put(thread);
1417
1418         return err;
1419 }
1420
1421 static void combine_result(void)
1422 {
1423         unsigned int i;
1424         struct lock_stat *st;
1425
1426         if (!combine_locks)
1427                 return;
1428
1429         for (i = 0; i < LOCKHASH_SIZE; i++) {
1430                 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1431                         combine_lock_stats(st);
1432                 }
1433         }
1434 }
1435
1436 static void sort_result(void)
1437 {
1438         unsigned int i;
1439         struct lock_stat *st;
1440
1441         for (i = 0; i < LOCKHASH_SIZE; i++) {
1442                 hlist_for_each_entry(st, &lockhash_table[i], hash_entry) {
1443                         insert_to_result(st, compare);
1444                 }
1445         }
1446 }
1447
1448 static const char *get_type_str(struct lock_stat *st)
1449 {
1450         static const struct {
1451                 unsigned int flags;
1452                 const char *name;
1453         } table[] = {
1454                 { 0,                            "semaphore" },
1455                 { LCB_F_SPIN,                   "spinlock" },
1456                 { LCB_F_SPIN | LCB_F_READ,      "rwlock:R" },
1457                 { LCB_F_SPIN | LCB_F_WRITE,     "rwlock:W"},
1458                 { LCB_F_READ,                   "rwsem:R" },
1459                 { LCB_F_WRITE,                  "rwsem:W" },
1460                 { LCB_F_RT,                     "rtmutex" },
1461                 { LCB_F_RT | LCB_F_READ,        "rwlock-rt:R" },
1462                 { LCB_F_RT | LCB_F_WRITE,       "rwlock-rt:W"},
1463                 { LCB_F_PERCPU | LCB_F_READ,    "pcpu-sem:R" },
1464                 { LCB_F_PERCPU | LCB_F_WRITE,   "pcpu-sem:W" },
1465                 { LCB_F_MUTEX,                  "mutex" },
1466                 { LCB_F_MUTEX | LCB_F_SPIN,     "mutex" },
1467         };
1468
1469         for (unsigned int i = 0; i < ARRAY_SIZE(table); i++) {
1470                 if (table[i].flags == st->flags)
1471                         return table[i].name;
1472         }
1473         return "unknown";
1474 }
1475
1476 static void sort_contention_result(void)
1477 {
1478         sort_result();
1479 }
1480
1481 static void print_contention_result(struct lock_contention *con)
1482 {
1483         struct lock_stat *st;
1484         struct lock_key *key;
1485         int bad, total, printed;
1486
1487         if (!quiet) {
1488                 list_for_each_entry(key, &lock_keys, list)
1489                         pr_info("%*s ", key->len, key->header);
1490
1491                 if (show_thread_stats)
1492                         pr_info("  %10s   %s\n\n", "pid", "comm");
1493                 else
1494                         pr_info("  %10s   %s\n\n", "type", "caller");
1495         }
1496
1497         bad = total = printed = 0;
1498         if (use_bpf)
1499                 bad = bad_hist[BROKEN_CONTENDED];
1500
1501         while ((st = pop_from_result())) {
1502                 total += use_bpf ? st->nr_contended : 1;
1503                 if (st->broken)
1504                         bad++;
1505
1506                 list_for_each_entry(key, &lock_keys, list) {
1507                         key->print(key, st);
1508                         pr_info(" ");
1509                 }
1510
1511                 if (show_thread_stats) {
1512                         struct thread *t;
1513                         int pid = st->addr;
1514
1515                         /* st->addr contains tid of thread */
1516                         t = perf_session__findnew(session, pid);
1517                         pr_info("  %10d   %s\n", pid, thread__comm_str(t));
1518                         goto next;
1519                 }
1520
1521                 pr_info("  %10s   %s\n", get_type_str(st), st->name);
1522                 if (verbose) {
1523                         struct map *kmap;
1524                         struct symbol *sym;
1525                         char buf[128];
1526                         u64 ip;
1527
1528                         for (int i = 0; i < max_stack_depth; i++) {
1529                                 if (!st->callstack || !st->callstack[i])
1530                                         break;
1531
1532                                 ip = st->callstack[i];
1533                                 sym = machine__find_kernel_symbol(con->machine, ip, &kmap);
1534                                 get_symbol_name_offset(kmap, sym, ip, buf, sizeof(buf));
1535                                 pr_info("\t\t\t%#lx  %s\n", (unsigned long)ip, buf);
1536                         }
1537                 }
1538
1539 next:
1540                 if (++printed >= print_nr_entries)
1541                         break;
1542         }
1543
1544         print_bad_events(bad, total);
1545 }
1546
1547 static const struct evsel_str_handler lock_tracepoints[] = {
1548         { "lock:lock_acquire",   evsel__process_lock_acquire,   }, /* CONFIG_LOCKDEP */
1549         { "lock:lock_acquired",  evsel__process_lock_acquired,  }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1550         { "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
1551         { "lock:lock_release",   evsel__process_lock_release,   }, /* CONFIG_LOCKDEP */
1552 };
1553
1554 static const struct evsel_str_handler contention_tracepoints[] = {
1555         { "lock:contention_begin", evsel__process_contention_begin, },
1556         { "lock:contention_end",   evsel__process_contention_end,   },
1557 };
1558
1559 static bool force;
1560
1561 static int __cmd_report(bool display_info)
1562 {
1563         int err = -EINVAL;
1564         struct perf_tool eops = {
1565                 .sample          = process_sample_event,
1566                 .comm            = perf_event__process_comm,
1567                 .mmap            = perf_event__process_mmap,
1568                 .namespaces      = perf_event__process_namespaces,
1569                 .ordered_events  = true,
1570         };
1571         struct perf_data data = {
1572                 .path  = input_name,
1573                 .mode  = PERF_DATA_MODE_READ,
1574                 .force = force,
1575         };
1576
1577         session = perf_session__new(&data, &eops);
1578         if (IS_ERR(session)) {
1579                 pr_err("Initializing perf session failed\n");
1580                 return PTR_ERR(session);
1581         }
1582
1583         /* for lock function check */
1584         symbol_conf.sort_by_name = true;
1585         symbol__init(&session->header.env);
1586
1587         if (!perf_session__has_traces(session, "lock record"))
1588                 goto out_delete;
1589
1590         if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
1591                 pr_err("Initializing perf session tracepoint handlers failed\n");
1592                 goto out_delete;
1593         }
1594
1595         if (perf_session__set_tracepoints_handlers(session, contention_tracepoints)) {
1596                 pr_err("Initializing perf session tracepoint handlers failed\n");
1597                 goto out_delete;
1598         }
1599
1600         if (setup_output_field(false, output_fields))
1601                 goto out_delete;
1602
1603         if (select_key(false))
1604                 goto out_delete;
1605
1606         if (show_thread_stats)
1607                 aggr_mode = LOCK_AGGR_TASK;
1608
1609         err = perf_session__process_events(session);
1610         if (err)
1611                 goto out_delete;
1612
1613         setup_pager();
1614         if (display_info) /* used for info subcommand */
1615                 err = dump_info();
1616         else {
1617                 combine_result();
1618                 sort_result();
1619                 print_result();
1620         }
1621
1622 out_delete:
1623         perf_session__delete(session);
1624         return err;
1625 }
1626
1627 static void sighandler(int sig __maybe_unused)
1628 {
1629 }
1630
1631 static int __cmd_contention(int argc, const char **argv)
1632 {
1633         int err = -EINVAL;
1634         struct perf_tool eops = {
1635                 .sample          = process_sample_event,
1636                 .comm            = perf_event__process_comm,
1637                 .mmap            = perf_event__process_mmap,
1638                 .ordered_events  = true,
1639         };
1640         struct perf_data data = {
1641                 .path  = input_name,
1642                 .mode  = PERF_DATA_MODE_READ,
1643                 .force = force,
1644         };
1645         struct lock_contention con = {
1646                 .target = &target,
1647                 .result = &lockhash_table[0],
1648                 .map_nr_entries = bpf_map_entries,
1649                 .max_stack = max_stack_depth,
1650                 .stack_skip = stack_skip,
1651         };
1652
1653         session = perf_session__new(use_bpf ? NULL : &data, &eops);
1654         if (IS_ERR(session)) {
1655                 pr_err("Initializing perf session failed\n");
1656                 return PTR_ERR(session);
1657         }
1658
1659         con.machine = &session->machines.host;
1660
1661         /* for lock function check */
1662         symbol_conf.sort_by_name = true;
1663         symbol__init(&session->header.env);
1664
1665         if (use_bpf) {
1666                 err = target__validate(&target);
1667                 if (err) {
1668                         char errbuf[512];
1669
1670                         target__strerror(&target, err, errbuf, 512);
1671                         pr_err("%s\n", errbuf);
1672                         goto out_delete;
1673                 }
1674
1675                 signal(SIGINT, sighandler);
1676                 signal(SIGCHLD, sighandler);
1677                 signal(SIGTERM, sighandler);
1678
1679                 con.evlist = evlist__new();
1680                 if (con.evlist == NULL) {
1681                         err = -ENOMEM;
1682                         goto out_delete;
1683                 }
1684
1685                 err = evlist__create_maps(con.evlist, &target);
1686                 if (err < 0)
1687                         goto out_delete;
1688
1689                 if (argc) {
1690                         err = evlist__prepare_workload(con.evlist, &target,
1691                                                        argv, false, NULL);
1692                         if (err < 0)
1693                                 goto out_delete;
1694                 }
1695
1696                 if (lock_contention_prepare(&con) < 0) {
1697                         pr_err("lock contention BPF setup failed\n");
1698                         goto out_delete;
1699                 }
1700         } else {
1701                 if (!perf_session__has_traces(session, "lock record"))
1702                         goto out_delete;
1703
1704                 if (!evlist__find_evsel_by_str(session->evlist,
1705                                                "lock:contention_begin")) {
1706                         pr_err("lock contention evsel not found\n");
1707                         goto out_delete;
1708                 }
1709
1710                 if (perf_session__set_tracepoints_handlers(session,
1711                                                 contention_tracepoints)) {
1712                         pr_err("Initializing perf session tracepoint handlers failed\n");
1713                         goto out_delete;
1714                 }
1715         }
1716
1717         if (setup_output_field(true, output_fields))
1718                 goto out_delete;
1719
1720         if (select_key(true))
1721                 goto out_delete;
1722
1723         if (show_thread_stats)
1724                 aggr_mode = LOCK_AGGR_TASK;
1725         else
1726                 aggr_mode = LOCK_AGGR_CALLER;
1727
1728         if (use_bpf) {
1729                 lock_contention_start();
1730                 if (argc)
1731                         evlist__start_workload(con.evlist);
1732
1733                 /* wait for signal */
1734                 pause();
1735
1736                 lock_contention_stop();
1737                 lock_contention_read(&con);
1738
1739                 /* abuse bad hist stats for lost entries */
1740                 bad_hist[BROKEN_CONTENDED] = con.lost;
1741         } else {
1742                 err = perf_session__process_events(session);
1743                 if (err)
1744                         goto out_delete;
1745         }
1746
1747         setup_pager();
1748
1749         sort_contention_result();
1750         print_contention_result(&con);
1751
1752 out_delete:
1753         evlist__delete(con.evlist);
1754         lock_contention_finish();
1755         perf_session__delete(session);
1756         return err;
1757 }
1758
1759
1760 static int __cmd_record(int argc, const char **argv)
1761 {
1762         const char *record_args[] = {
1763                 "record", "-R", "-m", "1024", "-c", "1", "--synth", "task",
1764         };
1765         const char *callgraph_args[] = {
1766                 "--call-graph", "fp," __stringify(CONTENTION_STACK_DEPTH),
1767         };
1768         unsigned int rec_argc, i, j, ret;
1769         unsigned int nr_tracepoints;
1770         unsigned int nr_callgraph_args = 0;
1771         const char **rec_argv;
1772         bool has_lock_stat = true;
1773
1774         for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
1775                 if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
1776                         pr_debug("tracepoint %s is not enabled. "
1777                                  "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
1778                                  lock_tracepoints[i].name);
1779                         has_lock_stat = false;
1780                         break;
1781                 }
1782         }
1783
1784         if (has_lock_stat)
1785                 goto setup_args;
1786
1787         for (i = 0; i < ARRAY_SIZE(contention_tracepoints); i++) {
1788                 if (!is_valid_tracepoint(contention_tracepoints[i].name)) {
1789                         pr_err("tracepoint %s is not enabled.\n",
1790                                contention_tracepoints[i].name);
1791                         return 1;
1792                 }
1793         }
1794
1795         nr_callgraph_args = ARRAY_SIZE(callgraph_args);
1796
1797 setup_args:
1798         rec_argc = ARRAY_SIZE(record_args) + nr_callgraph_args + argc - 1;
1799
1800         if (has_lock_stat)
1801                 nr_tracepoints = ARRAY_SIZE(lock_tracepoints);
1802         else
1803                 nr_tracepoints = ARRAY_SIZE(contention_tracepoints);
1804
1805         /* factor of 2 is for -e in front of each tracepoint */
1806         rec_argc += 2 * nr_tracepoints;
1807
1808         rec_argv = calloc(rec_argc + 1, sizeof(char *));
1809         if (!rec_argv)
1810                 return -ENOMEM;
1811
1812         for (i = 0; i < ARRAY_SIZE(record_args); i++)
1813                 rec_argv[i] = strdup(record_args[i]);
1814
1815         for (j = 0; j < nr_tracepoints; j++) {
1816                 const char *ev_name;
1817
1818                 if (has_lock_stat)
1819                         ev_name = strdup(lock_tracepoints[j].name);
1820                 else
1821                         ev_name = strdup(contention_tracepoints[j].name);
1822
1823                 if (!ev_name)
1824                         return -ENOMEM;
1825
1826                 rec_argv[i++] = "-e";
1827                 rec_argv[i++] = ev_name;
1828         }
1829
1830         for (j = 0; j < nr_callgraph_args; j++, i++)
1831                 rec_argv[i] = callgraph_args[j];
1832
1833         for (j = 1; j < (unsigned int)argc; j++, i++)
1834                 rec_argv[i] = argv[j];
1835
1836         BUG_ON(i != rec_argc);
1837
1838         ret = cmd_record(i, rec_argv);
1839         free(rec_argv);
1840         return ret;
1841 }
1842
1843 static int parse_map_entry(const struct option *opt, const char *str,
1844                             int unset __maybe_unused)
1845 {
1846         unsigned long *len = (unsigned long *)opt->value;
1847         unsigned long val;
1848         char *endptr;
1849
1850         errno = 0;
1851         val = strtoul(str, &endptr, 0);
1852         if (*endptr != '\0' || errno != 0) {
1853                 pr_err("invalid BPF map length: %s\n", str);
1854                 return -1;
1855         }
1856
1857         *len = val;
1858         return 0;
1859 }
1860
1861 int cmd_lock(int argc, const char **argv)
1862 {
1863         const struct option lock_options[] = {
1864         OPT_STRING('i', "input", &input_name, "file", "input file name"),
1865         OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
1866         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
1867         OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
1868         OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
1869                    "file", "vmlinux pathname"),
1870         OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1871                    "file", "kallsyms pathname"),
1872         OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any message"),
1873         OPT_END()
1874         };
1875
1876         const struct option info_options[] = {
1877         OPT_BOOLEAN('t', "threads", &info_threads,
1878                     "dump thread list in perf.data"),
1879         OPT_BOOLEAN('m', "map", &info_map,
1880                     "map of lock instances (address:name table)"),
1881         OPT_PARENT(lock_options)
1882         };
1883
1884         const struct option report_options[] = {
1885         OPT_STRING('k', "key", &sort_key, "acquired",
1886                     "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1887         OPT_STRING('F', "field", &output_fields, NULL,
1888                     "output fields (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
1889         /* TODO: type */
1890         OPT_BOOLEAN('c', "combine-locks", &combine_locks,
1891                     "combine locks in the same class"),
1892         OPT_BOOLEAN('t', "threads", &show_thread_stats,
1893                     "show per-thread lock stats"),
1894         OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
1895         OPT_PARENT(lock_options)
1896         };
1897
1898         struct option contention_options[] = {
1899         OPT_STRING('k', "key", &sort_key, "wait_total",
1900                     "key for sorting (contended / wait_total / wait_max / wait_min / avg_wait)"),
1901         OPT_STRING('F', "field", &output_fields, "contended,wait_total,wait_max,avg_wait",
1902                     "output fields (contended / wait_total / wait_max / wait_min / avg_wait)"),
1903         OPT_BOOLEAN('t', "threads", &show_thread_stats,
1904                     "show per-thread lock stats"),
1905         OPT_BOOLEAN('b', "use-bpf", &use_bpf, "use BPF program to collect lock contention stats"),
1906         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1907                     "System-wide collection from all CPUs"),
1908         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1909                     "List of cpus to monitor"),
1910         OPT_STRING('p', "pid", &target.pid, "pid",
1911                    "Trace on existing process id"),
1912         OPT_STRING(0, "tid", &target.tid, "tid",
1913                    "Trace on existing thread id (exclusive to --pid)"),
1914         OPT_CALLBACK(0, "map-nr-entries", &bpf_map_entries, "num",
1915                      "Max number of BPF map entries", parse_map_entry),
1916         OPT_INTEGER(0, "max-stack", &max_stack_depth,
1917                     "Set the maximum stack depth when collecting lock contention, "
1918                     "Default: " __stringify(CONTENTION_STACK_DEPTH)),
1919         OPT_INTEGER(0, "stack-skip", &stack_skip,
1920                     "Set the number of stack depth to skip when finding a lock caller, "
1921                     "Default: " __stringify(CONTENTION_STACK_SKIP)),
1922         OPT_INTEGER('E', "entries", &print_nr_entries, "display this many functions"),
1923         OPT_PARENT(lock_options)
1924         };
1925
1926         const char * const info_usage[] = {
1927                 "perf lock info [<options>]",
1928                 NULL
1929         };
1930         const char *const lock_subcommands[] = { "record", "report", "script",
1931                                                  "info", "contention", NULL };
1932         const char *lock_usage[] = {
1933                 NULL,
1934                 NULL
1935         };
1936         const char * const report_usage[] = {
1937                 "perf lock report [<options>]",
1938                 NULL
1939         };
1940         const char * const contention_usage[] = {
1941                 "perf lock contention [<options>]",
1942                 NULL
1943         };
1944         unsigned int i;
1945         int rc = 0;
1946
1947         for (i = 0; i < LOCKHASH_SIZE; i++)
1948                 INIT_HLIST_HEAD(lockhash_table + i);
1949
1950         argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
1951                                         lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
1952         if (!argc)
1953                 usage_with_options(lock_usage, lock_options);
1954
1955         if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
1956                 return __cmd_record(argc, argv);
1957         } else if (strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
1958                 trace_handler = &report_lock_ops;
1959                 if (argc) {
1960                         argc = parse_options(argc, argv,
1961                                              report_options, report_usage, 0);
1962                         if (argc)
1963                                 usage_with_options(report_usage, report_options);
1964                 }
1965                 rc = __cmd_report(false);
1966         } else if (!strcmp(argv[0], "script")) {
1967                 /* Aliased to 'perf script' */
1968                 return cmd_script(argc, argv);
1969         } else if (!strcmp(argv[0], "info")) {
1970                 if (argc) {
1971                         argc = parse_options(argc, argv,
1972                                              info_options, info_usage, 0);
1973                         if (argc)
1974                                 usage_with_options(info_usage, info_options);
1975                 }
1976                 /* recycling report_lock_ops */
1977                 trace_handler = &report_lock_ops;
1978                 rc = __cmd_report(true);
1979         } else if (strlen(argv[0]) > 2 && strstarts("contention", argv[0])) {
1980                 trace_handler = &contention_lock_ops;
1981                 sort_key = "wait_total";
1982                 output_fields = "contended,wait_total,wait_max,avg_wait";
1983
1984 #ifndef HAVE_BPF_SKEL
1985                 set_option_nobuild(contention_options, 'b', "use-bpf",
1986                                    "no BUILD_BPF_SKEL=1", false);
1987 #endif
1988                 if (argc) {
1989                         argc = parse_options(argc, argv, contention_options,
1990                                              contention_usage, 0);
1991                 }
1992                 rc = __cmd_contention(argc, argv);
1993         } else {
1994                 usage_with_options(lock_usage, lock_options);
1995         }
1996
1997         return rc;
1998 }